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