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