Debian Codegraph @

avogadro/qtgui/fileformatdialog.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "fileformatdialog.h"
7
8 #include <avogadro/core/molecule.h>
9 #include <avogadro/io/fileformatmanager.h>
10
11 #include <QtWidgets/QApplication>
12 #include <QtWidgets/QInputDialog>
13 #include <QtWidgets/QMessageBox>
14
15 #include <QtCore/QSettings>
16
17 #include <vector>
18
19 using Avogadro::Io::FileFormat;
20 using Avogadro::Io::FileFormatManager;
21 using std::vector;
22
23 namespace Avogadro::QtGui {
24
25 FileFormatDialog::FileFormatDialog(QWidget* parentW) : QFileDialog(parentW) {}
26
27 FileFormatDialog::~FileFormatDialog() {}
28
29 FileFormatDialog::FormatFilePair FileFormatDialog::fileToRead(
30 QWidget* parent, const QString& caption, const QString& dir,
31 const QString& filter)
32 {
33 FormatFilePair result(nullptr, QString());
34 // Use the default read filter if none specified:
35 const QString realFilter = filter.isEmpty() ? readFileFilter() : filter;
36
37 bool done = false;
38 do { // jump point for continue statements on retry
39 QString fileName =
40 QFileDialog::getOpenFileName(parent, caption, dir, realFilter);
41
42 if (fileName.isEmpty()) // user cancel
43 return result;
44
45 const Io::FileFormat* format = findFileFormat(
46 parent, caption, fileName, FileFormat::File | FileFormat::Read);
47
48 // If none found, give user the option to retry.
49 if (!format) {
50 QMessageBox::StandardButton reply = QMessageBox::question(
51 parent, caption,
52 tr("Unable to find a suitable file reader for "
53 "the selected file."),
54 QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);
55 switch (reply) {
56 default:
57 case QMessageBox::Retry:
58 continue;
59 case QMessageBox::Abort:
60 return result;
61 }
62 }
63
64 result.first = format;
65 result.second = fileName;
66 done = true;
67
68 } while (!done);
69
70 return result;
71 }
72
73 FileFormatDialog::FormatFilePair FileFormatDialog::fileToWrite(
74 QWidget* parentWidget, const QString& caption, const QString& dir,
75 const QString& filter)
76 {
77 FormatFilePair result(nullptr, QString());
78 // Use the default read filter if none specified:
79 const QString realFilter = filter.isEmpty() ? writeFileFilter() : filter;
80
81 QString fileName;
82 do { // jump point for continue statements on retry
83 fileName =
84 QFileDialog::getSaveFileName(parentWidget, caption, dir, realFilter);
85
86 if (fileName.isEmpty()) // user cancel
87 return result;
88
89 const Io::FileFormat* format = findFileFormat(
90 parentWidget, caption, fileName, FileFormat::File | FileFormat::Write);
91
92 // If none found, give user the option to retry.
93 if (!format) {
94 QString extension = QFileInfo(fileName).suffix().toLower();
95
96 if (extension.isEmpty()) {
97 QMessageBox::StandardButton reply = QMessageBox::question(
98 parentWidget, caption,
99 tr(
100 "The file extension is missing, so the format cannot be determined."
101 " Do you want to add it?"),
102 QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);
103 switch (reply) {
104 default:
105 case QMessageBox::Retry:
106 continue;
107 case QMessageBox::Abort:
108 return result;
109 }
110 }
111
112 QMessageBox::StandardButton reply = QMessageBox::question(
113 parentWidget, caption,
114 tr("Unable to find a suitable file writer for "
115 "the selected format."),
116 QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);
117 switch (reply) {
118 default:
119 case QMessageBox::Retry:
120 continue;
121 case QMessageBox::Abort:
122 return result;
123 }
124 }
125
126 result.first = format;
127 result.second = fileName;
128
129 } while (fileName.isEmpty());
130
131 return result;
132 }
133
134 const Io::FileFormat* FileFormatDialog::findFileFormat(
135 QWidget* parentWidget, const QString& caption, const QString& fileName,
136 const FileFormat::Operations formatFlags, const QString& formatPrefix)
137 {
138 if (fileName.isEmpty())
139 return nullptr;
140
141 // Extract extension from filename.
142 QFileInfo fileInfo(fileName);
143 QString extension = fileInfo.suffix();
144 if (extension.isEmpty())
145 extension = fileInfo.fileName();
146
147 // Lookup matching file formats.
148 vector<const FileFormat*> matches(
149 FileFormatManager::instance().fileFormatsFromFileExtension(
150 extension.toStdString(), formatFlags));
151
152 // Prepare the strings for selectFileFormat:
153 QString noun;
154 QString verb;
155 QString key;
156
157 // TODO: This does not work for translation...
158 // particularly since len(matches) is known
159 if ((formatFlags & FileFormat::Read && formatFlags & FileFormat::Write) ||
160 ((formatFlags & FileFormat::Read) == 0 &&
161 (formatFlags & FileFormat::Write) == 0)) {
162 // Both or neither read/write
163 noun = tr("handlers", "File handlers");
164 verb = tr("handle", "e.g. file handlers that can 'handle' this file.");
165 key = QLatin1String("fileToWrite"); // Just use the write settings
166 } else if (formatFlags & FileFormat::Read) {
167 // Read
168 noun = tr("readers", "File readers");
169 verb = tr("read", "e.g. file readers that can 'read' this file.");
170 key = QLatin1String("fileToRead");
171 } else if (formatFlags & FileFormat::Write) {
172 // Write
173 noun = tr("writers", "File writers");
174 verb = tr("write", "e.g. file writers that can 'write' this file.");
175 key = QLatin1String("fileToWrite");
176 }
177
178 return selectFileFormat(parentWidget, matches, caption,
179 tr("Multiple %1 found that can %2 this format. "
180 "Which should be used?")
181 .arg(noun, verb),
182 QString("FileFormatDialog/%1/%2"
183 "/lastUsed")
184 .arg(key, extension),
185 formatPrefix);
186 }
187
188 QString FileFormatDialog::readFileFilter()
189 {
190 static QString readFilter;
191 if (readFilter.isEmpty()) {
192 vector<const FileFormat*> formats =
193 FileFormatManager::instance().fileFormats(FileFormat::Read |
194 FileFormat::File);
195
196 readFilter = generateFilterString(formats, AllFiles | AllFormats);
197 }
198
199 return readFilter;
200 }
201
202 QString FileFormatDialog::writeFileFilter()
203 {
204 static QString writeFilter;
205 if (writeFilter.isEmpty()) {
206 vector<const FileFormat*> formats =
207 FileFormatManager::instance().fileFormats(FileFormat::Write |
208 FileFormat::File);
209
210 writeFilter = generateFilterString(formats, WriteFormats | AllFiles);
211 }
212
213 return writeFilter;
214 }
215
216 QString FileFormatDialog::generateFilterString(
217 const std::vector<const Io::FileFormat*>& ffs,
218 FileFormatDialog::FilterStringOptions options)
219 {
220 QString filterString;
221 // Create a map that groups the file extensions by name:
222 QMultiMap<QString, QString> formatMap;
223 for (auto ff : ffs) {
224 QString name(QString::fromStdString(ff->name()));
225 std::vector<std::string> exts = ff->fileExtensions();
226 for (auto& eit : exts) {
227 QString ext(QString::fromStdString(eit));
228 if (!formatMap.values(name).contains(ext)) {
229 formatMap.insertMulti(name, ext);
230 }
231 }
232 }
233
234 // This is a list of "extensions" returned by OB that are not actually
235 // file extensions, but rather the full filename of the file. These
236 // will be used as-is in the filter string, while others will be prepended
237 // with "*.".
238 QStringList nonExtensions;
239 nonExtensions << QStringLiteral("POSCAR") // VASP input geometry
240 << QStringLiteral("CONTCAR") // VASP output geometry
241 << QStringLiteral("HISTORY") // DL-POLY history file
242 << QStringLiteral("CONFIG") // DL-POLY config file
243 ;
244
245 // This holds all known extensions:
246 QStringList allExtensions;
247
248 foreach (const QString& desc, formatMap.uniqueKeys()) {
249 QStringList extensions;
250 QStringList formatExtensions = formatMap.values(desc);
251
252 // When writing formats, only list one common extension
253 // .. to ensure the OS appends the extension to the filename
254 if (options & WriteFormats) {
255 if (formatExtensions.contains(QStringLiteral("cml")))
256 formatExtensions = QStringList("cml");
257 else if (formatExtensions.contains(QStringLiteral("mol2")))
258 formatExtensions = QStringList("mol2");
259 else if (formatExtensions.contains(QStringLiteral("pdb")))
260 formatExtensions = QStringList("pdb");
261 else if (formatExtensions.contains(QStringLiteral("sdf")))
262 formatExtensions = QStringList("sdf");
263 else if (formatExtensions.contains(QStringLiteral("xyz")))
264 formatExtensions = QStringList("xyz");
265 }
266
267 foreach (QString extension, formatExtensions) {
268 if (!nonExtensions.contains(extension))
269 extension.prepend("*.");
270 extensions << extension;
271 }
272 if (options & AllFormats)
273 allExtensions << extensions;
274 filterString += QStringLiteral("%1 (%2);;")
275 .arg(desc, extensions.join(QStringLiteral(" ")));
276 }
277
278 if (options & AllFiles)
279 filterString.prepend(tr("All files") + " (*);;");
280
281 if (options & AllFormats) {
282 filterString.prepend((tr("All supported formats") + " (%1);;")
283 .arg(allExtensions.join(QStringLiteral(" "))));
284 }
285
286 return filterString;
287 }
288
289 const Io::FileFormat* FileFormatDialog::selectFileFormat(
290 QWidget* parentWidget, const std::vector<const Io::FileFormat*>& ffs,
291 const QString& caption, const QString& prompt, const QString& settingsKey,
292 const QString& formatPrefix)
293 {
294 if (ffs.empty())
295 return nullptr;
296 else if (ffs.size() == 1)
297 return ffs[0];
298
299 // If more than one format found, prompt user to select one.
300 QStringList idents;
301 for (auto ff : ffs) {
302 idents << QString::fromStdString(ff->identifier());
303 }
304
305 // If there is a format prefix, see if that can reduce the results down.
306 QStringList preferred;
307 foreach (const QString& id, idents)
308 if (id.startsWith(formatPrefix))
309 preferred << id;
310 if (preferred.size() == 1)
311 return ffs[idents.indexOf(preferred.first())];
312
313 // We will only show the dialog if the user is pressing
314 // the shift, control or meta keys.
315 if (!(QApplication::keyboardModifiers() &
316 (Qt::ShiftModifier | Qt::ControlModifier | Qt::MetaModifier))) {
317 // use a script format if set (i.e., these override internal)
318 // otherwise use internal over Open Babel
319 for (int i = 0; i < static_cast<int>(ffs.size()); ++i) {
320 if (idents[i].startsWith("User")) {
321 return ffs[i];
322 } else if (idents[i].startsWith("Avogadro")) {
323 return ffs[i];
324 } else if (idents[i].startsWith("OpenBabel")) {
325 return ffs[i];
326 }
327 }
328 // if we get here, we should show the user the dialog
329 // .. but it should never happen
330 }
331
332 // See if they used one before:
333 QString lastIdent = settingsKey.isNull()
334 ? QString()
335 : QSettings().value(settingsKey).toString();
336
337 int lastIdentIndex = idents.indexOf(lastIdent);
338
339 // we're going to show the dialog - if there wasn't a choice
340 // the default should be the first one
341 if (lastIdentIndex < 0)
342 lastIdentIndex = 0;
343
344 bool ok;
345 QString item = QInputDialog::getItem(parentWidget, caption, prompt, idents,
346 lastIdentIndex, false, &ok);
347 int index = idents.indexOf(item);
348
349 // user cancel
350 if (!ok || index < 0 || index + 1 > static_cast<int>(ffs.size()))
351 return nullptr;
352
353 // Store chosen reader for next time
354 if (!settingsKey.isNull())
355 QSettings().setValue(settingsKey, item);
356
357 return ffs[index];
358 }
359
360 } // namespace Avogadro::QtGui