2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
38 * Implements classes in filenameoption.h and filenameoptionstorage.h.
40 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_options
45 #include "filenameoption.h"
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"
60 #include "filenameoptionstorage.h"
68 //! \addtogroup module_options
72 * Mapping from OptionFileType to a file type in filetypes.h.
74 struct FileTypeMapping
76 //! OptionFileType value to map.
77 OptionFileType optionType;
78 //! Corresponding file type from filetypes.h.
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 } };
88 /********************************************************************
94 * Handles a single file type known to FileNameOptionStorage.
96 * Methods in this class do not throw, except for a possible std::bad_alloc
97 * when constructing std::string return values.
103 * Returns a handler for a single file type.
105 * \param[in] fileType File type (from filetypes.h) to use.
107 explicit FileTypeHandler(int fileType);
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;
114 //! Returns whether \p fileType (from filetypes.h) is accepted for this type.
115 bool isValidType(int fileType) const;
119 * File type (from filetypes.h) represented by this handler.
121 * -1 represents an unknown file type.
124 //! Number of different extensions this type supports.
127 * List of simple file types that are included in this type.
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.
135 const int* genericTypes_;
138 FileTypeHandler::FileTypeHandler(int fileType) :
141 genericTypes_(nullptr)
145 const int genericTypeCount = ftp2generic_count(fileType_);
146 if (genericTypeCount > 0)
148 extensionCount_ = genericTypeCount;
149 genericTypes_ = ftp2generic_list(fileType_);
151 else if (ftp2ext_with_dot(fileType_)[0] != '\0')
158 int FileTypeHandler::extensionCount() const
160 return extensionCount_;
163 const char* FileTypeHandler::extension(int i) const
165 GMX_ASSERT(i >= 0 && i < extensionCount_, "Invalid extension index");
166 if (genericTypes_ != nullptr)
168 return ftp2ext_with_dot(genericTypes_[i]);
170 return ftp2ext_with_dot(fileType_);
173 bool FileTypeHandler::isValidType(int fileType) const
175 if (genericTypes_ != nullptr)
177 for (int i = 0; i < extensionCount(); ++i)
179 if (fileType == genericTypes_[i])
188 return fileType == fileType_;
196 /********************************************************************
197 * FileNameOptionStorage
200 FileNameOptionStorage::FileNameOptionStorage(const FileNameOption& settings, FileNameOptionManager* manager) :
205 defaultExtension_(""),
206 bRead_(settings.bRead_),
207 bWrite_(settings.bWrite_),
208 bLibrary_(settings.bLibrary_),
209 bAllowMissing_(settings.bAllowMissing_)
211 GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
212 "allowMultiple() is not supported for file name options");
213 if (settings.optionType_ == eftUnknown && settings.legacyType_ >= 0)
215 fileType_ = settings.legacyType_;
219 ArrayRef<const FileTypeMapping> map(c_fileTypeMapping);
220 ArrayRef<const FileTypeMapping>::const_iterator i;
221 for (i = map.begin(); i != map.end(); ++i)
223 if (i->optionType == settings.optionType_)
225 fileType_ = i->fileType;
230 FileTypeHandler typeHandler(fileType_);
231 if (settings.defaultType_ >= 0 && settings.defaultType_ < efNR)
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);
240 else if (typeHandler.extensionCount() > 0)
242 defaultExtension_ = typeHandler.extension(0);
244 if (settings.defaultBasename_ != nullptr)
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");
253 defaultValue.append(defaultExtension());
255 setDefaultValueIfSet(defaultValue);
256 if (isRequired() || settings.bLegacyOptionalBehavior_)
258 setDefaultValue(defaultValue);
263 std::string FileNameOptionStorage::typeString() const
265 FileTypeHandler typeHandler(fileType_);
268 for (count = 0; count < 2 && count < typeHandler.extensionCount(); ++count)
274 result.append(typeHandler.extension(count));
276 if (count < typeHandler.extensionCount())
278 result.append("/...");
282 if (isDirectoryOption())
294 std::string FileNameOptionStorage::formatExtraDescription() const
296 FileTypeHandler typeHandler(fileType_);
298 if (typeHandler.extensionCount() > 2)
301 for (int i = 0; i < typeHandler.extensionCount(); ++i)
303 result.append(" [REF]");
305 result.append(typeHandler.extension(i) + 1);
306 result.append("[ref]");
312 std::string FileNameOptionStorage::formatSingleValue(const std::string& value) const
317 void FileNameOptionStorage::initConverter(ConverterType* /*converter*/) {}
319 std::string FileNameOptionStorage::processValue(const std::string& value) const
321 if (manager_ != nullptr)
323 std::string processedValue = manager_->completeFileName(value, info_);
324 if (!processedValue.empty())
326 // If the manager returns a value, use it without further checks,
327 // except for sanity checking.
328 if (!isDirectoryOption())
330 const int fileType = fn2ftp(processedValue.c_str());
331 if (fileType == efNR)
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");
342 GMX_ASSERT(isValidType(fileType), "Manager returned an invalid file name");
345 return processedValue;
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())
355 const int fileType = fn2ftp(value.c_str());
356 if (fileType == efNR)
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));
365 else if (!isValidType(fileType))
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));
376 void FileNameOptionStorage::processAll()
378 if (manager_ != nullptr && hasFlag(efOption_HasDefaultValue))
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())
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)
391 GMX_ASSERT(isValidType(fn2ftp(newValue.c_str())),
392 "Manager returned an invalid default value");
393 valueList[0] = newValue;
399 bool FileNameOptionStorage::isDirectoryOption() const
401 return fileType_ == efRND;
404 bool FileNameOptionStorage::isTrajectoryOption() const
406 return fileType_ == efTRX;
409 const char* FileNameOptionStorage::defaultExtension() const
411 return defaultExtension_;
414 std::vector<const char*> FileNameOptionStorage::extensions() const
416 FileTypeHandler typeHandler(fileType_);
417 std::vector<const char*> result;
418 result.reserve(typeHandler.extensionCount());
419 for (int i = 0; i < typeHandler.extensionCount(); ++i)
421 result.push_back(typeHandler.extension(i));
426 bool FileNameOptionStorage::isValidType(int fileType) const
428 FileTypeHandler typeHandler(fileType_);
429 return typeHandler.isValidType(fileType);
432 ArrayRef<const int> FileNameOptionStorage::fileTypes() const
436 return ArrayRef<const int>();
438 const int genericTypeCount = ftp2generic_count(fileType_);
439 if (genericTypeCount > 0)
441 return constArrayRefFromArray<int>(ftp2generic_list(fileType_), genericTypeCount);
443 return constArrayRefFromArray<int>(&fileType_, 1);
446 /********************************************************************
450 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage* option) : OptionInfo(option) {}
452 const FileNameOptionStorage& FileNameOptionInfo::option() const
454 return static_cast<const FileNameOptionStorage&>(OptionInfo::option());
457 bool FileNameOptionInfo::isInputFile() const
459 return option().isInputFile();
462 bool FileNameOptionInfo::isOutputFile() const
464 return option().isOutputFile();
467 bool FileNameOptionInfo::isInputOutputFile() const
469 return option().isInputOutputFile();
472 bool FileNameOptionInfo::isLibraryFile() const
474 return option().isLibraryFile();
477 bool FileNameOptionInfo::allowMissing() const
479 return option().allowMissing();
482 bool FileNameOptionInfo::isDirectoryOption() const
484 return option().isDirectoryOption();
487 bool FileNameOptionInfo::isTrajectoryOption() const
489 return option().isTrajectoryOption();
492 const char* FileNameOptionInfo::defaultExtension() const
494 return option().defaultExtension();
497 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
499 return option().extensions();
502 bool FileNameOptionInfo::isValidType(int fileType) const
504 return option().isValidType(fileType);
507 ArrayRef<const int> FileNameOptionInfo::fileTypes() const
509 return option().fileTypes();
512 /********************************************************************
516 AbstractOptionStorage* FileNameOption::createStorage(const OptionManagerContainer& managers) const
518 return new FileNameOptionStorage(*this, managers.get<FileNameOptionManager>());