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