8c06ea6887f20c904a2fc0fe292d9c883785ddcf
[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 "filenameoption.h"
43 #include "filenameoptionstorage.h"
44
45 #include <cstring>
46
47 #include <string>
48 #include <vector>
49
50 #include "gromacs/fileio/filenm.h"
51 #include "gromacs/options/filenameoptionmanager.h"
52 #include "gromacs/options/optionmanagercontainer.h"
53 #include "gromacs/utility/arrayref.h"
54 #include "gromacs/utility/exceptions.h"
55 #include "gromacs/utility/gmxassert.h"
56 #include "gromacs/utility/stringutil.h"
57
58 namespace gmx
59 {
60
61 namespace
62 {
63
64 //! \addtogroup module_options
65 //! \{
66
67 /*! \brief
68  * Mapping from OptionFileType to a file type in filenm.h.
69  */
70 struct FileTypeMapping
71 {
72     //! OptionFileType value to map.
73     OptionFileType optionType;
74     //! Corresponding file type from filenm.h.
75     int            fileType;
76 };
77
78 //! Mappings from OptionFileType to file types in filenm.h.
79 const FileTypeMapping c_fileTypeMapping[] =
80 {
81     { eftTopology,    efTPS },
82     { eftTrajectory,  efTRX },
83     { eftPDB,         efPDB },
84     { eftIndex,       efNDX },
85     { eftPlot,        efXVG },
86     { eftGenericData, efDAT }
87 };
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 filenm.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 filenm.h) is accepted for this type.
116         bool isValidType(int fileType) const;
117
118     private:
119         /*! \brief
120          * File type (from filenm.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 filenm.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), extensionCount_(0), genericTypes_(NULL)
141 {
142     if (fileType_ >= 0)
143     {
144         const int genericTypeCount = ftp2generic_count(fileType_);
145         if (genericTypeCount > 0)
146         {
147             extensionCount_ = genericTypeCount;
148             genericTypes_   = ftp2generic_list(fileType_);
149         }
150         else if (ftp2ext_with_dot(fileType_)[0] != '\0')
151         {
152             extensionCount_ = 1;
153         }
154     }
155 }
156
157 int FileTypeHandler::extensionCount() const
158 {
159     return extensionCount_;
160 }
161
162 const char *FileTypeHandler::extension(int i) const
163 {
164     GMX_ASSERT(i >= 0 && i < extensionCount_, "Invalid extension index");
165     if (genericTypes_ != NULL)
166     {
167         return ftp2ext_with_dot(genericTypes_[i]);
168     }
169     return ftp2ext_with_dot(fileType_);
170 }
171
172 bool
173 FileTypeHandler::isValidType(int fileType) const
174 {
175     if (genericTypes_ != NULL)
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,
201                                              FileNameOptionManager *manager)
202     : MyBase(settings), info_(this), manager_(manager), fileType_(-1),
203       bRead_(settings.bRead_), bWrite_(settings.bWrite_),
204       bLibrary_(settings.bLibrary_)
205 {
206     GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
207                        "allowMultiple() is not supported for file name options");
208     if (settings.optionType_ == eftUnknown && settings.legacyType_ >= 0)
209     {
210         fileType_ = settings.legacyType_;
211     }
212     else
213     {
214         ConstArrayRef<FileTypeMapping>                 map(c_fileTypeMapping);
215         ConstArrayRef<FileTypeMapping>::const_iterator i;
216         for (i = map.begin(); i != map.end(); ++i)
217         {
218             if (i->optionType == settings.optionType_)
219             {
220                 fileType_ = i->fileType;
221                 break;
222             }
223         }
224     }
225     if (settings.defaultBasename_ != NULL)
226     {
227         std::string defaultValue(settings.defaultBasename_);
228         defaultValue.append(defaultExtension());
229         setDefaultValueIfSet(defaultValue);
230         if (isRequired() || settings.bLegacyOptionalBehavior_)
231         {
232             setDefaultValue(defaultValue);
233         }
234     }
235 }
236
237 std::string FileNameOptionStorage::typeString() const
238 {
239     FileTypeHandler typeHandler(fileType_);
240     std::string     result;
241     int             count;
242     for (count = 0; count < 2 && count < typeHandler.extensionCount(); ++count)
243     {
244         if (count > 0)
245         {
246             result.append("/");
247         }
248         result.append(typeHandler.extension(count));
249     }
250     if (count < typeHandler.extensionCount())
251     {
252         result.append("/...");
253     }
254     if (result.empty())
255     {
256         if (isDirectoryOption())
257         {
258             result = "dir";
259         }
260         else
261         {
262             result = "file";
263         }
264     }
265     return result;
266 }
267
268 std::string FileNameOptionStorage::formatExtraDescription() const
269 {
270     FileTypeHandler typeHandler(fileType_);
271     std::string     result;
272     if (typeHandler.extensionCount() > 2)
273     {
274         result.append(":");
275         for (int i = 0; i < typeHandler.extensionCount(); ++i)
276         {
277             result.append(" ");
278             // Skip the dot.
279             result.append(typeHandler.extension(i) + 1);
280         }
281     }
282     return result;
283 }
284
285 std::string FileNameOptionStorage::formatSingleValue(const std::string &value) const
286 {
287     return value;
288 }
289
290 void FileNameOptionStorage::convertValue(const std::string &value)
291 {
292     if (manager_ != NULL)
293     {
294         std::string processedValue = manager_->completeFileName(value, info_);
295         if (!processedValue.empty())
296         {
297             // If the manager returns a value, use it without further checks,
298             // except for sanity checking.
299             if (!isDirectoryOption())
300             {
301                 const int fileType = fn2ftp(processedValue.c_str());
302                 if (fileType == efNR)
303                 {
304                     // If the manager returned an invalid file name, assume
305                     // that it knows what it is doing.  But assert that it
306                     // only does that for the only case that it is currently
307                     // required for: VMD plugins.
308                     GMX_ASSERT(isInputFile() && isTrajectoryOption(),
309                                "Manager returned an invalid file name");
310                 }
311                 else
312                 {
313                     GMX_ASSERT(isValidType(fileType),
314                                "Manager returned an invalid file name");
315                 }
316             }
317             addValue(processedValue);
318             return;
319         }
320     }
321     // Currently, directory options are simple, and don't need any
322     // special processing.
323     // TODO: Consider splitting them into a separate DirectoryOption.
324     if (isDirectoryOption())
325     {
326         addValue(value);
327         return;
328     }
329     const int fileType = fn2ftp(value.c_str());
330     if (fileType == efNR)
331     {
332         std::string message
333             = formatString("File '%s' cannot be used by GROMACS because it "
334                            "does not have a recognizable extension.\n"
335                            "The following extensions are possible for this option:\n  %s",
336                            value.c_str(), joinStrings(extensions(), ", ").c_str());
337         GMX_THROW(InvalidInputError(message));
338     }
339     else if (!isValidType(fileType))
340     {
341         std::string message
342             = formatString("File name '%s' cannot be used for this option.\n"
343                            "Only the following extensions are possible:\n  %s",
344                            value.c_str(), joinStrings(extensions(), ", ").c_str());
345         GMX_THROW(InvalidInputError(message));
346     }
347     addValue(value);
348 }
349
350 void FileNameOptionStorage::processAll()
351 {
352     if (manager_ != NULL && hasFlag(efOption_HasDefaultValue))
353     {
354         ValueList &valueList = values();
355         GMX_RELEASE_ASSERT(valueList.size() == 1,
356                            "There should be only one default value");
357         if (!valueList[0].empty())
358         {
359             const std::string &oldValue = valueList[0];
360             GMX_ASSERT(endsWith(oldValue, defaultExtension()),
361                        "Default value does not have the expected extension");
362             const std::string  prefix
363                 = stripSuffixIfPresent(oldValue, defaultExtension());
364             const std::string  newValue
365                 = manager_->completeDefaultFileName(prefix, info_);
366             if (!newValue.empty() && newValue != oldValue)
367             {
368                 GMX_ASSERT(isValidType(fn2ftp(newValue.c_str())),
369                            "Manager returned an invalid default value");
370                 valueList[0] = newValue;
371                 refreshValues();
372             }
373         }
374     }
375 }
376
377 bool FileNameOptionStorage::isDirectoryOption() const
378 {
379     return fileType_ == efRND;
380 }
381
382 bool FileNameOptionStorage::isTrajectoryOption() const
383 {
384     return fileType_ == efTRX;
385 }
386
387 const char *FileNameOptionStorage::defaultExtension() const
388 {
389     FileTypeHandler typeHandler(fileType_);
390     if (typeHandler.extensionCount() == 0)
391     {
392         return "";
393     }
394     return typeHandler.extension(0);
395 }
396
397 std::vector<const char *> FileNameOptionStorage::extensions() const
398 {
399     FileTypeHandler           typeHandler(fileType_);
400     std::vector<const char *> result;
401     result.reserve(typeHandler.extensionCount());
402     for (int i = 0; i < typeHandler.extensionCount(); ++i)
403     {
404         result.push_back(typeHandler.extension(i));
405     }
406     return result;
407 }
408
409 bool FileNameOptionStorage::isValidType(int fileType) const
410 {
411     FileTypeHandler typeHandler(fileType_);
412     return typeHandler.isValidType(fileType);
413 }
414
415 ConstArrayRef<int> FileNameOptionStorage::fileTypes() const
416 {
417     if (fileType_ < 0)
418     {
419         return ConstArrayRef<int>();
420     }
421     const int genericTypeCount = ftp2generic_count(fileType_);
422     if (genericTypeCount > 0)
423     {
424         return constArrayRefFromArray<int>(ftp2generic_list(fileType_), genericTypeCount);
425     }
426     return constArrayRefFromArray<int>(&fileType_, 1);
427 }
428
429 /********************************************************************
430  * FileNameOptionInfo
431  */
432
433 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage *option)
434     : OptionInfo(option)
435 {
436 }
437
438 const FileNameOptionStorage &FileNameOptionInfo::option() const
439 {
440     return static_cast<const FileNameOptionStorage &>(OptionInfo::option());
441 }
442
443 bool FileNameOptionInfo::isInputFile() const
444 {
445     return option().isInputFile();
446 }
447
448 bool FileNameOptionInfo::isOutputFile() const
449 {
450     return option().isOutputFile();
451 }
452
453 bool FileNameOptionInfo::isInputOutputFile() const
454 {
455     return option().isInputOutputFile();
456 }
457
458 bool FileNameOptionInfo::isLibraryFile() const
459 {
460     return option().isLibraryFile();
461 }
462
463 bool FileNameOptionInfo::isDirectoryOption() const
464 {
465     return option().isDirectoryOption();
466 }
467
468 bool FileNameOptionInfo::isTrajectoryOption() const
469 {
470     return option().isTrajectoryOption();
471 }
472
473 const char *FileNameOptionInfo::defaultExtension() const
474 {
475     return option().defaultExtension();
476 }
477
478 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
479 {
480     return option().extensions();
481 }
482
483 bool FileNameOptionInfo::isValidType(int fileType) const
484 {
485     return option().isValidType(fileType);
486 }
487
488 ConstArrayRef<int> FileNameOptionInfo::fileTypes() const
489 {
490     return option().fileTypes();
491 }
492
493 /********************************************************************
494  * FileNameOption
495  */
496
497 AbstractOptionStorage *
498 FileNameOption::createStorage(const OptionManagerContainer &managers) const
499 {
500     return new FileNameOptionStorage(*this, managers.get<FileNameOptionManager>());
501 }
502
503 } // namespace gmx