Make (most) HTML links to file formats work again
[alexxy/gromacs.git] / src / gromacs / options / filenameoption.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015, 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 classes in filenameoption.h and filenameoptionstorage.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_options
41  */
42 #include "gmxpre.h"
43
44 #include "filenameoption.h"
45
46 #include <cstring>
47
48 #include <string>
49 #include <vector>
50
51 #include "gromacs/fileio/filenm.h"
52 #include "gromacs/options/filenameoptionmanager.h"
53 #include "gromacs/options/optionmanagercontainer.h"
54 #include "gromacs/utility/arrayref.h"
55 #include "gromacs/utility/exceptions.h"
56 #include "gromacs/utility/gmxassert.h"
57 #include "gromacs/utility/stringutil.h"
58
59 #include "filenameoptionstorage.h"
60
61 namespace gmx
62 {
63
64 namespace
65 {
66
67 //! \addtogroup module_options
68 //! \{
69
70 /*! \brief
71  * Mapping from OptionFileType to a file type in filenm.h.
72  */
73 struct FileTypeMapping
74 {
75     //! OptionFileType value to map.
76     OptionFileType optionType;
77     //! Corresponding file type from filenm.h.
78     int            fileType;
79 };
80
81 //! Mappings from OptionFileType to file types in filenm.h.
82 const FileTypeMapping c_fileTypeMapping[] =
83 {
84     { eftTopology,    efTPS },
85     { eftTrajectory,  efTRX },
86     { eftPDB,         efPDB },
87     { eftIndex,       efNDX },
88     { eftPlot,        efXVG },
89     { eftGenericData, efDAT }
90 };
91
92 /********************************************************************
93  * FileTypeHandler
94  */
95
96 /*! \internal
97  * \brief
98  * Handles a single file type known to FileNameOptionStorage.
99  *
100  * Methods in this class do not throw, except for a possible std::bad_alloc
101  * when constructing std::string return values.
102  */
103 class FileTypeHandler
104 {
105     public:
106         /*! \brief
107          * Returns a handler for a single file type.
108          *
109          * \param[in] fileType  File type (from filenm.h) to use.
110          */
111         explicit FileTypeHandler(int fileType);
112
113         //! Returns the number of acceptable extensions for this file type.
114         int extensionCount() const;
115         //! Returns the extension with the given index.
116         const char *extension(int i) const;
117
118         //! Returns whether \p fileType (from filenm.h) is accepted for this type.
119         bool isValidType(int fileType) const;
120
121     private:
122         /*! \brief
123          * File type (from filenm.h) represented by this handler.
124          *
125          * -1 represents an unknown file type.
126          */
127         int        fileType_;
128         //! Number of different extensions this type supports.
129         int        extensionCount_;
130         /*! \brief
131          * List of simple file types that are included in this type.
132          *
133          * If `fileType_` represents a generic type in filenm.h, i.e., a type
134          * that accepts multiple different types of files, then this is an
135          * array of `extensionCount_` elements, each element specifying one
136          * non-generic file type that this option accepts.
137          * `NULL` for single-extension types.
138          */
139         const int *genericTypes_;
140 };
141
142 FileTypeHandler::FileTypeHandler(int fileType)
143     : fileType_(fileType), extensionCount_(0), genericTypes_(NULL)
144 {
145     if (fileType_ >= 0)
146     {
147         const int genericTypeCount = ftp2generic_count(fileType_);
148         if (genericTypeCount > 0)
149         {
150             extensionCount_ = genericTypeCount;
151             genericTypes_   = ftp2generic_list(fileType_);
152         }
153         else if (ftp2ext_with_dot(fileType_)[0] != '\0')
154         {
155             extensionCount_ = 1;
156         }
157     }
158 }
159
160 int FileTypeHandler::extensionCount() const
161 {
162     return extensionCount_;
163 }
164
165 const char *FileTypeHandler::extension(int i) const
166 {
167     GMX_ASSERT(i >= 0 && i < extensionCount_, "Invalid extension index");
168     if (genericTypes_ != NULL)
169     {
170         return ftp2ext_with_dot(genericTypes_[i]);
171     }
172     return ftp2ext_with_dot(fileType_);
173 }
174
175 bool
176 FileTypeHandler::isValidType(int fileType) const
177 {
178     if (genericTypes_ != NULL)
179     {
180         for (int i = 0; i < extensionCount(); ++i)
181         {
182             if (fileType == genericTypes_[i])
183             {
184                 return true;
185             }
186         }
187         return false;
188     }
189     else
190     {
191         return fileType == fileType_;
192     }
193 }
194
195 //! \}
196
197 }   // namespace
198
199 /********************************************************************
200  * FileNameOptionStorage
201  */
202
203 FileNameOptionStorage::FileNameOptionStorage(const FileNameOption  &settings,
204                                              FileNameOptionManager *manager)
205     : MyBase(settings), info_(this), manager_(manager), fileType_(-1),
206       defaultExtension_(""), bRead_(settings.bRead_), bWrite_(settings.bWrite_),
207       bLibrary_(settings.bLibrary_), bAllowMissing_(settings.bAllowMissing_)
208 {
209     GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
210                        "allowMultiple() is not supported for file name options");
211     if (settings.optionType_ == eftUnknown && settings.legacyType_ >= 0)
212     {
213         fileType_ = settings.legacyType_;
214     }
215     else
216     {
217         ConstArrayRef<FileTypeMapping>                 map(c_fileTypeMapping);
218         ConstArrayRef<FileTypeMapping>::const_iterator i;
219         for (i = map.begin(); i != map.end(); ++i)
220         {
221             if (i->optionType == settings.optionType_)
222             {
223                 fileType_ = i->fileType;
224                 break;
225             }
226         }
227     }
228     FileTypeHandler typeHandler(fileType_);
229     if (settings.defaultType_ >= 0 && settings.defaultType_ < efNR)
230     {
231         // This also assures that the default type is not a generic type.
232         GMX_RELEASE_ASSERT(typeHandler.isValidType(settings.defaultType_),
233                            "Default type for a file option is not an accepted "
234                            "type for the option");
235         FileTypeHandler defaultHandler(settings.defaultType_);
236         defaultExtension_ = defaultHandler.extension(0);
237     }
238     else if (typeHandler.extensionCount() > 0)
239     {
240         defaultExtension_ = typeHandler.extension(0);
241     }
242     if (settings.defaultBasename_ != NULL)
243     {
244         std::string defaultValue(settings.defaultBasename_);
245         int         type = fn2ftp(settings.defaultBasename_);
246         GMX_RELEASE_ASSERT(type == efNR || type == settings.defaultType_,
247                            "Default basename has an extension that does not "
248                            "match the default type");
249         if (type == efNR)
250         {
251             defaultValue.append(defaultExtension());
252         }
253         setDefaultValueIfSet(defaultValue);
254         if (isRequired() || settings.bLegacyOptionalBehavior_)
255         {
256             setDefaultValue(defaultValue);
257         }
258     }
259 }
260
261 std::string FileNameOptionStorage::typeString() const
262 {
263     FileTypeHandler typeHandler(fileType_);
264     std::string     result;
265     int             count;
266     for (count = 0; count < 2 && count < typeHandler.extensionCount(); ++count)
267     {
268         if (count > 0)
269         {
270             result.append("/");
271         }
272         result.append(typeHandler.extension(count));
273     }
274     if (count < typeHandler.extensionCount())
275     {
276         result.append("/...");
277     }
278     if (result.empty())
279     {
280         if (isDirectoryOption())
281         {
282             result = "dir";
283         }
284         else
285         {
286             result = "file";
287         }
288     }
289     return result;
290 }
291
292 std::string FileNameOptionStorage::formatExtraDescription() const
293 {
294     FileTypeHandler typeHandler(fileType_);
295     std::string     result;
296     if (typeHandler.extensionCount() > 2)
297     {
298         result.append(":");
299         for (int i = 0; i < typeHandler.extensionCount(); ++i)
300         {
301             result.append(" [REF]");
302             // Skip the dot.
303             result.append(typeHandler.extension(i) + 1);
304             result.append("[ref]");
305         }
306     }
307     return result;
308 }
309
310 std::string FileNameOptionStorage::formatSingleValue(const std::string &value) const
311 {
312     return value;
313 }
314
315 void FileNameOptionStorage::convertValue(const std::string &value)
316 {
317     if (manager_ != NULL)
318     {
319         std::string processedValue = manager_->completeFileName(value, info_);
320         if (!processedValue.empty())
321         {
322             // If the manager returns a value, use it without further checks,
323             // except for sanity checking.
324             if (!isDirectoryOption())
325             {
326                 const int fileType = fn2ftp(processedValue.c_str());
327                 if (fileType == efNR)
328                 {
329                     // If the manager returned an invalid file name, assume
330                     // that it knows what it is doing.  But assert that it
331                     // only does that for the only case that it is currently
332                     // required for: VMD plugins.
333                     GMX_ASSERT(isInputFile() && isTrajectoryOption(),
334                                "Manager returned an invalid file name");
335                 }
336                 else
337                 {
338                     GMX_ASSERT(isValidType(fileType),
339                                "Manager returned an invalid file name");
340                 }
341             }
342             addValue(processedValue);
343             return;
344         }
345     }
346     // Currently, directory options are simple, and don't need any
347     // special processing.
348     // TODO: Consider splitting them into a separate DirectoryOption.
349     if (isDirectoryOption())
350     {
351         addValue(value);
352         return;
353     }
354     const int fileType = fn2ftp(value.c_str());
355     if (fileType == efNR)
356     {
357         std::string message
358             = formatString("File '%s' cannot be used by GROMACS because it "
359                            "does not have a recognizable extension.\n"
360                            "The following extensions are possible for this option:\n  %s",
361                            value.c_str(), joinStrings(extensions(), ", ").c_str());
362         GMX_THROW(InvalidInputError(message));
363     }
364     else if (!isValidType(fileType))
365     {
366         std::string message
367             = formatString("File name '%s' cannot be used for this option.\n"
368                            "Only the following extensions are possible:\n  %s",
369                            value.c_str(), joinStrings(extensions(), ", ").c_str());
370         GMX_THROW(InvalidInputError(message));
371     }
372     addValue(value);
373 }
374
375 void FileNameOptionStorage::processAll()
376 {
377     if (manager_ != NULL && hasFlag(efOption_HasDefaultValue))
378     {
379         ValueList &valueList = values();
380         GMX_RELEASE_ASSERT(valueList.size() == 1,
381                            "There should be only one default value");
382         if (!valueList[0].empty())
383         {
384             const std::string &oldValue = valueList[0];
385             GMX_ASSERT(endsWith(oldValue, defaultExtension()),
386                        "Default value does not have the expected extension");
387             const std::string  prefix
388                 = stripSuffixIfPresent(oldValue, defaultExtension());
389             const std::string  newValue
390                 = manager_->completeDefaultFileName(prefix, info_);
391             if (!newValue.empty() && newValue != oldValue)
392             {
393                 GMX_ASSERT(isValidType(fn2ftp(newValue.c_str())),
394                            "Manager returned an invalid default value");
395                 valueList[0] = newValue;
396                 refreshValues();
397             }
398         }
399     }
400 }
401
402 bool FileNameOptionStorage::isDirectoryOption() const
403 {
404     return fileType_ == efRND;
405 }
406
407 bool FileNameOptionStorage::isTrajectoryOption() const
408 {
409     return fileType_ == efTRX;
410 }
411
412 const char *FileNameOptionStorage::defaultExtension() const
413 {
414     return defaultExtension_;
415 }
416
417 std::vector<const char *> FileNameOptionStorage::extensions() const
418 {
419     FileTypeHandler           typeHandler(fileType_);
420     std::vector<const char *> result;
421     result.reserve(typeHandler.extensionCount());
422     for (int i = 0; i < typeHandler.extensionCount(); ++i)
423     {
424         result.push_back(typeHandler.extension(i));
425     }
426     return result;
427 }
428
429 bool FileNameOptionStorage::isValidType(int fileType) const
430 {
431     FileTypeHandler typeHandler(fileType_);
432     return typeHandler.isValidType(fileType);
433 }
434
435 ConstArrayRef<int> FileNameOptionStorage::fileTypes() const
436 {
437     if (fileType_ < 0)
438     {
439         return ConstArrayRef<int>();
440     }
441     const int genericTypeCount = ftp2generic_count(fileType_);
442     if (genericTypeCount > 0)
443     {
444         return constArrayRefFromArray<int>(ftp2generic_list(fileType_), genericTypeCount);
445     }
446     return constArrayRefFromArray<int>(&fileType_, 1);
447 }
448
449 /********************************************************************
450  * FileNameOptionInfo
451  */
452
453 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage *option)
454     : OptionInfo(option)
455 {
456 }
457
458 const FileNameOptionStorage &FileNameOptionInfo::option() const
459 {
460     return static_cast<const FileNameOptionStorage &>(OptionInfo::option());
461 }
462
463 bool FileNameOptionInfo::isInputFile() const
464 {
465     return option().isInputFile();
466 }
467
468 bool FileNameOptionInfo::isOutputFile() const
469 {
470     return option().isOutputFile();
471 }
472
473 bool FileNameOptionInfo::isInputOutputFile() const
474 {
475     return option().isInputOutputFile();
476 }
477
478 bool FileNameOptionInfo::isLibraryFile() const
479 {
480     return option().isLibraryFile();
481 }
482
483 bool FileNameOptionInfo::allowMissing() const
484 {
485     return option().allowMissing();
486 }
487
488 bool FileNameOptionInfo::isDirectoryOption() const
489 {
490     return option().isDirectoryOption();
491 }
492
493 bool FileNameOptionInfo::isTrajectoryOption() const
494 {
495     return option().isTrajectoryOption();
496 }
497
498 const char *FileNameOptionInfo::defaultExtension() const
499 {
500     return option().defaultExtension();
501 }
502
503 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
504 {
505     return option().extensions();
506 }
507
508 bool FileNameOptionInfo::isValidType(int fileType) const
509 {
510     return option().isValidType(fileType);
511 }
512
513 ConstArrayRef<int> FileNameOptionInfo::fileTypes() const
514 {
515     return option().fileTypes();
516 }
517
518 /********************************************************************
519  * FileNameOption
520  */
521
522 AbstractOptionStorage *
523 FileNameOption::createStorage(const OptionManagerContainer &managers) const
524 {
525     return new FileNameOptionStorage(*this, managers.get<FileNameOptionManager>());
526 }
527
528 } // namespace gmx