-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilities.cpp
448 lines (387 loc) · 13.3 KB
/
Utilities.cpp
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#include "Utilities.h"
#include <qsettings.h>
#include <qcoreapplication.h>
#include <QFileInfo>
#include <QProcess>
#include <QStandardPaths>
#include <QDir>
#include <QDirIterator>
#include <QTextStream>
#include <QDebug>
#include <fstream>
#include <map>
#ifdef _WIN32
#include "windows.h"
#include <QtWin>
#elif defined __unix__
#include <mntent.h>
#endif
QString getExeFileFilter()
{
#ifdef _WIN32
return "Executable(*.exe;*.bat);;All Files(*.*)";
#elif defined __unix__
return "All Files(*.*);;Shell script(*.sh)";
#endif
}
QString getProgramPath()
{
auto progPath = QCoreApplication::applicationFilePath();
#ifdef _WIN32
if (progPath.size() && progPath[0] != '"' && progPath[0] != '\'')
return QString("\"%1\"").arg(QCoreApplication::applicationFilePath());
else
return QCoreApplication::applicationFilePath();
#elif defined __unix__
auto appimagePath = qgetenv("APPIMAGE");
if (appimagePath.size())
{
return appimagePath;
}
if (progPath.size() && progPath[0] != '"' && progPath[0] != '\'')
return QString("\"%1\"").arg(QCoreApplication::applicationFilePath());
else
return QCoreApplication::applicationFilePath();
#endif
}
QString getDesktopFileName()
{
return "LMauricius.EmuDiscer.desktop";
}
QString getHomeDirectory()
{
return QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first();
}
QString getConfigDirectory()
{
return QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation).first();
}
QString getUsername()
{
return QDir::fromNativeSeparators(getHomeDirectory()).split('/').last();
}
QStringList getAppDirectories()
{
QStringList lst = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
#ifdef _WIN32
char *progDataC = getenv("ProgramData");
if (progDataC)
{
QString progData = QString::fromStdString(progDataC);
lst.push_back(progData + "\\Microsoft\\Windows\\Start Menu\\Programs");
}
#endif
return lst;
}
QStringList getRemovableDriveDirectories()
{
#ifdef _WIN32
return {};
#elif defined __unix__
return {
QString("/run/media/") + getUsername(),
QString("/media/") + getUsername()
};
#endif
}
AppDef getApps()
{
AppDef root;
#ifdef _WIN32
for (const QString &path : getAppDirectories())
{
QDir dir(path);
QDirIterator it(path, QDir::Filter::Files, QDirIterator::Subdirectories);
while (it.hasNext())
{
QString fstr = it.next();
QFileInfo info(fstr);
if (info.isSymLink())
{
QString name = info.baseName()/*.remove(".lnk")*/;
QString exec = QString("\"")+info.symLinkTarget()+"\"";
// extract icon
QString natFStr = QDir::toNativeSeparators(info.symLinkTarget());
AppDef *parent = &root;
QString relPath = info.absoluteFilePath().mid(path.size()+1);
QStringList parentNameList = relPath.split(QRegExp("[/\\\\]"));
parentNameList.pop_back();
for (auto& cat : parentNameList)
{
parent = &(parent->subApps[cat]);
}
parent->subApps[name] = AppDef(
exec,
[natFStr](){
QIcon icon;
wchar_t *cFilename = new wchar_t[natFStr.length()+1];
natFStr.toWCharArray(cFilename);
cFilename[natFStr.length()] = 0;
const UINT numIcons = ExtractIconExW(cFilename, -1, nullptr, nullptr, 0);
if (numIcons > 0)
{
QScopedArrayPointer<HICON> winIcons(new HICON[numIcons]);
const UINT numExtrIcons = ExtractIconExW(cFilename, 0, winIcons.data(), nullptr, 1);
if (numExtrIcons > 0)
{
icon = QtWin::fromHICON(winIcons[0]);
}
}
delete[] cFilename;
return icon;
}
);
}
}
}
#elif defined __unix__
std::list<WMiIni> settingsess;
std::map<QString, int> refs;
for (const QString &path : getAppDirectories())
{
QDir dir(path);
for (const QString &fstr : dir.entryList(QDir::Filter::Files|QDir::Filter::NoDotAndDotDot))
{
QFileInfo info(path + "/" + fstr);
if (info.suffix() == "desktop")
{
// Qt has better unicode reading support than MiIni, so we use read() with loaded text
WMiIni appInfo(L"", false);
QFile file(info.filePath());
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream qts(&file);
QString text;
while (!qts.atEnd())
text += qts.readLine()+"\n";
std::wstringstream ss(text.toStdWString());
appInfo.read(ss);
file.close();
if (appInfo.getStr(L"Desktop Entry", L"Type") == L"Application")
{
settingsess.push_back(appInfo);
QStringList cats = QString::fromStdWString(appInfo.getStr(L"Desktop Entry", L"Categories")).split(';');
for (const QString &cat : cats)
{
if (cat.size())
{
if (refs.find(cat) == refs.end())
{
refs[cat] = 1;
}
else
{
refs[cat]++;
}
}
}
}
}
}
}
for (WMiIni &appInfo : settingsess)
{
QStringList cats = QString::fromStdWString(appInfo.getStr(L"Desktop Entry", L"Categories")).split(';');
if (cats.size())
{
int maxRefs = 0;
QString cat = "";
for (const QString &c : cats)
{
if (c.size())
{
int r = refs[c];
if (r > maxRefs)
{
maxRefs = r;
cat = c;
}
}
}
if (cat.size())
{
QString name = QString::fromStdWString(appInfo.getStr(L"Desktop Entry", L"Name"));
QString exec = QString::fromStdWString(appInfo.getStr(L"Desktop Entry", L"Exec"));
QString iconFile = QString::fromStdWString(appInfo.getStr(L"Desktop Entry", L"Icon"));
root.subApps[cat].subApps[name] = AppDef(
exec,
[iconFile](){
return QIcon::fromTheme(iconFile);
}
);
}
}
}
#endif
return root;
}
QString getDrive(const QString& mountPoint)
{
#ifdef _WIN32
return QString(mountPoint[0]);
#elif defined __unix__
FILE *file = setmntent("/proc/mounts", "r");
mntent *entry = nullptr;
if (file)
{
while ((entry = getmntent(file)))
{
if (entry->mnt_dir && mountPoint == entry->mnt_dir)
{
endmntent(file);
return QString::fromStdString(entry->mnt_fsname);
}
}
}
endmntent(file);
return "";
#endif
}
// accepts drive letter (windows) or drive file (unix); returns chars read
size_t getDriveFileHeader(QString drive, char *headerBuffer, size_t charsToRead)
{
#ifdef _WIN32
std::string driveFilename = std::string("\\\\.\\")+drive.toStdString()+":";
#elif defined __unix__
std::string driveFilename = drive.toStdString();
#endif
size_t charsRead = 0;
memset(headerBuffer, 0, charsToRead);
std::ifstream driveFile(driveFilename, std::ios::binary);
if (driveFile.good()) {
driveFile.read(headerBuffer, charsToRead);
if (driveFile)
{
charsRead = charsToRead;
}
else
{
charsRead = driveFile.gcount();
}
driveFile.close();
}
else {
std::string reasons = strerror(errno);
qCritical() << "Couldn't open file: " << QString::fromStdString(reasons) << "\n";
}
return charsRead;
}
bool isAutoRun()
{
QString progPath = getProgramPath();
#ifdef _WIN32
QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
progPath.replace("/", "\\");
progPath = QString("\"") + progPath + "\"";
return settings.contains("EmuDiscer") && settings.value("EmuDiscer") == progPath;
#elif defined __unix__
QString target = getHomeDirectory() + "/.config/autostart/LMauricius.EmuDiscer.desktop";
if (!QFile::exists(target))
return false;
else
{
WMiIni desktop(target.toStdWString(), false);
return desktop.getStr(L"Desktop Entry", L"Exec", L"") == progPath.toStdWString();
}
#endif
}
void setAutoRun(bool autorun)
{
QString progPath = getProgramPath();
#ifdef _WIN32
QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
if (autorun)
{
progPath.replace("/", "\\");
progPath = QString("\"") + progPath + "\"";
//write value to the register
settings.setValue("EmuDiscer", progPath);
}
else
{
settings.remove("EmuDiscer");
}
#elif defined __unix__
QString target = getHomeDirectory() + "/.config/autostart/LMauricius.EmuDiscer.desktop";
if (autorun)
{
WMiIni desktop(target.toStdWString(), false);
desktop.setStr(L"Desktop Entry", L"Exec", progPath.toStdWString());
desktop.setStr(L"Desktop Entry", L"Name", L"EmuDiscer");
desktop.setStr(L"Desktop Entry", L"Icon", L"EmuDiscer");
desktop.setStr(L"Desktop Entry", L"Type", L"Application");
desktop.setStr(L"Desktop Entry", L"Terminal", L"false");
desktop.setStr(L"Desktop Entry", L"Categories", L"Game;");
desktop.setStr(L"Desktop Entry", L"Comment", L"A program for running emulators when a disc is inserted.");
desktop.sync();
QFile::setPermissions(target, QFile::permissions(target) | QFile::ExeOwner | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther);
}
else
{
QFile file(target);
file.remove();
}
#endif
}
bool fileExists(const QString& name)
{
if (name.size() > 0)
{
QString command;
if (name.size() > 1 && name[0] == '\"')
command = name.mid(1, name.indexOf('\"', 1)-1);
else if (name.size() > 1 && name[0] == '\'')
command = name.mid(1, name.indexOf('\'', 1)-1);
else
command = name.left(name.indexOf(' ', 1));
QFileInfo info(name), info2(command);
if ((info.exists() && info.isFile()) || (info2.exists() && info2.isFile()))
return true;
#ifdef __unix__
if (
!command.contains(' ') &&
system(
(QString("which ") + command + " > /dev/null 2>&1").toStdString().c_str()
) == 0
)
return true;
#endif
}
return false;
}
bool directoryExists(const QString& name)
{
QFileInfo info(name);
return info.exists() && info.isDir();
}
void replaceAll(std::wstring& str, const std::wstring& from, const std::wstring& to)
{
if (from.empty())
return;
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
void startProgram(const QString& path, const QString& options, const QString& workdir, const std::map<QString, QString>& envVars)
{
/*QStringList firstOptions = QProcess::splitCommand(path);
QStringList secondOptions = QProcess::splitCommand(options);
QString prog = firstOptions.first();
QStringList optionsList = QStringList(++firstOptions.begin(), firstOptions.end());
optionsList.append(secondOptions);
QProcess p(nullptr);
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
for (const auto& varValPair : envVars)
{
env.insert(varValPair.first, varValPair.second);
}
p.setProgram(prog);
p.setArguments(optionsList);
if (workdir.size())
{
p.setWorkingDirectory(workdir);
}
p.setProcessEnvironment(env);*/
QProcess::startDetached(path+" "+options);
}