Uniform headers in HTML pages
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlinemodulemanager.cpp
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  * 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 /*! \internal \file
36  * \brief
37  * Implements gmx::CommandLineModuleManager.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "cmdlinemodulemanager.h"
43
44 #include <cstdio>
45
46 #include <algorithm>
47 #include <map>
48 #include <string>
49 #include <utility>
50
51 #include <boost/scoped_ptr.hpp>
52
53 #include "gromacs/legacyheaders/copyrite.h"
54 #include "gromacs/legacyheaders/network.h"
55 #include "gromacs/legacyheaders/smalloc.h"
56
57 #include "gromacs/commandline/cmdlinehelpcontext.h"
58 #include "gromacs/commandline/cmdlinemodule.h"
59 #include "gromacs/commandline/cmdlineparser.h"
60 #include "gromacs/fileio/futil.h"
61 #include "gromacs/onlinehelp/helpformat.h"
62 #include "gromacs/onlinehelp/helpmanager.h"
63 #include "gromacs/onlinehelp/helptopic.h"
64 #include "gromacs/onlinehelp/helpwritercontext.h"
65 #include "gromacs/options/basicoptions.h"
66 #include "gromacs/options/options.h"
67 #include "gromacs/utility/exceptions.h"
68 #include "gromacs/utility/file.h"
69 #include "gromacs/utility/gmxassert.h"
70 #include "gromacs/utility/init.h"
71 #include "gromacs/utility/programinfo.h"
72 #include "gromacs/utility/stringutil.h"
73 #include "gromacs/utility/uniqueptr.h"
74
75 namespace gmx
76 {
77
78 //! Container type for mapping module names to module objects.
79 typedef std::map<std::string, CommandLineModulePointer> CommandLineModuleMap;
80 //! Smart pointer type for managing a CommandLineModuleGroup.
81 typedef gmx_unique_ptr<internal::CommandLineModuleGroupData>::type
82     CommandLineModuleGroupDataPointer;
83 //! Container type for keeping a list of module groups.
84 typedef std::vector<CommandLineModuleGroupDataPointer>
85     CommandLineModuleGroupList;
86
87 class CommandLineHelpModule;
88
89 namespace internal
90 {
91
92 /*! \internal
93  * \brief
94  * Internal data for a CommandLineModuleManager module group.
95  *
96  * This class contains the state of a module group.  CommandLineModuleGroup
97  * provides the public interface to construct/alter the state, and
98  * CommandLineModuleManager and its associated classes use it for help output.
99  *
100  * \ingroup module_commandline
101  */
102 class CommandLineModuleGroupData
103 {
104     public:
105         /*! \brief
106          * Shorthand for a list of modules contained in the group.
107          *
108          * The first element in the contained pair contains the tag
109          * (gmx-something) of the module, and the second element contains the
110          * description.  The second element is never NULL.
111          */
112         typedef std::vector<std::pair<std::string, const char *> > ModuleList;
113
114         /*! \brief
115          * Constructs an empty module group.
116          *
117          * \param[in] modules  List of all modules
118          *     (used for checking and default descriptions).
119          * \param[in] title    Title of the group.
120          *
121          * Does not throw.
122          */
123         CommandLineModuleGroupData(const CommandLineModuleMap &modules,
124                                    const char                 *title)
125             : allModules_(modules), title_(title)
126         {
127         }
128
129         //! Returns the title for the group.
130         const char *title() const { return title_; }
131         //! Returns the list of modules in the group.
132         const ModuleList &modules() const { return modules_; }
133
134         /*! \brief
135          * Adds a module to the group.
136          *
137          * \param[in] name        Name of the module.
138          * \param[in] description Description of the module in this group.
139          * \throws    std::bad_alloc if out of memory.
140          *
141          * If \p description is NULL, the description returned by the module is
142          * used.
143          */
144         void addModule(const char *name, const char *description)
145         {
146             CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
147             GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
148                                "Non-existent module added to a group");
149             if (description == NULL)
150             {
151                 description = moduleIter->second->shortDescription();
152                 GMX_RELEASE_ASSERT(description != NULL,
153                                    "Module without a description added to a group");
154             }
155             const char *const program =
156                 ProgramInfo::getInstance().invariantProgramName().c_str();
157             std::string       tag(formatString("%s-%s", program, name));
158             modules_.push_back(std::make_pair(tag, description));
159         }
160
161     private:
162         const CommandLineModuleMap &allModules_;
163         const char                 *title_;
164         ModuleList                  modules_;
165
166         GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineModuleGroupData);
167 };
168
169 }   // namespace internal
170
171 namespace
172 {
173
174 /********************************************************************
175  * RootHelpTopic
176  */
177
178 struct RootHelpText
179 {
180     static const char        name[];
181     static const char        title[];
182     static const char *const text[];
183 };
184
185 // The first two are not used.
186 const char        RootHelpText::name[]  = "";
187 const char        RootHelpText::title[] = "";
188 const char *const RootHelpText::text[]  = {
189     "Usage: [PROGRAM] <command> [<args>]",
190 };
191
192 /*! \brief
193  * Help topic that forms the root of the help tree for the help subcommand.
194  *
195  * \ingroup module_commandline
196  */
197 class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
198 {
199     public:
200         /*! \brief
201          * Creates a root help topic.
202          *
203          * \param[in] modules  List of modules for to use for module listings.
204          *
205          * Does not throw.
206          */
207         explicit RootHelpTopic(const CommandLineModuleMap &modules)
208             : modules_(modules)
209         {
210         }
211
212         virtual void writeHelp(const HelpWriterContext &context) const;
213
214     private:
215         void printModuleList(const HelpWriterContext &context) const;
216
217         const CommandLineModuleMap &modules_;
218
219         GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
220 };
221
222 void RootHelpTopic::writeHelp(const HelpWriterContext &context) const
223 {
224     if (context.outputFormat() != eHelpOutputFormat_Console)
225     {
226         // TODO: Implement once the situation with Redmine issue #969 is more
227         // clear.
228         GMX_THROW(NotImplementedError(
229                           "Root help is not implemented for this output format"));
230     }
231     writeBasicHelpTopic(context, *this, helpText());
232     // TODO: If/when this list becomes long, it may be better to only print
233     // "common" commands here, and have a separate topic (e.g.,
234     // "help commands") that prints the full list.
235     printModuleList(context);
236     context.writeTextBlock(
237             "For additional help on a command, use '[PROGRAM] help <command>'");
238     writeSubTopicList(context,
239                       "\nAdditional help is available on the following topics:");
240     context.writeTextBlock(
241             "To access the help, use '[PROGRAM] help <topic>'.");
242 }
243
244 void RootHelpTopic::printModuleList(const HelpWriterContext &context) const
245 {
246     if (context.outputFormat() != eHelpOutputFormat_Console)
247     {
248         // TODO: Implement once the situation with Redmine issue #969 is more
249         // clear.
250         GMX_THROW(NotImplementedError(
251                           "Module list is not implemented for this output format"));
252     }
253     int maxNameLength = 0;
254     CommandLineModuleMap::const_iterator module;
255     for (module = modules_.begin(); module != modules_.end(); ++module)
256     {
257         int nameLength = static_cast<int>(module->first.length());
258         if (module->second->shortDescription() != NULL
259             && nameLength > maxNameLength)
260         {
261             maxNameLength = nameLength;
262         }
263     }
264     File              &file = context.outputFile();
265     TextTableFormatter formatter;
266     formatter.addColumn(NULL, maxNameLength + 1, false);
267     formatter.addColumn(NULL, 72 - maxNameLength, true);
268     formatter.setFirstColumnIndent(4);
269     file.writeLine();
270     file.writeLine("Available commands:");
271     for (module = modules_.begin(); module != modules_.end(); ++module)
272     {
273         const char *name        = module->first.c_str();
274         const char *description = module->second->shortDescription();
275         if (description != NULL)
276         {
277             formatter.clear();
278             formatter.addColumnLine(0, name);
279             formatter.addColumnLine(1, description);
280             file.writeString(formatter.formatRow());
281         }
282     }
283 }
284
285 /********************************************************************
286  * ModuleHelpTopic declaration
287  */
288
289 /*! \brief
290  * Help topic wrapper for a command-line module.
291  *
292  * This class implements HelpTopicInterface such that it wraps a
293  * CommandLineModuleInterface, allowing subcommand "help <command>"
294  * to produce the help for "<command>".
295  *
296  * \ingroup module_commandline
297  */
298 class ModuleHelpTopic : public HelpTopicInterface
299 {
300     public:
301         //! Constructs a help topic for a specific module.
302         ModuleHelpTopic(const CommandLineModuleInterface &module,
303                         const CommandLineHelpModule      &helpModule)
304             : module_(module), helpModule_(helpModule)
305         {
306         }
307
308         virtual const char *name() const { return module_.name(); }
309         virtual const char *title() const { return NULL; }
310         virtual bool hasSubTopics() const { return false; }
311         virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
312         {
313             return NULL;
314         }
315         virtual void writeHelp(const HelpWriterContext &context) const;
316
317     private:
318         const CommandLineModuleInterface &module_;
319         const CommandLineHelpModule      &helpModule_;
320
321         GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
322 };
323
324 /********************************************************************
325  * HelpExportInterface
326  */
327
328 /*! \brief
329  * Callbacks for exporting help information for command-line modules.
330  *
331  * \ingroup module_commandline
332  */
333 class HelpExportInterface
334 {
335     public:
336         //! Shorthand for a list of modules contained in a group.
337         typedef internal::CommandLineModuleGroupData::ModuleList
338             ModuleGroupContents;
339
340         virtual ~HelpExportInterface() {};
341
342         /*! \brief
343          * Called once before exporting individual modules.
344          *
345          * Can, e.g., open shared output files (e.g., if the output is written
346          * into a single file, or if a separate index is required) and write
347          * headers into them.
348          */
349         virtual void startModuleExport() = 0;
350         /*! \brief
351          * Called to export the help for each module.
352          *
353          * \param[in] module      Module for which the help should be exported.
354          * \param[in] tag         Unique tag for the module (gmx-something).
355          * \param[in] displayName Display name for the module (gmx something).
356          */
357         virtual void exportModuleHelp(
358             const CommandLineModuleInterface &module,
359             const std::string                &tag,
360             const std::string                &displayName) = 0;
361         /*! \brief
362          * Called after all modules have been exported.
363          *
364          * Can close files opened in startModuleExport(), write footers to them
365          * etc.
366          */
367         virtual void finishModuleExport() = 0;
368
369         /*! \brief
370          * Called once before exporting module groups.
371          *
372          * Can, e.g., open a single output file for listing all the groups.
373          */
374         virtual void startModuleGroupExport() = 0;
375         /*! \brief
376          * Called to export the help for each module group.
377          *
378          * \param[in] title    Title for the group.
379          * \param[in] modules  List of modules in the group.
380          */
381         virtual void exportModuleGroup(const char                *title,
382                                        const ModuleGroupContents &modules) = 0;
383         /*! \brief
384          * Called after all module groups have been exported.
385          *
386          * Can close files opened in startModuleGroupExport(), write footers to them
387          * etc.
388          */
389         virtual void finishModuleGroupExport() = 0;
390 };
391
392 /*! \internal \brief
393  * Adds hyperlinks to modules within this binary.
394  *
395  * \param[in,out] links   Links are added here.
396  * \param[in]     modules Modules in the current binary.
397  * \throws        std::bad_alloc if out of memory.
398  *
399  * Initializes a HelpLinks object with links to modules defined in \p modules.
400  *
401  * \ingroup module_commandline
402  */
403 void initProgramLinks(HelpLinks *links, const CommandLineModuleMap &modules)
404 {
405     // TODO: Use the local ProgramInfo reference from CommandLineModuleManager
406     // (to do this nicely requires reordering the code in the file).
407     const char *const                    program =
408         ProgramInfo::getInstance().realBinaryName().c_str();
409     CommandLineModuleMap::const_iterator module;
410     for (module = modules.begin(); module != modules.end(); ++module)
411     {
412         if (module->second->shortDescription() != NULL)
413         {
414             std::string linkName("[gmx-" + module->first + "]");
415             std::string targetName(
416                     formatString("%s-%s", program, module->first.c_str()));
417             std::string displayName(
418                     formatString("[TT]%s %s[tt]", program, module->first.c_str()));
419             links->addLink(linkName, targetName, displayName);
420         }
421     }
422 }
423
424 /********************************************************************
425  * HelpExportMan
426  */
427
428 /*! \internal \brief
429  * Implements export for man pages.
430  *
431  * \ingroup module_commandline
432  */
433 class HelpExportMan : public HelpExportInterface
434 {
435     public:
436         //! Initializes man page exporter.
437         explicit HelpExportMan(const CommandLineModuleMap &modules)
438             : links_(eHelpOutputFormat_Man)
439         {
440             initProgramLinks(&links_, modules);
441         }
442
443         virtual void startModuleExport() {}
444         virtual void exportModuleHelp(
445             const CommandLineModuleInterface &module,
446             const std::string                &tag,
447             const std::string                &displayName);
448         virtual void finishModuleExport() {}
449
450         virtual void startModuleGroupExport() {}
451         virtual void exportModuleGroup(const char                * /*title*/,
452                                        const ModuleGroupContents & /*modules*/) {}
453         virtual void finishModuleGroupExport() {}
454
455     private:
456         HelpLinks  links_;
457 };
458
459 void HelpExportMan::exportModuleHelp(
460         const CommandLineModuleInterface &module,
461         const std::string                &tag,
462         const std::string                &displayName)
463 {
464     File file("man1/" + tag + ".1", "w");
465
466     // TODO: It would be nice to remove the VERSION prefix from the version
467     // string to make it shorter.
468     file.writeLine(formatString(".TH %s 1 \"\" \"%s\" \"GROMACS Manual\"\n",
469                                 tag.c_str(),
470                                 GromacsVersion()));
471     file.writeLine(".SH NAME");
472     file.writeLine(formatString("%s - %s", tag.c_str(),
473                                 module.shortDescription()));
474     file.writeLine();
475
476     CommandLineHelpContext context(&file, eHelpOutputFormat_Man, &links_);
477     context.setModuleDisplayName(displayName);
478     module.writeHelp(context);
479
480     file.writeLine(".SH SEE ALSO");
481     file.writeLine(".BR gromacs(7)");
482     file.writeLine();
483     file.writeLine("More information about \\fBGROMACS\\fR is available at <\\fIhttp://www.gromacs.org/\\fR>.");
484 }
485
486 /********************************************************************
487  * HelpExportHtml
488  */
489
490 /*! \internal \brief
491  * Implements export for HTML help.
492  *
493  * \ingroup module_commandline
494  */
495 class HelpExportHtml : public HelpExportInterface
496 {
497     public:
498         //! Initializes HTML exporter.
499         explicit HelpExportHtml(const CommandLineModuleMap &modules);
500
501         virtual void startModuleExport();
502         virtual void exportModuleHelp(
503             const CommandLineModuleInterface &module,
504             const std::string                &tag,
505             const std::string                &displayName);
506         virtual void finishModuleExport();
507
508         virtual void startModuleGroupExport();
509         virtual void exportModuleGroup(const char                *title,
510                                        const ModuleGroupContents &modules);
511         virtual void finishModuleGroupExport();
512
513     private:
514         void setupHeaderAndFooter();
515
516         void writeHtmlHeader(File *file, const std::string &title) const;
517         void writeHtmlFooter(File *file) const;
518
519         boost::scoped_ptr<File>  indexFile_;
520         HelpLinks                links_;
521         std::string              header_;
522         std::string              footer_;
523 };
524
525 HelpExportHtml::HelpExportHtml(const CommandLineModuleMap &modules)
526     : links_(eHelpOutputFormat_Html)
527 {
528     initProgramLinks(&links_, modules);
529     char *linksFilename = low_gmxlibfn("links.dat", FALSE, FALSE);
530     if (linksFilename != NULL)
531     {
532         scoped_ptr_sfree guard(linksFilename);
533         File             linksFile(linksFilename, "r");
534         std::string      line;
535         while (linksFile.readLine(&line))
536         {
537             links_.addLink(line, "../online/" + line, line);
538         }
539     }
540     setupHeaderAndFooter();
541 }
542
543 void HelpExportHtml::setupHeaderAndFooter()
544 {
545     header_ = gmx::File::readToString("header.html.in");
546     header_ = replaceAll(header_, "@VERSION@", GromacsVersion());
547     gmx::File::writeFileFromString("header.html", header_);
548     header_ = replaceAll(header_, "@ROOTPATH@", "../");
549     footer_ = gmx::File::readToString("footer.html");
550 }
551
552 void HelpExportHtml::startModuleExport()
553 {
554     indexFile_.reset(new File("final/programs/byname.html", "w"));
555     writeHtmlHeader(indexFile_.get(), "GROMACS Programs by Name");
556     indexFile_->writeLine("<H3>GROMACS Programs Alphabetically</H3>");
557 }
558
559 void HelpExportHtml::exportModuleHelp(
560         const CommandLineModuleInterface &module,
561         const std::string                &tag,
562         const std::string                &displayName)
563 {
564     File file("final/programs/" + tag + ".html", "w");
565     writeHtmlHeader(&file, displayName);
566
567     CommandLineHelpContext context(&file, eHelpOutputFormat_Html, &links_);
568     context.setModuleDisplayName(displayName);
569     module.writeHelp(context);
570
571     writeHtmlFooter(&file);
572     file.close();
573
574     indexFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
575                                        tag.c_str(), displayName.c_str(),
576                                        module.shortDescription()));
577 }
578
579 void HelpExportHtml::finishModuleExport()
580 {
581     writeHtmlFooter(indexFile_.get());
582     indexFile_->close();
583 }
584
585 void HelpExportHtml::startModuleGroupExport()
586 {
587     indexFile_.reset(new File("final/programs/bytopic.html", "w"));
588     writeHtmlHeader(indexFile_.get(), "GROMACS Programs by Topic");
589     indexFile_->writeLine("<H3>GROMACS Programs by Topic</H3>");
590 }
591
592 void HelpExportHtml::exportModuleGroup(const char                *title,
593                                        const ModuleGroupContents &modules)
594 {
595     indexFile_->writeLine(formatString("<H4>%s</H4>", title));
596
597     ModuleGroupContents::const_iterator module;
598     for (module = modules.begin(); module != modules.end(); ++module)
599     {
600         const std::string     &tag(module->first);
601         std::string            displayName(tag);
602         std::replace(displayName.begin(), displayName.end(), '-', ' ');
603         indexFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
604                                            tag.c_str(), displayName.c_str(),
605                                            module->second));
606     }
607 }
608
609 void HelpExportHtml::finishModuleGroupExport()
610 {
611     writeHtmlFooter(indexFile_.get());
612     indexFile_->close();
613 }
614
615 void HelpExportHtml::writeHtmlHeader(File *file, const std::string &title) const
616 {
617     file->writeLine(replaceAll(header_, "@TITLE@", title));
618 }
619
620 void HelpExportHtml::writeHtmlFooter(File *file) const
621 {
622     file->writeLine(footer_);
623 }
624
625 }   // namespace
626
627 /********************************************************************
628  * CommandLineHelpModule
629  */
630
631 /*! \internal
632  * \brief
633  * Command-line module for producing help.
634  *
635  * This module implements the 'help' subcommand that is automatically added by
636  * CommandLineModuleManager.
637  *
638  * \ingroup module_commandline
639  */
640 class CommandLineHelpModule : public CommandLineModuleInterface
641 {
642     public:
643         /*! \brief
644          * Creates a command-line help module.
645          *
646          * \param[in] programInfo Information about the running binary.
647          * \param[in] modules  List of modules for to use for module listings.
648          * \param[in] groups   List of module groups.
649          * \throws    std::bad_alloc if out of memory.
650          */
651         CommandLineHelpModule(const ProgramInfo                &programInfo,
652                               const CommandLineModuleMap       &modules,
653                               const CommandLineModuleGroupList &groups);
654
655         /*! \brief
656          * Adds a top-level help topic.
657          *
658          * \param[in] topic  Help topic to add.
659          * \throws    std::bad_alloc if out of memory.
660          */
661         void addTopic(HelpTopicPointer topic);
662         //! Sets whether hidden options will be shown in help.
663         void setShowHidden(bool bHidden) { bHidden_ = bHidden; }
664         /*! \brief
665          * Sets an override to show the help for the given module.
666          *
667          * If called, the help module directly prints the help for the given
668          * module when called, skipping any other processing.
669          */
670         void setModuleOverride(const CommandLineModuleInterface &module)
671         {
672             moduleOverride_ = &module;
673         }
674
675         //! Returns the context object for help output.
676         const CommandLineHelpContext &context() const
677         {
678             return *context_;
679         }
680         //! Returns the program info object for the running binary.
681         const ProgramInfo &programInfo() const
682         {
683             return programInfo_;
684         }
685
686         virtual const char *name() const { return "help"; }
687         virtual const char *shortDescription() const
688         {
689             return "Print help information";
690         }
691
692         virtual int run(int argc, char *argv[]);
693         virtual void writeHelp(const CommandLineHelpContext &context) const;
694
695     private:
696         void exportHelp(HelpExportInterface *exporter) const;
697
698         boost::scoped_ptr<RootHelpTopic>  rootTopic_;
699         const ProgramInfo                &programInfo_;
700         const CommandLineModuleMap       &modules_;
701         const CommandLineModuleGroupList &groups_;
702
703         CommandLineHelpContext           *context_;
704         const CommandLineModuleInterface *moduleOverride_;
705         bool                              bHidden_;
706
707         GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModule);
708 };
709
710 CommandLineHelpModule::CommandLineHelpModule(
711         const ProgramInfo                &programInfo,
712         const CommandLineModuleMap       &modules,
713         const CommandLineModuleGroupList &groups)
714     : rootTopic_(new RootHelpTopic(modules)), programInfo_(programInfo),
715       modules_(modules), groups_(groups),
716       context_(NULL), moduleOverride_(NULL), bHidden_(false)
717 {
718 }
719
720 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
721 {
722     rootTopic_->addSubTopic(move(topic));
723 }
724
725 int CommandLineHelpModule::run(int argc, char *argv[])
726 {
727     const char *const exportFormats[] = { "man", "html", "completion" };
728     std::string       exportFormat;
729     Options           options(NULL, NULL);
730     options.addOption(StringOption("export").store(&exportFormat)
731                           .enumValue(exportFormats));
732     CommandLineParser(&options).parse(&argc, argv);
733     if (!exportFormat.empty())
734     {
735         boost::scoped_ptr<HelpExportInterface> exporter;
736         if (exportFormat == "man")
737         {
738             exporter.reset(new HelpExportMan(modules_));
739         }
740         else if (exportFormat == "html")
741         {
742             exporter.reset(new HelpExportHtml(modules_));
743         }
744         else
745         {
746             GMX_THROW(NotImplementedError("This help format is not implemented"));
747         }
748         exportHelp(exporter.get());
749         return 0;
750     }
751
752     HelpLinks                                 links(eHelpOutputFormat_Console);
753     initProgramLinks(&links, modules_);
754     boost::scoped_ptr<CommandLineHelpContext> context(
755             new CommandLineHelpContext(&File::standardOutput(),
756                                        eHelpOutputFormat_Console, &links));
757     context->setShowHidden(bHidden_);
758     if (moduleOverride_ != NULL)
759     {
760         context->setModuleDisplayName(programInfo_.displayName());
761         moduleOverride_->writeHelp(*context);
762         return 0;
763     }
764     context_ = context.get();
765
766     HelpManager       helpManager(*rootTopic_, context->writerContext());
767     try
768     {
769         for (int i = 1; i < argc; ++i)
770         {
771             helpManager.enterTopic(argv[i]);
772         }
773     }
774     catch (const InvalidInputError &ex)
775     {
776         fprintf(stderr, "%s\n", ex.what());
777         return 2;
778     }
779     helpManager.writeCurrentTopic();
780     return 0;
781 }
782
783 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
784 {
785     const HelpWriterContext &writerContext = context.writerContext();
786     // TODO: Implement.
787     if (writerContext.outputFormat() != eHelpOutputFormat_Console)
788     {
789         return;
790     }
791     writerContext.writeTextBlock(
792             "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
793     // TODO: More information.
794 }
795
796 void CommandLineHelpModule::exportHelp(HelpExportInterface *exporter) const
797 {
798     // TODO: Would be nicer to have the file names supplied by the build system
799     // and/or export a list of files from here.
800     const char *const program = programInfo_.realBinaryName().c_str();
801
802     exporter->startModuleExport();
803     CommandLineModuleMap::const_iterator module;
804     for (module = modules_.begin(); module != modules_.end(); ++module)
805     {
806         if (module->second->shortDescription() != NULL)
807         {
808             const char *const moduleName = module->first.c_str();
809             std::string       tag(formatString("%s-%s", program, moduleName));
810             std::string       displayName(tag);
811             std::replace(displayName.begin(), displayName.end(), '-', ' ');
812             exporter->exportModuleHelp(*module->second, tag, displayName);
813         }
814     }
815     exporter->finishModuleExport();
816
817     exporter->startModuleGroupExport();
818     CommandLineModuleGroupList::const_iterator group;
819     for (group = groups_.begin(); group != groups_.end(); ++group)
820     {
821         exporter->exportModuleGroup((*group)->title(), (*group)->modules());
822     }
823     exporter->finishModuleGroupExport();
824 }
825
826 namespace
827 {
828
829 /********************************************************************
830  * ModuleHelpTopic implementation
831  */
832
833 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
834 {
835     CommandLineHelpContext context(helpModule_.context());
836     const char *const      program =
837         helpModule_.programInfo().realBinaryName().c_str();
838     context.setModuleDisplayName(formatString("%s %s", program, module_.name()));
839     module_.writeHelp(context);
840 }
841
842 /********************************************************************
843  * CMainCommandLineModule
844  */
845
846 /*! \internal \brief
847  * Implements a CommandLineModuleInterface, given a function with C/C++ main()
848  * signature.
849  *
850  * \ingroup module_commandline
851  */
852 class CMainCommandLineModule : public CommandLineModuleInterface
853 {
854     public:
855         //! \copydoc gmx::CommandLineModuleManager::CMainFunction
856         typedef CommandLineModuleManager::CMainFunction CMainFunction;
857
858         /*! \brief
859          * Creates a wrapper module for the given main function.
860          *
861          * \param[in] name             Name for the module.
862          * \param[in] shortDescription One-line description for the module.
863          * \param[in] mainFunction     Main function to wrap.
864          *
865          * Does not throw.  This is essential for correct implementation of
866          * CommandLineModuleManager::runAsMainCMain().
867          */
868         CMainCommandLineModule(const char *name, const char *shortDescription,
869                                CMainFunction mainFunction)
870             : name_(name), shortDescription_(shortDescription),
871               mainFunction_(mainFunction)
872         {
873         }
874
875         virtual const char *name() const
876         {
877             return name_;
878         }
879         virtual const char *shortDescription() const
880         {
881             return shortDescription_;
882         }
883
884         virtual int run(int argc, char *argv[])
885         {
886             return mainFunction_(argc, argv);
887         }
888         virtual void writeHelp(const CommandLineHelpContext &context) const
889         {
890             const HelpOutputFormat format = context.writerContext().outputFormat();
891             const char            *type;
892             switch (format)
893             {
894                 case eHelpOutputFormat_Console:
895                     type = "help";
896                     break;
897                 case eHelpOutputFormat_Man:
898                     type = "nroff";
899                     break;
900                 case eHelpOutputFormat_Html:
901                     type = "html";
902                     break;
903                 default:
904                     GMX_THROW(NotImplementedError(
905                                       "Command-line help is not implemented for this output format"));
906             }
907             char *argv[4];
908             int   argc = 3;
909             // TODO: The constness should not be cast away.
910             argv[0] = const_cast<char *>(name_);
911             argv[1] = const_cast<char *>("-man");
912             argv[2] = const_cast<char *>(type);
913             argv[3] = NULL;
914             GlobalCommandLineHelpContext global(context);
915             mainFunction_(argc, argv);
916         }
917
918     private:
919         const char             *name_;
920         const char             *shortDescription_;
921         CMainFunction           mainFunction_;
922
923 };
924
925 }   // namespace
926
927 /********************************************************************
928  * CommandLineModuleManager::Impl
929  */
930
931 /*! \internal \brief
932  * Private implementation class for CommandLineModuleManager.
933  *
934  * \ingroup module_commandline
935  */
936 class CommandLineModuleManager::Impl
937 {
938     public:
939         /*! \brief
940          * Initializes the implementation class.
941          *
942          * \param     programInfo  Program information for the running binary.
943          */
944         explicit Impl(ProgramInfo *programInfo);
945
946         /*! \brief
947          * Helper method that adds a given module to the module manager.
948          *
949          * \throws    std::bad_alloc if out of memory.
950          */
951         void addModule(CommandLineModulePointer module);
952         /*! \brief
953          * Creates the help module if it does not yet exist.
954          *
955          * \throws    std::bad_alloc if out of memory.
956          *
957          * This method should be called before accessing \a helpModule_.
958          */
959         void ensureHelpModuleExists();
960
961         /*! \brief
962          * Finds a module that matches a name.
963          *
964          * \param[in] name  Module name to find.
965          * \returns   Iterator to the found module, or
966          *      \c modules_.end() if not found.
967          *
968          * Does not throw.
969          */
970         CommandLineModuleMap::const_iterator
971         findModuleByName(const std::string &name) const;
972         /*! \brief
973          * Finds a module that the name of the binary.
974          *
975          * \param[in] programInfo  Program information object to use.
976          * \throws    std::bad_alloc if out of memory.
977          * \returns   Iterator to the found module, or
978          *      \c modules_.end() if not found.
979          *
980          * Checks whether the program is invoked through a symlink whose name
981          * is different from ProgramInfo::realBinaryName(), and if so, checks
982          * if a module name matches the name of the symlink.
983          *
984          * Note that the \p programInfo parameter is currently not necessary
985          * (as the program info object is also contained as a member), but it
986          * clarifies the control flow.
987          */
988         CommandLineModuleMap::const_iterator
989         findModuleFromBinaryName(const ProgramInfo &programInfo) const;
990
991         /*! \brief
992          * Processes command-line options for the wrapper binary.
993          *
994          * \param[in,out] argc On input, argc passed to run().
995          *     On output, argc to be passed to the module.
996          * \param[in,out] argv On input, argv passed to run().
997          *     On output, argv to be passed to the module.
998          * \throws    InvalidInputError if there are invalid options.
999          * \returns   The module that should be run.
1000          *
1001          * Handles command-line options that affect the wrapper binary
1002          * (potentially changing the members of \c this in response to the
1003          * options).  Also finds the module that should be run and the
1004          * arguments that should be passed to it.
1005          */
1006         CommandLineModuleInterface *
1007         processCommonOptions(int *argc, char ***argv);
1008
1009         /*! \brief
1010          * Maps module names to module objects.
1011          *
1012          * Owns the contained modules.
1013          */
1014         CommandLineModuleMap         modules_;
1015         /*! \brief
1016          * List of groupings for modules for help output.
1017          *
1018          * Owns the contained module group data objects.
1019          * CommandLineModuleGroup objects point to the data objects contained
1020          * here.
1021          */
1022         CommandLineModuleGroupList   moduleGroups_;
1023         //! Information about the currently running program.
1024         ProgramInfo                 &programInfo_;
1025         /*! \brief
1026          * Module that implements help for the binary.
1027          *
1028          * The pointed module is owned by the \a modules_ container.
1029          */
1030         CommandLineHelpModule       *helpModule_;
1031         //! Settings for what to write in the startup header.
1032         BinaryInformationSettings    binaryInfoSettings_;
1033         //! If non-NULL, run this module in single-module mode.
1034         CommandLineModuleInterface  *singleModule_;
1035         //! Whether all stderr output should be suppressed.
1036         bool                         bQuiet_;
1037         //! Whether to write the startup information to stdout iso stderr.
1038         bool                         bStdOutInfo_;
1039
1040     private:
1041         GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
1042 };
1043
1044 CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
1045     : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
1046       bQuiet_(false), bStdOutInfo_(false)
1047 {
1048     binaryInfoSettings_.copyright(true);
1049 }
1050
1051 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
1052 {
1053     GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
1054                "Attempted to register a duplicate module name");
1055     ensureHelpModuleExists();
1056     HelpTopicPointer helpTopic(new ModuleHelpTopic(*module, *helpModule_));
1057     modules_.insert(std::make_pair(std::string(module->name()),
1058                                    move(module)));
1059     helpModule_->addTopic(move(helpTopic));
1060 }
1061
1062 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
1063 {
1064     if (helpModule_ == NULL)
1065     {
1066         helpModule_ = new CommandLineHelpModule(programInfo_, modules_,
1067                                                 moduleGroups_);
1068         addModule(CommandLineModulePointer(helpModule_));
1069     }
1070 }
1071
1072 CommandLineModuleMap::const_iterator
1073 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
1074 {
1075     // TODO: Accept unambiguous prefixes?
1076     return modules_.find(name);
1077 }
1078
1079 CommandLineModuleMap::const_iterator
1080 CommandLineModuleManager::Impl::findModuleFromBinaryName(
1081         const ProgramInfo &programInfo) const
1082 {
1083     std::string binaryName = programInfo.invariantProgramName();
1084     if (binaryName == programInfo.realBinaryName())
1085     {
1086         return modules_.end();
1087     }
1088     if (binaryName.compare(0, 2, "g_") == 0)
1089     {
1090         binaryName.erase(0, 2);
1091     }
1092     if (binaryName.compare(0, 3, "gmx") == 0)
1093     {
1094         binaryName.erase(0, 3);
1095     }
1096     return findModuleByName(binaryName);
1097 }
1098
1099 CommandLineModuleInterface *
1100 CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
1101 {
1102     // Check if we are directly invoking a certain module.
1103     CommandLineModuleInterface *module = singleModule_;
1104     if (module == NULL)
1105     {
1106         // Also check for invokation through named symlinks.
1107         CommandLineModuleMap::const_iterator moduleIter
1108             = findModuleFromBinaryName(programInfo_);
1109         if (moduleIter != modules_.end())
1110         {
1111             module = moduleIter->second.get();
1112         }
1113     }
1114
1115     bool bHelp      = false;
1116     bool bHidden    = false;
1117     bool bVersion   = false;
1118     bool bCopyright = true;
1119     // TODO: Print the common options into the help.
1120     // TODO: It would be nice to propagate at least the -quiet option to
1121     // the modules so that they can also be quiet in response to this.
1122     Options options(NULL, NULL);
1123     options.addOption(BooleanOption("h").store(&bHelp));
1124     options.addOption(BooleanOption("hidden").store(&bHidden));
1125     options.addOption(BooleanOption("quiet").store(&bQuiet_));
1126     options.addOption(BooleanOption("version").store(&bVersion));
1127     options.addOption(BooleanOption("copyright").store(&bCopyright));
1128
1129     if (module == NULL)
1130     {
1131         // If not in single-module mode, process options to the wrapper binary.
1132         // TODO: Ideally, this could be done by CommandLineParser.
1133         int argcForWrapper = 1;
1134         while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
1135         {
1136             ++argcForWrapper;
1137         }
1138         if (argcForWrapper > 1)
1139         {
1140             CommandLineParser(&options).parse(&argcForWrapper, *argv);
1141         }
1142         // If no action requested and there is a module specified, process it.
1143         if (argcForWrapper < *argc && !bHelp && !bVersion)
1144         {
1145             const char *moduleName = (*argv)[argcForWrapper];
1146             CommandLineModuleMap::const_iterator moduleIter
1147                 = findModuleByName(moduleName);
1148             if (moduleIter == modules_.end())
1149             {
1150                 std::string message =
1151                     formatString("'%s' is not a GROMACS command.", moduleName);
1152                 GMX_THROW(InvalidInputError(message));
1153             }
1154             module = moduleIter->second.get();
1155             *argc -= argcForWrapper;
1156             *argv += argcForWrapper;
1157             // After this point, argc and argv are the same independent of
1158             // which path is taken: (*argv)[0] is the module name.
1159         }
1160     }
1161     if (module != NULL)
1162     {
1163         if (singleModule_ == NULL)
1164         {
1165             programInfo_.setDisplayName(
1166                     programInfo_.realBinaryName() + " " + module->name());
1167         }
1168         // Recognize the common options also after the module name.
1169         // TODO: It could be nicer to only recognize -h/-hidden if module is not
1170         // null.
1171         CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
1172     }
1173     options.finish();
1174     binaryInfoSettings_.extendedInfo(bVersion);
1175     binaryInfoSettings_.copyright(bCopyright);
1176     if (bVersion)
1177     {
1178         bQuiet_      = false;
1179         bStdOutInfo_ = true;
1180         return NULL;
1181     }
1182     // If no module specified and no other action, show the help.
1183     // Also explicitly specifying -h for the wrapper binary goes here.
1184     if (module == NULL || bHelp)
1185     {
1186         ensureHelpModuleExists();
1187         if (module != NULL)
1188         {
1189             helpModule_->setModuleOverride(*module);
1190         }
1191         *argc  = 1;
1192         module = helpModule_;
1193     }
1194     if (module == helpModule_)
1195     {
1196         helpModule_->setShowHidden(bHidden);
1197     }
1198     return module;
1199 }
1200
1201 /********************************************************************
1202  * CommandLineModuleManager
1203  */
1204
1205 CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
1206     : impl_(new Impl(programInfo))
1207 {
1208 }
1209
1210 CommandLineModuleManager::~CommandLineModuleManager()
1211 {
1212 }
1213
1214 void CommandLineModuleManager::setQuiet(bool bQuiet)
1215 {
1216     impl_->bQuiet_ = bQuiet;
1217 }
1218
1219 void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
1220 {
1221     impl_->singleModule_ = module;
1222 }
1223
1224 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
1225 {
1226     impl_->addModule(move(module));
1227 }
1228
1229 void CommandLineModuleManager::addModuleCMain(
1230         const char *name, const char *shortDescription,
1231         CMainFunction mainFunction)
1232 {
1233     CommandLineModulePointer module(
1234             new CMainCommandLineModule(name, shortDescription, mainFunction));
1235     addModule(move(module));
1236 }
1237
1238 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
1239         const char *title)
1240 {
1241     CommandLineModuleGroupDataPointer group(
1242             new internal::CommandLineModuleGroupData(impl_->modules_, title));
1243     impl_->moduleGroups_.push_back(move(group));
1244     return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
1245 }
1246
1247 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
1248 {
1249     impl_->ensureHelpModuleExists();
1250     impl_->helpModule_->addTopic(move(topic));
1251 }
1252
1253 int CommandLineModuleManager::run(int argc, char *argv[])
1254 {
1255     CommandLineModuleInterface *module;
1256     const bool                  bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
1257     try
1258     {
1259         module = impl_->processCommonOptions(&argc, &argv);
1260     }
1261     catch (const std::exception &)
1262     {
1263         if (bMaster && !impl_->bQuiet_)
1264         {
1265             printBinaryInformation(stderr, impl_->programInfo_,
1266                                    impl_->binaryInfoSettings_);
1267         }
1268         throw;
1269     }
1270     if (!bMaster)
1271     {
1272         impl_->bQuiet_ = true;
1273     }
1274     if (!impl_->bQuiet_)
1275     {
1276         FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
1277         printBinaryInformation(out, impl_->programInfo_,
1278                                impl_->binaryInfoSettings_);
1279         fprintf(out, "\n");
1280     }
1281     if (module == NULL)
1282     {
1283         return 0;
1284     }
1285     int rc = module->run(argc, argv);
1286     if (!impl_->bQuiet_)
1287     {
1288         gmx_thanx(stderr);
1289     }
1290     return rc;
1291 }
1292
1293 // static
1294 int CommandLineModuleManager::runAsMainSingleModule(
1295         int argc, char *argv[], CommandLineModuleInterface *module)
1296 {
1297     ProgramInfo &programInfo = gmx::init(&argc, &argv);
1298     try
1299     {
1300         CommandLineModuleManager manager(&programInfo);
1301         manager.setSingleModule(module);
1302         int rc = manager.run(argc, argv);
1303         gmx::finalize();
1304         return rc;
1305     }
1306     catch (const std::exception &ex)
1307     {
1308         printFatalErrorMessage(stderr, ex);
1309         return processExceptionAtExit(ex);
1310     }
1311 }
1312
1313 // static
1314 int CommandLineModuleManager::runAsMainCMain(
1315         int argc, char *argv[], CMainFunction mainFunction)
1316 {
1317     CMainCommandLineModule module(argv[0], NULL, mainFunction);
1318     return runAsMainSingleModule(argc, argv, &module);
1319 }
1320
1321 /********************************************************************
1322  * CommandLineModuleGroup
1323  */
1324
1325 void CommandLineModuleGroup::addModule(const char *name)
1326 {
1327     impl_->addModule(name, NULL);
1328 }
1329
1330 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
1331                                                       const char *description)
1332 {
1333     impl_->addModule(name, description);
1334 }
1335
1336 } // namespace gmx