Debian Codegraph @

avogadro/qtplugins/openbabel/obfileformat.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 "obfileformat.h"
7
8 #include "obprocess.h"
9
10 #include <nlohmann/json.hpp>
11
12 #include <QtCore/QCoreApplication>
13 #include <QtCore/QDebug>
14 #include <QtCore/QFileInfo>
15 #include <QtCore/QTemporaryFile>
16 #include <QtCore/QTimer>
17
18 using namespace std::string_literals;
19 using json = nlohmann::json;
20
21 namespace Avogadro::QtPlugins {
22
23 /**
24 * @brief The ProcessListener class allows synchronous use of OBProcess.
25 */
26 class OBFileFormat::ProcessListener : public QObject
27 {
28 Q_OBJECT
29 public:
30 ProcessListener() : QObject(), m_finished(false) {}
31
32 bool waitForOutput(QByteArray& output, int msTimeout = 120000)
33 {
34 if (!wait(msTimeout))
35 return false;
36
37 // success!
38 output = m_output;
39 return true;
40 }
41
42 public slots:
43 void responseReceived(const QByteArray& output)
44 {
45 m_finished = true;
46 m_output = output;
47 }
48
49 private:
50 bool wait(int msTimeout)
51 {
52 QTimer timer;
53 timer.start(msTimeout);
54
55 while (timer.isActive() && !m_finished)
56 qApp->processEvents(QEventLoop::AllEvents, 500);
57
58 return m_finished;
59 }
60
61 OBProcess* m_process;
62 bool m_finished;
63 QByteArray m_output;
64 };
65
66 OBFileFormat::OBFileFormat(const std::string& name_,
67 const std::string& identifier_,
68 const std::string& description_,
69 const std::string& specificationUrl_,
70 const std::vector<std::string> fileExtensions_,
71 const std::vector<std::string> mimeTypes_,
72 const std::string& defaultFormat_, bool fileOnly_)
73 : Io::FileFormat(), m_description(description_),
74 m_fileExtensions(fileExtensions_), m_mimeTypes(mimeTypes_),
75 m_identifier(identifier_), m_name(name_),
76 m_specificationUrl(specificationUrl_), m_defaultFormat(defaultFormat_),
77 m_fileOnly(fileOnly_)
78 {
79 }
80
81 OBFileFormat::~OBFileFormat() {}
82
83 bool OBFileFormat::read(std::istream& in, Core::Molecule& molecule)
84 {
85 json opts;
86 if (!options().empty())
87 opts = json::parse(options(), nullptr, false);
88 else
89 opts = json::object();
90
91 // Allow blocking until the read is completed.
92 OBProcess proc;
93 ProcessListener listener;
94 QObject::connect(&proc, SIGNAL(convertFinished(QByteArray)), &listener,
95 SLOT(responseReceived(QByteArray)));
96
97 // Just grab the first file extension from the list -- all extensions for a
98 // given format map to the same parsers in OB.
99 if (m_fileExtensions.empty()) {
100 appendError("Internal error: No file extensions set.");
101 return false;
102 }
103
104 // If we are reading a pure-2D format, generate 3D coordinates:
105 QStringList options;
106 QStringList formats2D;
107 formats2D << "smi"
108 << "smiles"
109 << "can"
110 << "inchi"
111 << "wln";
112 if (formats2D.contains(QString::fromStdString(m_fileExtensions.front())))
113 options << "--gen3d";
114
115 // Check if we have extra arguments for open babel
116 json extraArgs = opts.value("arguments", json::object());
117 if (extraArgs.is_array()) {
118 for (const auto& arg : extraArgs) {
119 if (arg.is_string())
120 options << arg.get<std::string>().c_str();
121 }
122 }
123
124 // check if we're going to read to a different format
125 // default is CML or CJSON
126 QString format =
127 QString::fromStdString(opts.value("format", m_defaultFormat));
128
129 if (!m_fileOnly) {
130 // Determine length of data
131 in.seekg(0, std::ios_base::end);
132 std::istream::pos_type length = in.tellg();
133 in.seekg(0, std::ios_base::beg);
134 in.clear();
135
136 // Extract char data
137 QByteArray input;
138 input.resize(static_cast<int>(length));
139 in.read(input.data(), length);
140 if (in.gcount() != length) {
141 appendError("Error reading stream into buffer!");
142 return false;
143 }
144
145 // Perform the conversion.
146 if (!proc.convert(input, QString::fromStdString(m_fileExtensions.front()),
147 format, options)) {
148 appendError("OpenBabel conversion failed!");
149 return false;
150 }
151 } else {
152 // Can only read files. Need absolute path.
153 QString filename = QString::fromStdString(fileName());
154 if (filename.isEmpty()) {
155 // no choice but to write to a temporary file
156 in.seekg(0, std::ios_base::end);
157 std::istream::pos_type length = in.tellg();
158 in.seekg(0, std::ios_base::beg);
159 in.clear();
160
161 // Extract data, hope it's not big
162 QByteArray input;
163 input.resize(static_cast<int>(length));
164 in.read(input.data(), length);
165
166 QTemporaryFile tmpFile;
167 tmpFile.setAutoRemove(false);
168 if (!tmpFile.open()) {
169 appendError("Internal error -- failed to create a temporary file");
170 return false;
171 }
172 tmpFile.write(input.data());
173 tmpFile.close();
174 filename = tmpFile.fileName();
175 }
176
177 if (!QFileInfo(filename).isAbsolute()) {
178 appendError("Internal error -- filename must be absolute! " +
179 filename.toStdString());
180 return false;
181 }
182
183 // Perform the conversion.
184 if (!proc.convert(filename,
185 QString::fromStdString(m_fileExtensions.front()), format,
186 options)) {
187 appendError("OpenBabel conversion failed!");
188 return false;
189 }
190 }
191
192 QByteArray output;
193 if (!listener.waitForOutput(output)) {
194 appendError("Conversion timed out."s);
195 return false;
196 }
197
198 if (output.isEmpty()) {
199 appendError("OpenBabel error: conversion failed."s);
200 return false;
201 }
202
203 if (format == "cml") {
204 if (!m_cmlFormat.readString(std::string(output.constData()), molecule)) {
205 appendError("Error while reading OpenBabel-generated CML:"s);
206 appendError(m_cmlFormat.error());
207 return false;
208 }
209 } else if (format == "cjson") {
210 if (!m_cjsonFormat.readString(std::string(output.constData()), molecule)) {
211 appendError("Error while reading OpenBabel-generated CJSON:"s);
212 appendError(m_cjsonFormat.error());
213 return false;
214 }
215 } else if (format == "pdb") {
216 if (!m_pdbFormat.readString(std::string(output.constData()), molecule)) {
217 appendError("Error while reading OpenBabel-generated PDB:"s);
218 appendError(m_pdbFormat.error());
219 return false;
220 }
221 } else {
222 return false; // unknown format
223 }
224
225 return true;
226 }
227
228 bool OBFileFormat::write(std::ostream& out, const Core::Molecule& molecule)
229 {
230 json opts;
231 if (!options().empty())
232 opts = json::parse(options(), nullptr, false);
233 else
234 opts = json::object();
235
236 // Check if we have extra arguments for open babel
237 QStringList options;
238 json extraArgs = opts.value("arguments", json::object());
239 if (extraArgs.is_array()) {
240 for (const auto& arg : extraArgs) {
241 if (arg.is_string())
242 options << arg.get<std::string>().c_str();
243 }
244 }
245
246 #ifndef NDEBUG
247 qDebug() << " writing to " << m_defaultFormat.c_str();
248 #endif
249
250 // Generate CML or CJSON to give to OpenBabel
251 std::string outputString;
252 if (m_defaultFormat == "cml") {
253 if (!m_cmlFormat.writeString(outputString, molecule)) {
254 appendError("Error while writing CML:"s);
255 appendError(m_cmlFormat.error());
256 return false;
257 }
258 } else if (m_defaultFormat == "cjson") {
259 if (!m_cjsonFormat.writeString(outputString, molecule)) {
260 appendError("Error while writing CJSON:"s);
261 appendError(m_cjsonFormat.error());
262 return false;
263 }
264 }
265
266 // Block until the OpenBabel conversion finishes:
267 OBProcess proc;
268 ProcessListener listener;
269 QObject::connect(&proc, SIGNAL(convertFinished(QByteArray)), &listener,
270 SLOT(responseReceived(QByteArray)));
271
272 // Just grab the first file extension from the list -- all extensions for a
273 // given format map to the same parsers in OB.
274 if (m_fileExtensions.empty()) {
275 appendError("Internal error: No file extensions set.");
276 return false;
277 }
278
279 proc.convert(QByteArray(outputString.c_str()), m_defaultFormat.c_str(),
280 QString::fromStdString(m_fileExtensions.front()), options);
281
282 QByteArray output;
283 if (!listener.waitForOutput(output)) {
284 appendError("Conversion timed out."s);
285 return false;
286 }
287
288 if (output.isEmpty()) {
289 appendError("OpenBabel error: conversion failed."s);
290 return false;
291 }
292
293 out.write(output.constData(), output.size());
294
295 return true;
296 }
297
298 void OBFileFormat::clear()
299 {
300 Io::FileFormat::clear();
301 }
302
303 Io::FileFormat* OBFileFormat::newInstance() const
304 {
305 return new OBFileFormat(m_name, m_identifier, m_description,
306 m_specificationUrl, m_fileExtensions, m_mimeTypes,
307 m_defaultFormat, m_fileOnly);
308 }
309
310 } // namespace Avogadro::QtPlugins
311
312 #include "obfileformat.moc"