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