qtutils.cpp
9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2012 The MITRE Corporation *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <QCryptographicHash>
#include <QDebug>
#ifndef BR_EMBEDDED
#include <QDesktopServices>
#endif // BR_EMBEDDED
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QProcessEnvironment>
#include <QRegExp>
#include <QStack>
#include <QUrl>
#include <openbr_plugin.h>
#include "qtutils.h"
using namespace br;
QStringList QtUtils::getFiles(QDir dir, bool recursive)
{
dir = QDir(dir.canonicalPath());
QStringList files;
foreach (const QString &file, dir.entryList(QDir::Files))
files.append(QDir::cleanPath(dir.absoluteFilePath(file)));
if (!recursive) return files;
foreach (const QString &folder, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
QDir subdir(dir);
bool success = subdir.cd(folder); if (!success) qFatal("cd failure.");
files.append(getFiles(subdir, true));
}
return files;
}
QStringList QtUtils::getFiles(const QString ®exp)
{
QFileInfo fileInfo(regexp);
QDir dir(fileInfo.dir());
QRegExp re(fileInfo.fileName());
re.setPatternSyntax(QRegExp::Wildcard);
QStringList files;
foreach (const QString &fileName, dir.entryList(QDir::Files))
if (re.exactMatch(fileName))
files.append(dir.filePath(fileName));
return files;
}
QStringList QtUtils::readLines(const QString &file)
{
QStringList lines;
readFile(file, lines);
return lines;
}
void QtUtils::readFile(const QString &file, QStringList &lines)
{
QFile f(file);
if (!f.open(QFile::ReadOnly)) qFatal("Unable to open %s for reading.", qPrintable(file));
lines = QString(f.readAll()).split('\n', QString::SkipEmptyParts);
for (int i=0; i<lines.size(); i++)
lines[i] = lines[i].simplified();
f.close();
}
void QtUtils::readFile(const QString &file, QByteArray &data, bool uncompress)
{
QFile f(file);
if (!f.open(QFile::ReadOnly)) qFatal("Unable to open %s for reading.", qPrintable(file));
data = f.readAll();
if (uncompress) data = qUncompress(data);
f.close();
}
void QtUtils::writeFile(const QString &file, const QStringList &lines)
{
writeFile(file, lines.join("\n"));
}
void QtUtils::writeFile(const QString &file, const QString &data)
{
writeFile(file, data.toLocal8Bit());
}
void QtUtils::writeFile(const QString &file, const QByteArray &data, int compression)
{
const QString baseName = QFileInfo(file).baseName();
const QByteArray contents = (compression == 0) ? data : qCompress(data, compression);
if (baseName == "terminal") {
printf("%s\n", qPrintable(contents));
} else if (baseName == "buffer") {
Globals->buffer = data;
} else {
QFile f(file);
touchDir(f);
if (!f.open(QFile::WriteOnly))
qFatal("Failed to open %s for writing.", qPrintable(file));
f.write(contents);
f.close();
}
}
void QtUtils::touchDir(const QDir &dir)
{
if (dir.exists(".")) return;
if (!dir.mkpath("."))
qFatal("Unable to create path to dir %s", qPrintable(dir.absolutePath()));
}
void QtUtils::touchDir(const QFile &file)
{
touchDir(QFileInfo(file));
}
void QtUtils::touchDir(const QFileInfo &fileInfo)
{
touchDir(fileInfo.dir());
}
void QtUtils::emptyDir(QDir &dir)
{
foreach (const QString &folder, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks)) {
QDir subdir(dir);
bool success = subdir.cd(folder); if (!success) qFatal("cd failure.");
emptyDir(subdir);
}
foreach (const QString &file, dir.entryList(QDir::Files))
dir.remove(file);
foreach (const QString &folder, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks))
dir.rmdir(folder);
foreach (const QString &symlink, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
dir.remove(symlink);
}
void QtUtils::deleteDir(QDir &dir)
{
emptyDir(dir);
dir.rmdir(".");
}
QString QtUtils::find(const QString &file, const QString &alt)
{
if (QFileInfo(file).exists()) return file;
if (QFileInfo(alt).exists()) return alt;
qFatal("Can't find file %s or alt %s\n", qPrintable(file), qPrintable(alt));
return "";
}
bool QtUtils::toBool(const QString &string)
{
bool ok;
bool result = (bool)string.toInt(&ok); if (!ok) qFatal("Expected integer value, got %s.", qPrintable(string));
return result;
}
int QtUtils::toInt(const QString &string)
{
bool ok;
int result = string.toInt(&ok); if (!ok) qFatal("Expected integer value, got %s.", qPrintable(string));
return result;
}
float QtUtils::toFloat(const QString &string)
{
bool ok;
float result = string.toFloat(&ok); if (!ok) qFatal("Expected floating point value, got %s.", qPrintable(string));
return result;
}
QList<float> QtUtils::toFloats(const QStringList &strings)
{
QList<float> floats;
bool ok;
foreach (const QString &string, strings) {
floats.append(string.toFloat(&ok));
if (!ok) qFatal("Failed to convert %s to floating point format.", qPrintable(string));
}
return floats;
}
QStringList QtUtils::toStringList(const std::vector<std::string> &string_list)
{
QStringList result;
foreach (const std::string &string, string_list)
result.append(QString::fromStdString(string));
return result;
}
QStringList QtUtils::toStringList(int num_strings, const char *strings[])
{
QStringList result;
for (int i=0; i<num_strings; i++)
result.append(strings[i]);
return result;
}
QString QtUtils::shortTextHash(QString string)
{
string.remove(QRegExp("[{}<>&]"));
return QString(QCryptographicHash::hash(qPrintable(string), QCryptographicHash::Md5).toBase64()).remove(QRegExp("[^a-zA-Z1-9]")).left(6);
}
QStringList QtUtils::parse(QString args, char split)
{
if (args.isEmpty()) return QStringList();
QStringList words;
int start = 0;
bool inQuote = false;
QStack<QChar> subexpressions;
for (int i=0; i<args.size(); i++) {
if (inQuote) {
if (args[i] == '\'')
inQuote = false;
} else {
if (args[i] == '\'') {
inQuote = true;
} else if ((args[i] == '(') || (args[i] == '[') || (args[i] == '<') || (args[i] == '{')) {
subexpressions.push(args[i]);
} else if (args[i] == ')') {
if (subexpressions.pop() != '(') qFatal("Unexpected ')'.");
} else if (args[i] == ']') {
if (subexpressions.pop() != '[') qFatal("Unexpected ']'.");
} else if (args[i] == '>') {
if (subexpressions.pop() != '<') qFatal("Unexpected '>'.");
} else if (args[i] == '}') {
if (subexpressions.pop() != '{') qFatal("Unexpected '}'.");
} else if (subexpressions.isEmpty() && (args[i] == split)) {
words.append(args.mid(start, i-start).trimmed());
start = i+1;
}
}
}
words.append(args.mid(start).trimmed());
return words;
}
void QtUtils::checkArgsSize(const QString &name, const QStringList &args, int min, int max)
{
if (max == -1) max = std::numeric_limits<int>::max();
if (max == 0) max = min;
if (args.size() < min) qFatal("%s expects at least %d arguments, got %d", qPrintable(name), min, args.size());
if (args.size() > max) qFatal("%s expects no more than %d arguments, got %d", qPrintable(name), max, args.size());
}
bool QtUtils::runRScript(const QString &file)
{
QProcess RScript;
RScript.start("Rscript", QStringList() << file);
RScript.waitForFinished(-1);
bool result = ((RScript.exitCode() == 0) && (RScript.error() == QProcess::UnknownError));
if (!result) qDebug("Failed to run 'Rscript', did you forget to install R? "
"See online documentation of 'br_plot' for required R packages. "
"Otherwise, try running Rscript on %s to get the exact error.", qPrintable(file));
return result;
}
bool QtUtils::runDot(const QString &file)
{
QProcess dot;
dot.start("dot -Tpdf -O " + file);
dot.waitForFinished(-1);
return ((dot.exitCode() == 0) && (dot.error() == QProcess::UnknownError));
}
void QtUtils::showFile(const QString &file)
{
#ifndef BR_EMBEDDED
(void) file;
// A bug in Qt5 currently prevents us from doing this:
// QDesktopServices::openUrl(QUrl::fromLocalFile(file));
#else // BR_EMBEDDED
(void) file;
#endif // BR_EMBEDDED
}