Scheduler: Remove obsolete 'Scheduler' class
[senf.git] / Console / Mainpage.dox
1 // $Id$
2 //
3 // Copyright (C) 2008 
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \mainpage The Configuration and Runtime Control Library
24
25     The Console library implements a runtime interactive (network) console which allows to
26     configure, control and manipulate a running application in any way. Additionally this library
27     provides support for configuration files and command line parsing which can be used with or
28     without the network console.
29
30     \autotoc
31
32
33     \section console_intro Introduction
34
35     There are three parts to the Config/console library:
36
37     The Config/Console library is built around several components
38
39     \li The \link node_tree Node tree\endlink represents all configuration options and commands
40         organized in a filesystem like structure.
41     \li \link console_commands Actions\endlink are added to the node tree in the form of command
42         nodes.
43     \li There exist several interfaces to \link console_access access\endlink entries in the node
44         tree: interactive console, reading configuration files etc.
45     
46     The node tree works like a directory structure. Commands are entered into this directory
47     structure and can be called passing arbitrary arguments. Configuration parameters are just
48     commands which set their respective parameter, however the library allows commands to do much
49     more than just that.
50
51
52     \section console_example Example
53
54     The following example shows a \e very short summary on how to integrate the config/console
55     library. See above links for more:
56
57     \code
58     #include <senf/Console.hh>
59
60     // Define callback function.
61     void mycommand(std::ostream & os, int foo, int bar)
62     {
63         // ...
64         os << "!! Important message ...\n";
65     }
66
67     namespace kw = senf::console::kw;
68
69     int main(int argc, char** argv)
70     {
71         // Provide global documentation
72         senf::console::root()
73             .doc("This is someServer server");
74
75         // Add a command
76         senf::console::root()
77             .add("mycommand", &mycommand)
78             .doc("If <bar> is given, flurgle the <foo>, otherwise burgle it")
79             .arg("foo")
80             .arg(kw::name = "bar", kw::default_value = 0);
81
82        // Parse command line parameters
83        senf::console::parseOptions(argc,argv);
84
85         // Start the interactive console server
86         senf::console::Server::start(senf::INet4SocketAddress(senf::INet4Address::None, 23232u))
87             .name("someServer");
88
89         // Run the scheduler
90        senf::scheduler::process();
91     }
92     \endcode
93
94     after this registration, we can call the command from the command-line using
95
96     <pre>
97     $ someServer --mycommand="1 2"
98     </pre>
99
100     the console can be accessed easily via telnet:
101     
102     <pre>
103     $ telnet localhost 23232
104     Trying 127.0.0.1...
105     Connected to localhost.
106     Escape character is '^]'
107     xxxx-xx-xx xx:xx:xx.xxxxxx-0000 [NOTICE][senf::console::Server] Registered new client 0xxxxxxx
108     someServer:/# ls
109     mycommand
110     someServer:/# mycommand
111     !! Important message  ...
112     someServer:/# exit
113     xxxx-xx-xx xx:xx:xx.xxxxxx-0000 [NOTICE][senf::console::Server] Disposing client 0xxxxxxx
114     Connection closed by foreign host.
115     $
116     </pre>
117
118     \see \ref console_testserver for a complete example application
119
120
121     \section intro_usage Using the Console: Configuration files, Network console, ...
122
123     There are several ways to access the node tree:
124     \li By parsing configuration files
125     \li By parsing command line parameters
126     \li By providing interactive or non-interactive network console access
127
128     \see console_access
129
130
131     \section intro_nodes The node tree
132
133     The basic idea is, that the console/config library manages a directory structure of parameters
134     and auxiliary commands. Parameters are just commands which set a parameter value so everything
135     is either a directory entry (senf::console::DirectoryNode) or a command
136     (senf::console::CommandNode).
137     
138     \see \ref node_tree
139
140
141     \section intro_commands Implementing console/config commands
142
143     The console/config language does not define, how arguments are passed to the commands, it just
144     tokenizes the input and passes the tokens to the commands which then handle the
145     conversion.
146
147     Since parsing the tokens into something usable is quite tedious and error prone, the library
148     implements automatic argument parsing where the argument tokens are automatically parsed
149     depending on argument types. This enables you to register a command taking an integer argument
150     which will be called with an already parsed integer value (or throw a
151     senf::console::SyntaxErrorException if the conversion fails). This will be the most often used
152     command.
153
154     \see \ref console_commands
155  */
156
157 /** \defgroup console_access Accessing the Console/Config tree
158
159     The Console/Config library provides several ways to use the node tree to configure and control
160     an application.
161
162     \autotoc
163
164
165     \section console_access_config Configuration support
166
167     The configuration support of the Console/Config library revolves around the ConfigSource
168     concept. Each ConfigSource will somehow provide commands which will then be executed against the
169     node tree.
170
171     To simplify the usage, there will always be three interfaces to a specific config source:
172     \li A constructor to build a bare config source which is then added to a
173         senf::console::ConfigBundle (see \ref console_access_multiple)
174     \li A class parsing and executing a single config source. The visible interface of this class is
175         a combination of the constructor and the senf::console::ConfigBundle interfaces.
176     \li A helper function which will do the complete parsing of a single source with default
177         parameters.
178
179     When parsing these configuration sources, it is always possible to optionally change the root
180     node used during parsing and it is also possible to restrict parsing to a command subset. See
181     \ref console_access_partial.
182
183
184     \subsection console_access_file Configuration files
185
186     <table class="senf fixedwidth">
187     <tr><td><b>Constructor</b></td> <td>senf::console::FileConfig()</td></tr>
188     <tr><td><b>Class</b></td>       <td>senf::console::ConfigFile</td></tr>
189     <tr><td><b>Helper</b></td>      <td>senf::console::parseFile()</td></tr>
190     </table>
191
192     In it's simplest form, parsing a configuration file consists of calling
193     senf::console::parseFile() with the name of the respective config file as argument.
194
195     \code
196     senf::console::parseFile("some.conf");
197     \endcode
198
199     To get more flexible, instantiate a senf::console::ConfigFile instance at use that to parse the
200     file
201     
202     \code
203     senf::console::ConfigFile cf ("some.conf");
204     cf.parse();
205     \endcode
206
207     If the application supports other configuration sources besides a single configuration file
208     (like command line options) or if it supports multiple configuration files (e.g. a system-wide
209     and a user specific configuration file) see \ref console_access_multiple and add one (or more)
210     senf::console::FileConfig() source to a senf::console::ConfigBundle.
211
212
213     \subsubsection console_access_file_syntax Configuration file syntax
214
215     Configuration files are written in a simple configuration language. This language is almost
216     declarative (e.g. it does not have any control-flow statements) but is processed imperatively
217     from top to bottom. This is very simple and flexible.
218
219     Commands are referenced by their path in the node tree. To simplify working with deeply nested
220     directory structures, the current directory may be changed persistently or temporarily for some
221     commands.
222     \code
223     /server/port 1234;
224     
225     /logger/targets/console {
226         accept senf::log::Debug IMPORTANT;
227         accept server::ServerLog CRITICAL;
228     }
229     \endcode
230
231     \see \ref console_parser
232
233
234     \subsection console_access_options Command line options
235
236     <table class="senf fixedwidth">
237     <tr><td><b>Constructor</b></td> <td>senf::console::OptionsConfig()</td></tr>
238     <tr><td><b>Class</b></td>       <td>senf::console::ProgramOptions</td></tr>
239     <tr><td><b>Helper</b></td>      <td>senf::console::parseOptions()</td></tr>
240     </table>
241
242     Command line options can either be parsed by calling the senf::console::parseOptions() helper
243
244     \code
245     senf::console::parseOptions(argc, argv)
246     \endcode
247
248     or more flexibly by instantiating a senf::console::ProgramOptions class
249
250     \code
251     std::vector<std::string> args;
252     senf::console::ProgramOptions opts (argc, argv);
253     opts
254         .nonOptions(args)
255         .alias('c', "--mycommand",true)
256         .alias('C', "--mycommand=2 3");
257     opts.parse();
258     \endcode
259
260     This registeres two short options and accumulates all non-option arguments in \c args.
261     
262     If the application supports other configuration sources besides the command line options (like
263     configuration files) see \ref console_access_multiple and add a senf::console::OptionsConfig()
264     source to a senf::console::ConfigBundle.
265
266     See \ref senf::console::ProgramOptions for the source specific additional parameters. These
267     apply to senf::console::ProgramOptions and to the senf::console::OptionsConfig() source.
268
269
270     \subsubsection console_access_options_syntax Options syntax
271
272     Command line options are primarily parsed as long-options. Long options start with '--'. Further
273     '-' characters serve as directory separators if required (that is, they are \e only interpreted
274     as directory separator is there is no entry in the current (sub-) directory matching more than a
275     single name component). This still allows using hyphens in node names.
276
277     Options can be abbreviated at each directory boundary: A command <tt>/foo/bar/do</tt> can be
278     called as <tt>--f-b-d</tt> as long as this name is unique.
279
280     Everything after the first '=' character is parsed into argument tokens using the normal
281     config/console parser. If the option has no '=' character, the list of argument tokens will be
282     empty.
283     
284     <table style="font-size:80%" class="senf">
285     <tr><th>Command</th><th>File syntax</th><th>Option syntax</th></tr>
286
287     <tr>
288       <td><tt>void doo()</tt></td>
289       <td><tt>/path/to/doo;</tt></td>
290       <td><tt>--path-to-doo</tt></td>
291     </tr>
292
293     <tr>
294       <td><tt>void doo(std::string const &)</tt></td>
295       <td><tt>/path/to/doo john.doe@everywhere.org;</tt></td>
296       <td><tt>--path-to-doo="john.doe@everywhere.org"</tt></td>
297     </tr>
298     
299     <tr>
300       <td><tt>void doo(std::string const &)</tt></td>
301       <td><tt>/path/to/doo "some test";</tt></td>
302       <td><tt>--path-to-doo='"some text"'</tt></td>
303     </tr>
304
305     <tr>
306       <td><tt>void doo(std::string const &, int)</tt></td>
307       <td><tt>/path/to/doo take 1;</tt></td>
308       <td><tt>--path-to-doo="take 1"</tt></td>
309     </tr>
310     </table>
311
312     The last column is additionally quoted using standard \c sh quoting: quotes in arguments need to
313     be additionally quoted for the shell.
314
315     Short options are registered as aliases for long options. They can be registered with or without
316     an implied parameter and can optionally take a parameter. so after
317
318     \code
319     opts
320         .alias('c', "--mycommand",true)
321         .alias('C', "--mycommand=2 3");
322     \endcode
323
324     we can call
325
326     <pre>
327     $ program -C -c "4 5"
328     $ program -Cc"4 5"
329     </pre>
330
331     which is the same as
332     
333     <pre>
334     $ program --mycommand="2 3" --mycommand="4 5"
335     </pre>
336
337     (Beware, that the second argument to \c alias() is \e not shell quoted). 
338
339
340     \subsection console_access_root Changing the root node
341
342     When used in it's default state, parsing will always interpret all commands relative to the
343     senf::console::root() node and will parse a file completely.
344
345     The first possibility to control this is to change the root node. This is done by 
346     \li passing that root node to the helper class or to the parse helper as an additional argument
347         (see the respective documentation).
348     \li passing it to the senf:;console::ConfigBundle constructor when parsing multiple sources.
349     
350     for example:
351
352     \code
353     senf::console::parseFile("/etc/myserver.conf", senf::console::root()['config']);
354     \endcode
355
356     This functionality is even more powerful by combining it with \c link nodes: This allows to
357     selectively choose commands from the node tree which are to be made accessible for
358     configuration. See \ref node_tree.
359
360
361     \subsection console_access_partial Partial / incremental configuration
362
363     Another feature provided by senf::console::ConfigBundle and all helper classes is partial
364     parsing.
365
366     \code
367     // Create a console/config aware object and place it into the node tree
368     FooObject foo;
369     senf::console::root().add("foo", foo.dir);
370
371     // Open configuration file
372     senf::console::ConfigFile cf ("/etc/myserver.conf");
373     
374     // Parse only commands in the configuration file which are in the foo.dir directory
375     cf.parse(foo.dir);
376
377     ...
378
379     // Anywhere later, parse the rest of the configuration file
380     cf.parse();
381     \endcode
382
383     This feature allows to parse parts of one or more configuration sources before the
384     console/config tree has been fully established. Partial parsing can be applied any number of
385     times to arbitrary nodes. Any command already parsed will be skipped automatically.
386
387     When combining partial parsing with \c chroot() and \c link's, it is important to realize, that
388     <em>partial parsing always applies to the \e real target and ignores links</em>. This is very
389     important: It allows a subsystem to parse it's configuration parameters irrespective of any
390     links pointing to nodes of that subsystem.
391
392
393     \subsection console_access_multiple Multiple sources
394
395     Most of the time, an application will utilize multiple configuration sources: A global
396     configuration file, maybe a user specific local configuration file, command line options ...
397
398     When parsing configuration commands, especially using partial / incremental parsing, all parse
399     commands should be applied to each configuration source in turn. This is the responsibility of
400     senf::console::ConfigBundle.
401
402     \code
403     senf::console::ScopedDirectory<> config;
404     senf::console::root().add("config", config);
405
406     // Let's enable all logger commands for configuration
407     config.link("logger", senf::console::root()["logger"]);
408
409     // Create bundle and add sources
410     std::vector<std::string> args;
411     senf::console::ConfigBundle conf (senf::console::root()["config"]);
412     conf.add( senf::console::FileConfig("/etc/myserver.conf") );
413     conf.add( senf::console::FileConfig(".myserver.conf") );
414     conf.add( senf::console::OptionsConfig(senf::Daemon::instance().argc(), 
415                                            senf::Daemon::instance().argv()) )
416         .nonOptions(args)
417         .alias('c', "--mycommand",true)
418         .alias('C', "--mycommand=2 3");
419
420     // Parse the logger subsystem commands in '/logger'
421     conf.parse(senf::console::root()['logger']);
422     
423     ...
424
425     // Parse all other configuration commands. All necessary commands and links in '/config' must by
426     // now have been created.  
427     conf.parse();
428     \endcode
429
430     This example parses three configuration sources: Two configuration files and additional
431     parameters specified on the command line. All the configuration commands are placed into the
432     <tt>/config</tt> directory (directly or via links). The configuration sources are parsed in the
433     order they are specified, so in this case, the command line options will override any options
434     specified in one of the configuration files.
435
436
437     \section console_access_console The network console
438
439     To make the network console accessible, it must be initialized when the program is started:
440     \code
441     #include <senf/Console.hh>
442
443     int main(int argc, char * argv [])
444     {
445         // Configure console nodes, add commands ...
446
447         // Start console server
448         senf::console::start(senf::INet4SocketAddress(12345u))
449            .name("myserver");
450
451         // You need to enter the scheduler main-loop for the server to work
452         senf::scheduler::process();
453        
454         // Alternatively enter the main-loop via the PPI
455         // senf::ppi::run();
456     }
457     \endcode
458
459     This will start the server on IPv4 port 12345. The servers name (as displayed in the interactive
460     console prompt) is set to 'myserver'.
461
462     After launching the application, the server can be accessed at the given port:
463     \htmlonly
464     <pre>
465     bash$ telnet localhost 12345
466     Trying 127.0.0.1...
467     Connected to localhost.
468     Escape character is '^]'.
469
470     myserver:/$ exit
471     Connection closed by foreign host.
472     bash$
473     </pre>
474     \endhtmlonly
475
476     It is possible to start multiple server consoles by calling \c start() multiple times with
477     different ports/addresses. Each server can be configured separately (e.g. root node, mode ...).q
478
479
480     \subsection console_serverclient Server and Client objects
481
482     The senf::console::Server and senf::console::Client objects offer further API calls. To access
483     the server instance you need to store away the senf::console::Server reference returned when
484     starting the server so you can later refer to it:
485     \code
486     int main(int, char**)
487     {
488         senf::console::Server & server ( senf::console::start( ... ) );
489     
490         // Do something ...
491
492         server.stop()
493     }
494     \endcode
495
496     The client instance can be accessed via the \c std::ostream arg of any command callback
497     \code
498     void someCallback(std::ostream & os, ... )
499     {
500         senf::console::Client & client (senf::console::Client::get(os));
501     
502         // Use the client's log target
503         client.route<senf::log::Debug, senf::Log::IMPORTANT>();
504     }
505     \endcode
506
507     \see 
508         senf::console::Server for the Server API \n
509         <a href="classsenf_1_1console_1_1Client-members.html">senf::console::Client / List of all
510         members</a> for the Client API
511
512
513     \subsection console_shell The interactive console shell
514
515     The interactive shell will use the GNU readline library for the first connected
516     instance. Further users will not have access to this functionality since GNU readline is
517     completely non-reentrant. GNU readline supports history and some command keys (like C-d for \c
518     exit or C-c to clear and restart the input).
519
520     The shell supports auto-cd and auto-completion: If you enter the name of a directory at the
521     prompt, the console will change to that directory. With auto-completion, any unique beginning of
522     a path component will be completed automatically and transparently to the corresponding full
523     name.
524
525
526     \subsection console_noninteractive Non-interactive network console
527
528     After a new connection is established, the console server waits a short time for data to arrive.
529     arrive. Only if nothing happens in the first 500ms, readline is initialized (if available) and
530     the interactive prompt is displayed.
531
532     By sending data immediately after opening the connection, the console is switched into
533     non-interactive mode. In this mode, no prompt is displayed. In this mode, commands are \e not
534     terminated automatically by end-of-line (CR). This allows, to easily cat an arbitrary
535     configuration file into the network console using netcat:
536     
537     <pre>
538     $ nc -q1 localhost 23232 < some.conf
539     </pre>
540
541     The argument <tt>-q1</tt> makes netcat close the sending end of the connection on EOF and wait
542     up to 1 second for the console to terminate. Even better, use \c netcat6, which has full TCP
543     half-close support.
544
545     <pre>
546     $ echo "ls" | nc6 --half-close localhost 23232 2>/dev/null
547     console/
548     server/
549     test/
550     $
551     </pre>
552
553     Commands are executed as soon as the terminating character (';', '{' or '}') is received or when
554     the sending end of the connection is closed.    
555  */
556
557 /** \defgroup console_commands Supported command types
558
559     The Console/config library supports quite a number of different command types. All these types
560     of command are registered, by passing them to DirectoryNode::add()
561
562     \autotoc
563
564
565     \section console_cmdadd Adding commands and setting attributes
566
567     Basically, all commands are added using senf::console::DirectoryNode::add(). What exactly
568     happens depends on the type of object added.
569     \code
570     dir.add("name", callback)
571     \endcode
572     will add a command 'name' which will execute 'callback' when called, where 'callback' can be a
573     lot of things as documented in the following chapters.
574
575     The add call always returns (something which can be used as) a reference to the command node
576     added:
577     \code
578     senf::console::CommandNode & node ( dir.add( ... ) );
579     \endcode
580
581     Depending on the object added, you can also bind to a more specific node type
582     (e.g. senf::console::SimpleCommand) if you know the type of node returned.
583
584     Depending on the type of object added, there are additional attributes which can be set. These
585     attributes are always set by calling them on the return value <b>before saving that value as a
586     node reference</b>. It is \e not guaranteed, you can call these members on the node
587     reference.
588     \code
589     dir.add("name", callback)
590         .doc("The documentation");
591     \endcode
592     sets the \e doc attribute (if that is available, otherwise this will fail to compile). The
593     attribute members return value is again (something which can be used as) a reference to the
594     command node
595     \code
596     senf::console::CommandNode & node (
597         dir.add("name", callback)
598             .doc("The documentation") );
599     \endcode
600
601
602     \section console_manualparse Manually parsing command arguments
603
604     This is the most primitive type of command. It will be called with an output stream and with a
605     senf::console::ParseCommandInfo reference which holds information about the command parsed.
606
607     From this information the command callback gets a list of arguments or tokens which then can be
608     interpreted in an arbitrary way.
609     \code
610     void fun1(std::ostream & os, senf::console::ParseCommandInfo const & command)
611     {
612         // Here we declare variables for the arguments
613         std::string value;
614
615         {
616             // We parse the arguments using the CheckedArgumentIteratorWrapper. This wrapper
617             // will throw a SyntaxErrorException if we access a nonexistent argument or if we
618             // do not parse all arguments.
619             senf::console::CheckedArgumentIteratorWrapper args (command.arguments());
620
621             senf::console::ParseCommandInfo::TokensRange argTokens ( *(args++) );
622             if (arg1Tokens.size() != 1)
623                 raise senf::console::SyntaxErrorException("argument syntax error");
624             value = arg1Tokens[0];
625         }
626
627         os << value << std::endl;
628     }
629     \endcode
630     
631     Registering this callback is done by simply adding it. To provide online help, pass it to
632     'doc()':
633     \code
634     senf::console::root()
635         .add("test1", &fun1)
636         .doc("Usage:\n"
637              "    test1 arg\n"
638              "\n"
639              "Echo 'arg' to the console");
640     \endcode
641
642     The callback may now be called interactively on the console by it's registered name:
643     \htmlonly
644     <pre>
645     server:/$ test1
646     invalid number of arguments
647     server:/$ test1 stefan@j32.de
648     stefan@j32.de
649     server:/$ test1 (echo me)
650     argument syntax error
651     server:/$ help test1
652     Usage:
653         test1 arg
654
655     Echo 'arg' to the console
656     server:/$
657     </pre>
658     \endhtmlonly
659
660     As you can see above, the arguments and tokens are returned as <a
661     href="http://www.boost.org/doc/libs/1_33_1/libs/range/doc/utility_class.html#iter_range">
662     boost::iterator_range</a> instances. These behave much like containers: They have \c begin() and
663     \c end() and some other useful members.
664     
665     The parser will have divided the argument tokens into arguments already. This simplifies further
666     parsing. If however you want to access the list of argument tokens as a single list, you can do
667     so using senf::console::ParseCommandInfo::tokens().
668     
669     Parsing arguments is quite simple but can get very tedious. To simplify this task, the parsing
670     can be delegated to the Console/config library. See the next section.
671
672     This type of command has only a single attribute, \e doc to set the commands documentation.
673
674
675     \section console_autoparse Automatic argument parsing
676     
677     To greatly simplify parsing complex commands, we turn to automatic argument parsing. 
678
679
680     \subsection console_autoadd Adding
681
682     Automatically parsed commands are registered by just adding a callback which has the correct
683     arguments and return-value defined:
684     \code
685     std::string fun2(std::string const & arg)
686     {
687         return arg;
688     }
689     \endcode
690
691     This extremely simple callback may be registered by adding it to a senf::console::DirectoryNode.
692     \code
693     senf::console::root()
694         .add("test2", &fun2);
695     \endcode
696     The functionality is now identical to \c test1:
697     \htmlonly
698     <pre>
699     server:/$ test2
700     invalid number of arguments
701     server:/$ test2 stefan@j32.de
702     stefan@j32.de
703     server:/$ test2 (echo me)
704     argument syntax error
705     server:/$ help test2
706     Usage:
707         test2 arg11:string
708     server:/$
709     </pre>
710     \endhtmlonly
711
712
713     \subsection command_ostream Accessing the console stream
714
715     Commands may have an optional first argument of type <tt>std::ostream &</tt>. This argument is
716     not considered part of the real interface. When the command is executed, the callback will be
717     passed the current consoles output stream object in this argument. With this, the callback can
718     output arbitrary messages to the network console.
719     \code
720     void fun3(std::ostream & os, unsigned n, std::string text)
721     {
722         while (n-- > 0) os << text << std::endl;
723     }
724
725     senf::console::root()
726         .add("test3", &fun3);
727     \endcode
728
729     This simple command can now be used thus:
730     \htmlonly
731     <pre>
732     server:/$ test3
733     invalid number of arguments
734     server:/$ test3 stefan@j32.de
735     invalid number of arguments
736     server:/$ test3 2 ok
737     ok
738     ok
739     server:/$ help test3
740     Usage:
741         test3 arg11:int arg12:string
742     server:/$
743     </pre>
744     \endhtmlonly
745
746
747     \subsection command_overload Overloading
748
749     Automatically parsed commands can be overloaded: You can register multiple commands under the
750     same name. Each overload is tried in turn until no SyntaxErrorException is raised.
751     \code
752     senf::console::root()
753         .add("test4", &fun3);
754     senf::console::root()
755         .add("test4", &fun2);
756     \endcode
757     And now, we can call \c test4 with one or two args:
758     <pre>
759     server:/$ test4
760     invalid number of arguments
761     server:/$ test4 stefan@j32.de
762     stefan@j32.de
763     server:/$ test4 2 ok
764     ok
765     ok
766     server:/$ help test4
767     Usage:
768         1- test4 arg11:int arg12:string
769         2- test4 arg21:string
770     server:/$
771     </pre>
772
773     One note: When taking the address of an overloaded function (member or non-member), the C++
774     language forces you to cast that address to one of the possible types so the compiler knows,
775     which overload is requested. So to add a function which is overloaded in C++, each overload
776     needs to be added explicitly, casting to the correct type:
777     \code
778     void over(int);
779     void over(int,int);
780
781     senf::console::root()
782         .add("over", static_cast<void (*)(int)>(&over));
783     senf::console::root()
784         .add("over", static_cast<void (*)(int,int)>(&over));
785     \endcode
786
787
788     \subsection console_attributes Attributes
789
790     As have seen so far, some documentation is automatically provided. We can add more info, by
791     setting additional attributes. 
792     \code
793     senf::console::root()
794         .add("test5", &fun3)
795         .doc("Echo text to the console")
796         .overloadDoc("Repeat {arg12} for {arg11} lines");
797     senf::console::root()
798         .add("test4", &fun2)
799         .overloadDoc("Echo the {arg21} argument")
800     \endcode
801
802     This additional info is used to provide more documentation:
803     \htmlonly
804     <pre>
805     server:/$ help test5
806     Usage:
807         1- test5 arg11:int arg12:string
808         2- test5 arg21:string
809
810     Echo text to the console
811
812     Variant 1:
813     Repeat {arg12} for {arg11} lines
814     
815     Variant 2:
816     Echo the {arg21} argument
817     senf:/$
818     </pre>
819     \endhtmlonly
820
821
822     \subsection console_argattributes Argument attributes
823
824     Additional attributes can be set for each parameter. They are all passed to the
825     senf::console::ParsedArgumentAttributor::arg() attribute.
826
827     \code
828     namespace kw = senf::console::kw;
829
830     senf::console::root()
831         .add("test6", &fun3)
832         .doc("Echo text to the console")
833         .overloadDoc("Repeat {text} for {n} lines");
834         .arg( kw::name = "n", kw::description="Number of repetitions" )
835         .arg( kw::name = "text", kw::description="Text to output" );
836     senf::console::root()
837         .add("test6", &fun2)
838         .overloadDoc("Echo the {text} argument")
839         .arg( kw::name = "text" );
840     \endcode
841
842     (Sadly, there is no way to automatically find out the \e name of an argument, just it's type.)
843     Every callback argument corresponds with a call of the \c arg() attribute. Argument attributes
844     are set using keywords from the \ref senf::console::kw namespace. You will probably either use
845     this namespace via a namespace alias (as above) or via a <tt>using namespace
846     senf::console::kw</tt> declaration (but beware of name collisions).
847
848     You don't need to specify any information for an argument: To skip an argument, just call \c
849     arg() without attributes for this argument.
850
851     After adding this information, the online help is much more readable
852       \htmlonly
853     <pre>
854     server:/$ help test6
855     Usage:
856         1- test6 n:int text:string
857         2- test6 text:string
858
859     With:
860         n         Number of repetitions
861         text      Text to output
862
863     Echo text to the console
864
865     Variant 1:
866     Repeat {text} for {n} lines
867     
868     Variant 2:
869     Echo the {text} argument
870     senf:/$
871     </pre>
872     \endhtmlonly
873
874     Since most of the time, we only need to set the name and possibly a description for arguments,
875     there is a shortcut: name and description can be specified as positional arguments in this
876     order. So the following will give the exactly same result as above:
877     \code
878     namespace kw = senf::console::kw;
879
880     senf::console::root()
881         .add("test6", &fun3)
882         .doc("Echo text to the console")
883         .overloadDoc("Repeat <text> for <n> lines");
884         .arg("n",    "Number of repetitions")
885         .arg("text", "Text to output");
886     senf::console::root()
887         .add("test6", &fun2)
888         .overloadDoc("Echo the <text> argument")
889         .arg("text");
890     \endcode
891     
892     Keyword arguments should always be used if additional attributes are set. You can however mix
893     positional and keyword arguments.
894
895     
896     \subsection console_defaults Default values
897     
898     Another information which can not be automatically gathered from the type system is default
899     values. These have to be declared explicitly:
900     \code
901     namespace kw = senf::console::kw;
902
903     senf::console::root()
904         .add("test7", &fun3)
905         .doc("Echo {text} to the console, repeating {text} for {n} lines")
906         .arg("n",    "Number of repetitions", kw::default_value=1)
907         .arg("text", "Text to output");
908     \endcode
909
910     Default values can be used together with overloading. Default (optional) value support is quite
911     flexible, it is not mandatory, for default values to be specified only for the trailing
912     arguments. For the exact definition, how parsed argument values are assigned to overload
913     arguments in the presence of default values, see \ref senf::console::kw::default_value.
914     
915     \htmlonly
916     <pre>
917     server:/$ test7 echo
918     echo
919     server:/$ test7 4 ok
920     ok
921     ok
922     ok
923     ok
924     server:/$ help test7
925     Usage:
926         test4 [n:unsigned] text:string
927     
928     With:
929         n         Number of repetitions
930             default: 1
931         text      Text to output
932
933     Echo {text} to the console, repeating {text} for {n} lines
934     server:/$
935     </pre>
936     \endhtmlonly
937
938
939     \subsection console_boostfn Non-function-pointer commands
940
941     It is possible to add other callable objects besides function (and member-function)
942     pointers. However, since it is not possible to automatically deduce the argument and return
943     types in this case, the callables have to be wrapped in a \c boost::function object:
944
945     \code
946     senf::console::root()
947         .add("test8", 
948              boost::function<void (std::ostream &, std::string const &)>(
949                  boost::bind(&fun3, _1, 4u, _2)));
950     \endcode
951
952     This works with any callable object where argument types cannot be deduced automatically:
953     Boost.Bind expressions, Boost.Lambda expressions, functors and so on.
954     
955     \htmlonly
956     <pre>
957     server:/$ test8 ok
958     ok
959     ok
960     ok
961     ok
962     server:/$ help test8
963     Usage:
964         test8 arg11:string
965     server:/$
966     </pre>
967     \endhtmlonly
968
969
970     \subsection console_attr_summary Attribute summary
971
972     Here a summary of the most common attributes
973
974     <table class="senf fixedwidth">
975
976     <tr><td style="width:14em">\link senf::console::ParsedArgumentAttributorBase::doc() .doc\endlink
977     ( \e doc )</td><td>Set documentation for all overloads</td></tr>
978     
979     <tr><td>\link senf::console::ParsedArgumentAttributorBase::overloadDoc()
980     .overloadDoc\endlink ( \e doc )</td><td>Set documentation for a specific overload</td></tr>
981
982     <tr><td>\link senf::console::ParsedArgumentAttributor::arg() .arg\endlink ( \e argument \e
983     attributes )</td><td>Set argument attributes (see below)</td></tr>
984
985     </table>
986
987     The most important argument attributes (all defined in the senf::console::kw namespace) are:
988     
989     <table class="senf fixed width">
990
991     <tr><td style="width:14em">\link senf::console::kw::name kw::name\endlink</td><td>Parameter
992     name</td></tr>
993
994     <tr><td>\link senf::console::kw::description kw::description\endlink</td><td>One-line
995     description of the argument</td></tr>
996
997     <tr><td>\link senf::console::kw::default_value kw::default_value\endlink</td><td>Arguments
998     default value</td></tr>
999
1000     </table>
1001
1002     \see <a
1003         href="classsenf_1_1console_1_1ParsedArgumentAttributor-members.html">senf::console::ParsedArgumentAttributor
1004         / List of all members</a> for the complete attribute interface \n
1005         \ref senf::console::kw for a list of all argument attribute keywords
1006
1007         
1008     \section console_memberfn Member functions
1009     
1010     Non-static member functions are supported like non-member functions (static member functions are
1011     identical to non-members). They must however be added through a senf::console::ScopedDirectory
1012     instance to bind them to their instance.
1013     \code
1014     class Test1
1015     {
1016     public:
1017         senf::console::ScopedDirectory<Test1> dir;
1018
1019         Test1(std::string label) : dir(this), label_ (label) 
1020             { dir.add("test", &Test::test1);
1021               dir.add("test", &Test::test2); }
1022     
1023         std::string test1(std::string const & text)
1024             { return label_ + ": " + text; }
1025
1026         void test2(std::ostream & os, unsigned n, std::string const & text) 
1027             { while (n-- > 0) os << label << ": " << text << std::endl; }
1028
1029     private:
1030         std::string label_;
1031     };
1032
1033     // ...
1034
1035     Test1 test1ob ("test");
1036     senf::console::root().add("test1ob", test1ob.dir);
1037     \endcode
1038
1039     Binding via senf::console::ScopedDirectory ensures, that the commands are automatically removed
1040     from the tree when the object is destroyed.
1041
1042
1043     \section console_variables Variables
1044     
1045     \subsection console_varadd Adding
1046
1047     The console/config library supports the direct registration of variables as commands. A
1048     variable command consists of two overloads, one to query the current value and one to change the
1049     value. 
1050     \code
1051     class Test2
1052     {
1053     public:
1054         senf::console::ScopedDirectory<Test2> dir;
1055
1056         Test2() : dir(this), var_(0)
1057             { dir.add("var", var_); }
1058
1059     private:
1060         int var_;
1061     };
1062
1063     Test2 test2ob;
1064     senf::console::root().add("test2ob", test2ob.dir);
1065     \endcode
1066     This shows the most common scenario: A member variable is added to a ScopedDirectory of the same
1067     class. This ensures, that the variable command node is removed from the tree when the instance
1068     (and thereby the variable) are destroyed. The variable can now be used like any other command:
1069     \htmlonly
1070     <pre>
1071     server:/$ test2ob/var
1072     0
1073     server:/$ test2ob/var 10
1074     server:/$ test2ob/var
1075     10
1076     server:/$ help test2ob
1077     Usage:
1078         1- var new_value:int
1079         2- var
1080     server:/$
1081     </pre>
1082     \endhtmlonly
1083
1084
1085     \subsection console_varro Read-only variables
1086     
1087     The library also supports read-only variables. To make a variable read-only, just wrap it in \c
1088     boost::cref() (where \c cref stands for \c const reference)
1089     \code
1090     int var (0);
1091
1092     senf::console::root().add("var1", boost::cref(var));
1093     \endcode
1094     A read-only variable only has a single overload:
1095     \htmlonly
1096     <pre>
1097     server:/$ var1
1098     0
1099     server:/$ help var1
1100     Usage:
1101         var1
1102     server:/$ 
1103     </pre>
1104     \endhtmlonly
1105
1106
1107     \subsection console_varattr Attributes
1108
1109     The most important Variable command attributes are
1110
1111     <table class="senf fixedwidth">
1112
1113     <tr><td style="width:14em">\link senf::console::VariableAttributor::doc() .doc\endlink
1114     ( \e doc )</td><td>Set variable documentation</td></tr>
1115     
1116     <tr><td>\link senf::console::VariableAttributor::onChange() .onChange\endlink
1117     ( \e handler )</td><td>Set change handler</td></tr>
1118     
1119     </table>
1120
1121     \see senf::console::VariableAttributor for the complete attribute interface
1122
1123
1124     \subsection console_varchange Change notification
1125
1126     A \e handler can be set to be called, whenever the variable is changed. It will be called with a
1127     reference to the old value. The handler is called, after the value has been changed
1128
1129     \code
1130     int var (0);
1131
1132     // Since this is int, it would make sense to declare the argument pass-by-value (int old)
1133     // but for more complex args, use a const & here
1134     void varChanged(int const & old)
1135     {
1136         // ...
1137     }
1138
1139     senf::console::root().add("var2",var)
1140         .onChange(&varChanged);
1141     \endcode
1142     
1143     After this setup, \c varChanged will be called, whenever the value has changed.
1144
1145
1146     \section console_args Special argument types
1147
1148     By default, argument types which can be read and written using \c iostreams are automatically
1149     supported. Other types need to be registered explicitly
1150
1151
1152     \subsection console_args_bool Boolean arguments and return values
1153
1154     The console library by default formats boolean values using the strings \c true and \c false for
1155     their representation. When parsing a boolean value, most sensible representations will be
1156     accepted:
1157     
1158     <table class="senf">
1159     <tr><td>\c true</td>    <td>\c false</td>    <td>\ref senf::console::formatTrueFalse</td></tr>
1160     <tr><td>\c on</td>      <td>\c off</td>      <td>\ref senf::console::formatOnOff</td></tr>
1161     <tr><td>\c enabled</td> <td>\c disabled</td> <td>\ref senf::console::formatEnabledDisabled</td></tr>
1162     <tr><td>\c yes</td>     <td>\c no</td>       <td>\ref senf::console::formatYesNo</td></tr>
1163     <tr><td><em>non-zero integer</em></td><td>\c 0</td><td>\ref senf::console::formatOneZero</td></tr>
1164     </table>
1165
1166     The boolean parser will accept these values in any (mixed) case and accepts any unique initial
1167     substring (e.g. \c Y / \c N).
1168
1169     The last column lists explicit formatters which can be set to customize the return value
1170     formatting of a registered overload accordingly.
1171
1172     
1173     \subsection console_args_enum Registering enum types
1174
1175     Enum types are a special case, since it is not possible, to find a string representation for the
1176     enumerator values automatically. Therefore, enum types need to be registered manually.
1177     \code
1178     enum MyEnum { Sit, Run, Jump };
1179     SENF_CONSOLE_REGISTER_ENUM( MyEnum, (Sit)(Run)(Jump) );
1180
1181     MyEnum fun4(MyEnum v) { return v }
1182
1183     senf::console::root()
1184         .add("test9", &fun4);
1185     \endcode
1186
1187     After an enum type is registered, it can be used like any other type for arguments or
1188     return-values:
1189
1190     \htmlonly
1191     <pre>
1192     server:/$ test9 Sit
1193     Sit
1194     server:/$ test9 Crawl
1195     argument syntax error: invalid enum value
1196     server:/$ help test9
1197     Usage:
1198         test9 arg11:MyEnum
1199     server:/$
1200     </pre>
1201     \endhtmlonly
1202
1203     \ref SENF_CONSOLE_REGISTER_ENUM() can only be used, to register enums at namespace scope. To
1204     register enums defined within some class, use \ref SENF_CONSOLE_REGISTER_ENUM_MEMBER()
1205
1206     \code
1207     class Test3
1208     {
1209     public:
1210         enum Color { Red, Green, Blue };
1211     
1212         senf::console::ScopedDirectory<MyClass> dir;
1213
1214         Test3();
1215
1216         Color mem3(Color c) { return c }
1217     };
1218     SENF_CONSOLE_REGISTER_ENUM_MEMBER( Test3, Color, (Red)(Green)(Blue) );
1219
1220     Test3::Test3() : dir(this)
1221         { dir.add("test", &MyClass::mem3); }
1222     
1223     Test3 test3ob;
1224     senf::console::root().add("test3ob", test3ob.dir);
1225     \endcode
1226
1227     Using this command/type is identical
1228     \htmlonly
1229     <pre>
1230     server:/$ test3ob/test Red
1231     Red
1232     server:/$ test3ob/test White
1233     argument syntax error: invalid enum value
1234     server:/$ help test3ob/test
1235     Usage:
1236         test arg11:Color
1237     </pre>
1238     \endhtmlonly
1239
1240
1241     \subsection console_args_custom Extending the library to support additional types
1242
1243     To support or customize parsing/formatting of other types, they need to be registered. In it's
1244     simplest case, this works, by just providing an appropriate overload for
1245     senf_console_parse_argument() and senf_console_format_value():
1246     \code
1247     struct Coordinate
1248     {
1249         Coordinate() : x(0), y(0) {}
1250         Coordinate(int x_, int y_) : x(x_), y(y_) {}
1251
1252         int x, y;
1253     }
1254
1255     void senf_console_parse_argument(senf::console::ParseCommandInfo::TokensRange const & tokens,
1256                                      Coordinate & out)
1257     {
1258         senf::console::CheckedArgumentIteratorWrapper arg (tokens);
1259         senf::console::parse( *(arg++), out.x );
1260         senf::console::parse( *(arg++), out.y );
1261     }
1262
1263     void senf_console_format_value(Coordinate const & value, std::ostream & os)
1264     {
1265         os << '(' << value.x << ' ' << value.y << ')';
1266     }
1267     \endcode 
1268
1269     The parser will accept an argument with two tokens which are each forwarded to the integer
1270     parser. The senf::console::CheckedArgumentIteratorWrapper ensures two things: That all input
1271     tokens are parsed and no extra trailing tokens are left unparsed and it checks, that all
1272     referenced tokens really exist.
1273
1274     The formatter writes out the value as a parenthesized pair.
1275
1276     \code
1277     Coordinate fun5(Coordinate const & p) { return Coordinate(2*p.x, 2*p.y) }
1278     
1279     namespace kw = senf::console::kw;
1280
1281     senf::console::root()
1282         .add("test10", &fun5)
1283         .arg("x","coordinate to double",
1284              kw::default_value = Coordinate())
1285     \endcode
1286     We can now call \c test10 with a coordinate argument:
1287     \htmlonly
1288     <pre>
1289     server:/$ test10 (2 7)
1290     (4 14)
1291     server:/$ help test10
1292     Usage:
1293         test10 [x:Coordinate]
1294
1295     With:
1296         x         Coordinate to double
1297             default: (0 0)
1298     server:/$
1299     </pre>
1300     \endhtmlonly
1301     
1302     If you want to customize the formatting of default values differently from the formating of
1303     return-values or if you want to change the displayed name of a type, you will need to specialize
1304     the senf::console::ArgumentTraits class instead of implementing
1305     senf_console_parse_argument(). See senf::console::ArgumentTraits and
1306     senf::console::ReturnValueTraits for more.
1307  */
1308
1309 \f
1310 // Local Variables:
1311 // mode: c++
1312 // fill-column: 100
1313 // comment-column: 40
1314 // c-file-style: "senf"
1315 // indent-tabs-mode: nil
1316 // ispell-local-dictionary: "american"
1317 // compile-command: "scons -u test"
1318 // mode: auto-fill
1319 // End:
1320