Add back mechanism for cross-tool hyperlinks.
[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 writeHtmlHeader(File *file, const std::string &title) const;
515         void writeHtmlFooter(File *file) const;
516
517         boost::scoped_ptr<File>  indexFile_;
518         HelpLinks                links_;
519 };
520
521 HelpExportHtml::HelpExportHtml(const CommandLineModuleMap &modules)
522     : links_(eHelpOutputFormat_Html)
523 {
524     initProgramLinks(&links_, modules);
525     char *linksFilename = low_gmxlibfn("links.dat", FALSE, FALSE);
526     if (linksFilename != NULL)
527     {
528         scoped_ptr_sfree guard(linksFilename);
529         File             linksFile(linksFilename, "r");
530         std::string      line;
531         while (linksFile.readLine(&line))
532         {
533             links_.addLink(line, "../online/" + line, line);
534         }
535     }
536 }
537
538 void HelpExportHtml::startModuleExport()
539 {
540     indexFile_.reset(new File("byname.html", "w"));
541     writeHtmlHeader(indexFile_.get(), "GROMACS Programs by Name");
542     indexFile_->writeLine("<H3>GROMACS Programs Alphabetically</H3>");
543 }
544
545 void HelpExportHtml::exportModuleHelp(
546         const CommandLineModuleInterface &module,
547         const std::string                &tag,
548         const std::string                &displayName)
549 {
550     File file(tag + ".html", "w");
551     writeHtmlHeader(&file, displayName);
552
553     CommandLineHelpContext context(&file, eHelpOutputFormat_Html, &links_);
554     context.setModuleDisplayName(displayName);
555     module.writeHelp(context);
556
557     writeHtmlFooter(&file);
558     file.close();
559
560     indexFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
561                                        tag.c_str(), displayName.c_str(),
562                                        module.shortDescription()));
563 }
564
565 void HelpExportHtml::finishModuleExport()
566 {
567     writeHtmlFooter(indexFile_.get());
568     indexFile_->close();
569 }
570
571 void HelpExportHtml::startModuleGroupExport()
572 {
573     indexFile_.reset(new File("bytopic.html", "w"));
574     writeHtmlHeader(indexFile_.get(), "GROMACS Programs by Topic");
575     indexFile_->writeLine("<H3>GROMACS Programs by Topic</H3>");
576 }
577
578 void HelpExportHtml::exportModuleGroup(const char                *title,
579                                        const ModuleGroupContents &modules)
580 {
581     indexFile_->writeLine(formatString("<H4>%s</H4>", title));
582
583     ModuleGroupContents::const_iterator module;
584     for (module = modules.begin(); module != modules.end(); ++module)
585     {
586         const std::string     &tag(module->first);
587         std::string            displayName(tag);
588         std::replace(displayName.begin(), displayName.end(), '-', ' ');
589         indexFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
590                                            tag.c_str(), displayName.c_str(),
591                                            module->second));
592     }
593 }
594
595 void HelpExportHtml::finishModuleGroupExport()
596 {
597     writeHtmlFooter(indexFile_.get());
598     indexFile_->close();
599 }
600
601 void HelpExportHtml::writeHtmlHeader(File *file, const std::string &title) const
602 {
603     file->writeLine("<HTML>");
604     file->writeLine("<HEAD>");
605     file->writeLine(formatString("<TITLE>%s</TITLE>", title.c_str()));
606     file->writeLine("<LINK rel=stylesheet href=\"../online/style.css\" type=\"text/css\">");
607     file->writeLine("<BODY text=\"#000000\" bgcolor=\"#FFFFFF\" link=\"#0000FF\" vlink=\"#990000\" alink=\"#FF0000\">");
608     file->writeLine("<TABLE WIDTH=\"98%%\" NOBORDER><TR>");
609     file->writeLine("<TD WIDTH=400><TABLE WIDTH=400 NOBORDER>");
610     file->writeLine("<TD WIDTH=116>");
611     file->writeLine("<A HREF=\"http://www.gromacs.org/\">"
612                     "<IMG SRC=\"../images/gmxlogo_small.jpg\" BORDER=0>"
613                     "</A>");
614     file->writeLine("</TD>");
615     file->writeLine(formatString("<TD ALIGN=LEFT VALIGN=TOP WIDTH=280>"
616                                  "<BR><H2>%s</H2>", title.c_str()));
617     file->writeLine("<FONT SIZE=-1><A HREF=\"../online.html\">Main Table of Contents</A></FONT>");
618     file->writeLine("</TD>");
619     file->writeLine("</TABLE></TD>");
620     file->writeLine("<TD WIDTH=\"*\" ALIGN=RIGHT VALIGN=BOTTOM>");
621     file->writeLine(formatString("<P><B>%s</B>", GromacsVersion()));
622     file->writeLine("</TD>");
623     file->writeLine("</TR></TABLE>");
624     file->writeLine("<HR>");
625 }
626
627 void HelpExportHtml::writeHtmlFooter(File *file) const
628 {
629     file->writeLine("<P>");
630     file->writeLine("<HR>");
631     file->writeLine("<DIV ALIGN=RIGHT><FONT SIZE=\"-1\">");
632     file->writeLine("<A HREF=\"http://www.gromacs.org\">http://www.gromacs.org</A><BR>");
633     file->writeLine("</FONT></DIV>");
634     file->writeLine("</BODY>");
635     file->writeLine("</HTML>");
636 }
637
638 }   // namespace
639
640 /********************************************************************
641  * CommandLineHelpModule
642  */
643
644 /*! \internal
645  * \brief
646  * Command-line module for producing help.
647  *
648  * This module implements the 'help' subcommand that is automatically added by
649  * CommandLineModuleManager.
650  *
651  * \ingroup module_commandline
652  */
653 class CommandLineHelpModule : public CommandLineModuleInterface
654 {
655     public:
656         /*! \brief
657          * Creates a command-line help module.
658          *
659          * \param[in] programInfo Information about the running binary.
660          * \param[in] modules  List of modules for to use for module listings.
661          * \param[in] groups   List of module groups.
662          * \throws    std::bad_alloc if out of memory.
663          */
664         CommandLineHelpModule(const ProgramInfo                &programInfo,
665                               const CommandLineModuleMap       &modules,
666                               const CommandLineModuleGroupList &groups);
667
668         /*! \brief
669          * Adds a top-level help topic.
670          *
671          * \param[in] topic  Help topic to add.
672          * \throws    std::bad_alloc if out of memory.
673          */
674         void addTopic(HelpTopicPointer topic);
675         //! Sets whether hidden options will be shown in help.
676         void setShowHidden(bool bHidden) { bHidden_ = bHidden; }
677         /*! \brief
678          * Sets an override to show the help for the given module.
679          *
680          * If called, the help module directly prints the help for the given
681          * module when called, skipping any other processing.
682          */
683         void setModuleOverride(const CommandLineModuleInterface &module)
684         {
685             moduleOverride_ = &module;
686         }
687
688         //! Returns the context object for help output.
689         const CommandLineHelpContext &context() const
690         {
691             return *context_;
692         }
693         //! Returns the program info object for the running binary.
694         const ProgramInfo &programInfo() const
695         {
696             return programInfo_;
697         }
698
699         virtual const char *name() const { return "help"; }
700         virtual const char *shortDescription() const
701         {
702             return "Print help information";
703         }
704
705         virtual int run(int argc, char *argv[]);
706         virtual void writeHelp(const CommandLineHelpContext &context) const;
707
708     private:
709         void exportHelp(HelpExportInterface *exporter) const;
710
711         boost::scoped_ptr<RootHelpTopic>  rootTopic_;
712         const ProgramInfo                &programInfo_;
713         const CommandLineModuleMap       &modules_;
714         const CommandLineModuleGroupList &groups_;
715
716         CommandLineHelpContext           *context_;
717         const CommandLineModuleInterface *moduleOverride_;
718         bool                              bHidden_;
719
720         GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModule);
721 };
722
723 CommandLineHelpModule::CommandLineHelpModule(
724         const ProgramInfo                &programInfo,
725         const CommandLineModuleMap       &modules,
726         const CommandLineModuleGroupList &groups)
727     : rootTopic_(new RootHelpTopic(modules)), programInfo_(programInfo),
728       modules_(modules), groups_(groups),
729       context_(NULL), moduleOverride_(NULL), bHidden_(false)
730 {
731 }
732
733 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
734 {
735     rootTopic_->addSubTopic(move(topic));
736 }
737
738 int CommandLineHelpModule::run(int argc, char *argv[])
739 {
740     const char *const exportFormats[] = { "man", "html", "completion" };
741     std::string       exportFormat;
742     Options           options(NULL, NULL);
743     options.addOption(StringOption("export").store(&exportFormat)
744                           .enumValue(exportFormats));
745     CommandLineParser(&options).parse(&argc, argv);
746     if (!exportFormat.empty())
747     {
748         boost::scoped_ptr<HelpExportInterface> exporter;
749         if (exportFormat == "man")
750         {
751             exporter.reset(new HelpExportMan(modules_));
752         }
753         else if (exportFormat == "html")
754         {
755             exporter.reset(new HelpExportHtml(modules_));
756         }
757         else
758         {
759             GMX_THROW(NotImplementedError("This help format is not implemented"));
760         }
761         exportHelp(exporter.get());
762         return 0;
763     }
764
765     HelpLinks                                 links(eHelpOutputFormat_Console);
766     initProgramLinks(&links, modules_);
767     boost::scoped_ptr<CommandLineHelpContext> context(
768             new CommandLineHelpContext(&File::standardOutput(),
769                                        eHelpOutputFormat_Console, &links));
770     context->setShowHidden(bHidden_);
771     if (moduleOverride_ != NULL)
772     {
773         context->setModuleDisplayName(programInfo_.displayName());
774         moduleOverride_->writeHelp(*context);
775         return 0;
776     }
777     context_ = context.get();
778
779     HelpManager       helpManager(*rootTopic_, context->writerContext());
780     try
781     {
782         for (int i = 1; i < argc; ++i)
783         {
784             helpManager.enterTopic(argv[i]);
785         }
786     }
787     catch (const InvalidInputError &ex)
788     {
789         fprintf(stderr, "%s\n", ex.what());
790         return 2;
791     }
792     helpManager.writeCurrentTopic();
793     return 0;
794 }
795
796 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
797 {
798     const HelpWriterContext &writerContext = context.writerContext();
799     // TODO: Implement.
800     if (writerContext.outputFormat() != eHelpOutputFormat_Console)
801     {
802         return;
803     }
804     writerContext.writeTextBlock(
805             "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
806     // TODO: More information.
807 }
808
809 void CommandLineHelpModule::exportHelp(HelpExportInterface *exporter) const
810 {
811     // TODO: Would be nicer to have the file names supplied by the build system
812     // and/or export a list of files from here.
813     const char *const program = programInfo_.realBinaryName().c_str();
814
815     exporter->startModuleExport();
816     CommandLineModuleMap::const_iterator module;
817     for (module = modules_.begin(); module != modules_.end(); ++module)
818     {
819         if (module->second->shortDescription() != NULL)
820         {
821             const char *const moduleName = module->first.c_str();
822             std::string       tag(formatString("%s-%s", program, moduleName));
823             std::string       displayName(tag);
824             std::replace(displayName.begin(), displayName.end(), '-', ' ');
825             exporter->exportModuleHelp(*module->second, tag, displayName);
826         }
827     }
828     exporter->finishModuleExport();
829
830     exporter->startModuleGroupExport();
831     CommandLineModuleGroupList::const_iterator group;
832     for (group = groups_.begin(); group != groups_.end(); ++group)
833     {
834         exporter->exportModuleGroup((*group)->title(), (*group)->modules());
835     }
836     exporter->finishModuleGroupExport();
837 }
838
839 namespace
840 {
841
842 /********************************************************************
843  * ModuleHelpTopic implementation
844  */
845
846 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
847 {
848     CommandLineHelpContext context(helpModule_.context());
849     const char *const      program =
850         helpModule_.programInfo().realBinaryName().c_str();
851     context.setModuleDisplayName(formatString("%s %s", program, module_.name()));
852     module_.writeHelp(context);
853 }
854
855 /********************************************************************
856  * CMainCommandLineModule
857  */
858
859 /*! \internal \brief
860  * Implements a CommandLineModuleInterface, given a function with C/C++ main()
861  * signature.
862  *
863  * \ingroup module_commandline
864  */
865 class CMainCommandLineModule : public CommandLineModuleInterface
866 {
867     public:
868         //! \copydoc gmx::CommandLineModuleManager::CMainFunction
869         typedef CommandLineModuleManager::CMainFunction CMainFunction;
870
871         /*! \brief
872          * Creates a wrapper module for the given main function.
873          *
874          * \param[in] name             Name for the module.
875          * \param[in] shortDescription One-line description for the module.
876          * \param[in] mainFunction     Main function to wrap.
877          *
878          * Does not throw.  This is essential for correct implementation of
879          * CommandLineModuleManager::runAsMainCMain().
880          */
881         CMainCommandLineModule(const char *name, const char *shortDescription,
882                                CMainFunction mainFunction)
883             : name_(name), shortDescription_(shortDescription),
884               mainFunction_(mainFunction)
885         {
886         }
887
888         virtual const char *name() const
889         {
890             return name_;
891         }
892         virtual const char *shortDescription() const
893         {
894             return shortDescription_;
895         }
896
897         virtual int run(int argc, char *argv[])
898         {
899             return mainFunction_(argc, argv);
900         }
901         virtual void writeHelp(const CommandLineHelpContext &context) const
902         {
903             const HelpOutputFormat format = context.writerContext().outputFormat();
904             const char            *type;
905             switch (format)
906             {
907                 case eHelpOutputFormat_Console:
908                     type = "help";
909                     break;
910                 case eHelpOutputFormat_Man:
911                     type = "nroff";
912                     break;
913                 case eHelpOutputFormat_Html:
914                     type = "html";
915                     break;
916                 default:
917                     GMX_THROW(NotImplementedError(
918                                       "Command-line help is not implemented for this output format"));
919             }
920             char *argv[4];
921             int   argc = 3;
922             // TODO: The constness should not be cast away.
923             argv[0] = const_cast<char *>(name_);
924             argv[1] = const_cast<char *>("-man");
925             argv[2] = const_cast<char *>(type);
926             argv[3] = NULL;
927             GlobalCommandLineHelpContext global(context);
928             mainFunction_(argc, argv);
929         }
930
931     private:
932         const char             *name_;
933         const char             *shortDescription_;
934         CMainFunction           mainFunction_;
935
936 };
937
938 }   // namespace
939
940 /********************************************************************
941  * CommandLineModuleManager::Impl
942  */
943
944 /*! \internal \brief
945  * Private implementation class for CommandLineModuleManager.
946  *
947  * \ingroup module_commandline
948  */
949 class CommandLineModuleManager::Impl
950 {
951     public:
952         /*! \brief
953          * Initializes the implementation class.
954          *
955          * \param     programInfo  Program information for the running binary.
956          */
957         explicit Impl(ProgramInfo *programInfo);
958
959         /*! \brief
960          * Helper method that adds a given module to the module manager.
961          *
962          * \throws    std::bad_alloc if out of memory.
963          */
964         void addModule(CommandLineModulePointer module);
965         /*! \brief
966          * Creates the help module if it does not yet exist.
967          *
968          * \throws    std::bad_alloc if out of memory.
969          *
970          * This method should be called before accessing \a helpModule_.
971          */
972         void ensureHelpModuleExists();
973
974         /*! \brief
975          * Finds a module that matches a name.
976          *
977          * \param[in] name  Module name to find.
978          * \returns   Iterator to the found module, or
979          *      \c modules_.end() if not found.
980          *
981          * Does not throw.
982          */
983         CommandLineModuleMap::const_iterator
984         findModuleByName(const std::string &name) const;
985         /*! \brief
986          * Finds a module that the name of the binary.
987          *
988          * \param[in] programInfo  Program information object to use.
989          * \throws    std::bad_alloc if out of memory.
990          * \returns   Iterator to the found module, or
991          *      \c modules_.end() if not found.
992          *
993          * Checks whether the program is invoked through a symlink whose name
994          * is different from ProgramInfo::realBinaryName(), and if so, checks
995          * if a module name matches the name of the symlink.
996          *
997          * Note that the \p programInfo parameter is currently not necessary
998          * (as the program info object is also contained as a member), but it
999          * clarifies the control flow.
1000          */
1001         CommandLineModuleMap::const_iterator
1002         findModuleFromBinaryName(const ProgramInfo &programInfo) const;
1003
1004         /*! \brief
1005          * Processes command-line options for the wrapper binary.
1006          *
1007          * \param[in,out] argc On input, argc passed to run().
1008          *     On output, argc to be passed to the module.
1009          * \param[in,out] argv On input, argv passed to run().
1010          *     On output, argv to be passed to the module.
1011          * \throws    InvalidInputError if there are invalid options.
1012          * \returns   The module that should be run.
1013          *
1014          * Handles command-line options that affect the wrapper binary
1015          * (potentially changing the members of \c this in response to the
1016          * options).  Also finds the module that should be run and the
1017          * arguments that should be passed to it.
1018          */
1019         CommandLineModuleInterface *
1020         processCommonOptions(int *argc, char ***argv);
1021
1022         /*! \brief
1023          * Maps module names to module objects.
1024          *
1025          * Owns the contained modules.
1026          */
1027         CommandLineModuleMap         modules_;
1028         /*! \brief
1029          * List of groupings for modules for help output.
1030          *
1031          * Owns the contained module group data objects.
1032          * CommandLineModuleGroup objects point to the data objects contained
1033          * here.
1034          */
1035         CommandLineModuleGroupList   moduleGroups_;
1036         //! Information about the currently running program.
1037         ProgramInfo                 &programInfo_;
1038         /*! \brief
1039          * Module that implements help for the binary.
1040          *
1041          * The pointed module is owned by the \a modules_ container.
1042          */
1043         CommandLineHelpModule       *helpModule_;
1044         //! Settings for what to write in the startup header.
1045         BinaryInformationSettings    binaryInfoSettings_;
1046         //! If non-NULL, run this module in single-module mode.
1047         CommandLineModuleInterface  *singleModule_;
1048         //! Whether all stderr output should be suppressed.
1049         bool                         bQuiet_;
1050         //! Whether to write the startup information to stdout iso stderr.
1051         bool                         bStdOutInfo_;
1052
1053     private:
1054         GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
1055 };
1056
1057 CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
1058     : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
1059       bQuiet_(false), bStdOutInfo_(false)
1060 {
1061     binaryInfoSettings_.copyright(true);
1062 }
1063
1064 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
1065 {
1066     GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
1067                "Attempted to register a duplicate module name");
1068     ensureHelpModuleExists();
1069     HelpTopicPointer helpTopic(new ModuleHelpTopic(*module, *helpModule_));
1070     modules_.insert(std::make_pair(std::string(module->name()),
1071                                    move(module)));
1072     helpModule_->addTopic(move(helpTopic));
1073 }
1074
1075 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
1076 {
1077     if (helpModule_ == NULL)
1078     {
1079         helpModule_ = new CommandLineHelpModule(programInfo_, modules_,
1080                                                 moduleGroups_);
1081         addModule(CommandLineModulePointer(helpModule_));
1082     }
1083 }
1084
1085 CommandLineModuleMap::const_iterator
1086 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
1087 {
1088     // TODO: Accept unambiguous prefixes?
1089     return modules_.find(name);
1090 }
1091
1092 CommandLineModuleMap::const_iterator
1093 CommandLineModuleManager::Impl::findModuleFromBinaryName(
1094         const ProgramInfo &programInfo) const
1095 {
1096     std::string binaryName = programInfo.invariantProgramName();
1097     if (binaryName == programInfo.realBinaryName())
1098     {
1099         return modules_.end();
1100     }
1101     if (binaryName.compare(0, 2, "g_") == 0)
1102     {
1103         binaryName.erase(0, 2);
1104     }
1105     if (binaryName.compare(0, 3, "gmx") == 0)
1106     {
1107         binaryName.erase(0, 3);
1108     }
1109     return findModuleByName(binaryName);
1110 }
1111
1112 CommandLineModuleInterface *
1113 CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
1114 {
1115     // Check if we are directly invoking a certain module.
1116     CommandLineModuleInterface *module = singleModule_;
1117     if (module == NULL)
1118     {
1119         // Also check for invokation through named symlinks.
1120         CommandLineModuleMap::const_iterator moduleIter
1121             = findModuleFromBinaryName(programInfo_);
1122         if (moduleIter != modules_.end())
1123         {
1124             module = moduleIter->second.get();
1125         }
1126     }
1127
1128     bool bHelp      = false;
1129     bool bHidden    = false;
1130     bool bVersion   = false;
1131     bool bCopyright = true;
1132     // TODO: Print the common options into the help.
1133     // TODO: It would be nice to propagate at least the -quiet option to
1134     // the modules so that they can also be quiet in response to this.
1135     Options options(NULL, NULL);
1136     options.addOption(BooleanOption("h").store(&bHelp));
1137     options.addOption(BooleanOption("hidden").store(&bHidden));
1138     options.addOption(BooleanOption("quiet").store(&bQuiet_));
1139     options.addOption(BooleanOption("version").store(&bVersion));
1140     options.addOption(BooleanOption("copyright").store(&bCopyright));
1141
1142     if (module == NULL)
1143     {
1144         // If not in single-module mode, process options to the wrapper binary.
1145         // TODO: Ideally, this could be done by CommandLineParser.
1146         int argcForWrapper = 1;
1147         while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
1148         {
1149             ++argcForWrapper;
1150         }
1151         if (argcForWrapper > 1)
1152         {
1153             CommandLineParser(&options).parse(&argcForWrapper, *argv);
1154         }
1155         // If no action requested and there is a module specified, process it.
1156         if (argcForWrapper < *argc && !bHelp && !bVersion)
1157         {
1158             const char *moduleName = (*argv)[argcForWrapper];
1159             CommandLineModuleMap::const_iterator moduleIter
1160                 = findModuleByName(moduleName);
1161             if (moduleIter == modules_.end())
1162             {
1163                 std::string message =
1164                     formatString("'%s' is not a GROMACS command.", moduleName);
1165                 GMX_THROW(InvalidInputError(message));
1166             }
1167             module = moduleIter->second.get();
1168             *argc -= argcForWrapper;
1169             *argv += argcForWrapper;
1170             // After this point, argc and argv are the same independent of
1171             // which path is taken: (*argv)[0] is the module name.
1172         }
1173     }
1174     if (module != NULL)
1175     {
1176         if (singleModule_ == NULL)
1177         {
1178             programInfo_.setDisplayName(
1179                     programInfo_.realBinaryName() + " " + module->name());
1180         }
1181         // Recognize the common options also after the module name.
1182         // TODO: It could be nicer to only recognize -h/-hidden if module is not
1183         // null.
1184         CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
1185     }
1186     options.finish();
1187     binaryInfoSettings_.extendedInfo(bVersion);
1188     binaryInfoSettings_.copyright(bCopyright);
1189     if (bVersion)
1190     {
1191         bQuiet_      = false;
1192         bStdOutInfo_ = true;
1193         return NULL;
1194     }
1195     // If no module specified and no other action, show the help.
1196     // Also explicitly specifying -h for the wrapper binary goes here.
1197     if (module == NULL || bHelp)
1198     {
1199         ensureHelpModuleExists();
1200         if (module != NULL)
1201         {
1202             helpModule_->setModuleOverride(*module);
1203         }
1204         *argc  = 1;
1205         module = helpModule_;
1206     }
1207     if (module == helpModule_)
1208     {
1209         helpModule_->setShowHidden(bHidden);
1210     }
1211     return module;
1212 }
1213
1214 /********************************************************************
1215  * CommandLineModuleManager
1216  */
1217
1218 CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
1219     : impl_(new Impl(programInfo))
1220 {
1221 }
1222
1223 CommandLineModuleManager::~CommandLineModuleManager()
1224 {
1225 }
1226
1227 void CommandLineModuleManager::setQuiet(bool bQuiet)
1228 {
1229     impl_->bQuiet_ = bQuiet;
1230 }
1231
1232 void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
1233 {
1234     impl_->singleModule_ = module;
1235 }
1236
1237 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
1238 {
1239     impl_->addModule(move(module));
1240 }
1241
1242 void CommandLineModuleManager::addModuleCMain(
1243         const char *name, const char *shortDescription,
1244         CMainFunction mainFunction)
1245 {
1246     CommandLineModulePointer module(
1247             new CMainCommandLineModule(name, shortDescription, mainFunction));
1248     addModule(move(module));
1249 }
1250
1251 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
1252         const char *title)
1253 {
1254     CommandLineModuleGroupDataPointer group(
1255             new internal::CommandLineModuleGroupData(impl_->modules_, title));
1256     impl_->moduleGroups_.push_back(move(group));
1257     return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
1258 }
1259
1260 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
1261 {
1262     impl_->ensureHelpModuleExists();
1263     impl_->helpModule_->addTopic(move(topic));
1264 }
1265
1266 int CommandLineModuleManager::run(int argc, char *argv[])
1267 {
1268     CommandLineModuleInterface *module;
1269     const bool                  bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
1270     try
1271     {
1272         module = impl_->processCommonOptions(&argc, &argv);
1273     }
1274     catch (const std::exception &)
1275     {
1276         if (bMaster && !impl_->bQuiet_)
1277         {
1278             printBinaryInformation(stderr, impl_->programInfo_,
1279                                    impl_->binaryInfoSettings_);
1280         }
1281         throw;
1282     }
1283     if (!bMaster)
1284     {
1285         impl_->bQuiet_ = true;
1286     }
1287     if (!impl_->bQuiet_)
1288     {
1289         FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
1290         printBinaryInformation(out, impl_->programInfo_,
1291                                impl_->binaryInfoSettings_);
1292         fprintf(out, "\n");
1293     }
1294     if (module == NULL)
1295     {
1296         return 0;
1297     }
1298     int rc = module->run(argc, argv);
1299     if (!impl_->bQuiet_)
1300     {
1301         gmx_thanx(stderr);
1302     }
1303     return rc;
1304 }
1305
1306 // static
1307 int CommandLineModuleManager::runAsMainSingleModule(
1308         int argc, char *argv[], CommandLineModuleInterface *module)
1309 {
1310     ProgramInfo &programInfo = gmx::init(&argc, &argv);
1311     try
1312     {
1313         CommandLineModuleManager manager(&programInfo);
1314         manager.setSingleModule(module);
1315         int rc = manager.run(argc, argv);
1316         gmx::finalize();
1317         return rc;
1318     }
1319     catch (const std::exception &ex)
1320     {
1321         printFatalErrorMessage(stderr, ex);
1322         return processExceptionAtExit(ex);
1323     }
1324 }
1325
1326 // static
1327 int CommandLineModuleManager::runAsMainCMain(
1328         int argc, char *argv[], CMainFunction mainFunction)
1329 {
1330     CMainCommandLineModule module(argv[0], NULL, mainFunction);
1331     return runAsMainSingleModule(argc, argv, &module);
1332 }
1333
1334 /********************************************************************
1335  * CommandLineModuleGroup
1336  */
1337
1338 void CommandLineModuleGroup::addModule(const char *name)
1339 {
1340     impl_->addModule(name, NULL);
1341 }
1342
1343 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
1344                                                       const char *description)
1345 {
1346     impl_->addModule(name, description);
1347 }
1348
1349 } // namespace gmx