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