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