4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
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.
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.
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.
24 \brief Node public header */
26 /** \defgroup node_tree The node tree
28 The console/config node tree is the central data-structure of the library. Into this tree, all
29 commands and parameters are entered. The tree is then exposed using a file-system like
34 \section console_tree The tree
36 We will start by giving a more complete example. This example contains most of the stuff needed
37 for using the console/config library.
40 // Define callback function.
41 void mycommand(std::ostream & os, senf::console::ParseCommandInfo const & command)
44 os << "!! Important message ...\n";
50 // Declare a directory node (proxy) for use by this class. This must be public so we can add
51 // it to the node tree later.
52 senf::console::ScopedDirectory<SomeClass> dir;
54 SomeClass() : dir(this)
56 // You may document the directory here or later when adding it to the tree
57 dir.doc("Manager for something");
59 // Add a member function (the pointer-to-member is automatically bound to this instance)
60 dir.add("member", &SomeClass::member)
61 .doc("Do the member operation");
64 void member(std::ostream & os, senf::console::ParseCommandInfo const & command)
72 // Provide global documentation
74 .doc("This is someServer server");
76 // Add a new directory to the root and document it. All the mutators return the node object
77 // itself so operations can be chained.
78 senf::console::DirectoryNode & mydir ( senf::console::root()
80 .doc("My server specific directory"));
82 // Add a command to that directory
83 mydir.add("mycommand", &mycommand)
84 .doc("mycommand <foo> [<bar>]\n\n"
85 "If <bar> is given, flurgle the <foo>, otherwise burgle it");
87 // Create a SomeClass instance and add it's directory.
89 mydir.add("someClass", someClass.dir);
91 // Start the interactive console server
92 senf::console::Server::start(senf::INet4SocketAddress(senf::INet4Address::None, 23232u))
97 \subsection console_nodes Node types
99 The console/config library tree consists of two basic node types:
101 \li senf::console::DirectoryNode provides internal nodes with an arbitrary number of children
102 \li senf::console::CommandNode describes a command entry in the tree
103 \li senf::console::LinkNode is a link to another node. It works much like a symlink on POSIX
106 senf::console::CommandNode is the base-class of all command nodes of which there are several,
107 depending on the type of command.
109 There is a single root node, the senf::console::DirectoryNode called senf::console::root(). From
110 this node, the tree is traversed.
112 All nodes are allocated on the heap and are managed using a smart pointer.
114 \subsection console_manipulate Manipulating the node tree
116 There are several ways to add nodes to the tree:
118 \li A senf::console::DirectoryNode can be added using senf::console::DirectoryNode::mkdir().
119 \li An arbitrary node can be created and then (possibly later) added to the tree using the
120 corresponding senf::console::DirectoryNode::add() overload.
121 \li A senf::console::CommandNode is normally added to the tree by directly adding a callback
122 using one of the overloaded senf::console::DirectoryNode::add() members. See \ref
124 \li A senf::console::LinkNode is created by senf::console::DirectoryNode::link()
126 When directly adding a node callback, the type of node added depends on the type of
127 callback. The callback types which can be added are listed at \ref console_callbacks.
130 void callback(std::ostream & os, senf::console::ParseCommandInfo const & command) { ... }
132 myDirectory.add("foo",&callback);
135 Every node is identified among it's siblings by it's name. The name of the node is set when
136 adding the node to the tree. If the name is empty or non-unique, a unique name will be
137 automatically provided.
139 To remove a node from the tree, just use the nodes senf::console::GenericNode::unlink() or the
140 parents senf::console::DirectoryNode::remove() member. This call removes the node from it's
141 parent and returns a (smart) node pointer.
143 \li If you ignore the return value, the node (and it's children) will be deleted.
144 \li Alternatively, you may store away the node and re-attach it later.
145 \li An node (or subtree) can be moved to a different place by unlinking the node at it's old
146 place and re-adding it at it's new location.
147 \li To rename a node, unlink and re-add it with a different name.
150 myDirectory.add("bar", myDirectory.remove("foo"));
153 \subsection console_node_param Assigning additional node parameters
155 Depending on the node type added, additional node parameters may be set. For example, every node
156 has a documentation parameter which is used by the online-help system. To assign these
157 parameters, the node exposes corresponding member functions. Since
158 senf::console::DirectoryNode::add() returns the newly added node by reference, additional
159 parameters may just be added to the end of the add command:
161 myDirectory.add("foo",&fooCallback).doc("The foo method");
163 Since the parameter setters all return the node reference, additional parameters may just be
164 added to the end of the command.
166 \subsection console_tree_traverse Traversing the tree
168 The simplest way to access tree elements is to save the return value of the
169 senf::console::DirectoryNode::add() members. However, saving the reference will not ensure, that
170 the node is not removed. If the node might be removed from the tree, you should use a smart
171 pointer (either <tt>ptr</tt> or <tt>weak_ptr</tt>) to hold the node.
173 Another possibility is to traverse the tree explicitly. For this purpose, the operators '[]' and
174 '()' have been overloaded in senf::console::DirectoryNode.
176 senf::console::root().getDirectory("myDirectory").getCommand("foo")
177 \\ or more concise but otherwise completely identical
178 senf::console::root()["myDirectory"]("foo")
181 getDirectory and the '[]' operator will return a senf::console::DirectoryNode whereas getCommand
182 and the '()' operator will return a senf::console::CommandNode. If the node is not found or is
183 not of the correct type, an exception will be raised.
185 \section console_object_dir Assigning a directory to an object instance
187 Most objects will register several commands. So it makes sense for these objects to manage their
188 own directory. Since directories are however allocated on the heap, they cannot be directly
189 added to a class. To facilitate this usage, the senf::console::ScopedDirectory is used. This
190 class provides a senf::console::DirectoryNode facade. Internally, it automatically creates a
191 senf::console::DirectoryNode to which all calls are forwarded.
193 The senf::console::ScopedDirectory member should be declared public. This allows the user of the
194 class to add the node to the tree.
197 #ifndef HH_SENF_Scheduler_Console_Node_
198 #define HH_SENF_Scheduler_Console_Node_ 1
202 #include <boost/shared_ptr.hpp>
203 #include <boost/weak_ptr.hpp>
204 #include <boost/enable_shared_from_this.hpp>
205 #include <boost/utility.hpp>
206 #include <boost/range/iterator_range.hpp>
207 #include <boost/any.hpp>
208 #include <senf/Utils/Exception.hh>
209 #include <senf/Utils/mpl.hh>
210 #include <senf/Utils/Logger/SenfLog.hh>
211 #include <senf/Utils/type_traits.hh>
214 //#include "Node.mpp"
215 ///////////////////////////////hh.p////////////////////////////////////////
224 namespace detail { struct NodeFactory {}; }
226 /** \brief Get console root node */
227 DirectoryNode & root();
229 /** \brief Dump console directory structure
231 Recursively dumps the console directory structure starting at \a dir. By default, dumps the
232 complete tree beginning at the root node.
234 In contrast to the console 'lr' command, links are dumped by showing the \e absolute path
237 void dump(std::ostream & os, DirectoryNode & dir=root());
239 /** \brief Config/console node tree base-class
241 GenericNode is the base class of all node objects. There are two basic node types derived
242 from GenericNode: DirectoryNode and CommandNode.
244 All nodes are dynamically allocated and automatically managed using reference counting.
246 All nodes are normally linked into a single tree which root node is
247 senf::console::root(). Nodes may however be orphaned (not linked to the tree) either
248 directly (the node has no parent) or indirectly (the node has a parent but is part of an
249 orphaned subtree which is not linked to the root node).
251 Every active (non-orphaned) node (except the root() node) has a non-empty node name. This
252 name is assigned to the node when adding the node to the tree.
257 : public boost::enable_shared_from_this<GenericNode>
259 SENF_LOG_CLASS_AREA();
261 ///////////////////////////////////////////////////////////////////////////
264 typedef boost::shared_ptr<GenericNode> ptr;
265 typedef boost::shared_ptr<GenericNode const> cptr;
266 typedef boost::weak_ptr<GenericNode> weak_ptr;
268 ///////////////////////////////////////////////////////////////////////////
270 virtual ~GenericNode();
272 std::string const & name() const; ///< Node name
273 boost::shared_ptr<DirectoryNode> parent() const; ///< Parent node
274 /**< May be null, if the node is the root node or if it is
275 not linked to the tree */
277 std::string path() const; ///< Node path
278 /**< The node path is built by joining the names of all
279 parent nodes with '/' chars. */
280 std::string path(DirectoryNode const & root) const;
281 ///< Node path up to \a root
282 /**< The node path is built by joining the names of all
283 parent nodes up to \a root with '/' chars. */
285 ptr unlink(); ///< Remove node from it's parent directory
286 /**< You may either discard the return value and thereby
287 dispose the node or may re-attach the node at some
288 other place using DirectoryNode::add(). */
290 bool active() const; ///< \c true, if node is attached to the root() node
292 void help(std::ostream & output) const; ///< Write help info to \a output
293 std::string shorthelp() const; ///< Get short (one-line) documentation
295 ptr thisptr(); ///< Get smart pointer to node
296 cptr thisptr() const; ///< Get smart pointer to node (const)
298 bool isChildOf(DirectoryNode & parent) const;
299 ///< \c true, if node is a child of \a parent
300 /**< Will also return \c true, if \a parent is the current
303 bool operator== (GenericNode & other) const;
304 ///< \c true, if this and \a other are the same node
305 bool operator!= (GenericNode & other) const;
306 ///< \c true, if this and \a other are different nodes
308 bool isDirectory() const; ///< \c true, if this is a directory node
309 bool isLink() const; ///< \c true, if this is a link node
310 bool isCommand() const; ///< \c true, if this is a command node
312 GenericNode const & followLink() const; ///< Follow link if \c this node is a link node
313 GenericNode & followLink(); ///< Follow link if \c this node is a link node
318 void name(std::string const & name);
325 virtual void v_help(std::ostream & output) const = 0;
326 ///< Provide help information
327 /**< This member must be implemented in derived classes to
328 provide node specific help information. */
329 virtual std::string v_shorthelp() const = 0;
330 ///< Provide short documentation
331 /**< This member must be implemented in derived classes to
332 provide node specific documentation. */
336 DirectoryNode * parent_;
338 friend class DirectoryNode;
341 /** \brief Config/console tree link node
343 A LinkNode references another node and provides an additional alias name for that node. A
344 LinkNode works like a mixture of UNIX symlinks and hardlinks: It is an explicit link like a
345 UNIX symlink but references another node directly (not via it's path) like a UNIX
346 hardlink. Therefore, a LinkNode works across chroot().
352 ///////////////////////////////////////////////////////////////////////////
355 typedef boost::shared_ptr<LinkNode> ptr;
356 typedef boost::shared_ptr<LinkNode const> cptr;
357 typedef boost::weak_ptr<LinkNode> weak_ptr;
359 ///////////////////////////////////////////////////////////////////////////
360 ///\name Structors and default members
363 static ptr create(GenericNode & node); ///< Create new link node.
364 /**< You should normally use DirectoryNode::link() to
365 create a link node. */
368 ///////////////////////////////////////////////////////////////////////////
370 GenericNode & follow() const; ///< Access the referenced node
375 explicit LinkNode(GenericNode & node);
377 virtual void v_help(std::ostream &) const;
378 virtual std::string v_shorthelp() const;
380 GenericNode::ptr node_;
383 class SimpleCommandNode;
385 /** \brief Config/console tree directory node
387 This node type provides the internal and root nodes of the tree. It allows to add arbitrary
388 children and supports directory traversal.
390 Nodes are normally not instantiated manually but are created by the DirectoryNode via
391 mkdir() or add(). Special add() members however allow externally allocated node objects.
393 Nodes may be added to the tree only once, otherwise chaos will ensue. Since nodes are always
394 managed dynamically, there is a special ScopedDirectory proxy template which provides a
395 DirectoryNode facade. ScopedDirectory is used if a class wants to manage it's own directory
398 Every node is assigned a (new) name when it is added to a directory. If the directory
399 already has an entry of that name, the name is made unique by appending a suffix of the form
400 '-n' where n is a number starting at 1. If the name is empty, int is set to 'unnamed' and
401 then uniquified as above. Automatically providing unique names simplifies adding
402 configuration/console support to generic components.
406 class DirectoryNode : public GenericNode
408 SENF_LOG_CLASS_AREA();
409 typedef std::map<std::string, GenericNode::ptr> ChildMap;
411 ///////////////////////////////////////////////////////////////////////////
414 typedef boost::shared_ptr<DirectoryNode> ptr;
415 typedef boost::shared_ptr<DirectoryNode const> cptr;
416 typedef boost::weak_ptr<DirectoryNode> weak_ptr;
418 typedef boost::iterator_range<ChildMap::const_iterator> ChildrenRange;
419 typedef ChildMap::const_iterator child_iterator;
421 typedef DirectoryNode node_type;
422 typedef DirectoryNode & return_type;
424 ///////////////////////////////////////////////////////////////////////////
425 ///\name Structors and default members
428 static ptr create(); ///< Create node object.
429 /**< You should normally use either mkdir() or
430 ScopedDirectory instead of create() */
434 ///////////////////////////////////////////////////////////////////////////
438 template <class NodeType>
439 NodeType & add(std::string const & name, boost::shared_ptr<NodeType> node);
440 ///< Add node to tree
441 /**< Adds the \a node to the tree as a child of \a this
442 node. The node is given the name \a name. If a node of
443 that name already exists, a numeric suffix of the form
444 '-n' is added to the name until the name is unique. If
445 \a name is empty, it is set to 'unnamed'. */
447 template <class NodeType>
448 NodeType & add(std::string const & name, NodeType & node,
449 typename boost::enable_if< boost::is_convertible<NodeType &, GenericNode &> >::type * = 0);
451 template <class Factory>
452 typename Factory::result_type add(std::string const & name, Factory const & factory,
453 typename boost::enable_if< boost::is_convertible<Factory const &, detail::NodeFactory const &> >::type * = 0);
454 ///< Generic child node factory
455 /**< This member is used to create a new child node of the
456 current directory. The type of node created depends on
457 the type of argument passed. */
459 GenericNode::ptr remove(std::string const & name);
460 ///< Remove node \a name from the tree
461 /**< The returned pointer may either be discarded, which
462 will automatically dispose the removed node, or it may
463 be saved and/or re-attached at some other place in the
466 bool hasChild(std::string const & name) const;
467 ///< \c true, if there is a child with name \a name
469 GenericNode & get(std::string const & name) const;
470 ///< Get child node automatically dereferencing links
471 /**< \throws UnknownNodeNameException if a child \a name
473 GenericNode & getLink(std::string const & name) const;
474 ///< Get child node without dereferencing links
475 /**< \throws UnknownNodeNameException if a child \a name
478 DirectoryNode & getDirectory(std::string const & name) const;
479 ///< Get directory child node (dereferencing links)
480 /**< Same as operator[]
481 \throws UnknownNodeNameException if a child \a name
483 \throws std::bad_cast if the child \a name is not a
486 DirectoryNode & operator[](std::string const & name) const;
487 ///< Get directory child node (dereferencing links)
488 /**< Same as getDirectory
489 \throws UnknownNodeNameException if a child \a name
491 \throws std::bad_cast if the child \a name is not a
494 CommandNode & getCommand(std::string const & name) const;
495 ///< Get command child node (dereferencing links)
496 /**< Same as operator()
497 \throws UnknownNodeNameException if a child \a name
499 \throws std::bad_cast if the child \a name is not a
502 CommandNode & operator()(std::string const & name) const;
503 ///< Get command child node (dereferencing links)
504 /**< Same as getCommand()
505 \throws UnknownNodeNameException if a child \a name
507 \throws std::bad_cast if the child \a name is not a
510 DirectoryNode & mkdir(std::string const & name);
511 ///< Create sub-directory node
512 DirectoryNode & provideDirectory(std::string const & name);
513 ///< Return subdirectory, possibly creating it
515 ChildrenRange children() const; ///< Return iterator range over all children.
516 /**< The returned range is sorted by child name. */
518 ChildrenRange completions(std::string const & s) const;
519 ///< Return iterator range of completions for \a s
520 /**< The returned range is sorted by child name. */
522 void link(std::string const & name, GenericNode & target);
523 ///< Create a child node which is a link to target. \a s
524 /**< The new link node will be a child of the node for which this member function is called. */
527 ///////////////////////////////////////////////////////////////////////////
529 DirectoryNode & doc(std::string const & doc); ///< Set node documentation
530 DirectoryNode & shortdoc(std::string const & doc); ///< Set node short documentation
533 cptr thisptr() const;
539 void add(GenericNode::ptr node);
540 virtual void v_help(std::ostream & output) const;
541 virtual std::string v_shorthelp() const;
545 std::string shortdoc_;
547 friend DirectoryNode & root();
550 /// Exception: Unknown node name
551 struct UnknownNodeNameException : public senf::Exception
552 { UnknownNodeNameException() : senf::Exception("Unknown node name") {}};
554 /** \brief Config/console tree command node
556 The CommandNode is the base-class for the tree leaf nodes. Concrete command node
557 implementations are derived from this class.
559 To execute a command, CommandNode::operator()() or CommandNode::execute() is called.
561 Subclass instances of this node type are automatically created when adding commands to the
562 tree. See \ref console_commands.
566 class CommandNode : public GenericNode
568 SENF_LOG_CLASS_AREA();
570 ///////////////////////////////////////////////////////////////////////////
573 typedef boost::shared_ptr<CommandNode> ptr;
574 typedef boost::shared_ptr<CommandNode const> cptr;
575 typedef boost::weak_ptr<CommandNode> weak_ptr;
577 ///////////////////////////////////////////////////////////////////////////
579 void execute(std::ostream & output, ParseCommandInfo const & command) const;
580 ///< Execute the command
581 /**< \param[in] output stream where result messages may be
583 \param[in] command command arguments. This is a
584 range of ranges of Token instances. */
586 void execute(boost::any & rv, std::ostream & output, ParseCommandInfo const & command)
588 ///< Execute the command
589 /**< \param[out] rv command return value
590 \param[in] output stream where result messages may be
592 \param[in] command command arguments. This is a
593 range of ranges of Token instances. */
595 void operator()(std::ostream & output, ParseCommandInfo const & command) const;
596 ///< Execute the command
597 /**< Same as execute()
598 \param[in] output stream where result messages may be
600 \param[in] command command arguments. This is a
601 range of ranges of Token instances. */
602 void operator()(boost::any & rv, std::ostream & output, ParseCommandInfo const & command)
606 cptr thisptr() const;
614 virtual void v_execute(boost::any & rv, std::ostream & os, ParseCommandInfo const & command)
616 ///< Called to execute the command
617 /**< \param[out] rv return value holder
618 \param[in] os stream where result messages may be
620 \param[in] command command arguments. This is a
621 range of ranges of Token instances. */
626 /** \brief Most simple CommandNode implementation
628 This CommandNode implementation simply forwards the \a output and \a arguments arguments to
629 an arbitrary callback. Thus, it allows to add callbacks with the signature
631 void callback(std::ostream & os, senf::console::ParseCommandInfo const & command)
636 \ingroup console_commands
638 class SimpleCommandNode : public CommandNode
640 SENF_LOG_CLASS_AREA();
642 ///////////////////////////////////////////////////////////////////////////
645 typedef boost::shared_ptr<SimpleCommandNode> ptr;
646 typedef boost::shared_ptr<SimpleCommandNode const> cptr;
647 typedef boost::weak_ptr<SimpleCommandNode> weak_ptr;
649 typedef boost::function<void (std::ostream &, ParseCommandInfo const &)> Function;
651 typedef SimpleCommandNode node_type;
652 typedef SimpleCommandNode & return_type;
654 ///////////////////////////////////////////////////////////////////////////
655 ///\name Structors and default members
658 static ptr create(Function const & fn);
661 ///////////////////////////////////////////////////////////////////////////
664 cptr thisptr() const;
666 SimpleCommandNode & doc(std::string const & doc);
667 SimpleCommandNode & shortdoc(std::string const & doc);
670 SimpleCommandNode(Function const & fn);
673 virtual void v_help(std::ostream & output) const;
674 virtual std::string v_shorthelp() const;
675 virtual void v_execute(boost::any & rv, std::ostream & os, ParseCommandInfo const & command)
681 std::string shortdoc_;
689 : public detail::NodeFactory
692 typedef SimpleCommandNode node_type;
693 typedef SimpleCommandNode & result_type;
695 explicit SimpleCommand(SimpleCommandNode::Function fn);
697 SimpleCommandNode & create(DirectoryNode & dir, std::string const & name) const;
699 SimpleCommand const & doc(std::string const & doc) const;
700 SimpleCommand const & shortdoc(std::string const & doc) const;
703 SimpleCommandNode::ptr node_;
712 ///////////////////////////////hh.e////////////////////////////////////////
722 // comment-column: 40
723 // c-file-style: "senf"
724 // indent-tabs-mode: nil
725 // ispell-local-dictionary: "american"
726 // compile-command: "scons -u test"