Simplify ProgramInfo
[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,2014, 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 CommandLineModuleGroupData;
55 class CommandLineModuleInterface;
56 class ProgramInfo;
57
58 //! Smart pointer type for managing a CommandLineModuleInterface.
59 typedef gmx_unique_ptr<CommandLineModuleInterface>::type
60     CommandLineModulePointer;
61
62 /*! \brief
63  * Implements a wrapper command-line interface for multiple modules.
64  *
65  * Typical usage:
66  * \code
67    int main(int argc, char *argv[])
68    {
69        gmx::ProgramInfo &programInfo = gmx::init(&argc, &argv);
70        try
71        {
72            gmx::CommandLineModuleManager manager("gmx", &programInfo);
73            // <register all necessary modules>
74            int rc = manager.run(argc, argv);
75            gmx::finalize();
76            return rc;
77        }
78        catch (const std::exception &ex)
79        {
80            gmx::printFatalErrorMessage(stderr, ex);
81            return gmx::processExceptionAtExit(ex);
82        }
83    }
84  * \endcode
85  *
86  * \inpublicapi
87  * \ingroup module_commandline
88  */
89 class CommandLineModuleManager
90 {
91     public:
92         //! Function pointer type for a C main function.
93         typedef int (*CMainFunction)(int argc, char *argv[]);
94
95         /*! \brief
96          * Implements a main() method that runs a single module.
97          *
98          * \param argc   \c argc passed to main().
99          * \param argv   \c argv passed to main().
100          * \param module Module to run.
101          *
102          * This method allows for uniform behavior for binaries that only
103          * contain a single module without duplicating any of the
104          * implementation from CommandLineModuleManager (startup headers,
105          * common options etc.).
106          *
107          * The signature assumes that \p module construction does not throw
108          * (because otherwise the caller would need to duplicate all the
109          * exception handling code).  It is possible to move the construction
110          * inside the try/catch in this method using an indirection similar to
111          * TrajectoryAnalysisCommandLineRunner::runAsMain(), but until that is
112          * necessary, the current approach leads to simpler code.
113          *
114          * Usage:
115          * \code
116            int main(int argc, char *argv[])
117            {
118                CustomCommandLineModule module;
119                return gmx::CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
120            }
121          * \endcode
122          *
123          * Does not throw.  All exceptions are caught and handled internally.
124          */
125         static int runAsMainSingleModule(int argc, char *argv[],
126                                          CommandLineModuleInterface *module);
127         /*! \brief
128          * Implements a main() method that runs a given function.
129          *
130          * \param argc         \c argc passed to main().
131          * \param argv         \c argv passed to main().
132          * \param mainFunction The main()-like method to wrap.
133          *
134          * This method creates a dummy command-line module that does its
135          * processing by calling \p mainFunction; see addModuleCMain() for
136          * details.  It then runs this module with runAsMainSingleModule().
137          * This allows the resulting executable to handle common options and do
138          * other common actions (e.g., startup headers) without duplicate code
139          * in the main methods.
140          *
141          * Usage:
142          * \code
143            int my_main(int argc, char *argv[])
144            {
145                // <...>
146            }
147
148            int main(int argc, char *argv[])
149            {
150                return gmx::CommandLineModuleManager::runAsMainCMain(argc, argv, &my_main);
151            }
152          * \endcode
153          *
154          * Does not throw.  All exceptions are caught and handled internally.
155          */
156         static int runAsMainCMain(int argc, char *argv[],
157                                   CMainFunction mainFunction);
158
159         /*! \brief
160          * Initializes a command-line module manager.
161          *
162          * \param[in] binaryName   Name of the running binary
163          *     (without Gromacs binary suffix or .exe on Windows).
164          * \param     programInfo  Program information for the running binary.
165          * \throws    std::bad_alloc if out of memory.
166          *
167          * \p binaryName is used to detect when the binary is run through a
168          * symlink, and automatically invoke a matching module in such a case.
169          *
170          * \p programInfo is non-const to allow the manager to amend it based
171          * on the actual module that is getting executed.
172          */
173         CommandLineModuleManager(const char  *binaryName,
174                                  ProgramInfo *programInfo);
175         ~CommandLineModuleManager();
176
177         /*! \brief
178          * Sets the module manager to quiet mode: don't print anything.
179          *
180          * \param[in] bQuiet  Whether the module manager should remain silent.
181          *
182          * Normally, the module manager prints out some information to stderr
183          * before it starts the module and after it finishes.  This removes
184          * that output, which is useful in particular for unit tests so that
185          * they don't spam stderr.
186          */
187         void setQuiet(bool bQuiet);
188
189         /*! \brief
190          * Makes the manager always run a single module.
191          *
192          * \param     module  Module to run.
193          *
194          * This method disables all mechanisms for selecting a module, and
195          * directly passes all command-line arguments to \p module.
196          * Help arguments are an exception: these are still recognized by the
197          * manager and translated into a call to
198          * CommandLineModuleInterface::writeHelp().
199          *
200          * This is public mainly for unit testing purposes; for other code,
201          * runAsMainSingleModule() typically provides the desired
202          * functionality.
203          *
204          * Does not throw.
205          */
206         void setSingleModule(CommandLineModuleInterface *module);
207         /*! \brief
208          * Adds a given module to this manager.
209          *
210          * \param   module  Module to add.
211          * \throws  std::bad_alloc if out of memory.
212          *
213          * The manager takes ownership of the object.
214          *
215          * This method is public mostly for testing purposes; for typical uses,
216          * registerModule() is a more convenient way of adding modules.
217          *
218          * \see registerModule()
219          */
220         void addModule(CommandLineModulePointer module);
221         /*! \brief
222          * Adds a module that runs a given main()-like function.
223          *
224          * \param[in] name             Name for the module.
225          * \param[in] shortDescription One-line description for the module.
226          * \param[in] mainFunction     Main function to wrap.
227          * \throws    std::bad_alloc if out of memory.
228          *
229          * There is normally no need to call this method outside the Gromacs
230          * library.  User code usually wants to use runAsMainCMain().
231          *
232          * \p name and \p shortDescription should be string constants, or the
233          * caller should otherwise ensure that they stay in scope for the
234          * duration the CommandLineModuleManager object exists.
235          * \p mainFunction should call parse_common_args() to process its
236          * command-line arguments.
237          */
238         void addModuleCMain(const char *name, const char *shortDescription,
239                             CMainFunction mainFunction);
240         /*! \brief
241          * Registers a module of a certain type to this manager.
242          *
243          * \tparam  Module  Type of module to register.
244          * \throws  std::bad_alloc if out of memory.
245          *
246          * \p Module must be default-constructible and implement
247          * CommandLineModuleInterface.
248          *
249          * This method is provided as a convenient alternative to addModule()
250          * for cases where each module is implemented by a different type
251          * (which should be the case for typical situations outside unit
252          * tests).
253          */
254         template <class Module>
255         void registerModule()
256         {
257             addModule(CommandLineModulePointer(new Module));
258         }
259
260         /*! \brief
261          * Adds a group for modules to use in help output.
262          *
263          * \param[in] title  Short title for the group.
264          * \returns   Handle that can be used to add modules to the group.
265          * \throws    std::bad_alloc if out of memory.
266          *
267          * Creates a group that is used to structure the list of all modules in
268          * help output.  Modules are added to the group using the returned
269          * object.
270          */
271         CommandLineModuleGroup addModuleGroup(const char *title);
272
273         /*! \brief
274          * Makes given help topic available through the manager's help module.
275          *
276          * \param[in]  topic  Help topic to add.
277          * \throws     std::bad_alloc if out of memory.
278          *
279          * The manager takes ownership of the help topic.
280          */
281         void addHelpTopic(HelpTopicPointer topic);
282
283         /*! \brief
284          * Runs a module based on given command line.
285          *
286          * \param[in] argc  Number of elements in \p argv.
287          * \param[in] argv  Command-line arguments.
288          * \throws   unspecified  Throws any exception that the selected module
289          *      throws.
290          * \returns  Exit code for the program.
291          * \retval   0 on successful termination.
292          * \retval   2 if no module is specified, or if the module is not found.
293          *
294          * Runs the module whose name matches \p argv[1].
295          */
296         int run(int argc, char *argv[]);
297
298     private:
299         class Impl;
300
301         PrivateImplPointer<Impl> impl_;
302 };
303
304 /*! \brief
305  * Handle to add content to a group added with
306  * CommandLineModuleManager::addModuleGroup().
307  *
308  * This class only provides a public interface to construct a module group for
309  * CommandLineModuleManager, and has semantics similar to a pointer: copies all
310  * point to the same group.  The actual state of the group is maintained in an
311  * internal implementation class.
312  *
313  * \inpublicapi
314  * \ingroup module_commandline
315  */
316 class CommandLineModuleGroup
317 {
318     public:
319         /*! \cond internal */
320         //! Shorthand for the implementation type that holds all the data.
321         typedef CommandLineModuleGroupData Impl;
322
323         //! Creates a new group (only called by CommandLineModuleManager).
324         explicit CommandLineModuleGroup(Impl *impl) : impl_(impl) {}
325         //! \endcond
326
327         /*! \brief
328          * Adds a module to this group.
329          *
330          * \param[in] name  Name of the module.
331          * \throws    std::bad_alloc if out of memory.
332          *
333          * This works as addModuleWithDescription(), but uses the short
334          * description of the module itself as the description.
335          *
336          * \see addModuleWithDescription()
337          */
338         void addModule(const char *name);
339         /*! \brief
340          * Adds a module to this group with a custom description.
341          *
342          * \param[in] name        Name of the module.
343          * \param[in] description Description of the module in this group.
344          * \throws    std::bad_alloc if out of memory.
345          *
346          * \p name must name a module added into the CommandLineModuleManager.
347          * It is possible to add the same module into multiple groups.
348          */
349         void addModuleWithDescription(const char *name, const char *description);
350
351     private:
352         //! Pointer to the data owned by CommandLineModuleManager.
353         Impl                     *impl_;
354 };
355
356 } // namespace gmx
357
358 #endif