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