9df3722459ea383fae4194513bd7b66b089c2182
[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,2016 by the GROMACS development team.
5  * Copyright (c) 2017,2019,2020, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements classes in filenameoption.h and filenameoptionstorage.h.
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \ingroup module_options
42  */
43 #include "gmxpre.h"
44
45 #include "filenameoption.h"
46
47 #include <cstring>
48
49 #include <string>
50 #include <vector>
51
52 #include "gromacs/fileio/filetypes.h"
53 #include "gromacs/options/filenameoptionmanager.h"
54 #include "gromacs/options/optionmanagercontainer.h"
55 #include "gromacs/utility/arrayref.h"
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/gmxassert.h"
58 #include "gromacs/utility/stringutil.h"
59
60 #include "filenameoptionstorage.h"
61
62 namespace gmx
63 {
64
65 namespace
66 {
67
68 //! \addtogroup module_options
69 //! \{
70
71 /*! \brief
72  * Mapping from OptionFileType to a file type in filetypes.h.
73  */
74 struct FileTypeMapping
75 {
76     //! OptionFileType value to map.
77     OptionFileType optionType;
78     //! Corresponding file type from filetypes.h.
79     int fileType;
80 };
81
82 //! Mappings from OptionFileType to file types in filetypes.h.
83 const FileTypeMapping c_fileTypeMapping[] = { { eftTopology, efTPS },   { eftRunInput, efTPR },
84                                               { eftTrajectory, efTRX }, { eftEnergy, efEDR },
85                                               { eftPDB, efPDB },        { eftIndex, efNDX },
86                                               { eftPlot, efXVG },       { eftGenericData, efDAT },
87                                               { eftCsv, efCSV } };
88
89 /********************************************************************
90  * FileTypeHandler
91  */
92
93 /*! \internal
94  * \brief
95  * Handles a single file type known to FileNameOptionStorage.
96  *
97  * Methods in this class do not throw, except for a possible std::bad_alloc
98  * when constructing std::string return values.
99  */
100 class FileTypeHandler
101 {
102 public:
103     /*! \brief
104      * Returns a handler for a single file type.
105      *
106      * \param[in] fileType  File type (from filetypes.h) to use.
107      */
108     explicit FileTypeHandler(int fileType);
109
110     //! Returns the number of acceptable extensions for this file type.
111     int extensionCount() const;
112     //! Returns the extension with the given index.
113     const char* extension(int i) const;
114
115     //! Returns whether \p fileType (from filetypes.h) is accepted for this type.
116     bool isValidType(int fileType) const;
117
118 private:
119     /*! \brief
120      * File type (from filetypes.h) represented by this handler.
121      *
122      * -1 represents an unknown file type.
123      */
124     int fileType_;
125     //! Number of different extensions this type supports.
126     int extensionCount_;
127     /*! \brief
128      * List of simple file types that are included in this type.
129      *
130      * If `fileType_` represents a generic type in filetypes.h, i.e., a type
131      * that accepts multiple different types of files, then this is an
132      * array of `extensionCount_` elements, each element specifying one
133      * non-generic file type that this option accepts.
134      * `NULL` for single-extension types.
135      */
136     const int* genericTypes_;
137 };
138
139 FileTypeHandler::FileTypeHandler(int fileType) :
140     fileType_(fileType),
141     extensionCount_(0),
142     genericTypes_(nullptr)
143 {
144     if (fileType_ >= 0)
145     {
146         const int genericTypeCount = ftp2generic_count(fileType_);
147         if (genericTypeCount > 0)
148         {
149             extensionCount_ = genericTypeCount;
150             genericTypes_   = ftp2generic_list(fileType_);
151         }
152         else if (ftp2ext_with_dot(fileType_)[0] != '\0')
153         {
154             extensionCount_ = 1;
155         }
156     }
157 }
158
159 int FileTypeHandler::extensionCount() const
160 {
161     return extensionCount_;
162 }
163
164 const char* FileTypeHandler::extension(int i) const
165 {
166     GMX_ASSERT(i >= 0 && i < extensionCount_, "Invalid extension index");
167     if (genericTypes_ != nullptr)
168     {
169         return ftp2ext_with_dot(genericTypes_[i]);
170     }
171     return ftp2ext_with_dot(fileType_);
172 }
173
174 bool FileTypeHandler::isValidType(int fileType) const
175 {
176     if (genericTypes_ != nullptr)
177     {
178         for (int i = 0; i < extensionCount(); ++i)
179         {
180             if (fileType == genericTypes_[i])
181             {
182                 return true;
183             }
184         }
185         return false;
186     }
187     else
188     {
189         return fileType == fileType_;
190     }
191 }
192
193 //! \}
194
195 } // namespace
196
197 /********************************************************************
198  * FileNameOptionStorage
199  */
200
201 FileNameOptionStorage::FileNameOptionStorage(const FileNameOption& settings, FileNameOptionManager* manager) :
202     MyBase(settings),
203     info_(this),
204     manager_(manager),
205     fileType_(-1),
206     defaultExtension_(""),
207     bRead_(settings.bRead_),
208     bWrite_(settings.bWrite_),
209     bLibrary_(settings.bLibrary_),
210     bAllowMissing_(settings.bAllowMissing_)
211 {
212     GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
213                        "allowMultiple() is not supported for file name options");
214     if (settings.optionType_ == eftUnknown && settings.legacyType_ >= 0)
215     {
216         fileType_ = settings.legacyType_;
217     }
218     else
219     {
220         ArrayRef<const FileTypeMapping>                 map(c_fileTypeMapping);
221         ArrayRef<const FileTypeMapping>::const_iterator i;
222         for (i = map.begin(); i != map.end(); ++i)
223         {
224             if (i->optionType == settings.optionType_)
225             {
226                 fileType_ = i->fileType;
227                 break;
228             }
229         }
230     }
231     FileTypeHandler typeHandler(fileType_);
232     if (settings.defaultType_ >= 0 && settings.defaultType_ < efNR)
233     {
234         // This also assures that the default type is not a generic type.
235         GMX_RELEASE_ASSERT(typeHandler.isValidType(settings.defaultType_),
236                            "Default type for a file option is not an accepted "
237                            "type for the option");
238         FileTypeHandler defaultHandler(settings.defaultType_);
239         defaultExtension_ = defaultHandler.extension(0);
240     }
241     else if (typeHandler.extensionCount() > 0)
242     {
243         defaultExtension_ = typeHandler.extension(0);
244     }
245     if (settings.defaultBasename_ != nullptr)
246     {
247         std::string defaultValue(settings.defaultBasename_);
248         int         type = fn2ftp(settings.defaultBasename_);
249         GMX_RELEASE_ASSERT(type == efNR || type == settings.defaultType_,
250                            "Default basename has an extension that does not "
251                            "match the default type");
252         if (type == efNR)
253         {
254             defaultValue.append(defaultExtension());
255         }
256         setDefaultValueIfSet(defaultValue);
257         if (isRequired() || settings.bLegacyOptionalBehavior_)
258         {
259             setDefaultValue(defaultValue);
260         }
261     }
262 }
263
264 std::string FileNameOptionStorage::typeString() const
265 {
266     FileTypeHandler typeHandler(fileType_);
267     std::string     result;
268     int             count;
269     for (count = 0; count < 2 && count < typeHandler.extensionCount(); ++count)
270     {
271         if (count > 0)
272         {
273             result.append("/");
274         }
275         result.append(typeHandler.extension(count));
276     }
277     if (count < typeHandler.extensionCount())
278     {
279         result.append("/...");
280     }
281     if (result.empty())
282     {
283         if (isDirectoryOption())
284         {
285             result = "dir";
286         }
287         else
288         {
289             result = "file";
290         }
291     }
292     return result;
293 }
294
295 std::string FileNameOptionStorage::formatExtraDescription() const
296 {
297     FileTypeHandler typeHandler(fileType_);
298     std::string     result;
299     if (typeHandler.extensionCount() > 2)
300     {
301         result.append(":");
302         for (int i = 0; i < typeHandler.extensionCount(); ++i)
303         {
304             result.append(" [REF]");
305             // Skip the dot.
306             result.append(typeHandler.extension(i) + 1);
307             result.append("[ref]");
308         }
309     }
310     return result;
311 }
312
313 std::string FileNameOptionStorage::formatSingleValue(const std::string& value) const
314 {
315     return value;
316 }
317
318 void FileNameOptionStorage::initConverter(ConverterType* /*converter*/) {}
319
320 std::string FileNameOptionStorage::processValue(const std::string& value) const
321 {
322     if (manager_ != nullptr)
323     {
324         std::string processedValue = manager_->completeFileName(value, info_);
325         if (!processedValue.empty())
326         {
327             // If the manager returns a value, use it without further checks,
328             // except for sanity checking.
329             if (!isDirectoryOption())
330             {
331                 const int fileType = fn2ftp(processedValue.c_str());
332                 if (fileType == efNR)
333                 {
334                     // If the manager returned an invalid file name, assume
335                     // that it knows what it is doing.  But assert that it
336                     // only does that for the only case that it is currently
337                     // required for: VMD plugins.
338                     GMX_ASSERT(isInputFile() && isTrajectoryOption(),
339                                "Manager returned an invalid file name");
340                 }
341                 else
342                 {
343                     GMX_ASSERT(isValidType(fileType), "Manager returned an invalid file name");
344                 }
345             }
346             return processedValue;
347         }
348     }
349     // Currently, directory options are simple, and don't need any
350     // special processing.
351     // TODO: Consider splitting them into a separate DirectoryOption.
352     if (isDirectoryOption())
353     {
354         return value;
355     }
356     const int fileType = fn2ftp(value.c_str());
357     if (fileType == efNR)
358     {
359         std::string message = formatString(
360                 "File '%s' cannot be used by GROMACS because it "
361                 "does not have a recognizable extension.\n"
362                 "The following extensions are possible for this option:\n  %s",
363                 value.c_str(), joinStrings(extensions(), ", ").c_str());
364         GMX_THROW(InvalidInputError(message));
365     }
366     else if (!isValidType(fileType))
367     {
368         std::string message = formatString(
369                 "File name '%s' cannot be used for this option.\n"
370                 "Only the following extensions are possible:\n  %s",
371                 value.c_str(), joinStrings(extensions(), ", ").c_str());
372         GMX_THROW(InvalidInputError(message));
373     }
374     return value;
375 }
376
377 void FileNameOptionStorage::processAll()
378 {
379     if (manager_ != nullptr && hasFlag(efOption_HasDefaultValue))
380     {
381         ArrayRef<std::string> valueList = values();
382         GMX_RELEASE_ASSERT(valueList.size() == 1, "There should be only one default value");
383         if (!valueList[0].empty())
384         {
385             const std::string& oldValue = valueList[0];
386             GMX_ASSERT(endsWith(oldValue, defaultExtension()),
387                        "Default value does not have the expected extension");
388             const std::string prefix   = stripSuffixIfPresent(oldValue, defaultExtension());
389             const std::string newValue = manager_->completeDefaultFileName(prefix, info_);
390             if (!newValue.empty() && newValue != oldValue)
391             {
392                 GMX_ASSERT(isValidType(fn2ftp(newValue.c_str())),
393                            "Manager returned an invalid default value");
394                 valueList[0] = newValue;
395             }
396         }
397     }
398 }
399
400 bool FileNameOptionStorage::isDirectoryOption() const
401 {
402     return fileType_ == efRND;
403 }
404
405 bool FileNameOptionStorage::isTrajectoryOption() const
406 {
407     return fileType_ == efTRX;
408 }
409
410 const char* FileNameOptionStorage::defaultExtension() const
411 {
412     return defaultExtension_;
413 }
414
415 std::vector<const char*> FileNameOptionStorage::extensions() const
416 {
417     FileTypeHandler          typeHandler(fileType_);
418     std::vector<const char*> result;
419     result.reserve(typeHandler.extensionCount());
420     for (int i = 0; i < typeHandler.extensionCount(); ++i)
421     {
422         result.push_back(typeHandler.extension(i));
423     }
424     return result;
425 }
426
427 bool FileNameOptionStorage::isValidType(int fileType) const
428 {
429     FileTypeHandler typeHandler(fileType_);
430     return typeHandler.isValidType(fileType);
431 }
432
433 ArrayRef<const int> FileNameOptionStorage::fileTypes() const
434 {
435     if (fileType_ < 0)
436     {
437         return ArrayRef<const int>();
438     }
439     const int genericTypeCount = ftp2generic_count(fileType_);
440     if (genericTypeCount > 0)
441     {
442         return constArrayRefFromArray<int>(ftp2generic_list(fileType_), genericTypeCount);
443     }
444     return constArrayRefFromArray<int>(&fileType_, 1);
445 }
446
447 /********************************************************************
448  * FileNameOptionInfo
449  */
450
451 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage* option) : OptionInfo(option) {}
452
453 const FileNameOptionStorage& FileNameOptionInfo::option() const
454 {
455     return static_cast<const FileNameOptionStorage&>(OptionInfo::option());
456 }
457
458 bool FileNameOptionInfo::isInputFile() const
459 {
460     return option().isInputFile();
461 }
462
463 bool FileNameOptionInfo::isOutputFile() const
464 {
465     return option().isOutputFile();
466 }
467
468 bool FileNameOptionInfo::isInputOutputFile() const
469 {
470     return option().isInputOutputFile();
471 }
472
473 bool FileNameOptionInfo::isLibraryFile() const
474 {
475     return option().isLibraryFile();
476 }
477
478 bool FileNameOptionInfo::allowMissing() const
479 {
480     return option().allowMissing();
481 }
482
483 bool FileNameOptionInfo::isDirectoryOption() const
484 {
485     return option().isDirectoryOption();
486 }
487
488 bool FileNameOptionInfo::isTrajectoryOption() const
489 {
490     return option().isTrajectoryOption();
491 }
492
493 const char* FileNameOptionInfo::defaultExtension() const
494 {
495     return option().defaultExtension();
496 }
497
498 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
499 {
500     return option().extensions();
501 }
502
503 bool FileNameOptionInfo::isValidType(int fileType) const
504 {
505     return option().isValidType(fileType);
506 }
507
508 ArrayRef<const int> FileNameOptionInfo::fileTypes() const
509 {
510     return option().fileTypes();
511 }
512
513 /********************************************************************
514  * FileNameOption
515  */
516
517 AbstractOptionStorage* FileNameOption::createStorage(const OptionManagerContainer& managers) const
518 {
519     return new FileNameOptionStorage(*this, managers.get<FileNameOptionManager>());
520 }
521
522 } // namespace gmx