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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
|
#include "processrunner.h"
#include "organizercore.h"
#include "instancemanager.h"
#include "lockeddialog.h"
#include "iuserinterface.h"
#include "envmodule.h"
#include <log.h>
using namespace MOBase;
enum class WaitResults
{
Completed = 1,
Error,
Cancelled
};
WaitResults waitForProcess(
HANDLE handle, DWORD* exitCode, std::function<bool ()> progress)
{
if (handle == INVALID_HANDLE_VALUE) {
return WaitResults::Error;
}
log::debug("waiting for completion on pid {}", ::GetProcessId(handle));
std::vector<HANDLE> handles;
handles.push_back(handle);
std::vector<DWORD> exitCodes;
for (;;) {
// Wait for a an event on the handle, a key press, mouse click or timeout
const auto res = MsgWaitForMultipleObjects(
1, &handle, FALSE, 50, QS_KEY | QS_MOUSEBUTTON);
if (res == WAIT_FAILED) {
// error
const auto e = ::GetLastError();
log::error(
"failed waiting for process completion, {}", formatSystemMessage(e));
return WaitResults::Error;
} else if (res == WAIT_OBJECT_0) {
// completed
if (exitCode) {
if (!::GetExitCodeProcess(handle, exitCode)) {
const auto e = ::GetLastError();
log::warn(
"failed to get exit code of process, {}",
formatSystemMessage(e));
}
}
return WaitResults::Completed;
}
// keep processing events so the app doesn't appear dead
QCoreApplication::sendPostedEvents();
QCoreApplication::processEvents();
if (progress && progress()) {
return WaitResults::Cancelled;
}
}
}
env::Process* getInterestingProcess(std::vector<env::Process>& processes)
{
if (processes.empty()) {
return nullptr;
}
// Certain process names we wish to "hide" for aesthetic reason:
const std::vector<QString> hiddenList = {
QFileInfo(QCoreApplication::applicationFilePath()).fileName()
};
auto isHidden = [&](auto&& p) {
for (auto h : hiddenList) {
if (p.name().contains(h, Qt::CaseInsensitive)) {
return true;
}
}
return false;
};
for (auto&& root : processes) {
if (!isHidden(root)) {
return &root;
}
for (auto&& child : root.children()) {
if (!isHidden(child)) {
return &child;
}
}
}
// everything is hidden, just pick the first one
return &processes[0];
}
WaitResults waitForProcesses(
std::vector<env::Process>& processes,
LPDWORD exitCode, ILockedWaitingForProcess* uilock)
{
const auto* interesting = getInterestingProcess(processes);
if (!interesting) {
return WaitResults::Error;
}
if (uilock) {
uilock->setProcessInformation(interesting->pid(), interesting->name());
}
auto interestingHandle = interesting->openHandleForWait();
if (!interestingHandle) {
return WaitResults::Error;
}
auto progress = [&]{ return uilock->unlockForced(); };
return waitForProcess(interestingHandle.get(), exitCode, progress);
}
SpawnedProcess::SpawnedProcess(HANDLE handle, spawn::SpawnParameters sp)
: m_handle(handle), m_parameters(std::move(sp))
{
}
SpawnedProcess::SpawnedProcess(SpawnedProcess&& other)
: m_handle(other.m_handle), m_parameters(std::move(other.m_parameters))
{
other.m_handle = INVALID_HANDLE_VALUE;
}
SpawnedProcess& SpawnedProcess::operator=(SpawnedProcess&& other)
{
if (this != &other) {
destroy();
m_handle = other.m_handle;
other.m_handle = INVALID_HANDLE_VALUE;
m_parameters = std::move(other.m_parameters);
}
return *this;
}
SpawnedProcess::~SpawnedProcess()
{
destroy();
}
HANDLE SpawnedProcess::releaseHandle()
{
const auto h = m_handle;
m_handle = INVALID_HANDLE_VALUE;
return h;
}
void SpawnedProcess::destroy()
{
if (m_handle != INVALID_HANDLE_VALUE) {
::CloseHandle(m_handle);
m_handle = INVALID_HANDLE_VALUE;
}
}
ProcessRunner::ProcessRunner(OrganizerCore& core)
: m_core(core), m_ui(nullptr)
{
}
void ProcessRunner::setUserInterface(IUserInterface* ui)
{
m_ui = ui;
}
bool ProcessRunner::runFile(QWidget* parent, const QFileInfo& targetInfo)
{
if (!parent && m_ui) {
parent = m_ui->qtWidget();
}
const auto fec = spawn::getFileExecutionContext(parent, targetInfo);
switch (fec.type)
{
case spawn::FileExecutionTypes::Executable:
{
runExecutableFile(fec.binary, fec.arguments, targetInfo.absoluteDir());
return true;
}
case spawn::FileExecutionTypes::Other: // fall-through
default:
{
auto r = shell::Open(targetInfo.absoluteFilePath());
if (!r.success()) {
return false;
}
// not all files will return a valid handle even if opening them was
// successful, such as inproc handlers (like the photo viewer)
if (r.processHandle() != INVALID_HANDLE_VALUE) {
// steal because it gets closed after the wait
return waitForProcessCompletionWithLock(r.stealProcessHandle(), nullptr);
}
return true;
}
}
}
bool ProcessRunner::runExecutableFile(
const QFileInfo &binary, const QString &arguments,
const QDir ¤tDirectory, const QString &steamAppID,
const QString &customOverwrite,
const QList<MOBase::ExecutableForcedLoadSetting> &forcedLibraries,
bool refresh)
{
DWORD processExitCode = 0;
HANDLE processHandle = spawnAndWait(
binary, arguments, m_core.currentProfile()->name(),
currentDirectory, steamAppID, customOverwrite, forcedLibraries,
&processExitCode);
if (processHandle == INVALID_HANDLE_VALUE) {
// failed
return false;
}
if (refresh) {
m_core.afterRun(binary, processExitCode);
}
return true;
}
bool ProcessRunner::runExecutable(const Executable& exe, bool refresh)
{
const auto* profile = m_core.currentProfile();
if (!profile) {
throw MyException(QObject::tr("No profile set"));
}
const QString customOverwrite = profile->setting(
"custom_overwrites", exe.title()).toString();
QList<MOBase::ExecutableForcedLoadSetting> forcedLibraries;
if (profile->forcedLibrariesEnabled(exe.title())) {
forcedLibraries = profile->determineForcedLibraries(exe.title());
}
return runExecutableFile(
exe.binaryInfo(),
exe.arguments(),
exe.workingDirectory().length() != 0 ? exe.workingDirectory() : exe.binaryInfo().absolutePath(),
exe.steamAppID(),
customOverwrite,
forcedLibraries,
refresh);
}
bool ProcessRunner::runShortcut(const MOShortcut& shortcut)
{
if (shortcut.hasInstance() && shortcut.instance() != InstanceManager::instance().currentInstance()) {
throw std::runtime_error(
QString("Refusing to run executable from different instance %1:%2")
.arg(shortcut.instance(),shortcut.executable())
.toLocal8Bit().constData());
}
const Executable& exe = m_core.executablesList()->get(shortcut.executable());
return runExecutable(exe, false);
}
HANDLE ProcessRunner::runExecutableOrExecutableFile(
const QString& executable, const QStringList &args, const QString &cwd,
const QString& profileOverride, const QString &forcedCustomOverwrite,
bool ignoreCustomOverwrite)
{
const auto* profile = m_core.currentProfile();
if (!profile) {
throw MyException(QObject::tr("No profile set"));
}
QString profileName = profileOverride;
if (profileName == "") {
profileName = profile->name();
}
QFileInfo binary;
QString arguments = args.join(" ");
QString currentDirectory = cwd;
QString steamAppID;
QString customOverwrite;
QList<ExecutableForcedLoadSetting> forcedLibraries;
if (executable.contains('\\') || executable.contains('/')) {
// file path
binary = QFileInfo(executable);
if (binary.isRelative()) {
// relative path, should be relative to game directory
binary = m_core.managedGame()->gameDirectory().absoluteFilePath(executable);
}
if (currentDirectory == "") {
currentDirectory = binary.absolutePath();
}
try {
const Executable& exe = m_core.executablesList()->getByBinary(binary);
steamAppID = exe.steamAppID();
customOverwrite = profile->setting("custom_overwrites", exe.title()).toString();
if (profile->forcedLibrariesEnabled(exe.title())) {
forcedLibraries = profile->determineForcedLibraries(exe.title());
}
} catch (const std::runtime_error &) {
// nop
}
} else {
// only a file name, search executables list
try {
const Executable &exe = m_core.executablesList()->get(executable);
steamAppID = exe.steamAppID();
customOverwrite = profile->setting("custom_overwrites", exe.title()).toString();
if (profile->forcedLibrariesEnabled(exe.title())) {
forcedLibraries = profile->determineForcedLibraries(exe.title());
}
if (arguments == "") {
arguments = exe.arguments();
}
binary = exe.binaryInfo();
if (currentDirectory == "") {
currentDirectory = exe.workingDirectory();
}
} catch (const std::runtime_error &) {
log::warn("\"{}\" not set up as executable", executable);
binary = QFileInfo(executable);
}
}
if (!forcedCustomOverwrite.isEmpty())
customOverwrite = forcedCustomOverwrite;
if (ignoreCustomOverwrite)
customOverwrite.clear();
return spawnAndWait(
binary,
arguments,
profileName,
currentDirectory,
steamAppID,
customOverwrite,
forcedLibraries);
}
HANDLE ProcessRunner::spawnAndWait(
const QFileInfo &binary, const QString &arguments, const QString &profileName,
const QDir ¤tDirectory, const QString &steamAppID,
const QString &customOverwrite,
const QList<MOBase::ExecutableForcedLoadSetting> &forcedLibraries,
LPDWORD exitCode)
{
spawn::SpawnParameters sp;
sp.binary = binary;
sp.arguments = arguments;
sp.currentDirectory = currentDirectory;
sp.steamAppID = steamAppID;
sp.hooked = true;
if (!m_core.beforeRun(binary, profileName, customOverwrite, forcedLibraries)) {
return INVALID_HANDLE_VALUE;
}
HANDLE handle = spawn(sp).releaseHandle();
if (handle == INVALID_HANDLE_VALUE) {
// failed
return INVALID_HANDLE_VALUE;
}
waitForProcessCompletionWithLock(handle, exitCode);
return handle;
}
void adjustForVirtualized(
const IPluginGame* game, spawn::SpawnParameters& sp, const Settings& settings)
{
const QString modsPath = settings.paths().mods();
// Check if this a request with either an executable or a working directory
// under our mods folder then will start the process in a virtualized
// "environment" with the appropriate paths fixed:
// (i.e. mods\FNIS\path\exe => game\data\path\exe)
QString cwdPath = sp.currentDirectory.absolutePath();
bool virtualizedCwd = cwdPath.startsWith(modsPath, Qt::CaseInsensitive);
QString binPath = sp.binary.absoluteFilePath();
bool virtualizedBin = binPath.startsWith(modsPath, Qt::CaseInsensitive);
if (virtualizedCwd || virtualizedBin) {
if (virtualizedCwd) {
int cwdOffset = cwdPath.indexOf('/', modsPath.length() + 1);
QString adjustedCwd = cwdPath.mid(cwdOffset, -1);
cwdPath = game->dataDirectory().absolutePath();
if (cwdOffset >= 0)
cwdPath += adjustedCwd;
}
if (virtualizedBin) {
int binOffset = binPath.indexOf('/', modsPath.length() + 1);
QString adjustedBin = binPath.mid(binOffset, -1);
binPath = game->dataDirectory().absolutePath();
if (binOffset >= 0)
binPath += adjustedBin;
}
QString cmdline
= QString("launch \"%1\" \"%2\" %3")
.arg(QDir::toNativeSeparators(cwdPath),
QDir::toNativeSeparators(binPath), sp.arguments);
sp.binary = QFileInfo(QCoreApplication::applicationFilePath());
sp.arguments = cmdline;
sp.currentDirectory.setPath(QCoreApplication::applicationDirPath());
}
}
SpawnedProcess ProcessRunner::spawn(spawn::SpawnParameters sp)
{
QWidget* parent = nullptr;
if (m_ui) {
parent = m_ui->qtWidget();
}
if (!checkBinary(parent, sp)) {
return {INVALID_HANDLE_VALUE, sp};
}
const auto* game = m_core.managedGame();
auto& settings = m_core.settings();
if (!checkSteam(parent, sp, game->gameDirectory(), sp.steamAppID, settings)) {
return {INVALID_HANDLE_VALUE, sp};
}
if (!checkEnvironment(parent, sp)) {
return {INVALID_HANDLE_VALUE, sp};
}
if (!checkBlacklist(parent, sp, settings)) {
return {INVALID_HANDLE_VALUE, sp};
}
adjustForVirtualized(game, sp, settings);
return {startBinary(parent, sp), sp};
}
void ProcessRunner::withLock(std::function<void (ILockedWaitingForProcess*)> f)
{
std::unique_ptr<LockedDialog> dlg;
ILockedWaitingForProcess* uilock = nullptr;
if (m_ui != nullptr) {
uilock = m_ui->lock();
}
else {
// i.e. when running command line shortcuts there is no user interface
dlg.reset(new LockedDialog);
dlg->show();
dlg->setEnabled(true);
uilock = dlg.get();
}
Guard g([&]() {
if (m_ui != nullptr) {
m_ui->unlock();
}
});
f(uilock);
}
bool ProcessRunner::waitForProcessCompletionWithLock(
HANDLE handle, LPDWORD exitCode)
{
if (!Settings::instance().interface().lockGUI()) {
return true;
}
bool r = false;
withLock([&](auto* uilock) {
DWORD ignoreExitCode;
r = waitForProcessCompletion(handle, exitCode ? exitCode : &ignoreExitCode, uilock);
});
return r;
}
bool ProcessRunner::waitForApplication(HANDLE handle, LPDWORD exitCode)
{
if (!Settings::instance().interface().lockGUI())
return true;
bool r = false;
withLock([&](auto* uilock) {
r = waitForProcessCompletion(handle, exitCode, uilock);
});
return r;
}
bool ProcessRunner::waitForProcessCompletion(
HANDLE handle, LPDWORD exitCode, ILockedWaitingForProcess* uilock)
{
const auto tree = env::getProcessTree(handle);
std::vector<env::Process> processes = {tree};
const auto r = waitForProcesses(processes, exitCode, uilock);
return (r != WaitResults::Error);
}
bool ProcessRunner::waitForAllUSVFSProcessesWithLock()
{
if (!Settings::instance().interface().lockGUI())
return true;
bool r = false;
withLock([&](auto* uilock) {
r = waitForAllUSVFSProcesses(uilock);
});
return r;
}
bool ProcessRunner::waitForAllUSVFSProcesses(ILockedWaitingForProcess* uilock)
{
for (;;) {
const auto handles = getRunningUSVFSProcesses();
if (handles.empty()) {
break;
}
std::vector<env::Process> processes;
for (auto&& h : handles) {
auto p = env::getProcessTree(h);
if (p.isValid()) {
processes.emplace_back(std::move(p));
}
}
const auto r = waitForProcesses(processes, nullptr, uilock);
switch (r)
{
case WaitResults::Completed:
// this process is completed, check for others
break;
case WaitResults::Cancelled:
// force unlocked
log::debug("waiting for process completion aborted by UI");
return true;
case WaitResults::Error: // fall-through
default:
log::debug("waiting for process completion not successful");
return false;
}
}
log::debug("waiting for process completion successful");
return true;
}
|