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