Use filenm.c data 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, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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 <string>
46 #include <vector>
47
48 #include "gromacs/legacyheaders/filenm.h"
49
50 #include "gromacs/utility/file.h"
51 #include "gromacs/utility/stringutil.h"
52
53 namespace gmx
54 {
55
56 namespace
57 {
58
59 class FileTypeRegistry;
60
61 /********************************************************************
62  * FileTypeHandler
63  */
64
65 /*! \internal \brief
66  * Handles a single file type known to FileNameOptionStorage.
67  *
68  * \ingroup module_options
69  */
70 class FileTypeHandler
71 {
72     public:
73         //! Returns whether \p filename has a valid extension for this type.
74         bool hasKnownExtension(const std::string &filename) const;
75         //! Adds a default extension for this type to \p filename.
76         std::string addExtension(const std::string &filename) const;
77         /*! \brief
78          * Adds an extension to \p filename if it results in an existing file.
79          *
80          * Tries to add each extension for this file type to \p filename and
81          * checks whether this results in an existing file.
82          * The first match is returned.
83          * Returns an empty string if no existing file is found.
84          */
85         std::string findFileWithExtension(const std::string &filename) const;
86
87     private:
88         //! Possible extensions for this file type.
89         std::vector<const char *> extensions_;
90
91         /*! \brief
92          * Needed for initialization; all initialization is handled by
93          * FileTypeRegistry.
94          */
95         friend class FileTypeRegistry;
96 };
97
98 bool
99 FileTypeHandler::hasKnownExtension(const std::string &filename) const
100 {
101     for (size_t i = 0; i < extensions_.size(); ++i)
102     {
103         if (endsWith(filename, extensions_[i]))
104         {
105             return true;
106         }
107     }
108     return false;
109 }
110
111 std::string
112 FileTypeHandler::addExtension(const std::string &filename) const
113 {
114     if (extensions_.empty())
115     {
116         return filename;
117     }
118     return filename + extensions_[0];
119 }
120
121 std::string
122 FileTypeHandler::findFileWithExtension(const std::string &filename) const
123 {
124     for (size_t i = 0; i < extensions_.size(); ++i)
125     {
126         std::string testFilename(filename + extensions_[i]);
127         if (File::exists(testFilename))
128         {
129             return testFilename;
130         }
131     }
132     return std::string();
133 }
134
135 /********************************************************************
136  * FileTypeRegistry
137  */
138
139 /*! \internal \brief
140  * Singleton for managing static file type info for FileNameOptionStorage.
141  *
142  * \ingroup module_options
143  */
144 class FileTypeRegistry
145 {
146     public:
147         //! Returns a singleton instance of this class.
148         static const FileTypeRegistry &instance();
149         //! Returns a handler for a single file type.
150         const FileTypeHandler &handlerForType(OptionFileType type) const;
151
152     private:
153         //! Initializes the file type registry.
154         FileTypeRegistry();
155
156         //! Registers a file type that corresponds to a ftp in filenm.h.
157         void registerType(OptionFileType type, int ftp);
158         //! Registers a file type with a single extension.
159         void registerType(OptionFileType type, const char *extension);
160
161         std::vector<FileTypeHandler> filetypes_;
162 };
163
164 // static
165 const FileTypeRegistry &
166 FileTypeRegistry::instance()
167 {
168     static FileTypeRegistry singleton;
169     return singleton;
170 }
171
172 const FileTypeHandler &
173 FileTypeRegistry::handlerForType(OptionFileType type) const
174 {
175     GMX_RELEASE_ASSERT(type >= 0 && static_cast<size_t>(type) < filetypes_.size(),
176                        "Invalid file type");
177     return filetypes_[type];
178 }
179
180 FileTypeRegistry::FileTypeRegistry()
181 {
182     filetypes_.resize(eftOptionFileType_NR);
183     registerType(eftTopology,    efTPS);
184     registerType(eftTrajectory,  efTRX);
185     registerType(eftPDB,         efPDB);
186     registerType(eftIndex,       efNDX);
187     registerType(eftPlot,        efXVG);
188     registerType(eftGenericData, efDAT);
189 }
190
191 void FileTypeRegistry::registerType(OptionFileType type, int ftp)
192 {
193     GMX_RELEASE_ASSERT(type >= 0 && static_cast<size_t>(type) < filetypes_.size(),
194                        "Invalid file type");
195     const int genericTypeCount = ftp2generic_count(ftp);
196     if (genericTypeCount > 0)
197     {
198         const int *const genericTypes = ftp2generic_list(ftp);
199         filetypes_[type].extensions_.clear();
200         filetypes_[type].extensions_.reserve(genericTypeCount);
201         for (int i = 0; i < genericTypeCount; ++i)
202         {
203             filetypes_[type].extensions_.push_back(ftp2ext_with_dot(genericTypes[i]));
204         }
205     }
206     else
207     {
208         registerType(type, ftp2ext_with_dot(ftp));
209     }
210 }
211
212 void FileTypeRegistry::registerType(OptionFileType type,
213                                     const char    *extension)
214 {
215     GMX_RELEASE_ASSERT(type >= 0 && static_cast<size_t>(type) < filetypes_.size(),
216                        "Invalid file type");
217     filetypes_[type].extensions_.assign(1, extension);
218 }
219
220 /*! \brief
221  * Helper method to complete a file name provided to a file name option.
222  *
223  * \param[in] value     Value provided to the file name option.
224  * \param[in] filetype  File type for the option.
225  * \param[in] bCompleteToExisting
226  *      Whether to check existing files when completing the extension.
227  * \returns   \p value with possible extension added.
228  */
229 std::string completeFileName(const std::string &value, OptionFileType filetype,
230                              bool bCompleteToExisting)
231 {
232     if (bCompleteToExisting && File::exists(value))
233     {
234         // TODO: This may not work as expected if the value is passed to a
235         // function that uses fn2ftp() to determine the file type and the input
236         // file has an unrecognized extension.
237         return value;
238     }
239     const FileTypeRegistry &registry    = FileTypeRegistry::instance();
240     const FileTypeHandler  &typeHandler = registry.handlerForType(filetype);
241     if (typeHandler.hasKnownExtension(value))
242     {
243         return value;
244     }
245     if (bCompleteToExisting)
246     {
247         std::string newValue = typeHandler.findFileWithExtension(value);
248         if (!newValue.empty())
249         {
250             return newValue;
251         }
252     }
253     return typeHandler.addExtension(value);
254 }
255
256 }   // namespace
257
258 /********************************************************************
259  * FileNameOptionStorage
260  */
261
262 FileNameOptionStorage::FileNameOptionStorage(const FileNameOption &settings)
263     : MyBase(settings), info_(this), filetype_(settings.filetype_),
264       bRead_(settings.bRead_), bWrite_(settings.bWrite_),
265       bLibrary_(settings.bLibrary_)
266 {
267     if (settings.defaultBasename_ != NULL)
268     {
269         if (isRequired())
270         {
271             setDefaultValue(completeFileName(settings.defaultBasename_,
272                                              filetype_, false));
273         }
274         else
275         {
276             setDefaultValueIfSet(completeFileName(settings.defaultBasename_,
277                                                   filetype_, false));
278         }
279     }
280 }
281
282 std::string FileNameOptionStorage::formatSingleValue(const std::string &value) const
283 {
284     return value;
285 }
286
287 void FileNameOptionStorage::convertValue(const std::string &value)
288 {
289     bool bInput = isInputFile() || isInputOutputFile();
290     addValue(completeFileName(value, filetype_, bInput));
291 }
292
293 /********************************************************************
294  * FileNameOptionInfo
295  */
296
297 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage *option)
298     : OptionInfo(option)
299 {
300 }
301
302 const FileNameOptionStorage &FileNameOptionInfo::option() const
303 {
304     return static_cast<const FileNameOptionStorage &>(OptionInfo::option());
305 }
306
307 bool FileNameOptionInfo::isInputFile() const
308 {
309     return option().isInputFile();
310 }
311
312 bool FileNameOptionInfo::isOutputFile() const
313 {
314     return option().isOutputFile();
315 }
316
317 bool FileNameOptionInfo::isInputOutputFile() const
318 {
319     return option().isInputOutputFile();
320 }
321
322 bool FileNameOptionInfo::isLibraryFile() const
323 {
324     return option().isLibraryFile();
325 }
326
327 /********************************************************************
328  * FileNameOption
329  */
330
331 AbstractOptionStoragePointer FileNameOption::createStorage() const
332 {
333     return AbstractOptionStoragePointer(new FileNameOptionStorage(*this));
334 }
335
336 } // namespace gmx