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