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