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