Merge release-4-6 into master
[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  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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 CommandLineModuleInterface;
54 class ProgramInfo;
55
56 //! Smart pointer type for managing a CommandLineModuleInterface.
57 typedef gmx_unique_ptr<CommandLineModuleInterface>::type
58     CommandLineModulePointer;
59
60 /*! \brief
61  * Implements a wrapper command-line interface for multiple modules.
62  *
63  * Typical usage:
64  * \code
65    int main(int argc, char *argv[])
66    {
67        gmx::ProgramInfo &programInfo = gmx::init("gmx", &argc, &argv);
68        try
69        {
70            gmx::CommandLineModuleManager manager(&programInfo);
71            // <register all necessary modules>
72            int rc = manager.run(argc, argv);
73            gmx::finalize();
74            return rc;
75        }
76        catch (const std::exception &ex)
77        {
78            gmx::printFatalErrorMessage(stderr, ex);
79            return gmx::processExceptionAtExit(ex);
80        }
81    }
82  * \endcode
83  *
84  * \inpublicapi
85  * \ingroup module_commandline
86  */
87 class CommandLineModuleManager
88 {
89     public:
90         //! Function pointer type for a C main function.
91         typedef int (*CMainFunction)(int argc, char *argv[]);
92
93         /*! \brief
94          * Implements a main() method that runs a single module.
95          *
96          * \param argc   \c argc passed to main().
97          * \param argv   \c argv passed to main().
98          * \param module Module to run.
99          *
100          * This method allows for uniform behavior for binaries that only
101          * contain a single module without duplicating any of the
102          * implementation from CommandLineModuleManager (startup headers,
103          * common options etc.).
104          *
105          * The signature assumes that \p module construction does not throw
106          * (because otherwise the caller would need to duplicate all the
107          * exception handling code).  It is possible to move the construction
108          * inside the try/catch in this method using an indirection similar to
109          * TrajectoryAnalysisCommandLineRunner::runAsMain(), but until that is
110          * necessary, the current approach leads to simpler code.
111          *
112          * Usage:
113          * \code
114            int main(int argc, char *argv[])
115            {
116                CustomCommandLineModule module;
117                return gmx::CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
118            }
119          * \endcode
120          *
121          * Does not throw.  All exceptions are caught and handled internally.
122          */
123         static int runAsMainSingleModule(int argc, char *argv[],
124                                          CommandLineModuleInterface *module);
125         /*! \brief
126          * Implements a main() method that runs a given function.
127          *
128          * \param argc         \c argc passed to main().
129          * \param argv         \c argv passed to main().
130          * \param mainFunction The main()-like method to wrap.
131          *
132          * This method creates a dummy command-line module that does its
133          * processing by calling \p mainFunction; see addModuleCMain() for
134          * details.  It then runs this module with runAsMainSingleModule().
135          * This allows the resulting executable to handle common options and do
136          * other common actions (e.g., startup headers) without duplicate code
137          * in the main methods.
138          *
139          * Usage:
140          * \code
141            int my_main(int argc, char *argv[])
142            {
143                // <...>
144            }
145
146            int main(int argc, char *argv[])
147            {
148                return gmx::CommandLineModuleManager::runAsMainCMain(argc, argv, &my_main);
149            }
150          * \endcode
151          *
152          * Does not throw.  All exceptions are caught and handled internally.
153          */
154         static int runAsMainCMain(int argc, char *argv[],
155                                   CMainFunction mainFunction);
156
157         /*! \brief
158          * Initializes a command-line module manager.
159          *
160          * \param     programInfo  Program information for the running binary.
161          * \throws    std::bad_alloc if out of memory.
162          *
163          * The binary name is used to detect when the binary is run through a
164          * symlink, and automatically invoke a matching module in such a case.
165          *
166          * \p programInfo is non-const to allow the manager to amend it based
167          * on the actual module that is getting executed.
168          */
169         explicit CommandLineModuleManager(ProgramInfo *programInfo);
170         ~CommandLineModuleManager();
171
172         /*! \brief
173          * Sets the module manager to quiet mode: don't print anything.
174          *
175          * \param[in] bQuiet  Whether the module manager should remain silent.
176          *
177          * Normally, the module manager prints out some information to stderr
178          * before it starts the module and after it finishes.  This removes
179          * that output, which is useful in particular for unit tests so that
180          * they don't spam stderr.
181          */
182         void setQuiet(bool bQuiet);
183
184         /*! \brief
185          * Adds a given module to this manager.
186          *
187          * \param   module  Module to add.
188          * \throws  std::bad_alloc if out of memory.
189          *
190          * The manager takes ownership of the object.
191          *
192          * This method is public mostly for testing purposes; for typical uses,
193          * registerModule() is a more convenient way of adding modules.
194          *
195          * \see registerModule()
196          */
197         void addModule(CommandLineModulePointer module);
198         /*! \brief
199          * Adds a module that runs a given main()-like function.
200          *
201          * \param[in] name             Name for the module.
202          * \param[in] shortDescription One-line description for the module.
203          * \param[in] mainFunction     Main function to wrap.
204          * \throws    std::bad_alloc if out of memory.
205          *
206          * There is normally no need to call this method outside the Gromacs
207          * library.  User code usually wants to use runAsMainCMain().
208          *
209          * \p name and \p shortDescription should be string constants, or the
210          * caller should otherwise ensure that they stay in scope for the
211          * duration the CommandLineModuleManager object exists.
212          * \p mainFunction should call parse_common_args() to process its
213          * command-line arguments.
214          */
215         void addModuleCMain(const char *name, const char *shortDescription,
216                             CMainFunction mainFunction);
217         /*! \brief
218          * Registers a module of a certain type to this manager.
219          *
220          * \tparam  Module  Type of module to register.
221          * \throws  std::bad_alloc if out of memory.
222          *
223          * \p Module must be default-constructible and implement
224          * CommandLineModuleInterface.
225          *
226          * This method is provided as a convenient alternative to addModule()
227          * for cases where each module is implemented by a different type
228          * (which should be the case for typical situations outside unit
229          * tests).
230          */
231         template <class Module>
232         void registerModule()
233         {
234             addModule(CommandLineModulePointer(new Module));
235         }
236
237         /*! \brief
238          * Make given help topic available through the manager's help module.
239          *
240          * \param[in]  topic  Help topic to add.
241          * \throws     std::bad_alloc if out of memory.
242          *
243          * The manager takes ownership of the help topic.
244          */
245         void addHelpTopic(HelpTopicPointer topic);
246
247         /*! \brief
248          * Runs a module based on given command line.
249          *
250          * \param[in] argc  Number of elements in \p argv.
251          * \param[in] argv  Command-line arguments.
252          * \throws   unspecified  Throws any exception that the selected module
253          *      throws.
254          * \returns  Exit code for the program.
255          * \retval   0 on successful termination.
256          * \retval   2 if no module is specified, or if the module is not found.
257          *
258          * Runs the module whose name matches \p argv[1].
259          */
260         int run(int argc, char *argv[]);
261
262     private:
263         class Impl;
264
265         PrivateImplPointer<Impl> impl_;
266 };
267
268 } // namespace gmx
269
270 #endif