Reformat existing LGPL copyright notices.
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlinemodulemanager.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \file
36  * \brief
37  * Declares gmx::CommandLineModuleManager.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \inpublicapi
41  * \ingroup module_commandline
42  */
43 #ifndef GMX_COMMANDLINE_CMDLINEMODULEMANAGER_H
44 #define GMX_COMMANDLINE_CMDLINEMODULEMANAGER_H
45
46 #include "../onlinehelp/helptopicinterface.h"
47 #include "../utility/common.h"
48 #include "../utility/uniqueptr.h"
49
50 namespace gmx
51 {
52
53 class CommandLineModuleGroup;
54 class CommandLineModuleInterface;
55 class ProgramInfo;
56
57 //! Smart pointer type for managing a CommandLineModuleInterface.
58 typedef gmx_unique_ptr<CommandLineModuleInterface>::type
59     CommandLineModulePointer;
60
61 namespace internal
62 {
63 class CommandLineModuleGroupData;
64 }   // namespace internal
65
66 /*! \brief
67  * Implements a wrapper command-line interface for multiple modules.
68  *
69  * Typical usage:
70  * \code
71    int main(int argc, char *argv[])
72    {
73        gmx::ProgramInfo &programInfo = gmx::init("gmx", &argc, &argv);
74        try
75        {
76            gmx::CommandLineModuleManager manager(&programInfo);
77            // <register all necessary modules>
78            int rc = manager.run(argc, argv);
79            gmx::finalize();
80            return rc;
81        }
82        catch (const std::exception &ex)
83        {
84            gmx::printFatalErrorMessage(stderr, ex);
85            return gmx::processExceptionAtExit(ex);
86        }
87    }
88  * \endcode
89  *
90  * \inpublicapi
91  * \ingroup module_commandline
92  */
93 class CommandLineModuleManager
94 {
95     public:
96         //! Function pointer type for a C main function.
97         typedef int (*CMainFunction)(int argc, char *argv[]);
98
99         /*! \brief
100          * Implements a main() method that runs a single module.
101          *
102          * \param argc   \c argc passed to main().
103          * \param argv   \c argv passed to main().
104          * \param module Module to run.
105          *
106          * This method allows for uniform behavior for binaries that only
107          * contain a single module without duplicating any of the
108          * implementation from CommandLineModuleManager (startup headers,
109          * common options etc.).
110          *
111          * The signature assumes that \p module construction does not throw
112          * (because otherwise the caller would need to duplicate all the
113          * exception handling code).  It is possible to move the construction
114          * inside the try/catch in this method using an indirection similar to
115          * TrajectoryAnalysisCommandLineRunner::runAsMain(), but until that is
116          * necessary, the current approach leads to simpler code.
117          *
118          * Usage:
119          * \code
120            int main(int argc, char *argv[])
121            {
122                CustomCommandLineModule module;
123                return gmx::CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
124            }
125          * \endcode
126          *
127          * Does not throw.  All exceptions are caught and handled internally.
128          */
129         static int runAsMainSingleModule(int argc, char *argv[],
130                                          CommandLineModuleInterface *module);
131         /*! \brief
132          * Implements a main() method that runs a given function.
133          *
134          * \param argc         \c argc passed to main().
135          * \param argv         \c argv passed to main().
136          * \param mainFunction The main()-like method to wrap.
137          *
138          * This method creates a dummy command-line module that does its
139          * processing by calling \p mainFunction; see addModuleCMain() for
140          * details.  It then runs this module with runAsMainSingleModule().
141          * This allows the resulting executable to handle common options and do
142          * other common actions (e.g., startup headers) without duplicate code
143          * in the main methods.
144          *
145          * Usage:
146          * \code
147            int my_main(int argc, char *argv[])
148            {
149                // <...>
150            }
151
152            int main(int argc, char *argv[])
153            {
154                return gmx::CommandLineModuleManager::runAsMainCMain(argc, argv, &my_main);
155            }
156          * \endcode
157          *
158          * Does not throw.  All exceptions are caught and handled internally.
159          */
160         static int runAsMainCMain(int argc, char *argv[],
161                                   CMainFunction mainFunction);
162
163         /*! \brief
164          * Initializes a command-line module manager.
165          *
166          * \param     programInfo  Program information for the running binary.
167          * \throws    std::bad_alloc if out of memory.
168          *
169          * The binary name is used to detect when the binary is run through a
170          * symlink, and automatically invoke a matching module in such a case.
171          *
172          * \p programInfo is non-const to allow the manager to amend it based
173          * on the actual module that is getting executed.
174          */
175         explicit CommandLineModuleManager(ProgramInfo *programInfo);
176         ~CommandLineModuleManager();
177
178         /*! \brief
179          * Sets the module manager to quiet mode: don't print anything.
180          *
181          * \param[in] bQuiet  Whether the module manager should remain silent.
182          *
183          * Normally, the module manager prints out some information to stderr
184          * before it starts the module and after it finishes.  This removes
185          * that output, which is useful in particular for unit tests so that
186          * they don't spam stderr.
187          */
188         void setQuiet(bool bQuiet);
189
190         /*! \brief
191          * Adds a given module to this manager.
192          *
193          * \param   module  Module to add.
194          * \throws  std::bad_alloc if out of memory.
195          *
196          * The manager takes ownership of the object.
197          *
198          * This method is public mostly for testing purposes; for typical uses,
199          * registerModule() is a more convenient way of adding modules.
200          *
201          * \see registerModule()
202          */
203         void addModule(CommandLineModulePointer module);
204         /*! \brief
205          * Adds a module that runs a given main()-like function.
206          *
207          * \param[in] name             Name for the module.
208          * \param[in] shortDescription One-line description for the module.
209          * \param[in] mainFunction     Main function to wrap.
210          * \throws    std::bad_alloc if out of memory.
211          *
212          * There is normally no need to call this method outside the Gromacs
213          * library.  User code usually wants to use runAsMainCMain().
214          *
215          * \p name and \p shortDescription should be string constants, or the
216          * caller should otherwise ensure that they stay in scope for the
217          * duration the CommandLineModuleManager object exists.
218          * \p mainFunction should call parse_common_args() to process its
219          * command-line arguments.
220          */
221         void addModuleCMain(const char *name, const char *shortDescription,
222                             CMainFunction mainFunction);
223         /*! \brief
224          * Registers a module of a certain type to this manager.
225          *
226          * \tparam  Module  Type of module to register.
227          * \throws  std::bad_alloc if out of memory.
228          *
229          * \p Module must be default-constructible and implement
230          * CommandLineModuleInterface.
231          *
232          * This method is provided as a convenient alternative to addModule()
233          * for cases where each module is implemented by a different type
234          * (which should be the case for typical situations outside unit
235          * tests).
236          */
237         template <class Module>
238         void registerModule()
239         {
240             addModule(CommandLineModulePointer(new Module));
241         }
242
243         /*! \brief
244          * Adds a group for modules to use in help output.
245          *
246          * \param[in] title  Short title for the group.
247          * \returns   Handle that can be used to add modules to the group.
248          * \throws    std::bad_alloc if out of memory.
249          *
250          * Creates a group that is used to structure the list of all modules in
251          * help output.  Modules are added to the group using the returned
252          * object.
253          */
254         CommandLineModuleGroup addModuleGroup(const char *title);
255
256         /*! \brief
257          * Makes given help topic available through the manager's help module.
258          *
259          * \param[in]  topic  Help topic to add.
260          * \throws     std::bad_alloc if out of memory.
261          *
262          * The manager takes ownership of the help topic.
263          */
264         void addHelpTopic(HelpTopicPointer topic);
265
266         /*! \brief
267          * Runs a module based on given command line.
268          *
269          * \param[in] argc  Number of elements in \p argv.
270          * \param[in] argv  Command-line arguments.
271          * \throws   unspecified  Throws any exception that the selected module
272          *      throws.
273          * \returns  Exit code for the program.
274          * \retval   0 on successful termination.
275          * \retval   2 if no module is specified, or if the module is not found.
276          *
277          * Runs the module whose name matches \p argv[1].
278          */
279         int run(int argc, char *argv[]);
280
281     private:
282         class Impl;
283
284         PrivateImplPointer<Impl> impl_;
285 };
286
287 /*! \brief
288  * Handle to add content to a group added with
289  * CommandLineModuleManager::addModuleGroup().
290  *
291  * This class only provides a public interface to construct a module group for
292  * CommandLineModuleManager, and has semantics similar to a pointer: copies all
293  * point to the same group.  The actual state of the group is maintained in an
294  * internal implementation class.
295  *
296  * \inpublicapi
297  * \ingroup module_commandline
298  */
299 class CommandLineModuleGroup
300 {
301     public:
302         /*! \cond internal */
303         //! Shorthand for the implementation type that holds all the data.
304         typedef internal::CommandLineModuleGroupData Impl;
305
306         //! Creates a new group (only called by CommandLineModuleManager).
307         explicit CommandLineModuleGroup(Impl *impl) : impl_(impl) {}
308         //! \endcond
309
310         /*! \brief
311          * Adds a module to this group.
312          *
313          * \param[in] name  Name of the module.
314          * \throws    std::bad_alloc if out of memory.
315          *
316          * This works as addModuleWithDescription(), but uses the short
317          * description of the module itself as the description.
318          *
319          * \see addModuleWithDescription()
320          */
321         void addModule(const char *name);
322         /*! \brief
323          * Adds a module to this group with a custom description.
324          *
325          * \param[in] name        Name of the module.
326          * \param[in] description Description of the module in this group.
327          * \throws    std::bad_alloc if out of memory.
328          *
329          * \p name must name a module added into the CommandLineModuleManager.
330          * It is possible to add the same module into multiple groups.
331          */
332         void addModuleWithDescription(const char *name, const char *description);
333
334     private:
335         //! Pointer to the data owned by CommandLineModuleManager.
336         Impl                     *impl_;
337 };
338
339 } // namespace gmx
340
341 #endif