game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_process.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_process.cpp
4// ==============================================================================
5// Implementation of GameProcess and GameProcessManager
6// ==============================================================================
7
8#include "game_process.h"
10#include "file_handle.h"
11#include "frame_metrics.h"
13#include "logger.h"
14#include "process_executor.h"
15#include "proton_cache.h"
16#include "shell_utils.h"
17#include "steam_constants.h"
18#include "system_info_service.h"
19#include <algorithm> // For std::all_of, std::sort
20#include <chrono>
21#include <cstdlib> // For std::strtol (cert-err34-c-safe int parse)
22#include <cstring> // For strlen, strerror
23#include <ctime>
24#include <fstream> // For std::ifstream (native Steam game detection)
25#include <limits> // For std::numeric_limits<int>::max()
26#include <set> // For std::set in child process tracking
27#include <sstream>
28#include <thread>
29
30// Platform-specific includes
31#ifdef _WIN32
32#include <tlhelp32.h>
33#include <windows.h>
34#else
35#include <cctype> // For std::isdigit (used in /proc/<pid> filtering)
36#include <cerrno> // For errno
37#include <dirent.h> // For opendir/readdir (proc-scan in findGamePidsByAppId)
38#include <dlfcn.h> // For dlopen/dlsym (GameMode API)
39#include <fstream> // For ifstream (GPU detection)
40#include <signal.h>
41#include <sys/utsname.h> // For uname (kernel version detection)
42#include <sys/wait.h>
43#include <unistd.h>
44#include <utility>
45#endif
46
47// ==============================================================================
48// GameMode API (dlopen-based, no hard dependency)
49// ==============================================================================
50// Provides gamemode_request_start_for(pid) and gamemode_request_end_for(pid)
51// to apply GameMode scheduling optimizations to the actual game PID.
52// This complements the gamemoderun wrapper by targeting the specific game process
53// once its PID is known (important for launcher games like Battle.net, EA App).
54// If libgamemode.so.0 is not installed, all calls are silent no-ops.
55// ==============================================================================
56
57#ifndef _WIN32
58namespace
59{
60class GameModeAPI
61{
62 public:
63 static GameModeAPI& instance()
64 {
65 static GameModeAPI inst;
66 return inst;
67 }
68
69 // Request GameMode for a specific PID. Returns true on success.
70 bool requestStartFor(pid_t pid)
71 {
72 if (!startForFn_)
73 return false;
74 int ret = startForFn_(pid);
75 if (ret == 0)
76 {
77 Logger::info("GameMode: requested start for PID {}", pid);
78 return true;
79 }
80 else
81 {
82 // Log but don't treat as fatal - the gamemoderun wrapper is still active
83 if (errorStringFn_)
84 Logger::warn("GameMode: request_start_for({}) failed: {}", pid, errorStringFn_());
85 else
86 Logger::warn("GameMode: request_start_for({}) failed (ret={})", pid, ret);
87 return false;
88 }
89 }
90
91 // End GameMode for a specific PID. Returns true on success.
92 bool requestEndFor(pid_t pid)
93 {
94 if (!endForFn_)
95 return false;
96 int ret = endForFn_(pid);
97 if (ret == 0)
98 {
99 Logger::info("GameMode: requested end for PID {}", pid);
100 return true;
101 }
102 else
103 {
104 if (errorStringFn_)
105 Logger::warn("GameMode: request_end_for({}) failed: {}", pid, errorStringFn_());
106 else
107 Logger::warn("GameMode: request_end_for({}) failed (ret={})", pid, ret);
108 return false;
109 }
110 }
111
112 bool isAvailable() const
113 {
114 return handle_ != nullptr;
115 }
116
117 private:
119 {
120 handle_ = dlopen("libgamemode.so.0", RTLD_NOW);
121 if (!handle_)
122 {
123 // Try without version suffix
124 handle_ = dlopen("libgamemode.so", RTLD_NOW);
125 }
126 if (!handle_)
127 {
129 "GameMode API: libgamemode.so.0 not found ({}), PID-targeted GameMode unavailable",
130 dlerror());
131 return;
132 }
133
134 startForFn_ =
135 reinterpret_cast<int (*)(pid_t)>(dlsym(handle_, "real_gamemode_request_start_for"));
136 endForFn_ =
137 reinterpret_cast<int (*)(pid_t)>(dlsym(handle_, "real_gamemode_request_end_for"));
138 errorStringFn_ =
139 reinterpret_cast<const char* (*)()>(dlsym(handle_, "real_gamemode_error_string"));
140
141 if (!startForFn_ || !endForFn_)
142 {
143 Logger::warn("GameMode API: loaded libgamemode.so but missing required symbols");
144 dlclose(handle_);
145 handle_ = nullptr;
146 startForFn_ = nullptr;
147 endForFn_ = nullptr;
148 errorStringFn_ = nullptr;
149 return;
150 }
151
152 Logger::info("GameMode API: loaded libgamemode.so.0 successfully");
153 }
154
155 ~GameModeAPI()
156 {
157 if (handle_)
158 dlclose(handle_);
159 }
160
161 public:
162 // Deleted copy ops are public so a misuse triggers the clearer
163 // `function deleted` diagnostic rather than `function private`
164 // (modernize-use-equals-delete).
165 GameModeAPI(const GameModeAPI&) = delete;
166 GameModeAPI& operator=(const GameModeAPI&) = delete;
167
168 private:
169 void* handle_ = nullptr;
170 int (*startForFn_)(pid_t) = nullptr;
171 int (*endForFn_)(pid_t) = nullptr;
172 const char* (*errorStringFn_)() = nullptr;
173};
174} // anonymous namespace
175#endif // !_WIN32
176
177// ==============================================================================
178// /proc/<pid>/stat Start Time Parser
179// ==============================================================================
180// Parses field 22 (starttime) from /proc/<pid>/stat to recover the actual
181// process start time. Returns 0 on failure.
182// ==============================================================================
183
184#ifndef _WIN32
185static time_t parseProcessStartTime(pid_t pid)
186{
187 std::string statPath = "/proc/" + std::to_string(pid) + "/stat";
188 std::ifstream statFile(statPath);
189 if (!statFile.is_open())
190 return 0;
191
192 std::string line;
193 if (!std::getline(statFile, line))
194 return 0;
195
196 // Fields after the comm field (which is in parentheses) start at field 3.
197 // Field 22 is starttime (clock ticks since boot), so after skipping the
198 // closing paren we need field index 20 (22 - 2).
199 size_t lastParen = line.rfind(')');
200 if (lastParen == std::string::npos || lastParen + 2 >= line.size())
201 return 0;
202
203 std::istringstream iss(line.substr(lastParen + 2));
204 std::string token;
205 int field = 0;
206 while (iss >> token)
207 {
208 field++;
209 if (field == 20)
210 {
211 try
212 {
213 unsigned long long startTicks = std::stoull(token);
214 std::ifstream uptimeFile("/proc/uptime");
215 if (!uptimeFile.is_open())
216 return 0;
217
218 double uptimeSeconds;
219 if (!(uptimeFile >> uptimeSeconds))
220 return 0;
221
222 long ticksPerSecond = sysconf(_SC_CLK_TCK);
223 double processStartSinceBoot =
224 static_cast<double>(startTicks) / static_cast<double>(ticksPerSecond);
225 time_t now = time(nullptr);
226 return now - static_cast<time_t>(uptimeSeconds - processStartSinceBoot);
227 }
228 catch (...)
229 {
230 return 0;
231 }
232 }
233 }
234 return 0;
235}
236#endif // !_WIN32
237
238// ==============================================================================
239// Flatpak Steam Detection
240// ==============================================================================
241// Detects whether Steam is installed via Flatpak (and native Steam is absent).
242// Used to select the correct command for launching Steam and Steam games.
243// ==============================================================================
244
245#ifndef _WIN32
246static bool isSteamFlatpak()
247{
248 static std::once_flag flag;
249 static bool flatpak = false;
250 std::call_once(flag,
251 []()
252 {
253 // Check if native Steam is installed
254 bool nativeSteamExists = std::filesystem::exists("/usr/bin/steam") ||
255 std::filesystem::exists("/usr/local/bin/steam");
256 if (!nativeSteamExists)
257 {
258 // Check for Flatpak Steam
260 "flatpak info com.valvesoftware.Steam 2>/dev/null");
261 flatpak = result.success;
262 }
263 });
264 return flatpak;
265}
266
267static std::string getSteamCommand()
268{
269 if (isSteamFlatpak())
270 return "flatpak run com.valvesoftware.Steam";
271 return "steam";
272}
273#endif // !_WIN32
274
275// ==============================================================================
276// GameProcess - Constructor & Destructor
277// ==============================================================================
278
280 : game_(game), state_(State::NotStarted), pid_(-1), trackedPid_(-1), startTime_(0),
281 isAttachedProcess_(false), gamemodePid_(-1)
282{
283 // Note: game_ is now a copy, not a reference, to prevent dangling references
284 // when the original Game object is destroyed (e.g., by GameLaunchManager::currentGame_.reset())
285}
286
288{
289 // Only stop processes that we actually launched
290 // For attached processes (games that were already running when we detected them),
291 // we should NOT stop them when the game launcher closes
292 if (isRunning() && !isAttachedProcess_)
293 {
294 stop();
295 }
296}
297
298// ==============================================================================
299// GameProcess - Notification Helper
300// ==============================================================================
301
302void GameProcess::notify(NotificationType type, const std::string& message) const
303{
304 if (onNotification_)
305 {
306 onNotification_(type, message);
307 }
308}
309
310// ==============================================================================
311// GameProcess - Launch Option Conflict Detection
312// ==============================================================================
313
314void GameProcess::checkLaunchOptionConflicts()
315{
316 const auto& config = game_.runnerConfig;
317 const auto& envVars = config.environmentVariables;
318
319 // 1. FSR + DLSS both enabled (mutually exclusive upscalers)
320 bool fsrEnabled = config.gamescopeEnableFSR;
321 bool dlssEnabled = false;
322 auto it = envVars.find("PROTON_DLSS_UPGRADE");
323 if (it != envVars.end() && it->second == "1")
324 dlssEnabled = true;
325 if (fsrEnabled && dlssEnabled)
326 {
328 "Potential conflict: FSR and DLSS are both enabled — they are mutually "
329 "exclusive upscalers, only one will take effect");
330 }
331
332 // 2. MangoHUD + DXVK HUD both enabled (overlapping overlays)
333 bool dxvkHudEnabled = false;
334 it = envVars.find("DXVK_HUD");
335 if (it != envVars.end() && !it->second.empty())
336 dxvkHudEnabled = true;
337 if (config.enableMangoHud && dxvkHudEnabled)
338 {
340 "Potential conflict: MangoHUD and DXVK HUD are both enabled — overlapping "
341 "overlays may cause visual clutter or performance issues");
342 }
343
344 // 3. Wine runner with Proton version set (wrong runner for the config)
345 if (game_.runner == GameRunner::Wine && !config.protonVersion.empty())
346 {
348 "Potential conflict: Runner is set to Wine but a Proton version is "
349 "configured — the Proton version will be ignored");
350 }
351
352 // 4. Native runner with Wine prefix set (doesn't make sense)
353 if (game_.runner == GameRunner::Native && !config.winePrefix.empty())
354 {
356 "Potential conflict: Runner is set to Native but a Wine prefix is "
357 "configured — the Wine prefix will be ignored");
358 }
359
360 // 5. HDR enabled without Gamescope (HDR requires gamescope on Linux Wayland)
361 if (config.gamescopeEnableHDR && !config.enableGamescope)
362 {
364 "Potential conflict: HDR is enabled but Gamescope is disabled — HDR output "
365 "requires Gamescope on Linux");
366 }
367}
368
369// ==============================================================================
370// GameProcess - Process Control
371// ==============================================================================
372
374{
375 if (state_ != State::NotStarted && state_ != State::Stopped)
376 {
377 Logger::error("Cannot launch: process already running or starting");
378 return false;
379 }
380
381 updateState(State::Starting);
382
383 // =========================================================================
384 // Pre-launch validation
385 // =========================================================================
386
387 // Skip executable check for Steam games (Steam handles the launch)
388 bool isSteamManaged = game_.metadata.isSteamGame && game_.metadata.steamAppId > 0;
389
390 if (!isSteamManaged)
391 {
392 if (game_.runnerConfig.executablePath.empty())
393 {
394 Logger::error("No executable path configured for game: {}", game_.name);
395 updateState(State::Error);
397 "Cannot launch '" + game_.name + "': no executable path configured");
398 return false;
399 }
400
401 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
402 {
403 Logger::error("Executable not found for game '{}': {}", game_.name,
404 game_.runnerConfig.executablePath);
405 updateState(State::Error);
406 notify(NotificationType::Error, "Cannot launch '" + game_.name +
407 "': executable not found at '" +
408 game_.runnerConfig.executablePath + "'");
409 return false;
410 }
411 }
412
413 // Runner-specific validation
414 if (game_.runner == GameRunner::Wine)
415 {
416 // Check if any wine binary is available
417 bool wineFound = false;
418 if (!game_.runnerConfig.winePath.empty() &&
419 std::filesystem::exists(game_.runnerConfig.winePath))
420 {
421 wineFound = true;
422 }
423 else if (std::filesystem::exists("/opt/wine-cachyos/bin/wine"))
424 {
425 wineFound = true;
426 }
427 else
428 {
429 // Check if wine is in PATH via 'which'
430 ProcessResult whichResult =
431 ProcessExecutor::executeWithOutput("which wine 2>/dev/null", true);
432 if (whichResult.exitCode == 0 && !whichResult.output.empty())
433 wineFound = true;
434 }
435
436 if (!wineFound)
437 {
438 Logger::error("Wine not found for game: {}", game_.name);
439 updateState(State::Error);
441 "Cannot launch '" + game_.name +
442 "': Wine is not installed. Install Wine or configure a custom Wine path.");
443 return false;
444 }
445 }
446 else if (game_.runner == GameRunner::Proton)
447 {
448 if (!isSteamManaged)
449 {
450 bool protonAvailable = isUmuLauncherAvailable();
451 if (!protonAvailable)
452 {
453 std::string protonPath = findProtonPath(game_.runnerConfig.protonVersion);
454 protonAvailable = !protonPath.empty();
455 }
456
457 if (!protonAvailable)
458 {
459 Logger::error("Proton not available for game: {}", game_.name);
460 updateState(State::Error);
462 "Cannot launch '" + game_.name + "': Neither umu-run nor Proton version '" +
463 game_.runnerConfig.protonVersion +
464 "' was found. Install umu-run or a Proton version.");
465 return false;
466 }
467 }
468 }
469
470 // =========================================================================
471 // Launch option conflict detection (warnings only, does not block launch)
472 // =========================================================================
473 checkLaunchOptionConflicts();
474
475 bool success = false;
476
477 try
478 {
479 // Launch based on runner (preferred) or platform (deprecated fallback)
480 // The runner field is the modern way to specify how to launch a game
481 switch (game_.runner)
482 {
484 success = launchNative();
485 break;
486
487 case GameRunner::Wine:
488 success = launchWine();
489 break;
490
492 success = launchProton();
493 break;
494
496 success = launchDOSBox();
497 break;
498
500 success = launchScummVM();
501 break;
502
503 default:
504 Logger::error("Unsupported runner for game: {}", game_.name);
505 updateState(State::Error);
506 return false;
507 }
508 }
509 catch (const std::filesystem::filesystem_error& e)
510 {
511 Logger::error("Filesystem error launching game '{}': {}", game_.name, e.what());
512 updateState(State::Error);
513 return false;
514 }
515 catch (const std::exception& e)
516 {
517 Logger::error("Exception launching game '{}': {}", game_.name, e.what());
518 updateState(State::Error);
519 return false;
520 }
521 catch (...)
522 {
523 Logger::error("Unknown exception launching game '{}'", game_.name);
524 updateState(State::Error);
525 return false;
526 }
527
528 if (success)
529 {
530 startTime_ = time(nullptr);
531 updateState(State::Running);
532 Logger::info("Launched game: {} (PID: {})", game_.name, pid_);
533
534 // Start frame metrics collection for NON-Steam games only
535 // Steam games launched via "steam -applaunch" are detected by the background thread
536 // which handles frame metrics collection when the actual game process starts.
537 // Starting collection here for Steam games would use the wrong PID (steam launcher)
538 // and interfere with the background thread's detection.
539 if (pid_ > 0 && !game_.metadata.isSteamGame)
540 {
541 // The gamescope SysV message queue is a destructive single-consumer
542 // protocol — when --mangoapp is active, mangoapp does blocking
543 // msgrcv with no MSG_COPY (per upstream src/app/main.cpp), so any
544 // second reader starves once mangoapp's loop spins up. PR #1660 in
545 // ValveSoftware/gamescope tried to add a third-party-friendly
546 // queue but was abandoned. Until upstream provides a non-
547 // destructive path, stay on MangoHud CSV logging — its config
548 // is now isolated via MANGOHUD_CONFIGFILE.
549 FrameMetricsService::instance().startCollection(game_.id, pid_, false, true);
550 }
551
552#ifndef _WIN32
553 // Apply GameMode to the launched process PID via the libgamemode API.
554 // This complements the gamemoderun wrapper: the wrapper applies GameMode to the
555 // shell/wrapper process tree, while this targets the specific PID directly.
556 // For launcher games (Battle.net, EA App), the tracked PID will be updated later
557 // in checkProcessRunning() when the actual game process is detected.
558 if (game_.runnerConfig.enableGameMode && pid_ > 0)
559 {
560 GameModeAPI::instance().requestStartFor(static_cast<pid_t>(pid_));
561 gamemodePid_ = pid_;
562 }
563#endif
564 }
565 else
566 {
567 updateState(State::Error);
568 Logger::error("Failed to launch game: {}", game_.name);
569
570 // Show user-friendly error based on runner type
571 std::string errorMsg = "Failed to launch: " + game_.name;
572 switch (game_.runner)
573 {
574 case GameRunner::Wine:
575 errorMsg += " (Wine not available or executable not found)";
576 break;
578 errorMsg += " (Proton/umu-launcher not available or executable not found)";
579 break;
580 default:
581 errorMsg += " (check executable path)";
582 break;
583 }
585 }
586
587 return success;
588}
589
591{
592 if (!isRunning())
593 {
594 return false;
595 }
596
597 // Stop frame metrics collection
599
600 updateState(State::Stopping);
601
602#ifdef _WIN32
603 // Windows: Use TerminateProcess
604 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid_);
605 if (hProcess != NULL)
606 {
607 TerminateProcess(hProcess, 0);
608 CloseHandle(hProcess);
609 }
610#else
611 // Unix: Send SIGTERM to tracked game process first (if different from launcher)
612 if (trackedPid_ > 0 && trackedPid_ != pid_)
613 {
614 Logger::info("Stopping tracked game process: PID {} ({})", trackedPid_,
615 trackedProcessName_);
616 ::kill(trackedPid_, SIGTERM);
617 }
618
619 // For Wine games, kill all processes in the WINEPREFIX for clean shutdown
620 if (!game_.runnerConfig.winePrefix.empty())
621 {
622 killWinePrefix(false); // Graceful shutdown with SIGTERM
623 }
624
625 // Also terminate the launcher process
626 if (pid_ > 0)
627 {
628 ::kill(pid_, SIGTERM);
629
630 // Wait up to 3 seconds for graceful exit before proceeding
631 for (int i = 0; i < 30; ++i)
632 {
633 int status;
634 pid_t result = waitpid(pid_, &status, WNOHANG);
635 if (result > 0)
636 {
637 break; // Process exited gracefully
638 }
639 std::this_thread::sleep_for(std::chrono::milliseconds(100));
640 }
641
642 // If still running after 3 seconds, force kill
643 if (::kill(pid_, 0) == 0)
644 {
645 Logger::warn("Process {} did not exit after SIGTERM, sending SIGKILL", pid_);
646 ::kill(pid_, SIGKILL);
647 if (waitpid(pid_, nullptr, 0) < 0 && errno != ECHILD)
648 {
649 Logger::warn("waitpid after SIGKILL failed for pid {}: {}", pid_, strerror(errno));
650 }
651 }
652 }
653#endif
654
655 // Update play time
656 if (startTime_ > 0)
657 {
658 time_t now = time(nullptr);
659 double sessionTime = difftime(now, startTime_);
660 if (sessionTime > 0.0)
661 {
662 game_.statistics.totalPlayTimeSeconds += sessionTime;
663 game_.statistics.lastPlayed = now;
664 }
665 }
666
667 pid_ = -1;
668 trackedPid_ = -1;
669 trackedProcessName_.clear();
670 updateState(State::Stopped);
671
672 return true;
673}
674
676{
677 if (!isRunning())
678 {
679 return false;
680 }
681
682#ifdef _WIN32
683 // Windows: Use TerminateProcess with force
684 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid_);
685 if (hProcess != NULL)
686 {
687 TerminateProcess(hProcess, 1);
688 CloseHandle(hProcess);
689 }
690#else
691 // Unix: Force kill tracked game process first (if different from launcher)
692 if (trackedPid_ > 0 && trackedPid_ != pid_)
693 {
694 Logger::info("Force killing tracked game process: PID {} ({})", trackedPid_,
695 trackedProcessName_);
696 ::kill(trackedPid_, SIGKILL);
697 }
698
699 // For Wine games, force kill all processes in the WINEPREFIX
700 if (!game_.runnerConfig.winePrefix.empty())
701 {
702 killWinePrefix(true); // Force kill with SIGKILL
703 }
704
705 // Also kill the launcher process and reap the zombie
706 if (pid_ > 0)
707 {
708 ::kill(pid_, SIGKILL);
709 // Reap the child to avoid a zombie process
710 int status;
711 if (waitpid(pid_, &status, 0) < 0 && errno != ECHILD)
712 {
713 Logger::warn("waitpid after SIGKILL (kill) failed for pid {}: {}", pid_,
714 strerror(errno));
715 }
716 }
717#endif
718
719 // Update play time before clearing state (same as stop())
720 if (startTime_ > 0)
721 {
722 time_t now = time(nullptr);
723 double sessionTime = difftime(now, startTime_);
724 if (sessionTime > 0.0)
725 {
726 game_.statistics.totalPlayTimeSeconds += sessionTime;
727 game_.statistics.lastPlayed = now;
728 }
729 }
730
731 pid_ = -1;
732 trackedPid_ = -1;
733 trackedProcessName_.clear();
734 updateState(State::Stopped);
735
736 return true;
737}
738
739// ==============================================================================
740// GameProcess - Attach to Running Process
741// ==============================================================================
742
743void GameProcess::attachToRunningProcess(int pid, const std::string& processName)
744{
745 if (pid <= 0)
746 {
747 Logger::error("Cannot attach to process: invalid PID {}", pid);
748 return;
749 }
750
751 // Mark this as an attached process (not spawned by us)
752 isAttachedProcess_ = true;
753
754 // Set the process state
755 pid_ = pid;
756 trackedPid_ = pid;
757 trackedProcessName_ = processName;
758 startTime_ = time(nullptr); // Approximate - we don't know the actual start time
759
760 // Try to get the actual start time from /proc
761#ifndef _WIN32
762 {
763 time_t parsed = parseProcessStartTime(pid);
764 if (parsed > 0)
765 {
766 startTime_ = parsed;
767 Logger::debug("Recovered actual start time for PID {}: {} seconds ago", pid,
768 time(nullptr) - startTime_);
769 }
770 }
771
772 // For launcher games, immediately scan for the actual game process
773 // This is important when attaching to an already-running Battle.net that has WoW open
774 if (!game_.runnerConfig.excludeProcesses.empty())
775 {
776 int gameProc = findGameProcess();
777 if (gameProc > 0 && gameProc != pid)
778 {
779 // Get exe name directly from this specific PID's cmdline
780 std::string gameProcName;
781 std::string cmdlinePath = "/proc/" + std::to_string(gameProc) + "/cmdline";
782 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
783 if (cmdlineFile.is_open())
784 {
785 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
786 std::istreambuf_iterator<char>());
787 // Find first .exe argument
788 size_t cmdStart = 0;
789 while (cmdStart < cmdline.size())
790 {
791 size_t cmdEnd = cmdline.find('\0', cmdStart);
792 if (cmdEnd == std::string::npos)
793 cmdEnd = cmdline.size();
794 std::string arg = cmdline.substr(cmdStart, cmdEnd - cmdStart);
795 std::string argLower = arg;
796 for (char& c : argLower)
797 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
798 if (argLower.find(".exe") != std::string::npos)
799 {
800 size_t lastSlash = arg.find_last_of("/\\");
801 gameProcName =
802 (lastSlash != std::string::npos) ? arg.substr(lastSlash + 1) : arg;
803 break;
804 }
805 cmdStart = cmdEnd + 1;
806 }
807 }
808 if (gameProcName.empty())
809 {
810 gameProcName = getProcessName(gameProc);
811 }
812 trackedPid_ = gameProc;
813 trackedProcessName_ = gameProcName;
814
815 // Try to get the actual game's start time
816 {
817 time_t parsed = parseProcessStartTime(gameProc);
818 if (parsed > 0)
819 {
820 startTime_ = parsed;
821 Logger::debug("Updated start time to actual game process: {} seconds ago",
822 time(nullptr) - startTime_);
823 }
824 }
825
826 Logger::info("Detected actual game process: PID {} ({}) running under launcher PID {}",
827 trackedPid_, trackedProcessName_, pid);
828
829 // Try to start frame metrics collection for the actual game process
830 // This will work if MangoHud logging was enabled by Lutris or system-wide config
831 if (FrameMetricsService::instance().startCollection(game_.id, trackedPid_, false, true))
832 {
833 Logger::info("Started frame metrics collection for attached game process: PID {}",
834 trackedPid_);
835 }
836 }
837 }
838 else
839 {
840 // No exclude list - this might be a direct game, try to start metrics for main PID
841 if (FrameMetricsService::instance().startCollection(game_.id, pid, false, true))
842 {
843 Logger::info("Started frame metrics collection for attached process: PID {}", pid);
844 }
845 }
846
847 // Apply GameMode to the detected game PID for attached processes too
848 if (game_.runnerConfig.enableGameMode)
849 {
850 pid_t targetPid =
851 static_cast<pid_t>((trackedPid_ > 0 && trackedPid_ != pid_) ? trackedPid_ : pid_);
853 gamemodePid_ = static_cast<int>(targetPid);
854 }
855#endif
856
857 updateState(State::Running);
858 Logger::info("Attached to running process: PID {} ({})", pid, processName);
859}
860
861// ==============================================================================
862// GameProcess - State Query
863// ==============================================================================
864
865namespace
866{
867// Read process start time from /proc/<pid>/stat
868// Returns 0 on failure
870{
871#ifdef PLATFORM_LINUX
872 if (pid <= 0)
873 return 0;
874
875 // Read /proc/<pid>/stat
876 std::string statPath = "/proc/" + std::to_string(pid) + "/stat";
877 std::ifstream statFile(statPath);
878 if (!statFile.is_open())
879 return 0;
880
881 std::string line;
882 if (!std::getline(statFile, line))
883 return 0;
884
885 // Parse the stat file - field 22 is starttime (in clock ticks since boot)
886 // Format: pid (comm) state ppid pgrp session tty_nr tpgid flags minflt cminflt majflt cmajflt
887 // utime stime cutime cstime priority nice num_threads itrealvalue starttime ...
888 // Note: comm can contain spaces and parentheses, so we need to find the last ')' first
889
890 size_t lastParen = line.rfind(')');
891 if (lastParen == std::string::npos || lastParen + 2 >= line.size())
892 return 0;
893
894 // Skip past ") " and parse remaining fields
895 std::istringstream iss(line.substr(lastParen + 2));
896 std::string field;
897 int fieldNum = 0;
898 unsigned long long starttime = 0;
899
900 // Fields after (comm): state(1) ppid(2) ... starttime(20)
901 while (iss >> field && fieldNum < 20)
902 {
903 fieldNum++;
904 if (fieldNum == 20) // starttime is field 20 after the (comm)
905 {
906 try
907 {
908 starttime = std::stoull(field);
909 }
910 catch (...)
911 {
912 return 0;
913 }
914 break;
915 }
916 }
917
918 if (starttime == 0)
919 return 0;
920
921 // Get system boot time from /proc/stat
922 std::ifstream procStat("/proc/stat");
923 if (!procStat.is_open())
924 return 0;
925
926 time_t bootTime = 0;
927 while (std::getline(procStat, line))
928 {
929 if (line.compare(0, 6, "btime ") == 0)
930 {
931 try
932 {
933 bootTime = static_cast<time_t>(std::stoll(line.substr(6)));
934 }
935 catch (...)
936 {
937 return 0;
938 }
939 break;
940 }
941 }
942
943 if (bootTime == 0)
944 return 0;
945
946 // Get clock ticks per second
947 long ticksPerSec = sysconf(_SC_CLK_TCK);
948 if (ticksPerSec <= 0)
949 ticksPerSec = 100; // Default fallback
950
951 // Calculate actual start time
952 time_t processStartTime =
953 bootTime + static_cast<time_t>(starttime / static_cast<unsigned long long>(ticksPerSec));
954 return processStartTime;
955#else
956 return 0;
957#endif
958}
959} // namespace
960
962{
963 if (!isRunning())
964 {
965 return 0.0;
966 }
967
968 // Try to get the actual process start time from /proc for accuracy
969 int targetPid = (trackedPid_ > 0) ? trackedPid_ : pid_;
970 time_t procStartTime = getProcessStartTimeFromProc(targetPid);
971
972 if (procStartTime > 0)
973 {
974 // Use actual process start time from system
975 time_t now = time(nullptr);
976 return difftime(now, procStartTime);
977 }
978
979 // Fallback to our recorded start time
980 if (startTime_ == 0)
981 {
982 return 0.0;
983 }
984
985 time_t now = time(nullptr);
986 return difftime(now, startTime_);
987}
988
989// ==============================================================================
990// GameProcess - Update
991// ==============================================================================
992
994{
995 if (state_ == State::Running)
996 {
997 // Check if process is still running
998 if (!checkProcessRunning())
999 {
1000 // Process has exited
1001 Logger::info("Game process exited: {}", game_.name);
1002
1003 // Reap zombie process and get actual exit code
1004 int exitCode = 0;
1005#ifndef _WIN32
1006 if (pid_ > 0)
1007 {
1008 int status = 0;
1009 pid_t result = waitpid(pid_, &status, WNOHANG);
1010 if (result > 0)
1011 {
1012 if (WIFEXITED(status))
1013 {
1014 exitCode = WEXITSTATUS(status);
1015 }
1016 else if (WIFSIGNALED(status))
1017 {
1018 exitCode = 128 + WTERMSIG(status);
1019 Logger::warn("Game process killed by signal {}", WTERMSIG(status));
1020 }
1021 }
1022 }
1023#endif
1024
1025 // Stop frame metrics collection
1027
1028 // Update play time (guard against negative values from clock adjustments)
1029 if (startTime_ > 0)
1030 {
1031 time_t now = time(nullptr);
1032 double sessionTime = difftime(now, startTime_);
1033 if (sessionTime > 0.0)
1034 {
1035 game_.statistics.totalPlayTimeSeconds += sessionTime;
1036 game_.statistics.lastPlayed = now;
1037 }
1038 }
1039
1040 updateState(State::Stopped);
1041
1042 if (onExit_)
1043 {
1044 onExit_(exitCode);
1045 }
1046 }
1047 }
1048}
1049
1050// ==============================================================================
1051// GameProcess - Private Methods
1052// ==============================================================================
1053
1054void GameProcess::updateState(State newState)
1055{
1056 if (state_ != newState)
1057 {
1058#ifndef _WIN32
1059 // End GameMode API request when the game stops (complements gamemoderun wrapper cleanup)
1060 if ((newState == State::Stopped || newState == State::Error) && gamemodePid_ > 0)
1061 {
1062 GameModeAPI::instance().requestEndFor(static_cast<pid_t>(gamemodePid_));
1063 gamemodePid_ = -1;
1064 }
1065#endif
1066
1067 state_ = newState;
1068
1069 if (onStateChanged_)
1070 {
1071 onStateChanged_(newState);
1072 }
1073 }
1074}
1075
1076std::string GameProcess::buildLaunchCommand() const
1077{
1078 std::ostringstream cmd;
1079
1080 // ==========================================================================
1081 // Build launch command following CachyOS best practices:
1082 // <env variables> <wrappers> %command% <application arguments>
1083 // https://wiki.cachyos.org/configuration/gaming/
1084 //
1085 // SECURITY: All user-provided values are escaped using ShellUtils to prevent
1086 // command injection attacks.
1087 // ==========================================================================
1088
1089 // Step 1: Add all environment variables FIRST (with safe escaping)
1090 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
1091 {
1092 // Skip wrapper markers - these are internal flags, not actual env vars
1093 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
1094 continue;
1095
1096 // Validate environment variable name to prevent injection
1098 {
1099 Logger::warn("Skipping invalid environment variable name: {}", key);
1100 continue;
1101 }
1102
1103 // Use safe escaping for the value
1104 cmd << ShellUtils::formatEnvVar(key, value) << " ";
1105 }
1106
1107 // Detect if we're launching through Steam (steam -applaunch).
1108 // When Steam manages the launch, it handles Proton, env vars, overlays, etc.
1109 // We should NOT inject our own Steam compat env vars or game-performance wrapper
1110 // around the steam command — those need to go through Steam's launch options instead.
1111 bool isSteamManagedLaunch = game_.metadata.isSteamGame && game_.metadata.steamAppId > 0 &&
1112 game_.runnerConfig.executablePath == "steam";
1113
1114 if (!isSteamManagedLaunch)
1115 {
1116 // Direct Proton/Wine launch — add Steam compat environment variables
1117 if (game_.metadata.isSteamGame && game_.metadata.steamAppId > 0)
1118 {
1119 const char* home = std::getenv("HOME");
1120 if (home)
1121 {
1122 std::filesystem::path steamPath =
1123 std::filesystem::path(home) / ".local" / "share" / "Steam";
1124 std::filesystem::path compatDataPath = steamPath / "steamapps" / "compatdata" /
1125 std::to_string(game_.metadata.steamAppId);
1126
1127 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_DATA_PATH", compatDataPath.string())
1128 << " ";
1129 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_CLIENT_INSTALL_PATH",
1130 steamPath.string())
1131 << " ";
1132 cmd << "SteamAppId=" << game_.metadata.steamAppId << " ";
1133 cmd << "SteamGameId=" << game_.metadata.steamAppId << " ";
1134 }
1135 }
1136
1137 // Step 2: Add performance wrappers if enabled
1138 // Order follows CachyOS best practices: game-performance > gamemoderun > mangohud
1139 // Check both the bool flag and legacy env var markers for backwards compatibility
1140 if (game_.runnerConfig.enableGamePerformance ||
1141 game_.runnerConfig.environmentVariables.count("GAME_PERFORMANCE") > 0 ||
1142 game_.runnerConfig.environmentVariables.count("USE_GAME_PERFORMANCE") > 0)
1143 {
1144 cmd << "game-performance ";
1145 }
1146
1147 if (game_.runnerConfig.enableGameMode &&
1149 {
1150 cmd << "gamemoderun ";
1151 }
1152 else if (game_.runnerConfig.enableGameMode)
1153 {
1154 Logger::info("Skipping gamemoderun — ananicy-cpp.service is active "
1155 "and already manages scheduling");
1156 }
1157 }
1158
1159 // Step 3: Add the actual command/executable (safely escaped)
1160 cmd << ShellUtils::escapeArg(game_.runnerConfig.executablePath);
1161
1162 // Step 4: Add application arguments LAST (each argument escaped separately)
1163 // Note: arguments is a single string that may contain multiple args
1164 // For maximum safety, we escape the entire string - users should use proper quoting
1165 if (!game_.runnerConfig.arguments.empty())
1166 {
1167 // Split arguments by spaces (respecting quotes) and escape each one
1168 // Split args respecting shell quoting, then escape each token safely
1169 for (const auto& arg : ShellUtils::splitArgs(game_.runnerConfig.arguments))
1170 cmd << " " << ShellUtils::escapeArg(arg);
1171 }
1172
1173 return cmd.str();
1174}
1175
1176bool GameProcess::isSteamRunning()
1177{
1178 return ProcessExecutor::isProcessRunning("steam");
1179}
1180
1181bool GameProcess::ensureSteamRunning()
1182{
1183 if (isSteamRunning())
1184 {
1185 return true;
1186 }
1187
1188 // The `-silent` flag asks Steam to start in the system tray without
1189 // popping a foreground window. Per ValveSoftware/steam-for-linux#1983,
1190 // this only takes effect on a *cold* start — passing `-silent` to a
1191 // second invocation is IPC'd to the existing instance and ignored. We
1192 // are explicitly in the cold-start branch here (isSteamRunning() was
1193 // false), so honouring the user's `steamMinimized` setting is meaningful.
1194 const bool launchSilent = core::SettingsController::readSteamMinimizedFromDisk();
1195 Logger::info("Steam is not running. Starting Steam ({})...",
1196 launchSilent ? "silent / tray" : "foreground");
1197
1198#ifdef _WIN32
1199 ProcessExecutor::execute(launchSilent ? "start steam -silent" : "start steam://open/main");
1200#else
1201 std::string startCmd = getSteamCommand();
1202 if (launchSilent)
1203 startCmd += " -silent";
1205#endif
1206
1207 // Wait for Steam to initialize (give it up to 10 seconds)
1208 for (int i = 0; i < 20; i++)
1209 {
1210 std::this_thread::sleep_for(std::chrono::milliseconds(500));
1211
1212 if (isSteamRunning())
1213 {
1214 Logger::info("Steam started successfully");
1215 // Give it a bit more time to fully initialize
1216 std::this_thread::sleep_for(std::chrono::seconds(2));
1217 return true;
1218 }
1219 }
1220
1221 Logger::error("Failed to start Steam (timeout)");
1222 return false;
1223}
1224
1225bool GameProcess::launchDOSBox()
1226{
1227 // Find the DOSBox binary: try dosbox, dosbox-staging, dosbox-x
1228 std::string dosboxBin;
1229 for (const auto& candidate : {"dosbox", "dosbox-staging", "dosbox-x"})
1230 {
1231 auto result = ProcessExecutor::executeWithOutput(std::string("which ") + candidate, true);
1232 if (result.success)
1233 {
1234 dosboxBin = candidate;
1235 break;
1236 }
1237 }
1238
1239 if (dosboxBin.empty())
1240 {
1241 Logger::error("DOSBox not found. Install dosbox, dosbox-staging, or dosbox-x.");
1243 "DOSBox not found. Install dosbox, dosbox-staging, or dosbox-x.");
1244 return false;
1245 }
1246
1247 // Build the launch command
1248 std::ostringstream cmd;
1249
1250 // Add environment variables
1251 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
1252 {
1253 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
1254 continue;
1256 continue;
1257 cmd << ShellUtils::formatEnvVar(key, value) << " ";
1258 }
1259
1260 // If the executable path ends in .conf, launch as: dosbox -conf <path>
1261 // Otherwise, launch as: dosbox <path>
1262 const std::string& exePath = game_.runnerConfig.executablePath;
1263 if (exePath.size() >= 5 && exePath.substr(exePath.size() - 5) == ".conf")
1264 {
1265 cmd << dosboxBin << " -conf " << ShellUtils::escapeArg(exePath);
1266 }
1267 else
1268 {
1269 cmd << dosboxBin << " " << ShellUtils::escapeArg(exePath);
1270 }
1271
1272 // Add any additional arguments (split respecting quoting, escape each token)
1273 for (const auto& arg : ShellUtils::splitArgs(game_.runnerConfig.arguments))
1274 cmd << " " << ShellUtils::escapeArg(arg);
1275
1276 Logger::info("Launching DOSBox game: {}", cmd.str());
1277 return executeCommand(cmd.str());
1278}
1279
1280bool GameProcess::launchScummVM()
1281{
1282 // Check if scummvm command exists
1283 auto whichResult = ProcessExecutor::executeWithOutput("which scummvm", true);
1284 if (!whichResult.success)
1285 {
1286 Logger::error("ScummVM not found. Install scummvm.");
1287 notify(NotificationType::Error, "ScummVM not found. Install scummvm.");
1288 return false;
1289 }
1290
1291 // Build the launch command
1292 std::ostringstream cmd;
1293
1294 // Add environment variables
1295 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
1296 {
1297 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
1298 continue;
1300 continue;
1301 cmd << ShellUtils::formatEnvVar(key, value) << " ";
1302 }
1303
1304 // If a game ID is stored in runnerConfig.arguments, launch as: scummvm <game_id>
1305 // Otherwise, launch as: scummvm -p <install_dir>
1306 if (!game_.runnerConfig.arguments.empty())
1307 {
1308 cmd << "scummvm " << ShellUtils::escapeArg(game_.runnerConfig.arguments);
1309 }
1310 else if (!game_.runnerConfig.workingDirectory.empty())
1311 {
1312 cmd << "scummvm -p " << ShellUtils::escapeArg(game_.runnerConfig.workingDirectory);
1313 }
1314 else
1315 {
1316 Logger::error("ScummVM game '{}' has no game ID or install directory", game_.name);
1318 "ScummVM game has no game ID or install directory configured.");
1319 return false;
1320 }
1321
1322 Logger::info("Launching ScummVM game: {}", cmd.str());
1323 return executeCommand(cmd.str());
1324}
1325
1326bool GameProcess::launchNative()
1327{
1328 // If this is a Steam game, ensure Steam is running first
1329 if (game_.metadata.isSteamGame)
1330 {
1331 if (!ensureSteamRunning())
1332 {
1333 Logger::error("Cannot launch Steam game: Steam is not running and failed to start");
1334 return false;
1335 }
1336 }
1337
1338 std::string command = buildLaunchCommand();
1339
1340 Logger::info("Launching native game: {}", command);
1341
1342 // For Steam games, we can't track PID reliably because the steam command exits immediately
1343 // We'll need to manually track these games
1344
1345#ifdef _WIN32
1346 // Windows: Use CreateProcess
1347 STARTUPINFO si;
1348 PROCESS_INFORMATION pi;
1349 ZeroMemory(&si, sizeof(si));
1350 si.cb = sizeof(si);
1351 ZeroMemory(&pi, sizeof(pi));
1352
1353 // Convert command to mutable string
1354 std::vector<char> cmdLine(command.begin(), command.end());
1355 cmdLine.push_back('\0');
1356
1357 if (CreateProcess(NULL, cmdLine.data(), NULL, NULL, FALSE, 0, NULL,
1358 game_.runnerConfig.workingDirectory.empty()
1359 ? NULL
1360 : game_.runnerConfig.workingDirectory.c_str(),
1361 &si, &pi))
1362 {
1363 pid_ = pi.dwProcessId;
1364 CloseHandle(pi.hProcess);
1365 CloseHandle(pi.hThread);
1366 return true;
1367 }
1368 return false;
1369#else
1370 // Unix: Use fork/exec
1371 // Copy C strings before fork for async-signal safety in multithreaded programs
1372 std::string workDirCopy = game_.runnerConfig.workingDirectory;
1373 std::string commandCopy = command;
1374
1375 pid_t pid = fork();
1376
1377 if (pid == 0)
1378 {
1379 // Child process
1380 // IMPORTANT: After fork(), only use async-signal-safe functions
1381 // Logger is NOT safe to use here - use write() to stderr instead
1382
1383 // Change working directory if specified
1384 if (!workDirCopy.empty())
1385 {
1386 if (chdir(workDirCopy.c_str()) != 0)
1387 {
1388 const char* msg = "GameLauncher: Failed to change working directory\n";
1389 [[maybe_unused]] auto _ = write(STDERR_FILENO, msg, strlen(msg));
1390 _exit(127);
1391 }
1392 }
1393
1394 // Note: Environment variables are now part of the command string itself
1395 // following CachyOS best practices: <env vars> <wrappers> %command% <args>
1396 // This ensures proper ordering and compatibility with game-performance wrapper
1397
1398 // Close inherited file descriptors (except stdin/stdout/stderr)
1399 long maxFd = sysconf(_SC_OPEN_MAX);
1400 if (maxFd < 0)
1401 maxFd = 1024;
1402 for (long fd = 3; fd < maxFd; ++fd)
1403 {
1404 close(static_cast<int>(fd));
1405 }
1406
1407 // Execute the command
1408 execl("/bin/sh", "sh", "-c", commandCopy.c_str(), static_cast<char*>(nullptr));
1409
1410 // If execl returns, there was an error - only use async-safe functions
1411 const char* msg = "GameLauncher: Failed to execute command\n";
1412 [[maybe_unused]] auto _ = write(STDERR_FILENO, msg, strlen(msg));
1413 _exit(127);
1414 }
1415 else if (pid > 0)
1416 {
1417 // Parent process
1418 pid_ = pid;
1419 return true;
1420 }
1421 else
1422 {
1423 // Fork failed - safe to use Logger here (still in parent)
1424 Logger::error("Failed to fork process: {}", strerror(errno));
1425 return false;
1426 }
1427#endif
1428}
1429
1430bool GameProcess::executeCommand(const std::string& command)
1431{
1432 // ==========================================================================
1433 // Direct command execution for Wine/Proton games
1434 // This avoids modifying game_.runnerConfig which could corrupt state
1435 // ==========================================================================
1436
1437 Logger::info("Executing command: {}", command);
1438
1439#ifdef _WIN32
1440 // Windows: Use CreateProcess
1441 STARTUPINFO si;
1442 PROCESS_INFORMATION pi;
1443 ZeroMemory(&si, sizeof(si));
1444 si.cb = sizeof(si);
1445 ZeroMemory(&pi, sizeof(pi));
1446
1447 std::vector<char> cmdLine(command.begin(), command.end());
1448 cmdLine.push_back('\0');
1449
1450 if (CreateProcess(NULL, cmdLine.data(), NULL, NULL, FALSE, 0, NULL,
1451 game_.runnerConfig.workingDirectory.empty()
1452 ? NULL
1453 : game_.runnerConfig.workingDirectory.c_str(),
1454 &si, &pi))
1455 {
1456 pid_ = pi.dwProcessId;
1457 CloseHandle(pi.hProcess);
1458 CloseHandle(pi.hThread);
1459 return true;
1460 }
1461 return false;
1462#else
1463 // Unix: Use fork/exec
1464 //
1465 // Copy C strings into stack-local std::strings BEFORE fork. The
1466 // copies are intentional defence-in-depth: between fork() and execl()
1467 // the child must only call async-signal-safe functions, and while
1468 // libstdc++'s std::string::c_str() is currently a no-op (returns the
1469 // internal pointer), that's a libstdc++ implementation detail not a
1470 // standard guarantee. Constructing the local copies in the parent
1471 // before fork eliminates any future-libstdc++ surprise where c_str()
1472 // could touch ref-counts or the SSO buffer.
1473 //
1474 // NOLINT below: clang-tidy flags `commandCopy2` as
1475 // performance-unnecessary-copy-initialization because it isn't
1476 // mutated. It's the explicit pre-fork copy that's the point.
1477 std::string workDirCopy2 = game_.runnerConfig.workingDirectory;
1478 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) - see above.
1479 std::string commandCopy2 = command;
1480
1481 pid_t pid = fork();
1482
1483 if (pid == 0)
1484 {
1485 // Child process
1486 // IMPORTANT: After fork(), only use async-signal-safe functions
1487 // Logger is NOT safe to use here - use write() to stderr instead
1488
1489 // Change working directory if specified
1490 if (!workDirCopy2.empty())
1491 {
1492 if (chdir(workDirCopy2.c_str()) != 0)
1493 {
1494 // Use write() - async-signal-safe, unlike fprintf/Logger
1495 const char* msg = "GameLauncher: Failed to change working directory\n";
1496 [[maybe_unused]] auto _ = write(STDERR_FILENO, msg, strlen(msg));
1497 _exit(127); // Use _exit, not exit (safer after fork)
1498 }
1499 }
1500
1501 // Close inherited file descriptors (except stdin/stdout/stderr)
1502 long maxFd = sysconf(_SC_OPEN_MAX);
1503 if (maxFd < 0)
1504 maxFd = 1024;
1505 for (long fd = 3; fd < maxFd; ++fd)
1506 {
1507 close(static_cast<int>(fd));
1508 }
1509
1510 // Execute the command via shell
1511 execl("/bin/sh", "sh", "-c", commandCopy2.c_str(), static_cast<char*>(nullptr));
1512
1513 // If execl returns, there was an error - only use async-safe functions
1514 const char* msg = "GameLauncher: Failed to execute command\n";
1515 [[maybe_unused]] auto _ = write(STDERR_FILENO, msg, strlen(msg));
1516 _exit(127);
1517 }
1518 else if (pid > 0)
1519 {
1520 // Parent process
1521 pid_ = pid;
1522 return true;
1523 }
1524 else
1525 {
1526 // Fork failed - safe to use Logger here (still in parent)
1527 Logger::error("Failed to fork process: {}", strerror(errno));
1528 return false;
1529 }
1530#endif
1531}
1532
1533// ==============================================================================
1534// System Capability Detection Helpers
1535// ==============================================================================
1536
1537namespace
1538{
1539
1540// Wine system executables to always skip - these are never games. Wrapped
1541// in a Meyer's-singleton accessor: file-scope `static const std::vector`
1542// is bugprone-throwing-static-initialization / CERT ERR58-CPP because
1543// std::string allocations inside the vector aren't catchable at static
1544// init. Function-local statics defer init to first call (thread-safe per
1545// [stmt.dcl]/4).
1546const std::vector<std::string>& kWineSystemExes()
1547{
1548 static const std::vector<std::string> exes = {
1549 "winedevice.exe", "services.exe", "plugplay.exe", "wineboot.exe", "explorer.exe",
1550 "rpcss.exe", "tabtip.exe", "svchost.exe", "conhost.exe", "start.exe",
1551 "cmd.exe", "wineconsole.exe", "rundll32.exe", "regsvr32.exe",
1552 "steam.exe" // Proton shim
1553 };
1554 return exes;
1555}
1556
1557/**
1558 * @brief Detect GPU vendor for GPU-specific optimizations
1559 * @return "AMD", "NVIDIA", "Intel", or "Unknown"
1560 */
1561std::string detectGPUVendor()
1562{
1563 static std::once_flag flag;
1564 static std::string cached;
1565
1566 std::call_once(
1567 flag,
1568 []()
1569 {
1570 // Try reading from /sys/class/drm
1571 try
1572 {
1573 for (const auto& entry : std::filesystem::directory_iterator("/sys/class/drm"))
1574 {
1575 std::string name = entry.path().filename().string();
1576 if (name.find("card") == 0 && name.find("-") == std::string::npos)
1577 {
1578 std::filesystem::path vendorPath = entry.path() / "device" / "vendor";
1579 if (std::filesystem::exists(vendorPath))
1580 {
1581 std::ifstream vendorFile(vendorPath);
1582 std::string vendorId;
1583 if (vendorFile >> vendorId)
1584 {
1585 if (vendorId == "0x1002" || vendorId == "0x1022")
1586 {
1587 cached = "AMD";
1588 return;
1589 }
1590 else if (vendorId == "0x10de")
1591 {
1592 cached = "NVIDIA";
1593 return;
1594 }
1595 else if (vendorId == "0x8086")
1596 {
1597 cached = "Intel";
1598 return;
1599 }
1600 }
1601 }
1602 }
1603 }
1604 }
1605 catch (...)
1606 {
1607 // Filesystem errors are non-fatal
1608 }
1609
1610 cached = "Unknown";
1611 });
1612
1613 return cached;
1614}
1615
1616/**
1617 * @brief Check if kernel supports Fsync (futex2)
1618 * @return true if Fsync is supported
1619 */
1621{
1622 static std::once_flag flag;
1623 static bool result = false;
1624
1625 std::call_once(flag,
1626 []()
1627 {
1628 // Check kernel version - Fsync requires 5.16+.
1629 // strtol over sscanf so an unparseable major / minor
1630 // is detected (cert-err34-c: sscanf can't report
1631 // conversion errors).
1632 struct utsname uts;
1633 if (uname(&uts) == 0)
1634 {
1635 char* endMajor = nullptr;
1636 const long major = std::strtol(uts.release, &endMajor, 10);
1637 if (endMajor && *endMajor == '.' && endMajor != uts.release)
1638 {
1639 char* endMinor = nullptr;
1640 const long minor = std::strtol(endMajor + 1, &endMinor, 10);
1641 if (endMinor && endMinor != endMajor + 1)
1642 {
1643 result = (major > 5) || (major == 5 && minor >= 16);
1644 }
1645 }
1646 }
1647 });
1648
1649 return result;
1650}
1651
1652/**
1653 * @brief Check if kernel supports NTSync (kernel 6.14+ or CachyOS backport)
1654 * @return true if NTSync is available and the module is loaded
1655 *
1656 * NTSync is a new synchronization primitive that provides better Wine/Proton
1657 * performance than Fsync. It was merged in kernel 6.14 but CachyOS and some
1658 * other distributions backport it to earlier kernels.
1659 *
1660 * Detection checks:
1661 * 1. /dev/ntsync device exists (module loaded)
1662 * 2. /sys/module/ntsync exists (module loaded as module)
1663 * 3. /proc/kallsyms contains ntsync symbols (built-in)
1664 */
1666{
1667 // Use SystemInfoService for comprehensive detection
1669}
1670
1671/**
1672 * @brief Check if a wrapper/tool is available in PATH
1673 * @param name Name of the wrapper (e.g., "mangohud", "gamemoderun")
1674 * @return true if available
1675 */
1676bool isWrapperAvailable(const std::string& name)
1677{
1678 // Common paths to check
1679 std::vector<std::string> paths = {"/usr/bin/" + name, "/usr/local/bin/" + name};
1680
1681 const char* home = std::getenv("HOME");
1682 if (home)
1683 {
1684 paths.push_back(std::string(home) + "/.local/bin/" + name);
1685 }
1686
1687 for (const auto& path : paths)
1688 {
1689 if (std::filesystem::exists(path))
1690 {
1691 return true;
1692 }
1693 }
1694
1695 return false;
1696}
1697
1698/**
1699 * @brief Build the Gamescope wrapper prefix
1700 * @param config The runner configuration
1701 * @param modeInfo Output parameter for launch info display
1702 * @return Gamescope command prefix (empty if disabled or unavailable)
1703 *
1704 * Gamescope is a Wayland compositor for gaming that provides:
1705 * - FSR upscaling (render at lower res, upscale to native)
1706 * - VRR (Variable Refresh Rate) support
1707 * - HDR output
1708 * - Tearing control
1709 * - Improved fullscreen behavior
1710 *
1711 * Command structure:
1712 * `gamescope -W {width} -H {height} [-w {internal_w} -h {internal_h}] [options] -- {command}`
1713 */
1714std::string buildGamescopeWrapper(const GameRunnerConfig& config, std::string& modeInfo)
1715{
1716 if (!config.enableGamescope || !isWrapperAvailable("gamescope"))
1717 {
1718 return "";
1719 }
1720
1721 std::ostringstream gs;
1722 std::ostringstream mode;
1723 gs << "gamescope ";
1724
1725 // Output resolution (if specified)
1726 if (config.gamescopeWidth > 0 && config.gamescopeHeight > 0)
1727 {
1728 gs << "-W " << config.gamescopeWidth << " -H " << config.gamescopeHeight << " ";
1729 mode << config.gamescopeWidth << "x" << config.gamescopeHeight;
1730 }
1731
1732 // Internal/render resolution for FSR upscaling
1733 if (config.gamescopeInternalWidth > 0 && config.gamescopeInternalHeight > 0)
1734 {
1735 gs << "-w " << config.gamescopeInternalWidth << " -h " << config.gamescopeInternalHeight
1736 << " ";
1737 }
1738
1739 // Refresh rate limit
1740 if (config.gamescopeRefreshRate > 0)
1741 {
1742 gs << "-r " << config.gamescopeRefreshRate << " ";
1743 if (!mode.str().empty())
1744 mode << "@";
1745 mode << config.gamescopeRefreshRate;
1746 }
1747
1748 // Fullscreen mode
1749 if (config.gamescopeFullscreen)
1750 {
1751 gs << "-f ";
1752 }
1753 else if (config.gamescopeBorderless)
1754 {
1755 gs << "-b ";
1756 }
1757
1758 // FSR upscaling (gamescope renders at -w/-h, upscales to -W/-H)
1759 if (config.gamescopeEnableFSR)
1760 {
1761 gs << "--fsr-upscaling ";
1762 gs << "--fsr-sharpness " << config.gamescopeFSRSharpness << " ";
1763 if (!mode.str().empty())
1764 mode << " ";
1765 mode << "FSR";
1766 }
1767
1768 // Integer scaling
1769 if (config.gamescopeIntegerScaling)
1770 {
1771 gs << "-S integer ";
1772 if (!mode.str().empty())
1773 mode << " ";
1774 mode << "IntScale";
1775 }
1776
1777 // Variable Refresh Rate
1778 if (config.gamescopeEnableVRR)
1779 {
1780 gs << "--adaptive-sync ";
1781 if (!mode.str().empty())
1782 mode << " ";
1783 mode << "VRR";
1784 }
1785
1786 // HDR
1787 if (config.gamescopeEnableHDR)
1788 {
1789 gs << "--hdr-enabled ";
1790 if (!mode.str().empty())
1791 mode << " ";
1792 mode << "HDR";
1793 }
1794
1795 // HDR inverse tone mapping for SDR games on HDR displays
1796 if (config.gamescopeEnableHDR && config.gamescopeEnableITM)
1797 {
1798 gs << "--hdr-itm-enable ";
1799 if (config.gamescopeITMSDRNits > 0)
1800 {
1801 gs << "--hdr-itm-sdr-nits " << config.gamescopeITMSDRNits << " ";
1802 }
1803 }
1804
1805 // Force cursor grab (helps with some games)
1806 if (config.gamescopeForceGrabCursor)
1807 {
1808 gs << "--force-grab-cursor ";
1809 }
1810
1811 // MangoHud via mangoapp (preferred when running inside Gamescope)
1812 if (config.enableMangoHud)
1813 {
1814 gs << "--mangoapp ";
1815 Logger::info("Using MangoHud via --mangoapp (Gamescope native integration)");
1816 }
1817
1818 // Expose Wayland to nested applications (required for some apps)
1819 gs << "--expose-wayland ";
1820
1821 // End Gamescope args, next comes the actual command
1822 gs << "-- ";
1823
1824 modeInfo = mode.str().empty() ? "enabled" : mode.str();
1825 Logger::info("Using Gamescope compositor ({})", modeInfo);
1826
1827 return gs.str();
1828}
1829
1830/**
1831 * @brief Build the wrapper chain for a game launch.
1832 * @param config The runner configuration.
1833 * @param gameId Game ID, used to resolve any per-game wrapper config
1834 * (e.g. MangoHud per-launch config file in
1835 * `${XDG_STATE_HOME}/gamelauncher/<id>/mangohud.conf`).
1836 * @return String containing wrappers to prepend to command.
1837 *
1838 * CachyOS best practices: game-performance should be the OUTERMOST wrapper
1839 * so it can apply scheduling optimizations to the entire process tree.
1840 * Order: game-performance -> gamemoderun -> command
1841 * MangoHud and VkBasalt are activated via env vars (MANGOHUD=1, ENABLE_VKBASALT=1)
1842 *
1843 * Note: Gamescope is handled separately via buildGamescopeWrapper() as it
1844 * wraps the entire command differently (`gamescope [opts] -- {command}`).
1845 */
1846std::string buildWrapperChain(const GameRunnerConfig& config, const std::string& gameId)
1847{
1848 std::ostringstream wrappers;
1849
1850 // game-performance - CachyOS specific wrapper (MUST be first/outermost)
1851 // This applies CPU scheduling and priority optimizations to the entire process tree
1852 if (config.enableGamePerformance && isWrapperAvailable("game-performance"))
1853 {
1854 wrappers << "game-performance ";
1855 Logger::info("Using game-performance wrapper (outermost)");
1856 }
1857
1858 // GameMode - CPU governor optimization. Skip when ananicy-cpp is the
1859 // active system scheduler daemon (they conflict on sched_setscheduler).
1860 if (config.enableGameMode && isWrapperAvailable("gamemoderun") &&
1861 SystemInfoService::instance().getCapabilities().tools.shouldUseGameMode())
1862 {
1863 wrappers << "gamemoderun ";
1864 Logger::info("Using GameMode optimization");
1865 }
1866 else if (config.enableGameMode && isWrapperAvailable("gamemoderun"))
1867 {
1868 Logger::info("Skipping gamemoderun — ananicy-cpp.service is active");
1869 }
1870
1871 // MangoHud - performance overlay via Vulkan layer.
1872 // Two activation paths exist on this system:
1873 // 1. Our explicit MANGOHUD=1 (set when the user opted in via runner config)
1874 // 2. CachyOS's implicit Vulkan layer (active on every Vulkan app regardless
1875 // of MANGOHUD=1)
1876 // We need MANGOHUD_CONFIGFILE to win whenever MangoHud loads — including
1877 // path (2) — otherwise the implicit layer reads ~/.config/MangoHud/MangoHud.conf
1878 // (which goverlay populates with log_duration=30) and our metrics reader
1879 // sees only the first 30s of CSV data. Setting MANGOHUD_CONFIGFILE when
1880 // MangoHud isn't active is harmless: MangoHud only reads it on layer init.
1881 // When Gamescope is active, MangoHud is handled via --mangoapp instead.
1882 if (!config.enableGamescope)
1883 {
1885 gameId, config.mangoHudConfigFile);
1886 if (!cfgPath.empty())
1887 {
1888 wrappers << "MANGOHUD_CONFIGFILE=" << ShellUtils::escapeArg(cfgPath) << " ";
1889 }
1890 if (config.enableMangoHud)
1891 {
1892 wrappers << "MANGOHUD=1 ";
1893 Logger::info("Using MangoHud performance overlay with logging");
1894 }
1895 }
1896
1897 // VkBasalt - shader injection via Vulkan layer (env var, not wrapper command)
1898 if (config.enableVkBasalt)
1899 {
1900 wrappers << "ENABLE_VKBASALT=1 ";
1901 Logger::info("Using VkBasalt shader injection");
1902 }
1903
1904 return wrappers.str();
1905}
1906
1907/**
1908 * @brief Add synchronization environment variables
1909 * @param cmd The command stream to append to
1910 * @param config The runner configuration
1911 * @param isProton Whether this is a Proton launch (vs plain Wine)
1912 *
1913 * Sync method priority (best to fallback):
1914 * 1. NTSync - New kernel sync primitive (6.14+ or CachyOS backport)
1915 * - Proton: PROTON_USE_NTSYNC=1 (required on GE-Proton <=10-9; harmless
1916 * no-op on GE-Proton 10-10+ where it auto-enables). Disable with
1917 * PROTON_NO_NTSYNC=1.
1918 * - Plain Wine: auto-detects via /dev/ntsync; no env var needed.
1919 * 2. Fsync - futex2-based sync (kernel 5.16+)
1920 * 3. Esync - eventfd-based sync (always available)
1921 *
1922 * Note: WINEFSYNC/WINEESYNC should both be set as Esync serves as fallback
1923 * for code paths that don't support Fsync. Proton also supports
1924 * PROTON_NO_ESYNC/PROTON_NO_FSYNC to explicitly disable.
1925 */
1926void addSyncEnvironment(std::ostringstream& cmd, const GameRunnerConfig& config,
1927 bool isProton = false)
1928{
1929 if (config.autoDetectSync)
1930 {
1932 {
1933 // Proton needs PROTON_USE_NTSYNC=1 to route through the new sync
1934 // primitive (older GE-Proton requires it; newer auto-enables but
1935 // the var is harmless). Plain Wine opens /dev/ntsync itself.
1936 if (isProton)
1937 {
1938 cmd << "PROTON_USE_NTSYNC=1 ";
1939 }
1940 // Always set Fsync+Esync as fallbacks for non-ntsync code paths
1941 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
1942 Logger::info("Using NTSync (auto-detected kernel support)");
1943 }
1944 else if (kernelSupportsFsync())
1945 {
1946 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
1947 Logger::info("Using Fsync (auto-detected kernel support)");
1948 }
1949 else
1950 {
1951 cmd << "WINEESYNC=1 ";
1952 Logger::info("Using Esync (kernel doesn't support Fsync)");
1953 }
1954 }
1955 else if (config.enableFsync)
1956 {
1957 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
1958 Logger::info("Using Fsync (user configured)");
1959 }
1960}
1961
1962/**
1963 * @brief Add GPU-specific optimization environment variables
1964 * @param cmd The command stream to append to
1965 * @param isProton Whether this is a Proton launch (vs plain Wine)
1966 *
1967 * Note: RADV_PERFTEST is no longer set. In modern Mesa (24.x+), all commonly
1968 * useful flags (rt, nggc, sam, gpl) have graduated to being on by default.
1969 */
1970void addGPUOptimizations(std::ostringstream& cmd, bool isProton = false)
1971{
1972 std::string gpu = detectGPUVendor();
1973
1974 if (gpu == "AMD")
1975 {
1976 // AMD Anti-Lag for reduced input latency (Mesa Vulkan layer)
1977 cmd << "ENABLE_LAYER_MESA_ANTI_LAG=1 ";
1978 Logger::info("Enabling AMD Anti-Lag");
1979 }
1980 else if (gpu == "NVIDIA")
1981 {
1982 // DXVK_ENABLE_NVAPI tells DXVK to expose NVAPI interfaces
1983 cmd << "DXVK_ENABLE_NVAPI=1 ";
1984 if (isProton)
1985 {
1986 // PROTON_FORCE_NVAPI forces Proton's NVAPI implementation on
1987 cmd << "PROTON_FORCE_NVAPI=1 ";
1988 }
1989 Logger::info("Enabling NVIDIA NVAPI support");
1990 }
1991}
1992
1993/**
1994 * @brief Add application-specific environment variables for known problematic apps
1995 * @param cmd The command stream to append to
1996 * @param game The game being launched
1997 *
1998 * Some applications require specific environment variables to work correctly
1999 * under Wine/Proton. This function detects known problematic applications
2000 * and adds the necessary fixes automatically.
2001 *
2002 * Known fixes:
2003 * - Battle.net: Requires WINE_SIMULATE_WRITECOPY=1 to prevent "Update Agent went to sleep"
2004 * - EA App/Origin: May need specific DXVK settings
2005 * - Ubisoft Connect: May need specific dll overrides
2006 */
2007void addApplicationSpecificFixes(std::ostringstream& cmd, const Game& game)
2008{
2009 // Safety check - avoid operating on empty/invalid game data
2010 if (game.name.empty() && game.runnerConfig.executablePath.empty())
2011 {
2012 return;
2013 }
2014
2015 // Normalize game name and executable path for detection
2016 // Make copies to avoid any issues with the original strings
2017 std::string nameLower;
2018 std::string exeLower;
2019
2020 try
2021 {
2022 nameLower = game.name;
2023 exeLower = game.runnerConfig.executablePath;
2024 }
2025 catch (...)
2026 {
2027 Logger::warn("Failed to copy game strings for application fix detection");
2028 return;
2029 }
2030
2031 for (char& c : nameLower)
2032 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
2033 for (char& c : exeLower)
2034 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
2035
2036 // =========================================================================
2037 // Battle.net / Blizzard Launcher
2038 // Fixes: "Battle.net Update Agent went to sleep" error
2039 // Reference: https://github.com/ValveSoftware/Proton/issues/5029
2040 // =========================================================================
2041 bool isBattleNet = (nameLower.find("battle.net") != std::string::npos ||
2042 nameLower.find("battlenet") != std::string::npos ||
2043 nameLower.find("blizzard") != std::string::npos ||
2044 exeLower.find("battle.net") != std::string::npos ||
2045 exeLower.find("battlenet") != std::string::npos ||
2046 exeLower.find("agent.exe") != std::string::npos);
2047
2048 if (isBattleNet)
2049 {
2050 Logger::info("Detected Battle.net - applying compatibility fixes");
2051 // WINE_SIMULATE_WRITECOPY fixes the Update Agent sleep issue
2052 cmd << "WINE_SIMULATE_WRITECOPY=1 ";
2053 // Large address aware helps with memory issues
2054 cmd << "WINE_LARGE_ADDRESS_AWARE=1 ";
2055 }
2056
2057 // =========================================================================
2058 // EA App / Origin
2059 // Fixes: Various launcher issues
2060 // =========================================================================
2061 bool isEAApp = (nameLower.find("ea app") != std::string::npos ||
2062 nameLower.find("origin") != std::string::npos ||
2063 exeLower.find("eadesktop") != std::string::npos ||
2064 exeLower.find("origin.exe") != std::string::npos);
2065
2066 if (isEAApp)
2067 {
2068 Logger::info("Detected EA App/Origin - applying compatibility fixes");
2069 // EA App works better with these settings
2070 cmd << "WINE_LARGE_ADDRESS_AWARE=1 ";
2071 }
2072
2073 // =========================================================================
2074 // Ubisoft Connect / Uplay
2075 // =========================================================================
2076 bool isUbisoft = (nameLower.find("ubisoft") != std::string::npos ||
2077 nameLower.find("uplay") != std::string::npos ||
2078 exeLower.find("upc.exe") != std::string::npos ||
2079 exeLower.find("uplay") != std::string::npos);
2080
2081 if (isUbisoft)
2082 {
2083 Logger::info("Detected Ubisoft Connect - applying compatibility fixes");
2084 cmd << "WINE_LARGE_ADDRESS_AWARE=1 ";
2085 }
2086
2087 // =========================================================================
2088 // GOG Galaxy
2089 // =========================================================================
2090 bool isGOGGalaxy = (nameLower.find("gog galaxy") != std::string::npos ||
2091 exeLower.find("galaxyclient") != std::string::npos);
2092
2093 if (isGOGGalaxy)
2094 {
2095 Logger::info("Detected GOG Galaxy - applying compatibility fixes");
2096 cmd << "WINE_LARGE_ADDRESS_AWARE=1 ";
2097 }
2098}
2099
2100} // anonymous namespace
2101
2102bool GameProcess::launchWine()
2103{
2104 std::ostringstream cmd;
2105
2106 // ==========================================================================
2107 // Wine Launch Command Structure (following Lutris/CachyOS best practices):
2108 // <env variables> <wrappers> wine <executable> <arguments>
2109 //
2110 // Reference: https://github.com/lutris/lutris/blob/master/lutris/runners/wine.py
2111 // ==========================================================================
2112
2113 Logger::info("Launching Wine game: {}", game_.name);
2114
2115 // Reset launch info for this launch
2116 lastLaunchInfo_ = LaunchInfo();
2117 lastLaunchInfo_.runner = "Wine";
2118
2119 // Validate executable path exists
2120 if (game_.runnerConfig.executablePath.empty())
2121 {
2122 Logger::error("No executable path specified for game: {}", game_.name);
2123 return false;
2124 }
2125 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
2126 {
2127 Logger::error("Executable not found: {}", game_.runnerConfig.executablePath);
2128 return false;
2129 }
2130
2131 // Determine Wine prefix path (needed for directory creation and command)
2132 std::string winePrefix;
2133 if (!game_.runnerConfig.winePrefix.empty())
2134 {
2135 winePrefix = game_.runnerConfig.winePrefix;
2136 }
2137 else
2138 {
2139 const char* home = std::getenv("HOME");
2140 if (home)
2141 {
2142 std::string safeName = game_.name;
2143 for (char& c : safeName)
2144 {
2145 if (!std::isalnum(static_cast<unsigned char>(c)))
2146 c = '_';
2147 }
2148 winePrefix = std::string(home) + "/Games/wine-prefixes/" + safeName;
2149 }
2150 }
2151 lastLaunchInfo_.winePrefix = winePrefix;
2152
2153 // Create Wine prefix directory if it doesn't exist. A fresh prefix also
2154 // needs `wineboot -u` to populate system.reg / user.reg and the standard
2155 // Windows directory skeleton. Wine will lazy-init on first launch if we
2156 // skip this, but first-run behaviour becomes flaky for games that probe
2157 // the registry before the first frame. Synchronous init up-front avoids
2158 // that class of first-launch bug at the cost of ~5s on a cold prefix.
2159 bool freshPrefixNeedsInit = false;
2160 if (!winePrefix.empty())
2161 {
2162 try
2163 {
2164 if (!std::filesystem::exists(winePrefix))
2165 {
2166 std::filesystem::create_directories(winePrefix);
2167 Logger::info("Created Wine prefix directory: {}", winePrefix);
2168 freshPrefixNeedsInit = true;
2169 }
2170 else if (!std::filesystem::exists(std::filesystem::path(winePrefix) / "system.reg"))
2171 {
2172 // Directory exists but isn't a valid Wine prefix yet.
2173 freshPrefixNeedsInit = true;
2174 }
2175 }
2176 catch (const std::exception& e)
2177 {
2178 Logger::warn("Failed to create Wine prefix directory: {}", e.what());
2179 }
2180 }
2181
2182 if (freshPrefixNeedsInit && !winePrefix.empty())
2183 {
2184 // Run `wineboot -u` synchronously with a modest timeout. Use execvp
2185 // via process_executor semantics: for simplicity here, shell out
2186 // with a quoted WINEPREFIX and let the result log — a failure is
2187 // non-fatal (Wine will still lazy-init on the actual launch).
2188 const std::string bootCmd =
2189 ShellUtils::formatEnvVar("WINEPREFIX", winePrefix) + " WINEDEBUG=-all wineboot -u 2>&1";
2190 Logger::info("Initialising fresh Wine prefix via wineboot -u …");
2191 const int rc = std::system(bootCmd.c_str());
2192 if (rc != 0)
2193 {
2194 Logger::warn("wineboot -u returned rc={}; continuing with lazy init", rc);
2195 }
2196 }
2197
2198 // Step 1: Add all user-configured environment variables FIRST (with safe escaping)
2199 // SECURITY: All environment variables are validated and escaped to prevent injection
2200 int customEnvCount = 0;
2201 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
2202 {
2203 // Skip wrapper markers - these are internal flags, not actual env vars
2204 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
2205 continue;
2206
2207 // Validate environment variable name to prevent injection
2209 {
2210 Logger::warn("Skipping invalid environment variable name: {}", key);
2211 continue;
2212 }
2213
2214 customEnvCount++;
2215
2216 // Use safe escaping for the value
2217 cmd << ShellUtils::formatEnvVar(key, value) << " ";
2218 }
2219 lastLaunchInfo_.customEnvVars = customEnvCount;
2220
2221 // Step 2: Set WINEPREFIX (path is validated/sanitized internally)
2222 if (!winePrefix.empty())
2223 {
2224 cmd << ShellUtils::formatEnvVar("WINEPREFIX", winePrefix) << " ";
2225 Logger::info("Using Wine prefix: {}", winePrefix);
2226 }
2227
2228 // Step 3: Set WINEARCH (default to win64 for modern games)
2229 // Lutris sets this explicitly to ensure consistency
2230 cmd << "WINEARCH=win64 ";
2231
2232 // Step 4: Disable Wine debugging for better performance (unless user enabled it)
2233 if (game_.runnerConfig.environmentVariables.find("WINEDEBUG") ==
2234 game_.runnerConfig.environmentVariables.end())
2235 {
2236 cmd << "WINEDEBUG=-all ";
2237 }
2238
2239 // Step 5: Add DLL overrides if specified (safely escaped)
2240 if (!game_.runnerConfig.wineDLL.empty())
2241 {
2242 cmd << ShellUtils::formatEnvVar("WINEDLLOVERRIDES", game_.runnerConfig.wineDLL) << " ";
2243 }
2244
2245 // Step 6: Add sync primitives (NTSync > Fsync > Esync)
2246 // Plain Wine opens /dev/ntsync directly when the kernel module is loaded;
2247 // no Proton-specific env var is needed here. Set Fsync+Esync as fallbacks.
2248 if (game_.runnerConfig.autoDetectSync)
2249 {
2251 {
2252 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
2253 lastLaunchInfo_.syncMethod = "NTSync";
2254 Logger::info("Using NTSync (auto-detected kernel support)");
2255 }
2256 else if (kernelSupportsFsync())
2257 {
2258 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
2259 lastLaunchInfo_.syncMethod = "Fsync";
2260 Logger::info("Using Fsync (auto-detected kernel support)");
2261 }
2262 else
2263 {
2264 cmd << "WINEESYNC=1 ";
2265 lastLaunchInfo_.syncMethod = "Esync";
2266 Logger::info("Using Esync (kernel doesn't support Fsync)");
2267 }
2268 }
2269 else if (game_.runnerConfig.enableFsync)
2270 {
2271 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
2272 lastLaunchInfo_.syncMethod = "Fsync";
2273 Logger::info("Using Fsync (user configured)");
2274 }
2275
2276 // Step 7: Add GPU-specific optimizations (AMD Anti-Lag, NVIDIA NVAPI)
2277 std::string gpu = detectGPUVendor();
2278 lastLaunchInfo_.gpuVendor = gpu;
2279
2280 if (gpu == "AMD")
2281 {
2282 cmd << "ENABLE_LAYER_MESA_ANTI_LAG=1 ";
2283 lastLaunchInfo_.amdAntiLag = true;
2284 Logger::info("Enabling AMD Anti-Lag");
2285 }
2286 else if (gpu == "NVIDIA")
2287 {
2288 cmd << "DXVK_ENABLE_NVAPI=1 ";
2289 lastLaunchInfo_.nvidiaNvapi = true;
2290 Logger::info("Enabling NVIDIA NVAPI support");
2291 }
2292
2293 // Step 8: Add application-specific fixes (Battle.net, EA App, etc.)
2294 // Detect and apply fixes, tracking what was applied
2295 std::string nameLower = game_.name;
2296 std::string exeLower = game_.runnerConfig.executablePath;
2297 for (char& c : nameLower)
2298 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
2299 for (char& c : exeLower)
2300 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
2301
2302 bool isBattleNet = (nameLower.find("battle.net") != std::string::npos ||
2303 nameLower.find("battlenet") != std::string::npos ||
2304 nameLower.find("blizzard") != std::string::npos ||
2305 exeLower.find("battle.net") != std::string::npos ||
2306 exeLower.find("battlenet") != std::string::npos ||
2307 exeLower.find("agent.exe") != std::string::npos);
2308
2309 if (isBattleNet)
2310 {
2311 Logger::info("Detected Battle.net - applying compatibility fixes");
2312 cmd << "WINE_SIMULATE_WRITECOPY=1 ";
2313 cmd << "WINE_LARGE_ADDRESS_AWARE=1 ";
2314 lastLaunchInfo_.appliedFixes.push_back("Battle.net fix");
2315 }
2316
2317 bool isEAApp = (nameLower.find("ea app") != std::string::npos ||
2318 nameLower.find("origin") != std::string::npos ||
2319 exeLower.find("eadesktop") != std::string::npos ||
2320 exeLower.find("origin.exe") != std::string::npos);
2321
2322 if (isEAApp)
2323 {
2324 Logger::info("Detected EA App/Origin - applying compatibility fixes");
2325 cmd << "WINE_LARGE_ADDRESS_AWARE=1 ";
2326 lastLaunchInfo_.appliedFixes.push_back("EA App fix");
2327 }
2328
2329 // Step 9: Add detailed logging if enabled
2330 if (game_.runnerConfig.enableDetailedLogging)
2331 {
2332 cmd << "WINEDEBUG=+loaddll,+seh ";
2333 Logger::info("Enabling detailed Wine logging");
2334 }
2335
2336 // Step 10: Add performance wrappers and env var activations
2337 // Wrapper order: game-performance (outermost) → gamemoderun → wine
2338 // MangoHud and VkBasalt use env vars, not wrapper commands
2339 if (game_.runnerConfig.enableGamePerformance && isWrapperAvailable("game-performance"))
2340 {
2341 cmd << "game-performance ";
2342 lastLaunchInfo_.gamePerformance = true;
2343 Logger::info("Using game-performance wrapper (outermost)");
2344 }
2345 if (game_.runnerConfig.enableGameMode && isWrapperAvailable("gamemoderun") &&
2346 SystemInfoService::instance().getCapabilities().tools.shouldUseGameMode())
2347 {
2348 cmd << "gamemoderun ";
2349 lastLaunchInfo_.gameMode = true;
2350 Logger::info("Using GameMode optimization");
2351 }
2352 else if (game_.runnerConfig.enableGameMode && isWrapperAvailable("gamemoderun"))
2353 {
2354 Logger::info("Skipping gamemoderun — ananicy-cpp.service is active");
2355 }
2356 // MangoHud config injection — see buildWrapperChain for rationale on why
2357 // MANGOHUD_CONFIGFILE is decoupled from enableMangoHud (implicit Vulkan
2358 // layer activation).
2359 if (!game_.runnerConfig.enableGamescope)
2360 {
2362 game_.id, game_.runnerConfig.mangoHudConfigFile);
2363 if (!cfgPath.empty())
2364 {
2365 cmd << "MANGOHUD_CONFIGFILE=" << ShellUtils::escapeArg(cfgPath) << " ";
2366 }
2367 if (game_.runnerConfig.enableMangoHud)
2368 {
2369 cmd << "MANGOHUD=1 ";
2370 lastLaunchInfo_.mangoHud = true;
2371 Logger::info("Using MangoHud performance overlay (config: {})", cfgPath);
2372 }
2373 }
2374 // VkBasalt via Vulkan layer env var (not wrapper command)
2375 if (game_.runnerConfig.enableVkBasalt)
2376 {
2377 cmd << "ENABLE_VKBASALT=1 ";
2378 lastLaunchInfo_.vkBasalt = true;
2379 Logger::info("Using VkBasalt shader injection");
2380 }
2381
2382 // Step 10b: Add Gamescope compositor (wraps entire command with -- separator)
2383 std::string gamescopeMode;
2384 std::string gamescopeWrapper = buildGamescopeWrapper(game_.runnerConfig, gamescopeMode);
2385 if (!gamescopeWrapper.empty())
2386 {
2387 cmd << gamescopeWrapper;
2388 lastLaunchInfo_.gamescope = true;
2389 lastLaunchInfo_.gamescopeMode = gamescopeMode;
2390 }
2391
2392 // Step 11: Determine Wine binary to use
2393 std::string wineBinary = "wine";
2394
2395 // Priority 1: Use custom wine path from Lutris config if specified
2396 if (!game_.runnerConfig.winePath.empty() &&
2397 std::filesystem::exists(game_.runnerConfig.winePath))
2398 {
2399 wineBinary = game_.runnerConfig.winePath;
2400 // Extract version name from path (e.g., "/opt/wine-cachyos/bin/wine" -> "wine-cachyos")
2401 std::filesystem::path winePath(wineBinary);
2402 std::string parentDir = winePath.parent_path().parent_path().filename().string();
2403 lastLaunchInfo_.runnerVersion = parentDir;
2404 Logger::info("Using custom Wine path from config: {}", wineBinary);
2405
2406 // Set up PATH and LD_LIBRARY_PATH for the custom Wine
2407 // Note: We need to preserve existing PATH/LD_LIBRARY_PATH, so we use shell expansion
2408 // The paths here are internal (from filesystem) so they're safe
2409 std::filesystem::path wineBinDir = std::filesystem::path(wineBinary).parent_path();
2410 std::filesystem::path wineLibDir = wineBinDir.parent_path() / "lib";
2411 std::filesystem::path wineLib32Dir = wineBinDir.parent_path() / "lib32";
2412
2413 // PATH needs shell expansion for $PATH - escape the directory part only
2414 cmd << "PATH=" << ShellUtils::escapeArg(wineBinDir.string() + ":") << "\"$PATH\" ";
2415 if (std::filesystem::exists(wineLibDir) || std::filesystem::exists(wineLib32Dir))
2416 {
2417 std::string libPaths;
2418 if (std::filesystem::exists(wineLibDir))
2419 libPaths += wineLibDir.string() + ":";
2420 if (std::filesystem::exists(wineLib32Dir))
2421 libPaths += wineLib32Dir.string() + ":";
2422 cmd << "LD_LIBRARY_PATH=" << ShellUtils::escapeArg(libPaths) << "\"$LD_LIBRARY_PATH\" ";
2423 }
2424 }
2425 // Priority 2: Check for wine-cachyos-opt (CachyOS optimized Wine)
2426 else if (std::filesystem::exists("/opt/wine-cachyos/bin/wine"))
2427 {
2428 // Use wine-cachyos-opt with proper PATH and library setup
2429 // These are hardcoded safe paths, but we still properly format the command
2430 cmd << "PATH='/opt/wine-cachyos/bin':\"$PATH\" ";
2431 cmd << "LD_LIBRARY_PATH='/opt/wine-cachyos/lib:/opt/wine-cachyos/"
2432 "lib32':\"$LD_LIBRARY_PATH\" ";
2433 wineBinary = "/opt/wine-cachyos/bin/wine";
2434 lastLaunchInfo_.runnerVersion = "wine-cachyos";
2435 Logger::info("Using wine-cachyos-opt");
2436 }
2437 else
2438 {
2439 lastLaunchInfo_.runnerVersion = "system";
2440 }
2441
2442 // Step 12: Set virtual desktop if enabled
2443 if (game_.runnerConfig.useVirtualDesktop)
2444 {
2445 // Virtual desktop requires explorer.exe override
2446 // Wine binary path is safe (from filesystem or hardcoded)
2447 cmd << ShellUtils::escapeArg(wineBinary) << " explorer /desktop=GameLauncher,"
2448 << game_.runnerConfig.virtualDesktopWidth << "x"
2449 << game_.runnerConfig.virtualDesktopHeight << " ";
2450 }
2451 else
2452 {
2453 cmd << ShellUtils::escapeArg(wineBinary) << " ";
2454 }
2455
2456 // Step 13: Add executable path (safely escaped)
2457 cmd << ShellUtils::escapeArg(game_.runnerConfig.executablePath);
2458
2459 // Step 14: Add arguments (safely escaped)
2460 if (!game_.runnerConfig.arguments.empty())
2461 {
2462 // Split args respecting shell quoting, then escape each token safely
2463 for (const auto& arg : ShellUtils::splitArgs(game_.runnerConfig.arguments))
2464 cmd << " " << ShellUtils::escapeArg(arg);
2465 }
2466
2467 std::string command = cmd.str();
2468 Logger::info("Wine launch command: {}", command);
2469
2470 // Execute command directly (avoids corrupting game_.runnerConfig)
2471 bool success = executeCommand(command);
2472
2473 // Show notification with applied optimizations
2474 if (success)
2475 {
2476 std::string summary = lastLaunchInfo_.getSummary(false);
2477 notify(NotificationType::Info, "Launched: " + summary);
2478 }
2479
2480 return success;
2481}
2482
2483std::string GameProcess::findProtonExecutable(const std::string& versionName) const
2484{
2485 // If no version specified, use PATH proton
2486 if (versionName.empty())
2487 {
2488 return "proton";
2489 }
2490
2491 // Scan all known Proton locations to find the selected version (cached)
2492 auto protonPaths = ProtonCache::getVersions();
2493
2494 for (const auto& [name, path] : protonPaths)
2495 {
2496 if (name == versionName && !path.empty())
2497 {
2498 Logger::info("Found Proton version '{}' at: {}", versionName, path.string());
2499 return path.string();
2500 }
2501 }
2502
2503 // Version not found - warn user and fall back to PATH
2504 Logger::warn("Proton version '{}' not found, falling back to 'proton' from PATH", versionName);
2506 "Proton '" + versionName + "' not found, using system default");
2507 return "proton";
2508}
2509
2510bool GameProcess::isUmuLauncherAvailable()
2511{
2512 // Check if umu-run is available in PATH or common locations
2513 // Use filesystem check first (faster), then fall back to which
2514 static std::once_flag flag;
2515 static bool available = false;
2516
2517 std::call_once(flag,
2518 []()
2519 {
2520 // Check common umu-run locations
2521 const char* homeEnv = std::getenv("HOME");
2522 const std::string homeStr = homeEnv ? homeEnv : "";
2523 std::vector<std::string> umuPaths = {"/usr/bin/umu-run",
2524 "/usr/local/bin/umu-run",
2525 homeStr + "/.local/bin/umu-run"};
2526
2527 for (const auto& path : umuPaths)
2528 {
2529 if (!path.empty() && std::filesystem::exists(path))
2530 {
2531 Logger::info("Found umu-run at: {}", path);
2532 available = true;
2533 return;
2534 }
2535 }
2536
2537 // Fall back to which command
2538 ProcessResult result =
2539 ProcessExecutor::executeWithOutput("which umu-run 2>/dev/null", true);
2540 available = result.success && !result.output.empty();
2541
2542 if (available)
2543 {
2544 Logger::info("Found umu-run in PATH");
2545 }
2546 });
2547
2548 return available;
2549}
2550
2551bool GameProcess::launchProton()
2552{
2553 // ==========================================================================
2554 // Proton Launch for Non-Steam Games
2555 // ==========================================================================
2556 // For non-Steam games, we need to use umu-launcher (recommended) or fall back
2557 // to direct Proton execution with proper Steam runtime setup.
2558 //
2559 // Reference: https://github.com/Open-Wine-Components/umu-launcher
2560 // Reference: https://wiki.cachyos.org/configuration/gaming/
2561 // ==========================================================================
2562
2563 // Check if this is a Steam game - use different launch method
2564 if (game_.metadata.isSteamGame && game_.metadata.steamAppId > 0)
2565 {
2566 return launchProtonSteamGame();
2567 }
2568
2569 // For non-Steam games, prefer umu-launcher if available
2570 if (isUmuLauncherAvailable())
2571 {
2572 return launchProtonWithUmu();
2573 }
2574
2575 // Fall back to direct Proton execution (requires manual Steam runtime setup)
2576 Logger::warn("umu-launcher not found. Direct Proton execution may not work properly.");
2577 Logger::warn("Install umu-launcher for best non-Steam game compatibility: "
2578 "https://github.com/Open-Wine-Components/umu-launcher");
2579 return launchProtonDirect();
2580}
2581
2582bool GameProcess::launchProtonWithUmu()
2583{
2584 std::ostringstream cmd;
2585
2586 // ==========================================================================
2587 // umu-launcher Command Structure (matching Lutris implementation):
2588 // <env variables> umu-run <executable> <arguments>
2589 //
2590 // This implementation matches Lutris's wine.py runner behavior exactly.
2591 // Key differences from previous implementation:
2592 // - Sets WINEARCH=win64 (required for Proton)
2593 // - Sets WINEDLLOVERRIDES for DLL overrides
2594 // - Sets WINEDEBUG=-all for performance
2595 // - Sets PROTON_DXVK_D3D8=1 for D3D8 support
2596 // - Uses umu-default as GAMEID when no specific ID is known
2597 //
2598 // Reference: https://github.com/lutris/lutris/blob/master/lutris/runners/wine.py
2599 // Reference: https://github.com/Open-Wine-Components/umu-launcher
2600 // ==========================================================================
2601
2602 Logger::info("Launching non-Steam game with umu-launcher: {}", game_.name);
2603
2604 // Reset launch info for tracking
2605 lastLaunchInfo_ = LaunchInfo();
2606 lastLaunchInfo_.runner = "umu-launcher (Proton)";
2607
2608 // Validate executable path exists
2609 if (game_.runnerConfig.executablePath.empty())
2610 {
2611 Logger::error("No executable path specified for game: {}", game_.name);
2612 return false;
2613 }
2614 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
2615 {
2616 Logger::error("Executable not found: {}", game_.runnerConfig.executablePath);
2617 return false;
2618 }
2619
2620 // Warn about unsupported features in Proton/umu-launcher
2621 if (game_.runnerConfig.useVirtualDesktop)
2622 {
2623 Logger::warn("Virtual desktop is not supported with Proton/umu-launcher. "
2624 "This setting will be ignored. Wine-GE and Proton do not support "
2625 "the explorer /desktop= mode.");
2626 }
2627
2628 // Determine prefix path
2629 std::string winePrefix;
2630 const char* home = std::getenv("HOME");
2631
2632 if (!game_.runnerConfig.winePrefix.empty())
2633 {
2634 winePrefix = game_.runnerConfig.winePrefix;
2635 }
2636 else if (home)
2637 {
2638 std::string safeName = game_.name;
2639 for (char& c : safeName)
2640 {
2641 if (!std::isalnum(static_cast<unsigned char>(c)))
2642 c = '_';
2643 }
2644 winePrefix = std::string(home) + "/Games/umu/" + safeName;
2645 }
2646 lastLaunchInfo_.winePrefix = winePrefix;
2647
2648 // Create prefix directory if needed
2649 if (!winePrefix.empty())
2650 {
2651 try
2652 {
2653 std::filesystem::path prefixPath(winePrefix);
2654 std::filesystem::path gamesDir = prefixPath.parent_path();
2655 if (!std::filesystem::exists(gamesDir))
2656 {
2657 std::filesystem::create_directories(gamesDir);
2658 Logger::info("Created umu games directory: {}", gamesDir.string());
2659 }
2660 }
2661 catch (const std::exception& e)
2662 {
2663 Logger::warn("Failed to create umu directory: {}", e.what());
2664 }
2665 }
2666
2667 // ==========================================================================
2668 // Build environment variables (matching Lutris order and settings)
2669 // ==========================================================================
2670
2671 // Step 1: User-configured environment variables FIRST (with safe escaping)
2672 // SECURITY: All environment variables are validated and escaped to prevent injection
2673 int customEnvCount = 0;
2674 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
2675 {
2676 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
2677 continue;
2678
2679 // Validate environment variable name to prevent injection
2681 {
2682 Logger::warn("Skipping invalid environment variable name: {}", key);
2683 continue;
2684 }
2685
2686 customEnvCount++;
2687 cmd << ShellUtils::formatEnvVar(key, value) << " ";
2688 }
2689 lastLaunchInfo_.customEnvVars = customEnvCount;
2690
2691 // Step 2: WINEPREFIX (required, safely escaped)
2692 if (!winePrefix.empty())
2693 {
2694 cmd << ShellUtils::formatEnvVar("WINEPREFIX", winePrefix) << " ";
2695 Logger::info("Using WINEPREFIX: {}", winePrefix);
2696 }
2697
2698 // Step 3: WINEARCH=win64 (Proton is always 64-bit)
2699 cmd << "WINEARCH=win64 ";
2700
2701 // Step 4: WINEDEBUG=-all (disable debug output for performance)
2702 if (game_.runnerConfig.environmentVariables.find("WINEDEBUG") ==
2703 game_.runnerConfig.environmentVariables.end())
2704 {
2705 cmd << "WINEDEBUG=-all ";
2706 }
2707
2708 // Step 5: WINEDLLOVERRIDES (DLL overrides from config, safely escaped)
2709 std::string dllOverrides;
2710 if (!game_.runnerConfig.wineDLL.empty())
2711 {
2712 dllOverrides = game_.runnerConfig.wineDLL;
2713 }
2714 // Always add winemenubuilder='' to prevent menu pollution (like Lutris does)
2715 if (!dllOverrides.empty())
2716 {
2717 dllOverrides += ";winemenubuilder=";
2718 }
2719 else
2720 {
2721 dllOverrides = "winemenubuilder=";
2722 }
2723 cmd << ShellUtils::formatEnvVar("WINEDLLOVERRIDES", dllOverrides) << " ";
2724
2725 // Step 6: Sync primitives (NTSync > Fsync > Esync)
2726 // GE-Proton enables NTSync automatically via PROTON_USE_NTSYNC=1 when kernel supports it.
2727 // We just need to ensure Fsync+Esync are set as fallbacks.
2728 // Disable NTSync explicitly only if the user wants to (PROTON_NO_NTSYNC=1).
2729 if (game_.runnerConfig.autoDetectSync)
2730 {
2732 {
2733 // GE-Proton auto-enables NTSync; set fallbacks
2734 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
2735 lastLaunchInfo_.syncMethod = "NTSync";
2737 "Using NTSync (auto-detected kernel support, GE-Proton enables automatically)");
2738 }
2739 else if (kernelSupportsFsync())
2740 {
2741 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
2742 lastLaunchInfo_.syncMethod = "Fsync";
2743 Logger::info("Using Fsync (auto-detected kernel support)");
2744 }
2745 else
2746 {
2747 cmd << "WINEESYNC=1 ";
2748 lastLaunchInfo_.syncMethod = "Esync";
2749 Logger::info("Using Esync (kernel doesn't support Fsync)");
2750 }
2751 }
2752 else if (game_.runnerConfig.enableFsync)
2753 {
2754 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
2755 lastLaunchInfo_.syncMethod = "Fsync";
2756 Logger::info("Using Fsync (user configured)");
2757 }
2758
2759 // Step 7: GAMEID for umu-database fixes (safely escaped)
2760 // Use umu-default like Lutris does when no specific ID is known
2761 std::string gameId = "umu-default";
2762 if (game_.metadata.steamAppId > 0)
2763 {
2764 gameId = "umu-" + std::to_string(game_.metadata.steamAppId);
2765 }
2766 // Check if user set a specific GAMEID in env vars
2767 auto gameIdIt = game_.runnerConfig.environmentVariables.find("GAMEID");
2768 if (gameIdIt != game_.runnerConfig.environmentVariables.end() && !gameIdIt->second.empty())
2769 {
2770 gameId = gameIdIt->second;
2771 }
2772 cmd << ShellUtils::formatEnvVar("GAMEID", gameId) << " ";
2773 Logger::info("Using GAMEID: {}", gameId);
2774
2775 // Step 7b: GAME_LAUNCHER_UUID for process identification (like LUTRIS_GAME_UUID)
2776 // This helps identify which processes belong to which game during tracking
2777 if (!game_.id.empty())
2778 {
2779 cmd << ShellUtils::formatEnvVar("GAME_LAUNCHER_UUID", game_.id) << " ";
2780 }
2781
2782 // Step 8: PROTONPATH - path to Proton installation directory
2783 // umu-run handles WINE binary and library paths internally via the Steam Runtime
2784 // container (pressure-vessel). Do NOT set WINE= or LD_LIBRARY_PATH — doing so
2785 // breaks container isolation and can cause library mismatches.
2786 std::string protonPath;
2787 if (!game_.runnerConfig.protonVersion.empty())
2788 {
2789 protonPath = findProtonPath(game_.runnerConfig.protonVersion);
2790 if (!protonPath.empty())
2791 {
2792 cmd << ShellUtils::formatEnvVar("PROTONPATH", protonPath) << " ";
2793 lastLaunchInfo_.runnerVersion = game_.runnerConfig.protonVersion;
2794 Logger::info("Using PROTONPATH: {}", protonPath);
2795 }
2796 else
2797 {
2798 Logger::warn("Proton version '{}' not found, umu-launcher will use default",
2799 game_.runnerConfig.protonVersion);
2800 }
2801 }
2802
2803 // Step 9: PROTON_VERB (waitforexitandrun for proper initialization)
2804 if (game_.runnerConfig.environmentVariables.find("PROTON_VERB") ==
2805 game_.runnerConfig.environmentVariables.end())
2806 {
2807 cmd << "PROTON_VERB=waitforexitandrun ";
2808 }
2809
2810 // Step 10: Proton-specific optimizations
2811 cmd << "PROTON_DXVK_D3D8=1 "; // Enable D3D8 support via DXVK
2812
2813 // Step 11: GPU-specific optimizations
2814 // Note: RADV_PERFTEST is NOT set — all useful flags (rt, nggc, sam, gpl) have
2815 // graduated to defaults in modern Mesa 24.x+. Setting them is harmless but unnecessary.
2816 std::string gpu = detectGPUVendor();
2817 lastLaunchInfo_.gpuVendor = gpu;
2818
2819 if (gpu == "AMD")
2820 {
2821 cmd << "ENABLE_LAYER_MESA_ANTI_LAG=1 ";
2822 cmd << "WINE_FULLSCREEN_FSR=1 "; // FSR 1.0 upscaling in Wine/Proton
2823 lastLaunchInfo_.amdAntiLag = true;
2824 Logger::info("Enabling AMD optimizations (Anti-Lag, FSR)");
2825 }
2826 else if (gpu == "NVIDIA")
2827 {
2828 cmd << "DXVK_ENABLE_NVAPI=1 ";
2829 cmd << "PROTON_FORCE_NVAPI=1 ";
2830 cmd << "WINE_FULLSCREEN_FSR=1 "; // FSR 1.0 upscaling
2831 lastLaunchInfo_.nvidiaNvapi = true;
2832 Logger::info("Enabling NVIDIA NVAPI + FSR support");
2833 }
2834
2835 // Step 13: Detailed logging if enabled
2836 if (game_.runnerConfig.enableDetailedLogging)
2837 {
2838 cmd << "PROTON_LOG=1 ";
2839 cmd << "UMU_LOG=debug ";
2840 cmd << "WINEDEBUG=+loaddll,+seh "; // Override the -all above
2841 Logger::info("Enabling detailed Proton/umu logging");
2842 }
2843 else
2844 {
2845 cmd << "UMU_LOG=1 "; // Basic logging like Lutris
2846 }
2847
2848 // Step 14: Performance wrappers and env var activations
2849 // Wrapper order: game-performance (outermost) → gamemoderun → umu-run
2850 // MangoHud and VkBasalt use env vars, not wrapper commands
2851 if (game_.runnerConfig.enableGamePerformance && isWrapperAvailable("game-performance"))
2852 {
2853 cmd << "game-performance ";
2854 lastLaunchInfo_.gamePerformance = true;
2855 Logger::info("Using game-performance (outermost)");
2856 }
2857 if (game_.runnerConfig.enableGameMode && isWrapperAvailable("gamemoderun"))
2858 {
2859 cmd << "gamemoderun ";
2860 lastLaunchInfo_.gameMode = true;
2861 Logger::info("Using GameMode");
2862 }
2863 // MangoHud config injection — see buildWrapperChain for rationale.
2864 if (!game_.runnerConfig.enableGamescope)
2865 {
2867 game_.id, game_.runnerConfig.mangoHudConfigFile);
2868 if (!cfgPath.empty())
2869 {
2870 cmd << "MANGOHUD_CONFIGFILE=" << ShellUtils::escapeArg(cfgPath) << " ";
2871 }
2872 if (game_.runnerConfig.enableMangoHud)
2873 {
2874 cmd << "MANGOHUD=1 ";
2875 lastLaunchInfo_.mangoHud = true;
2876 Logger::info("Using MangoHud");
2877 }
2878 }
2879 // VkBasalt via Vulkan layer env var
2880 if (game_.runnerConfig.enableVkBasalt)
2881 {
2882 cmd << "ENABLE_VKBASALT=1 ";
2883 lastLaunchInfo_.vkBasalt = true;
2884 Logger::info("Using VkBasalt shader injection");
2885 }
2886
2887 // Step 14b: Gamescope compositor (wraps entire command with -- separator)
2888 std::string gamescopeMode;
2889 std::string gamescopeWrapper = buildGamescopeWrapper(game_.runnerConfig, gamescopeMode);
2890 if (!gamescopeWrapper.empty())
2891 {
2892 cmd << gamescopeWrapper;
2893 lastLaunchInfo_.gamescope = true;
2894 lastLaunchInfo_.gamescopeMode = gamescopeMode;
2895 }
2896
2897 // Step 15: The umu-run command
2898 cmd << "umu-run ";
2899
2900 // Step 16: Executable path (safely escaped)
2901 cmd << ShellUtils::escapeArg(game_.runnerConfig.executablePath);
2902
2903 // Step 17: Arguments (safely escaped)
2904 if (!game_.runnerConfig.arguments.empty())
2905 {
2906 // Split args respecting shell quoting, then escape each token safely
2907 for (const auto& arg : ShellUtils::splitArgs(game_.runnerConfig.arguments))
2908 cmd << " " << ShellUtils::escapeArg(arg);
2909 }
2910
2911 std::string command = cmd.str();
2912 Logger::info("umu-launcher command: {}", command);
2913
2914 // Execute command
2915 bool success = executeCommand(command);
2916
2917 if (success)
2918 {
2919 std::string summary = lastLaunchInfo_.getSummary(false);
2920 notify(NotificationType::Info, "Launched: " + summary);
2921 }
2922
2923 return success;
2924}
2925
2926bool GameProcess::launchProtonDirect()
2927{
2928 std::ostringstream cmd;
2929
2930 // ==========================================================================
2931 // Direct Proton Launch (fallback when umu-launcher not available)
2932 // This requires proper Steam runtime setup and may not work for all games.
2933 // Prefer umu-launcher when possible.
2934 //
2935 // Command structure:
2936 // <env variables> <proton> run <executable> <arguments>
2937 // ==========================================================================
2938
2939 Logger::info("Launching with direct Proton execution (fallback mode): {}", game_.name);
2940 Logger::warn("Direct Proton execution is less reliable than umu-launcher. "
2941 "Consider installing umu-launcher for better compatibility.");
2942
2943 // Validate executable path exists
2944 if (game_.runnerConfig.executablePath.empty())
2945 {
2946 Logger::error("No executable path specified for game: {}", game_.name);
2947 return false;
2948 }
2949 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
2950 {
2951 Logger::error("Executable not found: {}", game_.runnerConfig.executablePath);
2952 return false;
2953 }
2954
2955 // Determine prefix path
2956 std::string prefixPath;
2957 const char* home = std::getenv("HOME");
2958
2959 if (!game_.runnerConfig.winePrefix.empty())
2960 {
2961 prefixPath = game_.runnerConfig.winePrefix;
2962 }
2963 else if (home)
2964 {
2965 std::string safeName = game_.name;
2966 for (char& c : safeName)
2967 {
2968 if (!std::isalnum(static_cast<unsigned char>(c)))
2969 c = '_';
2970 }
2971 prefixPath = std::string(home) + "/Games/proton-prefixes/" + safeName;
2972 }
2973
2974 // Create prefix directory if it doesn't exist
2975 if (!prefixPath.empty())
2976 {
2977 try
2978 {
2979 if (!std::filesystem::exists(prefixPath))
2980 {
2981 std::filesystem::create_directories(prefixPath);
2982 Logger::info("Created Proton prefix directory: {}", prefixPath);
2983 }
2984 }
2985 catch (const std::exception& e)
2986 {
2987 Logger::warn("Failed to create prefix directory: {}", e.what());
2988 }
2989 }
2990
2991 // Step 1: Add all user-configured environment variables FIRST (with safe escaping)
2992 // SECURITY: All environment variables are validated and escaped to prevent injection
2993 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
2994 {
2995 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
2996 continue;
2997
2998 // Validate environment variable name to prevent injection
3000 {
3001 Logger::warn("Skipping invalid environment variable name: {}", key);
3002 continue;
3003 }
3004
3005 cmd << ShellUtils::formatEnvVar(key, value) << " ";
3006 }
3007
3008 // Step 2: Set STEAM_COMPAT_DATA_PATH (Wine prefix for Proton, safely escaped)
3009 if (!prefixPath.empty())
3010 {
3011 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_DATA_PATH", prefixPath) << " ";
3012 Logger::info("Using Proton prefix: {}", prefixPath);
3013 }
3014
3015 // Step 3: Set Steam client path and additional runtime variables (required for Proton)
3016 if (home)
3017 {
3018 std::filesystem::path steamPath =
3019 std::filesystem::path(home) / ".local" / "share" / "Steam";
3020 if (std::filesystem::exists(steamPath))
3021 {
3022 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_CLIENT_INSTALL_PATH", steamPath.string())
3023 << " ";
3024
3025 // Additional Steam runtime variables for better compatibility
3026 std::filesystem::path runtimePath = steamPath / "ubuntu12_32" / "steam-runtime";
3027 if (std::filesystem::exists(runtimePath))
3028 {
3029 cmd << ShellUtils::formatEnvVar("STEAM_RUNTIME", runtimePath.string()) << " ";
3030 }
3031 }
3032 }
3033
3034 // Step 4: Add sync primitives (NTSync > Fsync > Esync for best performance)
3035 addSyncEnvironment(cmd, game_.runnerConfig, true);
3036
3037 // Step 5: Add GPU-specific optimizations (AMD Anti-Lag, NVIDIA NVAPI)
3038 addGPUOptimizations(cmd, true);
3039
3040 // Step 6: Add application-specific fixes (Battle.net, EA App, etc.)
3041 addApplicationSpecificFixes(cmd, game_);
3042
3043 // Step 7: Add detailed logging if enabled
3044 if (game_.runnerConfig.enableDetailedLogging)
3045 {
3046 cmd << "PROTON_LOG=1 ";
3047 cmd << "STEAM_LINUX_RUNTIME_VERBOSE=1 ";
3048 Logger::info("Enabling detailed Proton logging");
3049 }
3050
3051 // Step 8: Add performance wrappers (MangoHud, GameMode, VkBasalt, game-performance)
3052 std::string wrapperChain = buildWrapperChain(game_.runnerConfig, game_.id);
3053 if (!wrapperChain.empty())
3054 {
3055 cmd << wrapperChain;
3056 }
3057
3058 // Step 8b: Add Gamescope compositor (wraps entire command with -- separator)
3059 std::string gamescopeMode;
3060 std::string gamescopeWrapper = buildGamescopeWrapper(game_.runnerConfig, gamescopeMode);
3061 if (!gamescopeWrapper.empty())
3062 {
3063 cmd << gamescopeWrapper;
3064 lastLaunchInfo_.gamescope = true;
3065 lastLaunchInfo_.gamescopeMode = gamescopeMode;
3066 }
3067
3068 // Step 9: Find and add Proton executable (safely escaped)
3069 std::string protonExe;
3070 try
3071 {
3072 protonExe = findProtonExecutable(game_.runnerConfig.protonVersion);
3073 }
3074 catch (const std::exception& e)
3075 {
3076 Logger::error("Failed to find Proton executable: {}", e.what());
3078 "Failed to find Proton executable. Install Proton via Steam or umu-launcher.");
3079 return false;
3080 }
3081 cmd << ShellUtils::escapeArg(protonExe) << " run ";
3082
3083 // Step 10: Add executable path (safely escaped)
3084 cmd << ShellUtils::escapeArg(game_.runnerConfig.executablePath);
3085
3086 // Step 11: Add arguments (safely escaped)
3087 if (!game_.runnerConfig.arguments.empty())
3088 {
3089 // Split args respecting shell quoting, then escape each token safely
3090 for (const auto& arg : ShellUtils::splitArgs(game_.runnerConfig.arguments))
3091 cmd << " " << ShellUtils::escapeArg(arg);
3092 }
3093
3094 std::string command = cmd.str();
3095 Logger::info("Direct Proton command: {}", command);
3096
3097 // Execute command directly (avoids corrupting game_.runnerConfig)
3098 return executeCommand(command);
3099}
3100
3101std::string GameProcess::buildDirectProtonCommand(const std::string& protonExe)
3102{
3103 std::ostringstream cmd;
3104
3105 // ==========================================================================
3106 // Direct Proton Launch Command
3107 // ==========================================================================
3108 // Format: <env vars> <wrappers> <proton_exe> run <game.exe> <game_args>
3109 //
3110 // Required environment variables for Proton:
3111 // STEAM_COMPAT_DATA_PATH — Wine prefix location (per-game)
3112 // STEAM_COMPAT_CLIENT_INSTALL_PATH — Steam installation root
3113 // SteamAppId / SteamGameId — Enables Steam overlay and Steamworks API
3114 //
3115 // Optional but recommended:
3116 // STEAM_COMPAT_SHADER_PATH — Shader cache location
3117 // PROTON_VERB — "run" (default), "waitforexitandrun", etc.
3118 //
3119 // Wrapper ordering (outermost → innermost):
3120 // game-performance → gamemoderun → gamescope -- → proton run <exe>
3121 // MangoHud and VkBasalt are activated via env vars (Vulkan layers).
3122 //
3123 // This follows the same pattern as Lutris and Heroic Launcher.
3124 // ==========================================================================
3125
3126 lastLaunchInfo_ = LaunchInfo{};
3127 lastLaunchInfo_.runner = "Proton (Direct)";
3128
3129 // --- Step 1: Steam/Proton environment variables ---
3130 const char* home = std::getenv("HOME");
3131 if (!home)
3132 {
3133 Logger::error("HOME environment variable not set");
3134 return {};
3135 }
3136
3137 std::filesystem::path steamPath = std::filesystem::path(home) / ".local" / "share" / "Steam";
3138
3139 // Find the correct Steam library for this game's compat data
3140 std::filesystem::path compatDataPath;
3141 std::filesystem::path gamePath = game_.runnerConfig.workingDirectory;
3142
3143 // Try the library the game is installed in first
3144 if (!gamePath.empty())
3145 {
3146 std::filesystem::path searchPath = gamePath;
3147 while (searchPath.has_parent_path() && searchPath.filename() != "steamapps")
3148 {
3149 searchPath = searchPath.parent_path();
3150 }
3151 if (searchPath.filename() == "steamapps")
3152 {
3153 std::filesystem::path candidate =
3154 searchPath / "compatdata" / std::to_string(game_.metadata.steamAppId);
3155 if (std::filesystem::exists(candidate))
3156 {
3157 compatDataPath = candidate;
3158 }
3159 }
3160 }
3161
3162 // Fall back to primary Steam installation
3163 if (compatDataPath.empty())
3164 {
3165 compatDataPath =
3166 steamPath / "steamapps" / "compatdata" / std::to_string(game_.metadata.steamAppId);
3167 }
3168
3169 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_DATA_PATH", compatDataPath.string()) << " ";
3170 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_CLIENT_INSTALL_PATH", steamPath.string()) << " ";
3171 cmd << "SteamAppId=" << game_.metadata.steamAppId << " ";
3172 cmd << "SteamGameId=" << game_.metadata.steamAppId << " ";
3173 lastLaunchInfo_.winePrefix = compatDataPath.string();
3174
3175 // Set winePrefix on the game config so checkProcessRunning/findGameProcess
3176 // can locate Wine processes running under this prefix after the shell exits.
3177 // Proton uses pfx/ subdirectory within STEAM_COMPAT_DATA_PATH.
3178 if (game_.runnerConfig.winePrefix.empty())
3179 {
3180 std::filesystem::path pfxPath = compatDataPath / "pfx";
3181 if (std::filesystem::exists(pfxPath))
3182 game_.runnerConfig.winePrefix = pfxPath.string();
3183 else
3184 game_.runnerConfig.winePrefix = compatDataPath.string();
3185 }
3186
3187 // Shader cache path
3188 std::filesystem::path shaderPath =
3189 steamPath / "steamapps" / "shadercache" / std::to_string(game_.metadata.steamAppId);
3190 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_SHADER_PATH", shaderPath.string()) << " ";
3191
3192 // --- Step 2: Wine debug suppression (unless detailed logging) ---
3193 if (!game_.runnerConfig.enableDetailedLogging)
3194 {
3195 cmd << "WINEDEBUG=-all ";
3196 }
3197
3198 // --- Step 3: PROTON_VERB ---
3199 if (game_.runnerConfig.environmentVariables.find("PROTON_VERB") ==
3200 game_.runnerConfig.environmentVariables.end())
3201 {
3202 cmd << "PROTON_VERB=waitforexitandrun ";
3203 }
3204
3205 // --- Step 4: Proton-specific optimizations ---
3206 cmd << "PROTON_DXVK_D3D8=1 ";
3207
3208 // --- Step 5: Sync primitives (NTSync > Fsync > Esync) ---
3209 if (game_.runnerConfig.autoDetectSync)
3210 {
3212 {
3213 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
3214 lastLaunchInfo_.syncMethod = "NTSync";
3215 Logger::info("Using NTSync (auto-detected kernel support)");
3216 }
3217 else if (kernelSupportsFsync())
3218 {
3219 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
3220 lastLaunchInfo_.syncMethod = "Fsync";
3221 Logger::info("Using Fsync (auto-detected kernel support)");
3222 }
3223 else
3224 {
3225 cmd << "WINEESYNC=1 ";
3226 lastLaunchInfo_.syncMethod = "Esync";
3227 Logger::info("Using Esync (kernel doesn't support Fsync)");
3228 }
3229 }
3230 else if (game_.runnerConfig.enableFsync)
3231 {
3232 cmd << "WINEFSYNC=1 WINEESYNC=1 ";
3233 lastLaunchInfo_.syncMethod = "Fsync";
3234 Logger::info("Using Fsync (user configured)");
3235 }
3236
3237 // --- Step 6: GPU-specific optimizations ---
3238 std::string gpu = detectGPUVendor();
3239 lastLaunchInfo_.gpuVendor = gpu;
3240
3241 if (gpu == "AMD")
3242 {
3243 cmd << "ENABLE_LAYER_MESA_ANTI_LAG=1 ";
3244 cmd << "WINE_FULLSCREEN_FSR=1 ";
3245 lastLaunchInfo_.amdAntiLag = true;
3246 Logger::info("Enabling AMD optimizations (Anti-Lag, FSR)");
3247 }
3248 else if (gpu == "NVIDIA")
3249 {
3250 cmd << "DXVK_ENABLE_NVAPI=1 ";
3251 cmd << "PROTON_FORCE_NVAPI=1 ";
3252 cmd << "WINE_FULLSCREEN_FSR=1 ";
3253 lastLaunchInfo_.nvidiaNvapi = true;
3254 Logger::info("Enabling NVIDIA NVAPI + FSR support");
3255 }
3256
3257 // --- Step 7: Detailed logging ---
3258 if (game_.runnerConfig.enableDetailedLogging)
3259 {
3260 cmd << "PROTON_LOG=1 ";
3261 cmd << "WINEDEBUG=+loaddll,+seh ";
3262 Logger::info("Enabling detailed Proton logging");
3263 }
3264
3265 // --- Step 8: User-configured environment variables ---
3266 int customEnvCount = 0;
3267 for (const auto& [key, value] : game_.runnerConfig.environmentVariables)
3268 {
3269 // Skip keys handled by dedicated toggles
3270 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE" || key == "MANGOHUD" ||
3271 key == "ENABLE_VKBASALT" || key == "PROTON_VERB" || key == "PROTON_LOG")
3272 continue;
3273
3275 {
3276 Logger::warn("Skipping invalid environment variable name: {}", key);
3277 continue;
3278 }
3279
3280 cmd << ShellUtils::formatEnvVar(key, value) << " ";
3281 customEnvCount++;
3282 }
3283 lastLaunchInfo_.customEnvVars = customEnvCount;
3284
3285 // --- Step 9: MangoHud config (always set MANGOHUD_CONFIGFILE so the
3286 // implicit Vulkan layer can't fall back to the user's MangoHud.conf;
3287 // see buildWrapperChain for full rationale). ---
3288 if (!game_.runnerConfig.enableGamescope)
3289 {
3291 game_.id, game_.runnerConfig.mangoHudConfigFile);
3292 if (!cfgPath.empty())
3293 {
3294 cmd << "MANGOHUD_CONFIGFILE=" << ShellUtils::escapeArg(cfgPath) << " ";
3295 }
3296 if (game_.runnerConfig.enableMangoHud)
3297 {
3298 cmd << "MANGOHUD=1 ";
3299 lastLaunchInfo_.mangoHud = true;
3300 Logger::info("Using MangoHud");
3301 }
3302 }
3303
3304 // --- Step 10: VkBasalt (env var) ---
3305 if (game_.runnerConfig.enableVkBasalt)
3306 {
3307 cmd << "ENABLE_VKBASALT=1 ";
3308 lastLaunchInfo_.vkBasalt = true;
3309 Logger::info("Using VkBasalt shader injection");
3310 }
3311
3312 // --- Step 11: Process identifier ---
3313 if (!game_.id.empty())
3314 {
3315 cmd << ShellUtils::formatEnvVar("GAME_LAUNCHER_UUID", game_.id) << " ";
3316 }
3317
3318 // --- Step 12: Performance wrappers (outermost → innermost) ---
3319 // game-performance (CachyOS CPU governor optimization) — outermost
3320 if (game_.runnerConfig.enableGamePerformance && isWrapperAvailable("game-performance"))
3321 {
3322 cmd << "game-performance ";
3323 lastLaunchInfo_.gamePerformance = true;
3324 Logger::info("Using game-performance (outermost)");
3325 }
3326
3327 // gamemoderun (Feral GameMode)
3328 if (game_.runnerConfig.enableGameMode && isWrapperAvailable("gamemoderun"))
3329 {
3330 cmd << "gamemoderun ";
3331 lastLaunchInfo_.gameMode = true;
3332 Logger::info("Using GameMode");
3333 }
3334
3335 // Gamescope compositor (wraps the proton command with -- separator)
3336 std::string gamescopeMode;
3337 std::string gamescopeWrapper = buildGamescopeWrapper(game_.runnerConfig, gamescopeMode);
3338 if (!gamescopeWrapper.empty())
3339 {
3340 cmd << gamescopeWrapper;
3341 lastLaunchInfo_.gamescope = true;
3342 lastLaunchInfo_.gamescopeMode = gamescopeMode;
3343 }
3344
3345 // --- Step 13: Proton executable ---
3346 lastLaunchInfo_.runnerVersion = protonExe;
3347 cmd << ShellUtils::escapeArg(protonExe) << " run ";
3348
3349 // --- Step 14: Game executable ---
3350 cmd << ShellUtils::escapeArg(game_.runnerConfig.executablePath);
3351
3352 // --- Step 15: Game arguments ---
3353 if (!game_.runnerConfig.arguments.empty())
3354 {
3355 // Split args respecting shell quoting, then escape each token safely
3356 for (const auto& arg : ShellUtils::splitArgs(game_.runnerConfig.arguments))
3357 cmd << " " << ShellUtils::escapeArg(arg);
3358 }
3359
3360 return cmd.str();
3361}
3362
3363bool GameProcess::launchProtonSteamGame()
3364{
3365 // ==========================================================================
3366 // Steam Proton Game Launch
3367 // ==========================================================================
3368 // Two modes:
3369 // 1. Direct Proton: We invoke Proton ourselves with full control over
3370 // env vars, wrappers (MangoHud, GameMode, game-performance, Gamescope),
3371 // and PID tracking. This is the preferred mode.
3372 // 2. Steam-managed: Delegate to "steam -applaunch" as a fallback for
3373 // DRM-protected games or when direct launch info isn't available.
3374 // ==========================================================================
3375
3376 // Route to the Steam-managed launch path if any of:
3377 // - per-game runner config opted in (useSteamLaunch=true)
3378 // - the saved executable is "steam" (no direct launch info captured)
3379 // - the global default is on (Settings → Steam Integration)
3380 // The global default is preferred because it gives users the Steam overlay,
3381 // achievements, and Cloud out-of-the-box. Power users who want our env-var
3382 // wrappers (MangoHud / Gamescope / GameMode) on a particular Steam title
3383 // can disable the global toggle and re-launch.
3384 //
3385 // launchViaSteamApplaunch() runs `steam -applaunch <appid>`, which is the
3386 // only path that works regardless of what executablePath is set to. The
3387 // original code called launchNative() here, but that runs buildLaunchCommand
3388 // which only short-circuits Proton injection when executablePath == "steam".
3389 // For globally-defaulted Steam games whose executablePath points at the
3390 // Windows .exe, that path tried to exec the .exe directly through /bin/sh
3391 // and failed instantly (start-then-stop loop).
3392 const bool steamLaunchByDefault =
3394 if (game_.runnerConfig.useSteamLaunch || game_.runnerConfig.executablePath == "steam" ||
3395 steamLaunchByDefault)
3396 {
3397 Logger::info("Launching Steam game via Steam client (App ID: {})",
3398 game_.metadata.steamAppId);
3399 return launchViaSteamApplaunch();
3400 }
3401
3402 // Direct Proton launch
3403 Logger::info("Launching Steam Proton game directly (App ID: {}): {}", game_.metadata.steamAppId,
3404 game_.runnerConfig.executablePath);
3405
3406 // Resolve Proton path — protonVersion may store a display name (e.g. "Proton (Steam-managed)")
3407 // or a filesystem path. Try as path first, then resolve via ProtonCache.
3408 std::string protonExe = resolveProtonExecutable();
3409
3410 if (protonExe.empty() || !std::filesystem::exists(protonExe))
3411 {
3412 Logger::warn("Proton path not found or invalid (protonVersion='{}', runnerVersion='{}') "
3413 "— falling back to steam -applaunch",
3414 game_.runnerConfig.protonVersion, game_.runnerConfig.runnerVersion);
3415 return launchViaSteamApplaunch();
3416 }
3417
3418 // Verify game executable
3419 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
3420 {
3421 Logger::warn("Game executable not found: '{}' — falling back to steam -applaunch",
3422 game_.runnerConfig.executablePath);
3423 return launchViaSteamApplaunch();
3424 }
3425
3426 // Ensure Steam is running (needed for Steam overlay, DRM, cloud saves)
3427 if (!ensureSteamRunning())
3428 {
3429 Logger::error("Cannot launch Steam game: Steam is not running and failed to start");
3430 return false;
3431 }
3432
3433 // Build the launch command (also populates lastLaunchInfo_)
3434 std::string command = buildDirectProtonCommand(protonExe);
3435 if (command.empty())
3436 {
3437 Logger::error("Failed to build direct Proton launch command");
3438 return false;
3439 }
3440 Logger::info("Direct Proton command: {}", command);
3441
3442 bool success = executeCommand(command);
3443
3444 if (success)
3445 {
3446 std::string summary = lastLaunchInfo_.getSummary(false);
3447 notify(NotificationType::Info, "Launched: " + summary);
3448 }
3449
3450 return success;
3451}
3452
3453bool GameProcess::launchViaSteamApplaunch()
3454{
3455 // Fallback: launch via Steam's IPC mechanism.
3456 // Environment variables and wrappers set here only affect the short-lived
3457 // "steam -applaunch" client, NOT the actual game process. Custom settings
3458 // must be synced to Steam's VDF launch options beforehand.
3459 int appId = game_.metadata.steamAppId;
3460 if (appId <= 0)
3461 {
3462 Logger::error("Cannot fall back to steam -applaunch: no Steam App ID");
3463 return false;
3464 }
3465
3466 if (!ensureSteamRunning())
3467 {
3468 Logger::error("Cannot launch Steam game: Steam is not running and failed to start");
3469 return false;
3470 }
3471
3472 std::string command = "steam -applaunch " + std::to_string(appId);
3473 if (!game_.runnerConfig.arguments.empty())
3474 {
3475 command += " " + ShellUtils::escapeArg(game_.runnerConfig.arguments);
3476 }
3477
3478 Logger::info("Launching via steam -applaunch fallback: {}", command);
3479 lastLaunchInfo_ = LaunchInfo{};
3480 lastLaunchInfo_.runner = "Steam (managed)";
3481
3482 bool success = executeCommand(command);
3483 if (success)
3484 {
3486 "Launched via Steam (App ID: " + std::to_string(appId) + ")");
3487 }
3488 return success;
3489}
3490
3491std::string GameProcess::resolveProtonExecutable() const
3492{
3493 // Strategy 1: protonVersion is already a valid filesystem path
3494 const std::string& pv = game_.runnerConfig.protonVersion;
3495 if (!pv.empty() && std::filesystem::exists(pv))
3496 {
3497 Logger::info("Proton path is already valid: {}", pv);
3498 return pv;
3499 }
3500
3501 // Strategy 2: Exact match of protonVersion display name in ProtonCache
3502 if (!pv.empty() && pv != "Proton (Steam-managed)")
3503 {
3504 std::string dir = findProtonPath(pv);
3505 if (!dir.empty())
3506 {
3507 std::string exe = (std::filesystem::path(dir) / "proton").string();
3508 if (std::filesystem::exists(exe))
3509 {
3510 Logger::info("Resolved protonVersion '{}' to: {}", pv, exe);
3511 return exe;
3512 }
3513 }
3514 }
3515
3516 // Strategy 3: Try runnerVersion (e.g., "proton-cachyos-slr (system)") — exact then partial
3517 const std::string& rv = game_.runnerConfig.runnerVersion;
3518 if (!rv.empty())
3519 {
3520 std::string dir = findProtonPath(rv);
3521 if (!dir.empty())
3522 {
3523 std::string exe = (std::filesystem::path(dir) / "proton").string();
3524 if (std::filesystem::exists(exe))
3525 {
3526 Logger::info("Resolved runnerVersion '{}' to: {}", rv, exe);
3527 return exe;
3528 }
3529 }
3530 }
3531
3532 // Strategy 4: Partial matching — find cache entries containing key substrings
3533 // e.g. "proton-cachyos-slr" should match "proton-cachyos-10.0-20251120-slr-x86_64 (system)"
3534 auto protonVersions = ProtonCache::getVersions();
3535
3536 // Build search terms from both fields, stripping common suffixes
3537 std::vector<std::string> searchTerms;
3538 for (const std::string& src : {pv, rv})
3539 {
3540 if (src.empty() || src == "Proton (Steam-managed)")
3541 continue;
3542
3543 // Strip " (system)" suffix for matching
3544 std::string term = src;
3545 auto sysPos = term.find(" (system)");
3546 if (sysPos != std::string::npos)
3547 term = term.substr(0, sysPos);
3548
3549 if (!term.empty())
3550 searchTerms.push_back(term);
3551
3552 // Also try splitting on hyphens and matching key parts
3553 // e.g., "proton-cachyos-slr" → look for entries containing "cachyos" AND "slr"
3554 }
3555
3556 for (const auto& term : searchTerms)
3557 {
3558 for (const auto& [name, path] : protonVersions)
3559 {
3560 if (path.empty())
3561 continue;
3562
3563 // Check if cache entry name contains the search term
3564 // or if search term contains the cache entry directory name
3565 std::string dirName = path.parent_path().filename().string();
3566
3567 if (name.find(term) != std::string::npos || dirName.find(term) != std::string::npos)
3568 {
3569 std::string exe = path.string();
3570 if (std::filesystem::exists(exe))
3571 {
3572 Logger::info("Partial match: '{}' matched cache entry '{}' → {}", term, name,
3573 exe);
3574 return exe;
3575 }
3576 }
3577
3578 // Reverse: check if term is a substring of the directory/display name
3579 // e.g., term="proton-cachyos-slr" → check if "proton-cachyos-10.0-slr" contains key
3580 // parts Extract hyphen-delimited tokens from term and check all are in the name
3581 bool allTokensMatch = true;
3582 std::istringstream tokenStream(term);
3583 std::string token;
3584 int tokenCount = 0;
3585 while (std::getline(tokenStream, token, '-'))
3586 {
3587 if (token.empty())
3588 continue;
3589 tokenCount++;
3590 if (dirName.find(token) == std::string::npos)
3591 {
3592 allTokensMatch = false;
3593 break;
3594 }
3595 }
3596
3597 if (allTokensMatch && tokenCount >= 2)
3598 {
3599 std::string exe = path.string();
3600 if (std::filesystem::exists(exe))
3601 {
3602 Logger::info("Token match: all tokens of '{}' found in '{}' → {}", term,
3603 dirName, exe);
3604 return exe;
3605 }
3606 }
3607 }
3608 }
3609
3610 Logger::warn("Could not resolve Proton executable from protonVersion='{}', runnerVersion='{}'",
3611 pv, rv);
3612 return "";
3613}
3614
3615std::string GameProcess::findProtonPath(const std::string& versionName) const
3616{
3617 if (versionName.empty())
3618 {
3619 return "";
3620 }
3621
3622 // Get cached Proton versions
3623 auto protonPaths = ProtonCache::getVersions();
3624
3625 for (const auto& [name, path] : protonPaths)
3626 {
3627 if (name == versionName && !path.empty())
3628 {
3629 // Return the directory containing proton, not the proton executable
3630 std::filesystem::path protonDir = path.parent_path();
3631 Logger::info("Found Proton path for '{}': {}", versionName, protonDir.string());
3632 return protonDir.string();
3633 }
3634 }
3635
3636 Logger::warn("Proton version '{}' not found", versionName);
3637 return "";
3638}
3639
3640bool GameProcess::checkProcessRunning()
3641{
3642 if (pid_ <= 0)
3643 {
3644 return false;
3645 }
3646
3647#ifdef _WIN32
3648 // Windows: Check if process handle is valid
3649 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid_);
3650 if (hProcess == NULL)
3651 {
3652 return false;
3653 }
3654
3655 DWORD exitCode;
3656 GetExitCodeProcess(hProcess, &exitCode);
3657 CloseHandle(hProcess);
3658
3659 return (exitCode == STILL_ACTIVE);
3660#else
3661 // ==========================================================================
3662 // Child Process Tracking for Launcher Games
3663 // ==========================================================================
3664 // Launchers (Battle.net, EA App, etc.) spawn child processes for actual games.
3665 // When tracking launcher games, we need to:
3666 // 1. Check if the launcher (pid_) is still running
3667 // 2. If not, check if any child processes are still running
3668 // 3. Filter out helper processes (e.g., Agent.exe, Battle.net Helper.exe)
3669 // 4. Track the actual game process
3670 // ==========================================================================
3671
3672 // If we're tracking a child game process (trackedPid_), check that instead
3673 if (trackedPid_ > 0 && trackedPid_ != pid_)
3674 {
3675 // Check if tracked game process is still running
3676 if (::kill(trackedPid_, 0) == 0)
3677 {
3678 return true; // Game process still running
3679 }
3680 else
3681 {
3682 Logger::info("Tracked game process {} has exited", trackedPid_);
3683 trackedPid_ = -1;
3684 // Continue to check for other child processes below
3685 }
3686 }
3687
3688 // Check if main launcher process is still running
3689 // For attached processes, we can't use waitpid() since we didn't spawn them
3690 // Instead, use kill(pid, 0) to check if the process exists
3691 bool mainProcessRunning = false;
3692
3693 if (isAttachedProcess_)
3694 {
3695 // For attached processes, use kill to check existence
3696 mainProcessRunning = (::kill(pid_, 0) == 0);
3697 }
3698 else
3699 {
3700 // For spawned processes, use waitpid
3701 int status;
3702 pid_t result = waitpid(pid_, &status, WNOHANG);
3703 mainProcessRunning = (result == 0);
3704 }
3705
3706 if (mainProcessRunning)
3707 {
3708 // Main process still running - but also try to find child game process
3709 // Keep looking even if we already found a launcher, in case the actual game starts
3710 if (!game_.runnerConfig.excludeProcesses.empty())
3711 {
3712 int gameProc = findGameProcess();
3713 if (gameProc > 0 && gameProc != trackedPid_)
3714 {
3715 // Found a new/different process - update tracking
3716 std::string newExeName = getWineExecutableName(gameProc);
3717 bool wasNotTracking = (trackedPid_ <= 0 || trackedPid_ == pid_);
3718 trackedPid_ = gameProc;
3719 trackedProcessName_ = newExeName;
3720
3721 if (wasNotTracking)
3722 {
3723 Logger::info("Found game process to track: PID {} ({}) (launcher: {})",
3724 trackedPid_, trackedProcessName_, pid_);
3725
3726 // Restart frame metrics collection with the actual game PID
3727 // This is important for launcher games where we initially had the wrong PID
3728 if (game_.runnerConfig.enableMangoHud)
3729 {
3731 FrameMetricsService::instance().startCollection(game_.id, trackedPid_,
3732 false, true);
3733 Logger::info("Restarted frame metrics for actual game process: PID {}",
3734 trackedPid_);
3735 }
3736
3737 // Apply GameMode to the actual game PID (complements gamemoderun wrapper)
3738 if (game_.runnerConfig.enableGameMode)
3739 {
3740 // End GameMode for old PID and start for the actual game PID
3741 if (gamemodePid_ > 0 && gamemodePid_ != trackedPid_)
3742 GameModeAPI::instance().requestEndFor(static_cast<pid_t>(gamemodePid_));
3743 GameModeAPI::instance().requestStartFor(static_cast<pid_t>(trackedPid_));
3744 gamemodePid_ = trackedPid_;
3745 }
3746 }
3747 else
3748 {
3749 // We already had a tracked process - only update if this is a better match
3750 // (i.e., the new one is the actual game, not a launcher)
3751 Logger::info("Updated tracked process: PID {} ({})", trackedPid_,
3752 trackedProcessName_);
3753
3754 // Update GameMode to follow the new tracked PID
3755 if (game_.runnerConfig.enableGameMode && gamemodePid_ != trackedPid_)
3756 {
3757 if (gamemodePid_ > 0)
3758 GameModeAPI::instance().requestEndFor(static_cast<pid_t>(gamemodePid_));
3759 GameModeAPI::instance().requestStartFor(static_cast<pid_t>(trackedPid_));
3760 gamemodePid_ = trackedPid_;
3761 }
3762 }
3763 }
3764 }
3765 return true;
3766 }
3767 else
3768 {
3769 // Main process has exited - check for child/Wine processes
3770 // This handles three cases:
3771 // 1. Launcher games (excludeProcesses set): launcher exits, game continues
3772 // 2. Wine/Proton games: sh -c exits quickly, Wine processes continue independently
3773 // 3. Native games that fork: parent shell exits, game child continues
3774 bool isWineGame = (game_.runner == GameRunner::Wine || game_.runner == GameRunner::Proton);
3775 bool hasExcludeProcesses = !game_.runnerConfig.excludeProcesses.empty();
3776 bool hasWinePrefix = !game_.runnerConfig.winePrefix.empty();
3777
3778 if (hasExcludeProcesses || isWineGame || hasWinePrefix)
3779 {
3780 int gameProc = findGameProcess();
3781 if (gameProc > 0)
3782 {
3783 if (trackedPid_ != gameProc)
3784 {
3785 trackedPid_ = gameProc;
3786 trackedProcessName_ = getWineExecutableName(gameProc);
3787 Logger::info("Shell/launcher exited, now tracking game process: PID {} ({})",
3788 trackedPid_, trackedProcessName_);
3789
3790 // Apply GameMode to the actual game PID
3791 if (game_.runnerConfig.enableGameMode)
3792 {
3793 if (gamemodePid_ > 0 && gamemodePid_ != trackedPid_)
3794 GameModeAPI::instance().requestEndFor(static_cast<pid_t>(gamemodePid_));
3795 GameModeAPI::instance().requestStartFor(static_cast<pid_t>(trackedPid_));
3796 gamemodePid_ = trackedPid_;
3797 }
3798 }
3799 return true; // Game is still running
3800 }
3801 else
3802 {
3803 Logger::info("Shell/launcher exited and no game processes found");
3804 }
3805 }
3806 // Process has exited
3807 return false;
3808 }
3809#endif
3810}
3811
3812// ==============================================================================
3813// Child Process Tracking Helpers
3814// ==============================================================================
3815
3816std::vector<int> GameProcess::getChildProcesses(int parentPid) const
3817{
3818 std::vector<int> children;
3819
3820#ifndef _WIN32
3821 // Read all process directories from /proc
3822 try
3823 {
3824 for (const auto& entry : std::filesystem::directory_iterator("/proc"))
3825 {
3826 if (!entry.is_directory())
3827 continue;
3828
3829 std::string name = entry.path().filename().string();
3830
3831 // Check if directory name is a PID (all digits)
3832 bool isPid = !name.empty() && std::all_of(name.begin(), name.end(), ::isdigit);
3833 if (!isPid)
3834 continue;
3835
3836 int pid = std::stoi(name);
3837
3838 // Read the process status file to get parent PID
3839 std::filesystem::path statPath = entry.path() / "stat";
3840 if (!std::filesystem::exists(statPath))
3841 continue;
3842
3843 std::ifstream statFile(statPath);
3844 if (!statFile.is_open())
3845 continue;
3846
3847 // Format: pid (comm) state ppid ...
3848 std::string line;
3849 if (std::getline(statFile, line))
3850 {
3851 // Find the closing paren of comm field (process name can contain spaces)
3852 size_t commEnd = line.rfind(')');
3853 if (commEnd != std::string::npos && commEnd + 2 < line.size())
3854 {
3855 // Parse fields after comm: state ppid
3856 std::istringstream iss(line.substr(commEnd + 2));
3857 char state;
3858 int ppid;
3859 if (iss >> state >> ppid)
3860 {
3861 if (ppid == parentPid)
3862 {
3863 children.push_back(pid);
3864 }
3865 }
3866 }
3867 }
3868 }
3869 }
3870 catch (const std::exception& e)
3871 {
3872 Logger::warn("Error reading /proc for child processes: {}", e.what());
3873 }
3874#endif
3875
3876 return children;
3877}
3878
3879std::string GameProcess::getProcessName(int pid) const
3880{
3881#ifndef _WIN32
3882 std::filesystem::path commPath = std::filesystem::path("/proc") / std::to_string(pid) / "comm";
3883
3884 try
3885 {
3886 if (std::filesystem::exists(commPath))
3887 {
3888 std::ifstream commFile(commPath);
3889 std::string name;
3890 if (std::getline(commFile, name))
3891 {
3892 // Trim whitespace
3893 while (!name.empty() && (name.back() == '\n' || name.back() == '\r'))
3894 {
3895 name.pop_back();
3896 }
3897 return name;
3898 }
3899 }
3900 }
3901 catch (const std::exception& e)
3902 {
3903 Logger::warn("Error reading process name for PID {}: {}", pid, e.what());
3904 }
3905#endif
3906
3907 return "";
3908}
3909
3910bool GameProcess::isExcludedProcess(const std::string& processName) const
3911{
3912 if (processName.empty())
3913 return false;
3914
3915 // Convert process name to lowercase for case-insensitive comparison
3916 std::string nameLower = processName;
3917 for (char& c : nameLower)
3918 {
3919 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
3920 }
3921
3922 // Remove .exe extension for base comparison
3923 std::string nameBase = nameLower;
3924 if (nameBase.size() > 4 && nameBase.substr(nameBase.size() - 4) == ".exe")
3925 {
3926 nameBase = nameBase.substr(0, nameBase.size() - 4);
3927 }
3928
3929 for (const auto& excluded : game_.runnerConfig.excludeProcesses)
3930 {
3931 std::string excludedLower = excluded;
3932 for (char& c : excludedLower)
3933 {
3934 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
3935 }
3936
3937 // Remove .exe extension from exclude pattern
3938 std::string excludeBase = excludedLower;
3939 if (excludeBase.size() > 4 && excludeBase.substr(excludeBase.size() - 4) == ".exe")
3940 {
3941 excludeBase = excludeBase.substr(0, excludeBase.size() - 4);
3942 }
3943
3944 // Check for exact match (with or without .exe)
3945 if (nameLower == excludedLower || nameBase == excludeBase)
3946 {
3947 return true;
3948 }
3949
3950 // Check if exclude pattern is contained in the process name
3951 // e.g., "battle.net" matches "battle.net launcher.exe"
3952 if (nameLower.find(excludeBase) != std::string::npos)
3953 {
3954 return true;
3955 }
3956
3957 // Check if process name base is contained in exclude pattern
3958 if (excludeBase.find(nameBase) != std::string::npos && !nameBase.empty())
3959 {
3960 return true;
3961 }
3962 }
3963
3964 return false;
3965}
3966
3967std::string GameProcess::getWineExecutableName(int pid) const
3968{
3969#ifndef _WIN32
3970 // Helper lambda to extract exe name from a cmdline
3971 auto extractExeFromCmdline = [](const std::string& cmdline) -> std::string
3972 {
3973 size_t start = 0;
3974 while (start < cmdline.size())
3975 {
3976 size_t end = cmdline.find('\0', start);
3977 if (end == std::string::npos)
3978 end = cmdline.size();
3979
3980 std::string arg = cmdline.substr(start, end - start);
3981
3982 // Look for .exe (case insensitive)
3983 std::string argLower = arg;
3984 for (char& c : argLower)
3985 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
3986
3987 if (argLower.find(".exe") != std::string::npos)
3988 {
3989 // Extract just the filename from the path
3990 size_t lastSlash = arg.find_last_of("/\\");
3991 if (lastSlash != std::string::npos)
3992 {
3993 return arg.substr(lastSlash + 1);
3994 }
3995 return arg;
3996 }
3997
3998 start = end + 1;
3999 }
4000 return "";
4001 };
4002
4003 // Helper to check if an exe is in the game's exclude list (launchers)
4004 auto isExcludedLauncher = [this](const std::string& exeName) -> bool
4005 {
4006 std::string exeNameLower = exeName;
4007 for (char& c : exeNameLower)
4008 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4009
4010 // Remove .exe extension for comparison
4011 std::string exeNameBase = exeNameLower;
4012 if (exeNameBase.size() > 4 && exeNameBase.substr(exeNameBase.size() - 4) == ".exe")
4013 {
4014 exeNameBase = exeNameBase.substr(0, exeNameBase.size() - 4);
4015 }
4016
4017 // Check game's exclude list (launchers like Battle.net.exe)
4018 for (const auto& excludeProc : game_.runnerConfig.excludeProcesses)
4019 {
4020 std::string excludeLower = excludeProc;
4021 for (char& c : excludeLower)
4022 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4023
4024 // Remove .exe extension from exclude pattern too
4025 std::string excludeBase = excludeLower;
4026 if (excludeBase.size() > 4 && excludeBase.substr(excludeBase.size() - 4) == ".exe")
4027 {
4028 excludeBase = excludeBase.substr(0, excludeBase.size() - 4);
4029 }
4030
4031 // Check exact match (with or without .exe)
4032 if (exeNameLower == excludeLower || exeNameBase == excludeBase)
4033 return true;
4034
4035 // Check if exclude pattern is contained in the exe name
4036 // e.g., "battle.net" matches "battle.net launcher.exe"
4037 if (exeNameLower.find(excludeBase) != std::string::npos)
4038 return true;
4039
4040 // Check if exe name base is contained in exclude pattern
4041 // e.g., "battle.net.exe" matches if exclude is "battle.net"
4042 if (excludeBase.find(exeNameBase) != std::string::npos && !exeNameBase.empty())
4043 return true;
4044 }
4045
4046 return false;
4047 };
4048
4049 // Scan ALL Wine processes in the prefix to find the actual game
4050 // This is necessary because the tracked PID might be a launcher (Battle.net)
4051 // but we want to display the actual game (WowClassic.exe)
4052 // We collect all candidates first, then pick the best one
4053 std::vector<std::string> gameExeCandidates; // Non-launcher executables (preferred)
4054 std::vector<std::string> launcherCandidates; // Launcher executables (fallback)
4055
4056 if (!game_.runnerConfig.winePrefix.empty())
4057 {
4058 try
4059 {
4060 for (const auto& entry : std::filesystem::directory_iterator("/proc"))
4061 {
4062 try
4063 {
4064 if (!entry.is_directory())
4065 continue;
4066
4067 std::string dirName = entry.path().filename().string();
4068 bool isPid =
4069 !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
4070 if (!isPid)
4071 continue;
4072
4073 // Check if this process uses our WINEPREFIX
4074 std::filesystem::path environPath = entry.path() / "environ";
4075 if (!std::filesystem::exists(environPath))
4076 continue;
4077
4078 std::ifstream environFile(environPath, std::ios::binary);
4079 if (!environFile.is_open())
4080 continue;
4081
4082 constexpr size_t kMaxEnviron = 1u << 20; // 1 MB cap
4083 std::string procEnviron;
4084 procEnviron.resize(kMaxEnviron);
4085 environFile.read(procEnviron.data(), static_cast<std::streamsize>(kMaxEnviron));
4086 procEnviron.resize(static_cast<size_t>(environFile.gcount()));
4087
4088 std::string prefixKey = "WINEPREFIX=";
4089 size_t pos = procEnviron.find(prefixKey);
4090 if (pos == std::string::npos)
4091 continue;
4092
4093 size_t valueStart = pos + prefixKey.size();
4094 size_t valueEnd = procEnviron.find('\0', valueStart);
4095 if (valueEnd == std::string::npos)
4096 continue; // malformed environ entry, skip
4097 std::string prefixValue = procEnviron.substr(valueStart, valueEnd - valueStart);
4098
4099 // Remove trailing slashes for comparison
4100 while (!prefixValue.empty() && prefixValue.back() == '/')
4101 prefixValue.pop_back();
4102
4103 std::string gamePrefix = game_.runnerConfig.winePrefix;
4104 while (!gamePrefix.empty() && gamePrefix.back() == '/')
4105 gamePrefix.pop_back();
4106
4107 // Check if this matches our prefix (including pfx subdirectory)
4108 bool prefixMatch =
4109 (prefixValue == gamePrefix) || (prefixValue.find(gamePrefix + "/") == 0);
4110 if (!prefixMatch)
4111 continue;
4112
4113 // This process uses our prefix - check its cmdline for game exe
4114 std::filesystem::path scanCmdlinePath = entry.path() / "cmdline";
4115 if (!std::filesystem::exists(scanCmdlinePath))
4116 continue;
4117
4118 std::ifstream scanCmdlineFile(scanCmdlinePath, std::ios::binary);
4119 std::string scanCmdline((std::istreambuf_iterator<char>(scanCmdlineFile)),
4120 std::istreambuf_iterator<char>());
4121
4122 std::string exeName = extractExeFromCmdline(scanCmdline);
4123 if (exeName.empty())
4124 continue;
4125
4126 // Check if this exe is a Wine system exe
4127 std::string exeNameLower = exeName;
4128 for (char& c : exeNameLower)
4129 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4130
4131 bool isWineSystemExe = false;
4132 for (const auto& sysExe : kWineSystemExes())
4133 {
4134 if (exeNameLower == sysExe)
4135 {
4136 isWineSystemExe = true;
4137 break;
4138 }
4139 }
4140
4141 if (isWineSystemExe)
4142 continue;
4143
4144 // Categorize as game or launcher
4145 if (isExcludedLauncher(exeName))
4146 {
4147 // Check if we already have this launcher
4148 bool alreadyHave = false;
4149 for (const auto& existing : launcherCandidates)
4150 {
4151 if (existing == exeName)
4152 {
4153 alreadyHave = true;
4154 break;
4155 }
4156 }
4157 if (!alreadyHave)
4158 {
4159 Logger::debug("Found launcher exe: '{}'", exeName);
4160 launcherCandidates.push_back(exeName);
4161 }
4162 }
4163 else
4164 {
4165 // Check if we already have this game
4166 bool alreadyHave = false;
4167 for (const auto& existing : gameExeCandidates)
4168 {
4169 if (existing == exeName)
4170 {
4171 alreadyHave = true;
4172 break;
4173 }
4174 }
4175 if (!alreadyHave)
4176 {
4177 Logger::debug("Found game exe: '{}'", exeName);
4178 gameExeCandidates.push_back(exeName);
4179 }
4180 }
4181 }
4182 catch (...)
4183 {
4184 // Process may have exited during scan - ignore and continue
4185 continue;
4186 }
4187 }
4188 }
4189 catch (const std::exception& e)
4190 {
4191 Logger::debug("Error scanning Wine processes for exe name: {}", e.what());
4192 }
4193 }
4194
4195 // Return the first game exe if we found any (prefer non-launcher games)
4196 if (!gameExeCandidates.empty())
4197 {
4198 Logger::info("Detected running game: '{}'", gameExeCandidates[0]);
4199 return gameExeCandidates[0];
4200 }
4201
4202 // Fall back to launcher if no game exe found
4203 if (!launcherCandidates.empty())
4204 {
4205 Logger::debug("No game exe found, using launcher: '{}'", launcherCandidates[0]);
4206 return launcherCandidates[0];
4207 }
4208
4209 // Last resort: try to get exe name from the specific tracked PID
4210 std::filesystem::path cmdlinePath =
4211 std::filesystem::path("/proc") / std::to_string(pid) / "cmdline";
4212 try
4213 {
4214 if (std::filesystem::exists(cmdlinePath))
4215 {
4216 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
4217 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
4218 std::istreambuf_iterator<char>());
4219 std::string exeName = extractExeFromCmdline(cmdline);
4220 if (!exeName.empty())
4221 {
4222 return exeName;
4223 }
4224 }
4225 }
4226 catch (...)
4227 {
4228 // /proc/<pid>/{cmdline,exists} is inherently racy — the pid we're
4229 // querying could exit between the exists() check and the open(),
4230 // or even between read iterations. Treat any error as "couldn't
4231 // determine exe name" and fall through to the empty-string return
4232 // at function exit. Same rationale as the per-pid catch at the
4233 // top of the wine-process scanner above.
4234 }
4235#else
4236 (void)pid;
4237#endif
4238
4239 // Final fallback to process name
4240 return getProcessName(pid);
4241}
4242
4243int GameProcess::findGameProcess() const
4244{
4245#ifndef _WIN32
4246 // ==========================================================================
4247 // Wine Process Tracking Strategy
4248 // ==========================================================================
4249 // Wine processes don't have simple parent-child relationships. Instead:
4250 // 1. The shell command we launch exits quickly
4251 // 2. wineserver manages all Wine processes
4252 // 3. wine-preloader/wine64-preloader run the actual Windows executables
4253 //
4254 // Strategy: Find Wine processes running under our WINEPREFIX
4255 // ==========================================================================
4256
4257 std::vector<int> candidates;
4258
4259 // If we have a Wine prefix, look for wine processes using it
4260 if (!game_.runnerConfig.winePrefix.empty())
4261 {
4262 try
4263 {
4264 for (const auto& entry : std::filesystem::directory_iterator("/proc"))
4265 {
4266 try
4267 {
4268 if (!entry.is_directory())
4269 continue;
4270
4271 std::string dirName = entry.path().filename().string();
4272 bool isPid =
4273 !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
4274 if (!isPid)
4275 continue;
4276
4277 int pid = std::stoi(dirName);
4278
4279 // Check if this is a wine process
4280 std::string name = getProcessName(pid);
4281 if (name.empty())
4282 continue;
4283
4284 // Wine process names: wine, wine64, wine-preloader, wine64-preloader
4285 // Skip wineserver (it's just a daemon, not the actual game)
4286 if (name == "wineserver")
4287 continue;
4288
4289 bool isWineProcess =
4290 (name == "wine" || name == "wine64" || name == "wine-preloader" ||
4291 name == "wine64-preloader" || name.find("wine") != std::string::npos);
4292
4293 if (!isWineProcess)
4294 continue;
4295
4296 // Check if this wine process is using our prefix by reading its environment
4297 std::filesystem::path environPath = entry.path() / "environ";
4298 if (!std::filesystem::exists(environPath))
4299 continue;
4300
4301 std::ifstream environFile(environPath, std::ios::binary);
4302 if (!environFile.is_open())
4303 continue;
4304
4305 // Read entire environment (null-separated)
4306 constexpr size_t kMaxEnviron = 1u << 20; // 1 MB cap
4307 std::string procEnviron;
4308 procEnviron.resize(kMaxEnviron);
4309 environFile.read(procEnviron.data(), static_cast<std::streamsize>(kMaxEnviron));
4310 procEnviron.resize(static_cast<size_t>(environFile.gcount()));
4311
4312 // Look for WINEPREFIX in environment
4313 std::string prefixKey = "WINEPREFIX=";
4314 size_t pos = procEnviron.find(prefixKey);
4315 if (pos != std::string::npos)
4316 {
4317 size_t valueStart = pos + prefixKey.size();
4318 size_t valueEnd = procEnviron.find('\0', valueStart);
4319 if (valueEnd == std::string::npos)
4320 continue; // malformed environ entry, skip
4321 std::string prefixValue =
4322 procEnviron.substr(valueStart, valueEnd - valueStart);
4323
4324 // Remove trailing slashes for comparison
4325 while (!prefixValue.empty() && prefixValue.back() == '/')
4326 prefixValue.pop_back();
4327
4328 std::string gamePrefix = game_.runnerConfig.winePrefix;
4329 while (!gamePrefix.empty() && gamePrefix.back() == '/')
4330 gamePrefix.pop_back();
4331
4332 // Check if this matches our prefix
4333 // umu-launcher/Proton uses a 'pfx' subdirectory, so check for both:
4334 // - Exact match
4335 // - Process prefix is inside our game prefix (e.g., /path/to/prefix/pfx)
4336 bool prefixMatch = (prefixValue == gamePrefix) ||
4337 (prefixValue.find(gamePrefix + "/") == 0);
4338 if (prefixMatch)
4339 {
4340 candidates.push_back(pid);
4341 Logger::debug("Found Wine process using our prefix: PID {} ({})", pid,
4342 name);
4343 }
4344 }
4345 }
4346 catch (...)
4347 {
4348 // Process may have exited during scan - ignore and continue
4349 continue;
4350 }
4351 }
4352 }
4353 catch (const std::exception& e)
4354 {
4355 Logger::warn("Error scanning for Wine processes: {}", e.what());
4356 }
4357 }
4358
4359 // Also check for descendant processes of our original PID (for native games)
4360 std::set<int> visited;
4361 std::vector<int> toProcess = {pid_};
4362
4363 while (!toProcess.empty())
4364 {
4365 int current = toProcess.back();
4366 toProcess.pop_back();
4367
4368 if (visited.count(current) > 0)
4369 continue;
4370 visited.insert(current);
4371
4372 std::vector<int> children = getChildProcesses(current);
4373 for (int child : children)
4374 {
4375 toProcess.push_back(child);
4376
4377 std::string name = getProcessName(child);
4378 if (!name.empty() && !isExcludedProcess(name))
4379 {
4380 if (::kill(child, 0) == 0)
4381 {
4382 candidates.push_back(child);
4383 Logger::debug("Found candidate child process: PID {} ({})", child, name);
4384 }
4385 }
4386 }
4387 }
4388
4389 // Helper to extract exe name from cmdline
4390 auto getExeFromCmdline = [](int pid) -> std::string
4391 {
4392 std::filesystem::path cmdlinePath =
4393 std::filesystem::path("/proc") / std::to_string(pid) / "cmdline";
4394 try
4395 {
4396 if (!std::filesystem::exists(cmdlinePath))
4397 return "";
4398
4399 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
4400 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
4401 std::istreambuf_iterator<char>());
4402
4403 // Find .exe in cmdline
4404 size_t start = 0;
4405 while (start < cmdline.size())
4406 {
4407 size_t end = cmdline.find('\0', start);
4408 if (end == std::string::npos)
4409 end = cmdline.size();
4410
4411 std::string arg = cmdline.substr(start, end - start);
4412 std::string argLower = arg;
4413 for (char& c : argLower)
4414 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4415
4416 if (argLower.find(".exe") != std::string::npos)
4417 {
4418 size_t lastSlash = arg.find_last_of("/\\");
4419 if (lastSlash != std::string::npos)
4420 return arg.substr(lastSlash + 1);
4421 return arg;
4422 }
4423 start = end + 1;
4424 }
4425 }
4426 catch (...)
4427 {
4428 // Same /proc race as in getProcessName above — a pid we're
4429 // examining can exit at any point. Fall through to "" so the
4430 // caller picks the next candidate.
4431 }
4432 return "";
4433 };
4434
4435 // Separate candidates into game processes and launcher processes
4436 std::vector<int> gameCandidates;
4437 std::vector<int> launcherCandidates;
4438
4439 for (int pid : candidates)
4440 {
4441 std::string exeName = getExeFromCmdline(pid);
4442 if (exeName.empty())
4443 continue;
4444
4445 std::string exeNameLower = exeName;
4446 for (char& c : exeNameLower)
4447 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4448
4449 // Skip Wine system executables
4450 bool isSystemExe = false;
4451 for (const auto& sysExe : kWineSystemExes())
4452 {
4453 if (exeNameLower == sysExe)
4454 {
4455 isSystemExe = true;
4456 break;
4457 }
4458 }
4459 if (isSystemExe)
4460 continue;
4461
4462 // Check if this is a launcher (excluded process)
4463 bool isLauncher = false;
4464 for (const auto& excludeProc : game_.runnerConfig.excludeProcesses)
4465 {
4466 std::string excludeLower = excludeProc;
4467 for (char& c : excludeLower)
4468 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
4469
4470 if (exeNameLower.find(excludeLower) != std::string::npos)
4471 {
4472 isLauncher = true;
4473 Logger::debug("Found launcher process: PID {} ({})", pid, exeName);
4474 break;
4475 }
4476 }
4477
4478 if (isLauncher)
4479 {
4480 launcherCandidates.push_back(pid);
4481 }
4482 else
4483 {
4484 Logger::debug("Found game process candidate: PID {} ({})", pid, exeName);
4485 gameCandidates.push_back(pid);
4486 }
4487 }
4488
4489 // Prefer game processes over launcher processes
4490 if (!gameCandidates.empty())
4491 {
4492 // Return the most recently started game process
4493 std::sort(gameCandidates.begin(), gameCandidates.end(), std::greater<int>());
4494 std::string exeName = getExeFromCmdline(gameCandidates.front());
4495 Logger::info("Tracking game process: PID {} ({})", gameCandidates.front(), exeName);
4496 return gameCandidates.front();
4497 }
4498
4499 // Fall back to launcher if no game process found yet
4500 if (!launcherCandidates.empty())
4501 {
4502 std::sort(launcherCandidates.begin(), launcherCandidates.end(), std::greater<int>());
4503 std::string exeName = getExeFromCmdline(launcherCandidates.front());
4504 Logger::debug("No game process yet, tracking launcher: PID {} ({})",
4505 launcherCandidates.front(), exeName);
4506 return launcherCandidates.front();
4507 }
4508#endif
4509
4510 return -1;
4511}
4512
4513void GameProcess::killWinePrefix(bool force) const
4514{
4515#ifndef _WIN32
4516 if (game_.runnerConfig.winePrefix.empty())
4517 {
4518 return;
4519 }
4520
4521 int signal = force ? SIGKILL : SIGTERM;
4522 const char* signalName = force ? "SIGKILL" : "SIGTERM";
4523 int killedCount = 0;
4524
4525 try
4526 {
4527 for (const auto& entry : std::filesystem::directory_iterator("/proc"))
4528 {
4529 if (!entry.is_directory())
4530 continue;
4531
4532 std::string dirName = entry.path().filename().string();
4533 bool isPid = !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
4534 if (!isPid)
4535 continue;
4536
4537 int pid = std::stoi(dirName);
4538
4539 // Skip our own process
4540 if (pid == getpid())
4541 continue;
4542
4543 // Check if this process is using our WINEPREFIX
4544 std::filesystem::path environPath = entry.path() / "environ";
4545 if (!std::filesystem::exists(environPath))
4546 continue;
4547
4548 std::ifstream environFile(environPath, std::ios::binary);
4549 if (!environFile.is_open())
4550 continue;
4551
4552 constexpr size_t kMaxEnviron = 1u << 20; // 1 MB cap
4553 std::string procEnviron;
4554 procEnviron.resize(kMaxEnviron);
4555 environFile.read(procEnviron.data(), static_cast<std::streamsize>(kMaxEnviron));
4556 procEnviron.resize(static_cast<size_t>(environFile.gcount()));
4557
4558 std::string prefixKey = "WINEPREFIX=";
4559 size_t pos = procEnviron.find(prefixKey);
4560 if (pos != std::string::npos)
4561 {
4562 size_t valueStart = pos + prefixKey.size();
4563 size_t valueEnd = procEnviron.find('\0', valueStart);
4564 if (valueEnd == std::string::npos)
4565 continue; // malformed environ entry, skip
4566 std::string prefixValue = procEnviron.substr(valueStart, valueEnd - valueStart);
4567
4568 // Normalize trailing slashes for comparison (consistent with findGameProcess)
4569 while (!prefixValue.empty() && prefixValue.back() == '/')
4570 prefixValue.pop_back();
4571
4572 std::string gamePrefix = game_.runnerConfig.winePrefix;
4573 while (!gamePrefix.empty() && gamePrefix.back() == '/')
4574 gamePrefix.pop_back();
4575
4576 bool prefixMatch =
4577 (prefixValue == gamePrefix) || (prefixValue.find(gamePrefix + "/") == 0);
4578 if (prefixMatch)
4579 {
4580 std::string processName = getProcessName(pid);
4581 Logger::debug("Sending {} to Wine process: PID {} ({})", signalName, pid,
4582 processName);
4583 ::kill(pid, signal);
4584 killedCount++;
4585 }
4586 }
4587 }
4588 }
4589 catch (const std::exception& e)
4590 {
4591 Logger::warn("Error killing Wine processes: {}", e.what());
4592 }
4593
4594 if (killedCount > 0)
4595 {
4596 Logger::info("Sent {} to {} Wine processes in prefix: {}", signalName, killedCount,
4597 game_.runnerConfig.winePrefix);
4598 }
4599#else
4600 (void)force; // Unused on Windows
4601#endif
4602}
4603
4604// ==============================================================================
4605// GameProcessManager - Notification Helper
4606// ==============================================================================
4607
4608void GameProcessManager::notify(GameProcess::NotificationType type, const std::string& message)
4609{
4610 // Snapshot under the lock, invoke outside — same pattern as the
4611 // detection-thread callsites at scanForRunningWineGames /
4612 // scanForRunningGames / pollRunningSteamGames. Safe even if a UI
4613 // thread races to setOnNotification(nullptr) between snapshot and call.
4614 auto cb = getOnNotification();
4615 if (cb)
4616 {
4617 cb(type, message);
4618 }
4619}
4620
4621// ============================================================================
4622// Callback setters / getters — std::function isn't atomic, and the
4623// detection thread reads onNotification_ / onGameStatsUpdated_ while the
4624// UI thread sets them at startup (and could in principle update later).
4625// callbacksMutex_ serializes the two.
4626// ============================================================================
4627
4629 std::function<void(GameProcess::NotificationType, const std::string&)> callback)
4630{
4631 std::lock_guard<std::mutex> lock(callbacksMutex_);
4632 onNotification_ = std::move(callback);
4633}
4634
4636 std::function<void(const std::string& gameId)> callback)
4637{
4638 std::lock_guard<std::mutex> lock(callbacksMutex_);
4639 onGameStatsUpdated_ = std::move(callback);
4640}
4641
4642std::function<void(GameProcess::NotificationType, const std::string&)>
4644{
4645 std::lock_guard<std::mutex> lock(callbacksMutex_);
4646 return onNotification_;
4647}
4648
4649std::function<void(const std::string&)> GameProcessManager::getOnGameStatsUpdated() const
4650{
4651 std::lock_guard<std::mutex> lock(callbacksMutex_);
4652 return onGameStatsUpdated_;
4653}
4654
4655// ==============================================================================
4656// GameProcessManager - Constructor & Destructor
4657// ==============================================================================
4658
4659GameProcessManager::GameProcessManager() : shouldStopDetection_(false)
4660{
4661 Logger::info("GameProcessManager: Starting background detection thread...");
4662 // Start the background detection thread
4663 detectionThread_ = std::thread(&GameProcessManager::detectionThreadFunction, this);
4664}
4665
4666GameProcessManager::~GameProcessManager()
4667{
4668 Logger::info("GameProcessManager: Stopping background detection thread...");
4669 // Signal thread to stop
4670 shouldStopDetection_ = true;
4671
4672 // Wait for thread to finish
4673 if (detectionThread_.joinable())
4674 {
4675 detectionThread_.join();
4676 }
4677}
4678
4679// ==============================================================================
4680// GameProcessManager - Singleton
4681// ==============================================================================
4682
4683GameProcessManager& GameProcessManager::instance()
4684{
4685 static GameProcessManager instance;
4686 return instance;
4687}
4688
4689// ==============================================================================
4690// GameProcessManager - Process Management
4691// ==============================================================================
4692
4693bool GameProcessManager::launchGame(const std::string& gameId, Game& game)
4694{
4695 // Check if already running
4696 if (isGameRunning(gameId))
4697 {
4698 Logger::info("Game is already running: {}", gameId);
4699 return false;
4700 }
4701
4702 // For Steam games, determine the best launch method:
4703 // 1. Direct Proton launch: Full control over env vars, wrappers, PID tracking.
4704 // Used when the game has a valid executable path (not "steam") and is not
4705 // forced to use Steam-managed launch. This is the preferred method because
4706 // "steam -applaunch" sends IPC to the running Steam instance, which means
4707 // env vars and wrappers set on the command line are NOT inherited by the game.
4708 // 2. Steam-managed launch: Fallback via "steam -applaunch <appid>".
4709 // Used when direct launch info is unavailable or explicitly requested.
4710 // Custom settings MUST be synced to Steam's VDF launch options beforehand.
4711 if (game.metadata.isSteamGame)
4712 {
4713 int steamAppId = game.metadata.steamAppId;
4714
4715 // Ensure Steam is running before launching the game
4716 // Proton requires Steam's runtime to be available
4717 if (!ensureSteamRunning())
4718 {
4719 Logger::error("Cannot launch game: Steam is not running and failed to start");
4721 "Cannot launch game: Steam is not running and failed to start");
4722 return false;
4723 }
4724
4725 // Check if we can use direct Proton launch (full wrapper support).
4726 //
4727 // CRITICAL: this decision must agree with the routing inside
4728 // GameProcess::launchProtonSteamGame (which also checks the global
4729 // useSteamLaunchByDefault setting). If we say "direct" here but
4730 // launchProtonSteamGame routes via steam-applaunch instead, the
4731 // resulting GameProcess holds a dead pid_ (steam-applaunch exits
4732 // immediately) but stays in runningProcesses_ — and after stopGame
4733 // erases it the background /proc scanner re-adds the still-running
4734 // game to runningSteamGames_, so isGameRunning() never returns false
4735 // and the UI gets stuck in "Stopping...".
4736 const bool steamLaunchByDefault =
4738 bool canDirectLaunch = !game.runnerConfig.useSteamLaunch && !steamLaunchByDefault &&
4739 game.runnerConfig.executablePath != "steam" &&
4740 !game.runnerConfig.executablePath.empty() &&
4741 game.runner == GameRunner::Proton;
4742
4743 if (canDirectLaunch)
4744 {
4745 Logger::info("Using direct Proton launch for Steam game (App ID: {})", steamAppId);
4746
4747 // Use GameProcess::launch() which routes through launchProtonSteamGame()
4748 // → buildDirectProtonCommand() with full env var and wrapper support
4749 auto process = std::make_unique<GameProcess>(game);
4750 process->setOnExit([this, gameId](int code) { storeExitCode(gameId, code); });
4751 bool success = process->launch();
4752
4753 if (success)
4754 {
4755 // Activate game session services
4757
4758 // Track via process tracking only (we have direct PID).
4759 // Do NOT also add to runningSteamGames_ — that's for Steam-managed
4760 // launches where we rely on reaper/env detection. Double-tracking
4761 // causes duplicate cleanup (onGameStopped called twice, playtime
4762 // double-counted) and stale running state from lingering Wine helpers.
4763 {
4764 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4765 runningProcesses_[gameId] = std::move(process);
4766 }
4767
4768 FrameMetricsService::instance().startCollection(gameId, 0, false, true);
4770
4771 Logger::info("Direct Proton launch successful for Steam game (App ID: {})",
4772 steamAppId);
4773 return true;
4774 }
4775
4776 // Direct launch failed — fall through to steam -applaunch fallback
4777 Logger::warn("Direct Proton launch failed for Steam game (App ID: {}), "
4778 "falling back to steam -applaunch",
4779 steamAppId);
4780 }
4781
4782 // Steam-managed launch via "steam -applaunch"
4783 // NOTE: Env vars and wrappers prepended here only affect the short-lived
4784 // "steam -applaunch" IPC client, NOT the actual game process. For custom
4785 // settings to take effect, they must be synced to Steam's VDF launch options
4786 // via checkAndSyncSettings() (requires useSteamDefaults=false).
4787 Logger::info("Launching via steam -applaunch (App ID: {})", steamAppId);
4788
4789 std::string command = "steam -applaunch " + std::to_string(steamAppId);
4790
4791 // Add any game-specific arguments (but not the "-applaunch APPID" itself)
4792 if (!game.runnerConfig.arguments.empty() &&
4793 game.runnerConfig.arguments.find("-applaunch") == std::string::npos)
4794 {
4795 command += " " + game.runnerConfig.arguments;
4796 }
4797
4798 Logger::info("Command: {}", command);
4799
4800 // Store launch details in game statistics
4801 game.statistics.lastLaunchCommand = command;
4804
4805 // Execute the command in the background
4807
4808 if (!result.success)
4809 {
4810 Logger::error("Failed to execute steam command");
4812 "Failed to launch Steam game: " + game.name);
4813 return false;
4814 }
4815
4816 // Add to tracking immediately - the background thread will verify it actually started
4817 // Track by Steam App ID (stable across re-imports) -> current game ID
4818 {
4819 std::lock_guard<std::mutex> lock(steamGamesMutex_);
4820 runningSteamGames_[steamAppId] = gameId;
4821 }
4822
4823 // Record start time for playtime tracking (also by Steam App ID)
4824 {
4825 std::lock_guard<std::mutex> lock(steamStartTimesMutex_);
4826 steamGameStartTimes_[steamAppId] = time(nullptr);
4827 }
4828
4829 // Start frame metrics collection for Steam games
4830 FrameMetricsService::instance().startCollection(gameId, 0, false, true);
4831
4832 // Activate game session services (screensaver inhibition, performance profile)
4834
4835 // Increment launch counter immediately
4837
4839 "Steam game launch command executed. Background thread will detect when it starts.");
4840 return true;
4841 }
4842
4843 // For non-Steam games, use normal process tracking
4844 auto process = std::make_unique<GameProcess>(game);
4845 process->setOnExit([this, gameId](int code) { storeExitCode(gameId, code); });
4846
4847 // Launch the process
4848 bool success = process->launch();
4849
4850 if (success)
4851 {
4852 // Activate game session services (screensaver inhibition, performance profile)
4854
4855 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4856 runningProcesses_[gameId] = std::move(process);
4857 }
4858
4859 return success;
4860}
4861
4862bool GameProcessManager::stopGame(const std::string& gameId, Game* game, bool force)
4863{
4864 // Check if it's a manually-tracked Steam game
4865 // First we need to find the Steam App ID from the game object or by searching the map
4866 int steamAppId = 0;
4867 {
4868 std::lock_guard<std::mutex> lock(steamGamesMutex_);
4869 // Search through the map to find which App ID maps to this game ID
4870 for (auto it = runningSteamGames_.begin(); it != runningSteamGames_.end(); ++it)
4871 {
4872 if (it->second == gameId)
4873 {
4874 steamAppId = it->first;
4875 // Remove from tracking now (background thread will detect it stopped)
4876 runningSteamGames_.erase(it);
4877 break;
4878 }
4879 }
4880 }
4881
4882 if (steamAppId > 0)
4883 {
4884 Logger::info("Stopping Steam game: {} (App ID: {})", gameId, steamAppId);
4885
4886 // Update statistics before killing
4887 if (game != nullptr)
4888 {
4889 time_t startTime = 0;
4890 {
4891 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
4892 auto it = steamGameStartTimes_.find(steamAppId);
4893 if (it != steamGameStartTimes_.end())
4894 {
4895 startTime = it->second;
4896 steamGameStartTimes_.erase(it);
4897 }
4898 }
4899
4900 if (startTime > 0)
4901 {
4902 time_t now = time(nullptr);
4903 double sessionTime = difftime(now, startTime);
4904 game->statistics.totalPlayTimeSeconds += sessionTime;
4905 game->statistics.lastPlayed = now;
4906
4907 Logger::info("Updated playtime for {}: +{}s (total: {}s)", game->name,
4908 static_cast<int>(sessionTime),
4909 static_cast<int>(game->statistics.totalPlayTimeSeconds));
4910 }
4911 }
4912
4913 // Actually kill the Steam game process
4914 bool killed = killSteamGame(steamAppId);
4915
4916 // Release game session services (screensaver, power profile)
4918
4919 if (killed)
4920 {
4921 Logger::info("Successfully stopped Steam game: {}", gameId);
4922 }
4923 else
4924 {
4925 Logger::warn("Failed to stop Steam game (it may have already exited): {}", gameId);
4926 }
4927
4928 return killed;
4929 }
4930
4931 // Try to stop a process-tracked game
4932 {
4933 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4934 auto it = runningProcesses_.find(gameId);
4935 if (it == runningProcesses_.end())
4936 {
4937 return false;
4938 }
4939
4940 bool success = force ? it->second->kill() : it->second->stop();
4941
4942 // Release game session services (screensaver, power profile)
4944
4945 // Remove from running processes
4946 runningProcesses_.erase(it);
4947
4948 return success;
4949 }
4950}
4951
4952bool GameProcessManager::isGameRunning(const std::string& gameId) const
4953{
4954 // Check both manually-tracked Steam games and process-tracked games
4955 {
4956 std::lock_guard<std::mutex> lock(steamGamesMutex_);
4957 // Search through the map to find if this game ID is tracked
4958 for (const auto& [appId, trackedGameId] : runningSteamGames_)
4959 {
4960 if (trackedGameId == gameId)
4961 {
4962 return true;
4963 }
4964 }
4965 }
4966
4967 // Check process-tracked games (non-Steam)
4968 {
4969 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4970 return runningProcesses_.find(gameId) != runningProcesses_.end();
4971 }
4972}
4973
4974const GameProcess* GameProcessManager::getRunningProcess(const std::string& gameId) const
4975{
4976 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4977 auto it = runningProcesses_.find(gameId);
4978 if (it != runningProcesses_.end())
4979 {
4980 return it->second.get();
4981 }
4982 return nullptr;
4983}
4984
4987{
4988 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4989 auto it = runningProcesses_.find(gameId);
4990 if (it == runningProcesses_.end())
4991 return {};
4992 const GameProcess* p = it->second.get();
4993 ProcessSnapshot snap;
4994 snap.found = true;
4995 snap.primaryPid = p->getProcessId();
4996 snap.trackedPid = p->getTrackedProcessId();
4998 snap.launchInfo = p->getLastLaunchInfo();
4999 return snap;
5000}
5001
5002std::vector<std::string> GameProcessManager::getRunningGameIds() const
5003{
5004 std::vector<std::string> ids;
5005
5006 // Add manually-tracked Steam games
5007 {
5008 std::lock_guard<std::mutex> lock(steamGamesMutex_);
5009 for (const auto& [appId, gameId] : runningSteamGames_)
5010 {
5011 ids.push_back(gameId);
5012 }
5013 }
5014
5015 // Add process-tracked games (non-Steam)
5016 {
5017 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5018 for (const auto& [id, process] : runningProcesses_)
5019 {
5020 ids.push_back(id);
5021 }
5022 }
5023
5024 return ids;
5025}
5026
5027std::chrono::seconds GameProcessManager::getGameSessionDuration(const std::string& gameId) const
5028{
5029 // First, try non-Steam game (has a GameProcess with running time)
5030 {
5031 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5032 auto it = runningProcesses_.find(gameId);
5033 if (it != runningProcesses_.end() && it->second)
5034 {
5035 double runningSeconds = it->second->getRunningTimeSeconds();
5036 if (runningSeconds > 0)
5037 {
5038 return std::chrono::seconds(static_cast<long long>(runningSeconds));
5039 }
5040 }
5041 }
5042
5043 // Second, try Steam game - get actual start time from the reaper process
5044 // Copy the steamAppId under lock, then release before doing I/O or acquiring other locks
5045 int matchedSteamAppId = 0;
5046 {
5047 std::lock_guard<std::mutex> steamLock(steamGamesMutex_);
5048 for (const auto& [steamAppId, id] : runningSteamGames_)
5049 {
5050 if (id == gameId)
5051 {
5052 matchedSteamAppId = steamAppId;
5053 break;
5054 }
5055 }
5056 }
5057
5058 if (matchedSteamAppId > 0)
5059 {
5060#ifdef PLATFORM_LINUX
5061 // Try to get the actual start time from the reaper process via /proc
5062 std::string findCmd =
5063 "pgrep -o -f '^/.*reaper SteamLaunch AppId=" + std::to_string(matchedSteamAppId) +
5064 "' 2>/dev/null";
5065 PipeHandle pipe(findCmd, "r");
5066 if (pipe)
5067 {
5068 char buffer[64];
5069 if (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
5070 {
5071 std::string pidStr(buffer);
5072 pidStr.erase(pidStr.find_last_not_of("\n\r") + 1);
5073 if (!pidStr.empty())
5074 {
5075 int reaperPid = std::stoi(pidStr);
5076 if (reaperPid > 0)
5077 {
5078 time_t procStartTime = getProcessStartTimeFromProc(reaperPid);
5079 if (procStartTime > 0)
5080 {
5081 time_t now = time(nullptr);
5082 double sessionTime = difftime(now, procStartTime);
5083 if (sessionTime > 0)
5084 {
5085 return std::chrono::seconds(static_cast<long long>(sessionTime));
5086 }
5087 }
5088 }
5089 }
5090 }
5091 }
5092#endif
5093 // Fallback to our recorded start time (no nested locks now)
5094 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5095 auto timeIt = steamGameStartTimes_.find(matchedSteamAppId);
5096 if (timeIt != steamGameStartTimes_.end() && timeIt->second > 0)
5097 {
5098 time_t now = time(nullptr);
5099 double sessionTime = difftime(now, timeIt->second);
5100 return std::chrono::seconds(static_cast<long long>(sessionTime));
5101 }
5102 }
5103
5104 return std::chrono::seconds(0);
5105}
5106
5107void GameProcessManager::storeExitCode(const std::string& gameId, int code)
5108{
5109 std::lock_guard<std::mutex> lock(exitCodesMutex_);
5110 lastExitCodes_[gameId] = code;
5111}
5112
5113int GameProcessManager::getLastExitCode(const std::string& gameId, int defaultCode) const
5114{
5115 std::lock_guard<std::mutex> lock(exitCodesMutex_);
5116 auto it = lastExitCodes_.find(gameId);
5117 return (it != lastExitCodes_.end()) ? it->second : defaultCode;
5118}
5119
5120// ==============================================================================
5121// GameProcessManager - Background Detection Thread
5122// ==============================================================================
5123
5124void GameProcessManager::detectionThreadFunction()
5125{
5126 Logger::info("Background detection thread started");
5127
5128 while (!shouldStopDetection_)
5129 {
5130 // Get all running Steam reaper processes from the system (Proton games)
5131 std::string findCmd = "pgrep -a -f '/reaper SteamLaunch AppId=' 2>/dev/null";
5132 PipeHandle pipe(findCmd, "r");
5133
5134 // Map of App ID -> true (discovered running games)
5135 std::map<int, bool> discoveredAppIds;
5136
5137 if (pipe)
5138 {
5139 char buffer[1024];
5140
5141 while (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
5142 {
5143 std::string line(buffer);
5144
5145 // Skip lines that don't contain the actual reaper process
5146 // (this filters out shell commands that match the search pattern)
5147 if (line.find("reaper SteamLaunch") == std::string::npos)
5148 {
5149 continue;
5150 }
5151
5152 // Extract App ID from line. strtol over sscanf so
5153 // overflow / unparseable input is detected
5154 // (cert-err34-c).
5155 size_t appIdPos = line.find("AppId=");
5156 if (appIdPos != std::string::npos)
5157 {
5158 constexpr size_t kAppIdPrefix = 6; // strlen("AppId=")
5159 const char* numStart = line.c_str() + appIdPos + kAppIdPrefix;
5160 char* end = nullptr;
5161 errno = 0;
5162 const long parsed = std::strtol(numStart, &end, 10);
5163 if (end != numStart && errno == 0 && parsed > 0 &&
5164 parsed <= std::numeric_limits<int>::max())
5165 {
5166 discoveredAppIds[static_cast<int>(parsed)] = true;
5167 }
5168 }
5169 }
5170 // PipeHandle automatically closes on scope exit
5171 }
5172
5173 // Also detect native Steam games by checking for SteamAppId in
5174 // process environments. Native Linux games on Steam don't use the
5175 // reaper, so the above pgrep won't find them.
5176 // IMPORTANT: Filter out Wine/Proton helper processes (wineserver,
5177 // winedevice.exe, services.exe, etc.) that inherit SteamAppId but
5178 // persist after the game exits, causing stale "running" state.
5179 {
5180 std::string envCmd = "grep -rl 'SteamAppId=' /proc/*/environ 2>/dev/null"
5181 " | head -50";
5182 PipeHandle envPipe(envCmd, "r");
5183 if (envPipe)
5184 {
5185 char buffer[512];
5186 while (fgets(buffer, sizeof(buffer), envPipe.get()) != nullptr)
5187 {
5188 std::string procPath(buffer);
5189 // Trim newline
5190 if (!procPath.empty() && procPath.back() == '\n')
5191 procPath.pop_back();
5192
5193 // Extract PID from /proc/PID/environ path
5194 std::string pidStr;
5195 size_t procPos = procPath.find("/proc/");
5196 size_t envPos = procPath.find("/environ");
5197 if (procPos != std::string::npos && envPos != std::string::npos)
5198 {
5199 pidStr = procPath.substr(procPos + 6, envPos - procPos - 6);
5200 }
5201
5202 // Check process command to filter out Wine/Proton helpers
5203 if (!pidStr.empty())
5204 {
5205 std::string cmdlinePath = "/proc/" + pidStr + "/cmdline";
5206 std::ifstream cmdFile(cmdlinePath, std::ios::binary);
5207 if (cmdFile)
5208 {
5209 std::string cmdline((std::istreambuf_iterator<char>(cmdFile)),
5210 std::istreambuf_iterator<char>());
5211
5212 // Skip Wine/Proton infrastructure processes that persist
5213 // after the game exits
5214 bool isHelper = false;
5215 static const char* helperNames[] = {
5216 "wineserver", "winedevice",
5217 "services.exe", "plugplay.exe",
5218 "svchost.exe", "rpcss.exe",
5219 "explorer.exe", "wineboot",
5220 "start.exe", "conhost.exe",
5221 "tabtip.exe", "wine64-preloader",
5222 "pressure-vessel", "steam-runtime-launcher"};
5223 for (const auto& helper : helperNames)
5224 {
5225 if (cmdline.find(helper) != std::string::npos)
5226 {
5227 isHelper = true;
5228 break;
5229 }
5230 }
5231
5232 if (isHelper)
5233 continue;
5234 }
5235 }
5236
5237 // Read the environ file to extract SteamAppId value
5238 std::ifstream envFile(procPath, std::ios::binary);
5239 if (envFile)
5240 {
5241 constexpr size_t kMaxEnviron = 1u << 20; // 1 MB cap
5242 std::string envData;
5243 envData.resize(kMaxEnviron);
5244 envFile.read(envData.data(), kMaxEnviron);
5245 envData.resize(static_cast<size_t>(envFile.gcount()));
5246 size_t pos = envData.find("SteamAppId=");
5247 if (pos != std::string::npos)
5248 {
5249 // strtol over sscanf so overflow / unparseable
5250 // input is detected (cert-err34-c).
5251 constexpr size_t kSteamAppIdPrefix = 11; // strlen("SteamAppId=")
5252 const char* numStart = envData.c_str() + pos + kSteamAppIdPrefix;
5253 char* end = nullptr;
5254 errno = 0;
5255 const long parsed = std::strtol(numStart, &end, 10);
5256 if (end != numStart && errno == 0 && parsed > 0 &&
5257 parsed <= std::numeric_limits<int>::max())
5258 {
5259 discoveredAppIds[static_cast<int>(parsed)] = true;
5260 }
5261 }
5262 }
5263 }
5264 }
5265 }
5266
5267 // Now update our tracking based on what we discovered
5268 {
5269 {
5270 std::lock_guard<std::mutex> lock(steamGamesMutex_);
5271
5272 // First, check which tracked games are still running
5273 std::vector<int> appIdsToRemove;
5274 for (const auto& [steamAppId, gameId] : runningSteamGames_)
5275 {
5276 if (discoveredAppIds.find(steamAppId) == discoveredAppIds.end())
5277 {
5278 // Game process not found - but give it a grace period
5279 // Steam games take time to start (steam:// launches Steam which then
5280 // launches the game)
5281 time_t gameStartTime = 0;
5282 {
5283 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5284 auto it = steamGameStartTimes_.find(steamAppId);
5285 if (it != steamGameStartTimes_.end())
5286 {
5287 gameStartTime = it->second;
5288 }
5289 }
5290
5291 // If the game was just launched (within last 15 seconds), give it time to
5292 // start
5293 time_t now = time(nullptr);
5294 double timeSinceLaunch = difftime(now, gameStartTime);
5295 if (timeSinceLaunch < 15.0)
5296 {
5297 // Still in grace period, don't remove yet
5298 Logger::debug("[Detection] Game not detected yet, but in grace period: "
5299 "{} (App ID: {}, launched {}s ago)",
5300 gameId, steamAppId, static_cast<int>(timeSinceLaunch));
5301 continue;
5302 }
5303
5304 // Grace period expired or no start time - game has stopped
5305 Logger::info("[Detection] Game stopped: {} (App ID: {})", gameId,
5306 steamAppId);
5307 appIdsToRemove.push_back(steamAppId);
5308 }
5309 }
5310
5311 // Remove stopped games and update their statistics
5312 for (const auto& steamAppId : appIdsToRemove)
5313 {
5314 // Get the game ID before removing it
5315 std::string gameId = runningSteamGames_[steamAppId];
5316
5317 // Stop frame metrics collection for this game
5319
5320 // Release game session services (screensaver, power profile)
5322
5323 // Update playtime statistics before removing
5324 time_t startTime = 0;
5325 {
5326 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5327 auto it = steamGameStartTimes_.find(steamAppId);
5328 if (it != steamGameStartTimes_.end())
5329 {
5330 startTime = it->second;
5331 steamGameStartTimes_.erase(it);
5332 }
5333 }
5334
5335 if (startTime > 0)
5336 {
5337 // Detect exit reason based on session duration
5338 std::string exitReason = detectSteamGameExitReason(steamAppId, startTime);
5339
5340 // Use callback to safely access game and update its statistics
5341 if (getGameCallback_)
5342 {
5343 time_t now = time(nullptr);
5344 double sessionTime = difftime(now, startTime);
5345
5346 // Compute baseline before entering the library lock
5347 double baseline = -1.0;
5348 auto baseIt = steamGameBasePlaytime_.find(steamAppId);
5349 if (baseIt != steamGameBasePlaytime_.end())
5350 {
5351 baseline = baseIt->second;
5352 steamGameBasePlaytime_.erase(baseIt);
5353 }
5354
5355 bool statsUpdated = false;
5356 getGameCallback_(
5357 gameId,
5358 [&](Game& game)
5359 {
5360 if (baseline >= 0.0)
5362 baseline + sessionTime;
5363 else
5364 // Fallback: no baseline recorded (shouldn't happen)
5365 game.statistics.totalPlayTimeSeconds += sessionTime;
5366
5367 game.statistics.lastPlayed = now;
5368 game.statistics.lastExitTime = now;
5369 game.statistics.lastExitReason = exitReason;
5370
5371 if (exitReason == "crash")
5372 {
5373 game.statistics.crashCount++;
5374 Logger::warn("[Detection] Game crashed! Total crashes: {}",
5375 game.statistics.crashCount);
5376 }
5377
5379 "[Detection] Updated playtime for {}: +{}s (total: {}s) "
5380 "[Exit: {}]",
5381 game.name, static_cast<int>(sessionTime),
5382 static_cast<int>(game.statistics.totalPlayTimeSeconds),
5383 exitReason);
5384 statsUpdated = true;
5385 });
5386
5387 // Notify persistence after the library lock is released
5388 if (statsUpdated)
5389 {
5390 // Snapshot under the mutex; invoke outside so the
5391 // callback can re-enter the manager safely.
5392 if (auto cb = getOnGameStatsUpdated())
5393 cb(gameId);
5394 }
5395 }
5396 }
5397
5398 runningSteamGames_.erase(steamAppId);
5399 }
5400
5401 // Second, check for newly discovered games that we should track
5402 // Build a local map of discovered games from our App ID mapping
5403 std::map<int, std::string> discoveredGames; // App ID -> Game ID
5404 {
5405 std::lock_guard<std::mutex> mapLock(appIdMapMutex_);
5406 for (const auto& [steamAppId, gameId] : steamAppIdToGameId_)
5407 {
5408 // If this app is running, save the mapping
5409 if (discoveredAppIds.find(steamAppId) != discoveredAppIds.end())
5410 {
5411 discoveredGames[steamAppId] = gameId;
5412 }
5413 }
5414 }
5415
5416 // Now add or update newly discovered games in tracking
5417 for (const auto& [steamAppId, gameId] : discoveredGames)
5418 {
5419 auto existingEntry = runningSteamGames_.find(steamAppId);
5420 if (existingEntry == runningSteamGames_.end())
5421 {
5422 // Skip if this game is already tracked via direct process
5423 // tracking (runningProcesses_). Direct Proton launches set
5424 // SteamAppId in the environment, which we'd detect here,
5425 // but they're already properly tracked with PID-based
5426 // monitoring. Adding to runningSteamGames_ too would cause
5427 // double-tracking and stale running state from Wine helpers.
5428 {
5429 std::lock_guard<std::mutex> procLock(runningProcessesMutex_);
5430 if (runningProcesses_.find(gameId) != runningProcesses_.end())
5431 {
5432 Logger::debug("[Detection] Skipping App ID {} — already tracked "
5433 "via direct process for game {}",
5434 steamAppId, gameId);
5435 continue;
5436 }
5437 }
5438
5439 // New game started
5440 Logger::info("[Detection] Game started: App ID {} -> Game ID {}",
5441 steamAppId, gameId);
5442 runningSteamGames_[steamAppId] = gameId;
5443
5444 // Record start time for playtime tracking (also by Steam App ID)
5445 {
5446 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5447 steamGameStartTimes_[steamAppId] = time(nullptr);
5448 }
5449
5450 // Capture pre-session baseline playtime for crash-safe heartbeats.
5451 // This lets heartbeats and exit handler compute:
5452 // totalPlayTimeSeconds = baseline + sessionTime
5453 // without double-counting.
5454 if (getGameCallback_)
5455 {
5456 int appIdCopy = steamAppId;
5457 getGameCallback_(gameId,
5458 [&, appIdCopy](Game& game)
5459 {
5460 steamGameBasePlaytime_[appIdCopy] =
5462 });
5463 }
5464
5465 // Start frame metrics collection for Steam games
5466 // Steam games use MangoHud via Steam's launch options or global config
5467 // We pass pid=0 since we don't have the actual PID for Steam games
5468 FrameMetricsService::instance().startCollection(gameId, 0, false, true);
5469
5470 // Activate game session services (screensaver inhibition, performance
5471 // profile)
5473 }
5474 else if (existingEntry->second != gameId)
5475 {
5476 // Game is still running but the game ID changed (e.g., after re-import)
5477 Logger::info("[Detection] Updating game ID for App ID {} from {} to {}",
5478 steamAppId, existingEntry->second, gameId);
5479 existingEntry->second = gameId;
5480 }
5481 }
5482 }
5483 }
5484
5485 // =====================================================================
5486 // Heartbeat: periodically persist playtime for running Steam games.
5487 // Every 60 seconds, update totalPlayTimeSeconds = baseline + session
5488 // and persist via onGameStatsUpdated_. If the launcher crashes, at most
5489 // 60 seconds of playtime is lost instead of the entire session.
5490 // =====================================================================
5491 {
5492 time_t heartbeatNow = time(nullptr);
5493 if (difftime(heartbeatNow, lastSteamHeartbeat_) >= 60.0)
5494 {
5495 lastSteamHeartbeat_ = heartbeatNow;
5496
5497 std::lock_guard<std::mutex> steamLock(steamGamesMutex_);
5498 for (const auto& [steamAppId, gameId] : runningSteamGames_)
5499 {
5500 time_t startTime = 0;
5501 {
5502 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5503 auto it = steamGameStartTimes_.find(steamAppId);
5504 if (it != steamGameStartTimes_.end())
5505 {
5506 startTime = it->second;
5507 }
5508 }
5509
5510 if (startTime <= 0 || !getGameCallback_)
5511 continue;
5512
5513 auto baseIt = steamGameBasePlaytime_.find(steamAppId);
5514 if (baseIt == steamGameBasePlaytime_.end())
5515 continue;
5516
5517 double sessionTime = difftime(heartbeatNow, startTime);
5518 double newTotal = baseIt->second + sessionTime;
5519 time_t hbNow = heartbeatNow;
5520
5521 bool statsUpdated = false;
5522 getGameCallback_(
5523 gameId,
5524 [&](Game& game)
5525 {
5526 game.statistics.totalPlayTimeSeconds = newTotal;
5527 game.statistics.lastPlayed = hbNow;
5528 Logger::debug("[Heartbeat] Persisted Steam playtime for {} "
5529 "(session: {}s, total: {}s)",
5530 game.name, static_cast<int>(sessionTime),
5531 static_cast<int>(game.statistics.totalPlayTimeSeconds));
5532 statsUpdated = true;
5533 });
5534
5535 if (statsUpdated)
5536 {
5537 // Snapshot under the mutex; invoke outside so the
5538 // callback can re-enter the manager safely.
5539 if (auto cb = getOnGameStatsUpdated())
5540 cb(gameId);
5541 }
5542 }
5543 }
5544 }
5545
5546 // Sleep before next scan, checking stop flag each second for responsiveness
5547 for (int s = 0; s < SteamConstants::GAME_DETECTION_INTERVAL_SEC && !shouldStopDetection_;
5548 ++s)
5549 {
5550 std::this_thread::sleep_for(std::chrono::seconds(1));
5551 }
5552 }
5553
5554 Logger::info("Background detection thread stopped");
5555}
5556
5557// ==============================================================================
5558// GameProcessManager - Scan for Running Wine/Proton Games
5559// ==============================================================================
5560
5561void GameProcessManager::scanForRunningWineGames(const std::vector<Game*>& games)
5562{
5563#ifndef _WIN32
5564 Logger::info("[Detection] Scanning for already-running Wine/Proton games...");
5565
5566 int foundCount = 0;
5567
5568 for (const auto* game : games)
5569 {
5570 if (!game)
5571 continue;
5572
5573 // Skip Steam games (handled by background thread)
5574 if (game->metadata.isSteamGame)
5575 continue;
5576
5577 // Skip games without Wine prefix
5578 if (game->runnerConfig.winePrefix.empty())
5579 continue;
5580
5581 // Skip if already tracked
5582 {
5583 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5584 if (runningProcesses_.find(game->id) != runningProcesses_.end())
5585 continue;
5586 }
5587
5588 // Scan /proc for processes using this Wine prefix
5589 bool foundRunning = false;
5590 int foundPid = -1;
5591 std::string foundExeName;
5592
5593 try
5594 {
5595 for (const auto& entry : std::filesystem::directory_iterator("/proc"))
5596 {
5597 if (!entry.is_directory())
5598 continue;
5599
5600 std::string dirName = entry.path().filename().string();
5601 bool isPid =
5602 !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
5603 if (!isPid)
5604 continue;
5605
5606 int pid = std::stoi(dirName);
5607
5608 // Read environment to check WINEPREFIX
5609 std::filesystem::path environPath = entry.path() / "environ";
5610 if (!std::filesystem::exists(environPath))
5611 continue;
5612
5613 std::ifstream environFile(environPath, std::ios::binary);
5614 if (!environFile.is_open())
5615 continue;
5616
5617 constexpr size_t kMaxEnviron = 1u << 20; // 1 MB cap
5618 std::string procEnviron;
5619 procEnviron.resize(kMaxEnviron);
5620 environFile.read(procEnviron.data(), static_cast<std::streamsize>(kMaxEnviron));
5621 procEnviron.resize(static_cast<size_t>(environFile.gcount()));
5622
5623 // Look for WINEPREFIX= in environment
5624 std::string prefixKey = "WINEPREFIX=";
5625 size_t pos = procEnviron.find(prefixKey);
5626 if (pos == std::string::npos)
5627 continue;
5628
5629 size_t valueStart = pos + prefixKey.size();
5630 size_t valueEnd = procEnviron.find('\0', valueStart);
5631 if (valueEnd == std::string::npos)
5632 continue; // malformed environ entry, skip
5633 std::string prefixValue = procEnviron.substr(valueStart, valueEnd - valueStart);
5634
5635 // Remove trailing slashes for comparison
5636 while (!prefixValue.empty() && prefixValue.back() == '/')
5637 prefixValue.pop_back();
5638
5639 std::string gamePrefix = game->runnerConfig.winePrefix;
5640 while (!gamePrefix.empty() && gamePrefix.back() == '/')
5641 gamePrefix.pop_back();
5642
5643 // Check if this matches our game's prefix
5644 // umu-launcher/Proton uses a 'pfx' subdirectory, so check for both:
5645 // - Exact match
5646 // - Process prefix is inside our game prefix (e.g., /path/to/prefix/pfx)
5647 // - Process prefix is parent of our game prefix
5648 bool prefixMatch = (prefixValue == gamePrefix) ||
5649 (prefixValue.find(gamePrefix + "/") == 0) ||
5650 (gamePrefix.find(prefixValue + "/") == 0);
5651 if (!prefixMatch)
5652 continue;
5653
5654 // Found a process in our prefix - extract exe name from cmdline
5655 std::filesystem::path cmdlinePath = entry.path() / "cmdline";
5656 if (std::filesystem::exists(cmdlinePath))
5657 {
5658 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
5659 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
5660 std::istreambuf_iterator<char>());
5661
5662 // Look for .exe in cmdline
5663 size_t start = 0;
5664 while (start < cmdline.size())
5665 {
5666 size_t end = cmdline.find('\0', start);
5667 if (end == std::string::npos)
5668 end = cmdline.size();
5669
5670 std::string arg = cmdline.substr(start, end - start);
5671 std::string argLower = arg;
5672 for (char& c : argLower)
5673 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
5674
5675 if (argLower.find(".exe") != std::string::npos)
5676 {
5677 // Extract filename
5678 size_t lastSlash = arg.find_last_of("/\\");
5679 std::string exeName =
5680 (lastSlash != std::string::npos) ? arg.substr(lastSlash + 1) : arg;
5681
5682 // Skip Wine system processes
5683 std::string exeLower = exeName;
5684 for (char& c : exeLower)
5685 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
5686
5687 bool isSystem = false;
5688 for (const auto& sysExe : kWineSystemExes())
5689 {
5690 if (exeLower == sysExe)
5691 {
5692 isSystem = true;
5693 break;
5694 }
5695 }
5696
5697 if (!isSystem)
5698 {
5699 foundRunning = true;
5700 foundPid = pid;
5701 foundExeName = exeName;
5702 break;
5703 }
5704 }
5705 start = end + 1;
5706 }
5707 }
5708
5709 if (foundRunning)
5710 break;
5711 }
5712 }
5713 catch (const std::exception& e)
5714 {
5715 Logger::debug("[Detection] Error scanning for Wine games: {}", e.what());
5716 }
5717
5718 if (foundRunning)
5719 {
5720 Logger::info("[Detection] Found running Wine game: {} (PID: {}, exe: {})", game->name,
5721 foundPid, foundExeName);
5722
5723 // Create a GameProcess and attach to the running process
5724 Game gameCopy = *game;
5725 auto process = std::make_unique<GameProcess>(gameCopy);
5726 process->attachToRunningProcess(foundPid, foundExeName);
5727
5728 {
5729 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5730 runningProcesses_[game->id] = std::move(process);
5731 }
5732
5733 foundCount++;
5734 }
5735 }
5736
5737 if (foundCount > 0)
5738 {
5739 Logger::info("[Detection] Found {} already-running Wine/Proton games", foundCount);
5740 }
5741#endif
5742}
5743
5744// ==============================================================================
5745// GameProcessManager - Scan for Running Games
5746// ==============================================================================
5747
5748void GameProcessManager::scanForRunningGames(const std::vector<Game*>& games,
5749 GameAccessCallback getGameCallback)
5750{
5751 Logger::info("Initializing game library cache for background thread...");
5752
5753 // Store the callback under runningProcessesMutex_ — same lock used in the heartbeat reader
5754 {
5755 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5756 getGameCallback_ = std::move(getGameCallback);
5757 }
5758
5759 // Update the Steam App ID → Game ID mapping for the background thread
5760 {
5761 std::lock_guard<std::mutex> lock(appIdMapMutex_);
5762 steamAppIdToGameId_.clear();
5763
5764 for (const auto* game : games)
5765 {
5766 if (game && game->metadata.isSteamGame && game->metadata.steamAppId > 0)
5767 {
5768 steamAppIdToGameId_[game->metadata.steamAppId] = game->id;
5769 }
5770 }
5771
5772 Logger::info("[Detection] Registered {} Steam games for detection (total {} games)",
5773 steamAppIdToGameId_.size(), games.size());
5774 }
5775
5776 // Update the runningSteamGames_ map to use current game IDs
5777 // This is important when games are deleted and re-imported with new IDs
5778 {
5779 std::lock_guard<std::mutex> lock(steamGamesMutex_);
5780 std::lock_guard<std::mutex> mapLock(appIdMapMutex_);
5781
5782 // Update all tracked games to use the current game IDs from our mapping
5783 std::vector<std::pair<int, std::string>> updates;
5784 for (const auto& [steamAppId, gameId] : runningSteamGames_)
5785 {
5786 auto it = steamAppIdToGameId_.find(steamAppId);
5787 if (it != steamAppIdToGameId_.end())
5788 {
5789 // Update to the current game ID
5790 if (it->second != gameId)
5791 {
5792 Logger::info("Updating tracked game ID for App ID {} from {} to {}", steamAppId,
5793 gameId, it->second);
5794 updates.push_back({steamAppId, it->second});
5795 }
5796 }
5797 // Note: If the game no longer exists in the library, we keep the old ID
5798 // and let the background thread clean it up when it detects the game stopped
5799 }
5800
5801 // Apply the updates
5802 for (const auto& [steamAppId, newGameId] : updates)
5803 {
5804 runningSteamGames_[steamAppId] = newGameId;
5805 }
5806 }
5807
5808 Logger::info("Game library cache updated with {} games.", games.size());
5809 Logger::info("Background detection thread will continuously monitor for running games.");
5810
5811 // Scan for already-running Wine/Proton games
5812 // This detects games that were launched externally (e.g., via Lutris) or before app start
5813 scanForRunningWineGames(games);
5814}
5815
5816// ==============================================================================
5817// GameProcessManager - Update
5818// ==============================================================================
5819
5821{
5822 // Note: Steam game detection is handled by the background detection thread
5823 // We only need to update non-Steam processes here
5824
5825 // Update all running processes (non-Steam games)
5826 std::vector<std::string> toRemove;
5827 std::vector<std::pair<std::string, GameStatistics>> stoppedGameStats;
5828
5829 {
5830 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5831 for (auto& [id, process] : runningProcesses_)
5832 {
5833 bool wasRunning = process->isRunning();
5834 process->update();
5835
5836 // If process has stopped, mark for removal and capture stats
5837 if (wasRunning && !process->isRunning())
5838 {
5839 // Capture stats from the process's game copy before removal
5840 stoppedGameStats.push_back({id, process->getGame().statistics});
5841 toRemove.push_back(id);
5842 }
5843 }
5844
5845 // Remove stopped processes
5846 for (const auto& id : toRemove)
5847 {
5848 runningProcesses_.erase(id);
5849 }
5850 }
5851
5852 // Release game session services for each stopped game
5853 for (size_t i = 0; i < toRemove.size(); i++)
5854 {
5856 }
5857
5858 // Update the master game objects and persist stats (outside the lock)
5859 for (const auto& entry : stoppedGameStats)
5860 {
5861 const std::string& gameId = entry.first;
5862 const GameStatistics& stats = entry.second;
5863 if (getGameCallback_)
5864 {
5865 bool statsUpdated = false;
5866 getGameCallback_(
5867 gameId,
5868 [&](Game& game)
5869 {
5870 // Copy the updated statistics to the library's game object
5871 game.statistics = stats;
5872 Logger::info("Updated playtime for {}: total {}s, last played {}", game.name,
5873 static_cast<int>(game.statistics.totalPlayTimeSeconds),
5874 game.statistics.lastPlayed);
5875 statsUpdated = true;
5876 });
5877
5878 // Notify persistence after the library lock is released
5879 if (statsUpdated)
5880 {
5881 // Snapshot under the mutex; invoke outside so the
5882 // callback can re-enter the manager safely.
5883 if (auto cb = getOnGameStatsUpdated())
5884 cb(gameId);
5885 }
5886 }
5887 }
5888
5889 // =========================================================================
5890 // Heartbeat: periodically persist playtime for running non-Steam games
5891 // This ensures playtime is not lost if the launcher crashes mid-session.
5892 // =========================================================================
5893 time_t now = time(nullptr);
5894 if (difftime(now, lastHeartbeat_) >= 60.0)
5895 {
5896 lastHeartbeat_ = now;
5897
5898 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5899 for (const auto& procEntry : runningProcesses_)
5900 {
5901 const std::string& id = procEntry.first;
5902 const auto& process = procEntry.second;
5903
5904 if (!process->isRunning())
5905 continue;
5906
5907 double sessionTime = process->getRunningTimeSeconds();
5908 if (sessionTime <= 0.0 || !getGameCallback_)
5909 continue;
5910
5911 // Compute total playtime as baseline + current session.
5912 // The process's game_ copy has the baseline totalPlayTimeSeconds
5913 // from before this session started (it gets += sessionTime only on exit).
5914 double baseline = process->getGame().statistics.totalPlayTimeSeconds;
5915 double newTotal = baseline + sessionTime;
5916 time_t hbNow = now;
5917
5918 bool statsUpdated = false;
5919 getGameCallback_(
5920 id,
5921 [&](Game& game)
5922 {
5923 game.statistics.totalPlayTimeSeconds = newTotal;
5924 game.statistics.lastPlayed = hbNow;
5925 Logger::debug("Heartbeat: persisted playtime for {} (session: {}s, total: {}s)",
5926 game.name, static_cast<int>(sessionTime),
5927 static_cast<int>(game.statistics.totalPlayTimeSeconds));
5928 statsUpdated = true;
5929 });
5930
5931 if (statsUpdated)
5932 {
5933 // Snapshot under the mutex; invoke outside so the
5934 // callback can re-enter the manager safely.
5935 if (auto cb = getOnGameStatsUpdated())
5936 cb(id);
5937 }
5938 }
5939 }
5940}
5941
5942// ==============================================================================
5943// GameProcessManager - Steam Game Polling
5944// ==============================================================================
5945
5946bool GameProcessManager::isSteamRunning() const
5947{
5948 return ProcessExecutor::isProcessRunning("steam");
5949}
5950
5951bool GameProcessManager::ensureSteamRunning()
5952{
5953 if (isSteamRunning())
5954 {
5955 Logger::info("Steam is already running");
5956 return true;
5957 }
5958
5959 Logger::info("Steam is not running, starting it...");
5960
5961#ifdef _WIN32
5962 ProcessResult result = ProcessExecutor::execute("start steam://open/main");
5963#else
5964 ProcessResult result = ProcessExecutor::executeBackground(getSteamCommand() + " -silent");
5965#endif
5966
5967 if (!result.success)
5968 {
5969 Logger::error("Failed to start Steam");
5970 return false;
5971 }
5972
5973 // Wait a bit for Steam to start
5974 Logger::info("Waiting for Steam to start...");
5975 for (int i = 0; i < 10; i++)
5976 {
5977 std::this_thread::sleep_for(std::chrono::seconds(1));
5978 if (isSteamRunning())
5979 {
5980 Logger::info("Steam started successfully");
5981 return true;
5982 }
5983 }
5984
5985 Logger::warn("Steam did not start within 10 seconds");
5986 return false;
5987}
5988
5989std::string GameProcessManager::detectSteamGameExitReason(int steamAppId, time_t startTime) const
5990{
5991 // For Steam games, we can't directly get exit codes
5992 // But we can use heuristics to detect likely causes
5993
5994 time_t now = time(nullptr);
5995 double sessionDuration = difftime(now, startTime);
5996
5997 // If game ran for less than 10 seconds, likely a crash or launch failure
5998 if (sessionDuration < 10.0)
5999 {
6000 Logger::warn("[Exit Detection] Game {} ran for only {} seconds - likely crash", steamAppId,
6001 static_cast<int>(sessionDuration));
6002 return "crash";
6003 }
6004
6005 // If game ran for less than 30 seconds, might be a timeout or quick crash
6006 if (sessionDuration < 30.0)
6007 {
6008 Logger::warn("[Exit Detection] Game {} ran for {} seconds - possible crash or timeout",
6009 steamAppId, static_cast<int>(sessionDuration));
6010 return "timeout";
6011 }
6012
6013 // Otherwise, assume normal exit
6014 Logger::debug("[Exit Detection] Game {} ran for {} seconds - normal exit", steamAppId,
6015 static_cast<int>(sessionDuration));
6016 return "normal";
6017}
6018
6019bool GameProcessManager::isSteamGameRunningOnSystem(int steamAppId) const
6020{
6021 if (steamAppId <= 0)
6022 {
6023 return false;
6024 }
6025
6026#ifdef _WIN32
6027 // Windows: Check for reaper process with this App ID
6028 std::string checkCmd =
6029 "tasklist /FI \"IMAGENAME eq steam.exe\" /FO CSV /NH 2>NUL | findstr /C:\"" +
6030 std::to_string(steamAppId) + "\"";
6031 ProcessResult result = ProcessExecutor::execute(checkCmd, true);
6032 return result.success;
6033#else
6034 // Linux: First look for the Steam reaper for this App ID — that's the
6035 // common case and the cheapest check (one pgrep). If no reaper exists
6036 // we ALSO scan /proc/*/environ for SteamAppId=<id>, because some games
6037 // (MTGA, Battle.net wrappers, etc.) escape the reaper's process tree
6038 // via launcher → game double-spawn — without the env-scan fallback,
6039 // killSteamGame would report "killed" while the game keeps running and
6040 // the detection thread would re-add it to runningSteamGames_, leaving
6041 // the launcher stuck in "Stopping...".
6042
6043 {
6044 std::string findCmd = "pgrep -a -f '/reaper SteamLaunch AppId=' 2>/dev/null";
6045 PipeHandle pipe(findCmd, "r");
6046 if (pipe)
6047 {
6048 char buffer[1024];
6049 const std::string searchPattern =
6050 "reaper SteamLaunch AppId=" + std::to_string(steamAppId) + " ";
6051 while (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
6052 {
6053 if (std::string(buffer).find(searchPattern) != std::string::npos)
6054 {
6055 return true;
6056 }
6057 }
6058 }
6059 }
6060
6061 // Fallback: env-scan via the same helper killSteamGame uses, so the
6062 // "running" set and "killable" set are guaranteed to match.
6063 return !findGamePidsByAppId(steamAppId).empty();
6064#endif
6065}
6066
6067void GameProcessManager::pollRunningSteamGames()
6068{
6069 // Snapshot-scan-mutate pattern. Originally we held steamGamesMutex_
6070 // across the entire isSteamGameRunningOnSystem() loop, but that
6071 // function shells out to pgrep + fgets via PipeHandle and walks
6072 // /proc — blocking I/O that can stall every other consumer of
6073 // steamGamesMutex_ (game list refresh, launchGame, stopGame, the
6074 // detection thread). clang-tidy flags this with
6075 // clang-analyzer-unix.BlockInCriticalSection.
6076 //
6077 // Fix: snapshot under lock, scan without it, re-acquire to remove.
6078 // Race guard on the second lock — only erase the entry if the value
6079 // we observed during the scan is still the same gameId; if a new
6080 // launch replaced the entry between snapshot and re-lock (same App ID,
6081 // different game ID — rare but possible after a re-import), the
6082 // newer entry is preserved.
6083 std::vector<std::pair<int, std::string>> snapshot;
6084 {
6085 std::lock_guard<std::mutex> lock(steamGamesMutex_);
6086 snapshot.reserve(runningSteamGames_.size());
6087 for (const auto& [appId, gameId] : runningSteamGames_)
6088 snapshot.emplace_back(appId, gameId);
6089 }
6090
6091 std::vector<std::pair<int, std::string>> toRemove;
6092 for (const auto& [appId, gameId] : snapshot)
6093 {
6094 if (!isSteamGameRunningOnSystem(appId))
6095 {
6096 Logger::info("Steam game stopped: {} (App ID: {})", gameId, appId);
6097 toRemove.emplace_back(appId, gameId);
6098 }
6099 }
6100
6101 if (toRemove.empty())
6102 return;
6103
6104 std::lock_guard<std::mutex> lock(steamGamesMutex_);
6105 for (const auto& [appId, snapshotGameId] : toRemove)
6106 {
6107 const auto it = runningSteamGames_.find(appId);
6108 if (it != runningSteamGames_.end() && it->second == snapshotGameId)
6109 {
6110 runningSteamGames_.erase(it);
6111 }
6112 // Otherwise: the entry was replaced (re-import) or already
6113 // removed (concurrent stopGame) since we snapshotted — leave it.
6114 }
6115}
6116
6117// ==============================================================================
6118// GameProcessManager - Steam Game Killer
6119// ==============================================================================
6120
6121std::vector<int> GameProcessManager::findGamePidsByAppId(int steamAppId) const
6122{
6123 std::vector<int> pids;
6124#ifdef PLATFORM_LINUX
6125 if (steamAppId <= 0)
6126 return pids;
6127
6128 // Match SteamAppId=<id> NUL-terminated within the env block. We compare
6129 // the byte after the digits against '\0' to avoid matching 21419 against
6130 // SteamAppId=2141910.
6131 const std::string searchTag = "SteamAppId=" + std::to_string(steamAppId);
6132
6133 DIR* proc = opendir("/proc");
6134 if (!proc)
6135 return pids;
6136
6137 struct dirent* entry;
6138 while ((entry = readdir(proc)) != nullptr)
6139 {
6140 // Skip non-PID directories (anything that isn't all digits).
6141 const std::string name = entry->d_name;
6142 if (name.empty() ||
6143 !std::all_of(name.begin(), name.end(), [](unsigned char c) { return std::isdigit(c); }))
6144 {
6145 continue;
6146 }
6147
6148 // Read /proc/<pid>/environ — bounded to 1 MB to defend against a
6149 // pathological process with a giant env block.
6150 const std::string envPath = "/proc/" + name + "/environ";
6151 std::ifstream envFile(envPath, std::ios::binary);
6152 if (!envFile)
6153 continue;
6154
6155 constexpr size_t kMaxEnviron = 1u << 20;
6156 std::string envData(kMaxEnviron, '\0');
6157 envFile.read(envData.data(), static_cast<std::streamsize>(kMaxEnviron));
6158 envData.resize(static_cast<size_t>(envFile.gcount()));
6159
6160 const size_t pos = envData.find(searchTag);
6161 if (pos == std::string::npos)
6162 continue;
6163 const size_t endPos = pos + searchTag.size();
6164 // Exact-match guard: the next byte must be the env-var terminator,
6165 // otherwise this is a longer App ID that happens to share a prefix.
6166 if (endPos < envData.size() && envData[endPos] != '\0')
6167 continue;
6168
6169 // Filter out Wine/Proton infrastructure that inherits SteamAppId but
6170 // isn't the actual game process. Same blocklist used by the
6171 // detection thread above so kill-set matches detection-set.
6172 const std::string cmdlinePath = "/proc/" + name + "/cmdline";
6173 std::ifstream cmdFile(cmdlinePath, std::ios::binary);
6174 if (cmdFile)
6175 {
6176 const std::string cmdline((std::istreambuf_iterator<char>(cmdFile)),
6177 std::istreambuf_iterator<char>());
6178 static const char* const helperNames[] = {"wineserver", "winedevice",
6179 "services.exe", "plugplay.exe",
6180 "svchost.exe", "rpcss.exe",
6181 "explorer.exe", "wineboot",
6182 "start.exe", "conhost.exe",
6183 "tabtip.exe", "wine64-preloader",
6184 "pressure-vessel", "steam-runtime-launcher"};
6185 bool isHelper = false;
6186 for (const char* helper : helperNames)
6187 {
6188 if (cmdline.find(helper) != std::string::npos)
6189 {
6190 isHelper = true;
6191 break;
6192 }
6193 }
6194 if (isHelper)
6195 continue;
6196 }
6197
6198 try
6199 {
6200 pids.push_back(std::stoi(name));
6201 }
6202 catch (const std::exception&)
6203 {
6204 // Directory name wasn't parseable as an int despite all-digits
6205 // check (huge PID overflowing int). Skip.
6206 }
6207 }
6208 closedir(proc);
6209#else
6210 (void)steamAppId;
6211#endif
6212 return pids;
6213}
6214
6215bool GameProcessManager::killSteamGame(int steamAppId)
6216{
6217 if (steamAppId <= 0)
6218 {
6219 return false;
6220 }
6221
6222 Logger::info("Attempting to kill Steam game with App ID: {}", steamAppId);
6223
6224#ifdef _WIN32
6225 // Windows: Kill the reaper process and all child processes
6226 std::string killCmd =
6227 "taskkill /F /T /FI \"COMMANDLINE eq *reaper*AppId=" + std::to_string(steamAppId) + "*\"";
6228 Logger::debug("Command: {}", killCmd);
6229 ProcessResult result = ProcessExecutor::execute(killCmd);
6230 return result.success;
6231#else
6232 // Linux: We need to kill the reaper process and its children.
6233 // Use multiple strategies because the reaper command line format can vary.
6234
6235 std::string appIdStr = std::to_string(steamAppId);
6236 std::string reaperPidStr;
6237
6238 // Strategy 1: pgrep with partial match (most reliable)
6239 {
6240 std::string findCmd = "pgrep -f 'reaper SteamLaunch AppId=" + appIdStr + "' 2>/dev/null";
6241 PipeHandle pipe(findCmd, "r");
6242 if (pipe)
6243 {
6244 char buffer[128];
6245 if (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
6246 {
6247 reaperPidStr = buffer;
6248 reaperPidStr.erase(reaperPidStr.find_last_not_of("\n\r") + 1);
6249 }
6250 }
6251 }
6252
6253 // Strategy 2: broader pgrep if strategy 1 failed
6254 if (reaperPidStr.empty())
6255 {
6256 std::string findCmd = "pgrep -f 'SteamLaunch AppId=" + appIdStr + "' 2>/dev/null";
6257 PipeHandle pipe(findCmd, "r");
6258 if (pipe)
6259 {
6260 char buffer[128];
6261 if (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
6262 {
6263 reaperPidStr = buffer;
6264 reaperPidStr.erase(reaperPidStr.find_last_not_of("\n\r") + 1);
6265 }
6266 }
6267 }
6268
6269 // ----------------------------------------------------------------------
6270 // Strategy 1: Kill the reaper's process tree (preferred — clean shutdown
6271 // of the whole Steam launch chain in one signal). Skip if no reaper was
6272 // found; fall straight through to the proc-environ scan below.
6273 // ----------------------------------------------------------------------
6274 if (!reaperPidStr.empty())
6275 {
6276 const int reaperPid = std::stoi(reaperPidStr);
6277 Logger::info("Found reaper process at PID: {}", reaperPid);
6278
6279 // Kill reaper and all descendants. pstree -> PIDs -> kill -9.
6280 const std::string killTreeCmd = "kill -9 $(pstree -p " + std::to_string(reaperPid) +
6281 " | grep -o '([0-9]\\+)' | grep -o '[0-9]\\+') 2>/dev/null";
6282 Logger::debug("Killing reaper and descendants: {}", killTreeCmd);
6283 ProcessExecutor::execute(killTreeCmd);
6284
6285 // Belt-and-suspenders SIGKILL to the reaper in case pstree failed.
6286 ::kill(reaperPid, SIGKILL);
6287 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
6288 }
6289
6290 // ----------------------------------------------------------------------
6291 // Strategy 2: Catch any orphaned game processes by scanning
6292 // /proc/<pid>/environ for SteamAppId=<id>. Required for games like
6293 // MTGA that use a launcher → game double-spawn — the reaper tracks the
6294 // launcher, the actual game double-forks itself out of the tree, so
6295 // strategy 1 misses it. Without this fallback the launcher's UI gets
6296 // stuck in "Stopping..." because the background detection thread
6297 // re-discovers the still-running game.
6298 // ----------------------------------------------------------------------
6299 {
6300 std::vector<int> orphanPids = findGamePidsByAppId(steamAppId);
6301 if (!orphanPids.empty())
6302 {
6303 Logger::info("Found {} game process(es) via /proc/*/environ scan for App ID {} — "
6304 "sending SIGTERM",
6305 orphanPids.size(), steamAppId);
6306 for (int pid : orphanPids)
6307 {
6308 ::kill(pid, SIGTERM);
6309 }
6310 // Give graceful exit a chance — most games clean up under SIGTERM.
6311 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
6312
6313 // SIGKILL any survivors.
6314 for (int pid : orphanPids)
6315 {
6316 if (::kill(pid, 0) == 0)
6317 {
6318 Logger::warn("Game PID {} survived SIGTERM, sending SIGKILL", pid);
6319 ::kill(pid, SIGKILL);
6320 }
6321 }
6322 std::this_thread::sleep_for(std::chrono::milliseconds(500));
6323 }
6324 else if (reaperPidStr.empty())
6325 {
6326 // Reaper gone AND no env-tagged process — nothing to kill. The
6327 // game has already exited; the launcher's stop request is moot.
6328 Logger::info("No reaper or env-tagged process for App ID {} — game already exited",
6329 steamAppId);
6330 return true;
6331 }
6332 }
6333
6334 // ----------------------------------------------------------------------
6335 // Strategy 3: As a last-ditch fallback, ask Steam to kill it via the
6336 // documented `steam://gamepadui/killgame/<id>` URL. Big Picture mode
6337 // may handle this; desktop Steam may ignore it. Cheap to attempt.
6338 // ----------------------------------------------------------------------
6339 if (isSteamGameRunningOnSystem(steamAppId))
6340 {
6341 Logger::warn("Game still detected after direct kill — trying steam://gamepadui/killgame/{}",
6342 steamAppId);
6343 const std::string steamCmd =
6344 "steam steam://gamepadui/killgame/" + appIdStr + " 2>/dev/null &";
6345 ProcessExecutor::execute(steamCmd);
6346 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
6347 }
6348
6349 // Final verification.
6350 if (isSteamGameRunningOnSystem(steamAppId))
6351 {
6352 Logger::warn("WARNING: Game may still be running after all kill attempts (App ID {})",
6353 steamAppId);
6354 return false;
6355 }
6356
6357 Logger::info("Successfully stopped Steam game with App ID: {}", steamAppId);
6358 return true;
6359#endif
6360}
6361
6362// ==============================================================================
6363// GameProcessManager - Launch Command Builder
6364// ==============================================================================
6365
6366std::string GameProcessManager::buildLaunchCommand(const Game& game)
6367{
6368 std::ostringstream cmd;
6369
6370 // ==========================================================================
6371 // Build launch command following CachyOS best practices:
6372 // <env variables> <wrappers> %command% <application arguments>
6373 // https://wiki.cachyos.org/configuration/gaming/
6374 //
6375 // SECURITY: All user-provided values are escaped using ShellUtils to prevent
6376 // command injection attacks.
6377 // ==========================================================================
6378
6379 // Step 1: Add all environment variables FIRST (with safe escaping)
6380 for (const auto& [key, value] : game.runnerConfig.environmentVariables)
6381 {
6382 // Skip wrapper markers - these are internal flags, not actual env vars
6383 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE")
6384 continue;
6385
6386 // Validate environment variable name to prevent injection
6388 {
6389 Logger::warn("Skipping invalid environment variable name: {}", key);
6390 continue;
6391 }
6392
6393 // Use safe escaping for the value
6394 cmd << ShellUtils::formatEnvVar(key, value) << " ";
6395 }
6396
6397 // For Steam games launched via Proton, add Steam-specific environment variables
6398 if (game.metadata.isSteamGame && game.metadata.steamAppId > 0)
6399 {
6400 // Find Steam installation path
6401 const char* home = std::getenv("HOME");
6402 if (home)
6403 {
6404 std::filesystem::path steamPath =
6405 std::filesystem::path(home) / ".local" / "share" / "Steam";
6406 std::filesystem::path compatDataPath =
6407 steamPath / "steamapps" / "compatdata" / std::to_string(game.metadata.steamAppId);
6408
6409 // Set Steam compatibility environment variables (paths are safe - constructed
6410 // internally)
6411 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_DATA_PATH", compatDataPath.string())
6412 << " ";
6413 cmd << ShellUtils::formatEnvVar("STEAM_COMPAT_CLIENT_INSTALL_PATH", steamPath.string())
6414 << " ";
6415 cmd << "SteamAppId=" << game.metadata.steamAppId << " ";
6416 cmd << "SteamGameId=" << game.metadata.steamAppId << " ";
6417 }
6418 }
6419
6420 // Step 2: Add game-performance wrapper if enabled
6421 // This must come AFTER env vars but BEFORE the actual command
6422 // Check for both old and new marker keys for backwards compatibility
6423 if (game.runnerConfig.environmentVariables.count("GAME_PERFORMANCE") > 0 ||
6424 game.runnerConfig.environmentVariables.count("USE_GAME_PERFORMANCE") > 0)
6425 {
6426 cmd << "game-performance ";
6427 }
6428
6429 // Step 3: Add the actual command/executable (safely escaped)
6431
6432 // Step 4: Add application arguments LAST (safely escaped)
6433 if (!game.runnerConfig.arguments.empty())
6434 {
6435 // Split args respecting shell quoting, then escape each token safely
6436 for (const auto& arg : ShellUtils::splitArgs(game.runnerConfig.arguments))
6437 cmd << " " << ShellUtils::escapeArg(arg);
6438 }
6439
6440 return cmd.str();
6441}
bool startCollection(const std::string &gameId, int pid, bool useGamescope=false, bool enableMangoHudLogging=true)
Start collecting metrics for a game.
static FrameMetricsService & instance()
Get the singleton instance.
std::string buildMangoHudLaunchConfigFile(const std::string &gameId, const std::string &userConfigFile={}) const
Materialise a complete MangoHud config file for a launch.
void stopCollection(const std::string &gameId)
Stop collecting metrics for a game.
void setOnGameStatsUpdated(std::function< void(const std::string &gameId)> callback)
const GameProcess * getRunningProcess(const std::string &gameId) const
std::function< void(GameProcess::NotificationType, const std::string &)> getOnNotification() const
int getLastExitCode(const std::string &gameId, int defaultCode=0) const
bool launchGame(const std::string &gameId, Game &game)
std::function< void(const std::string &)> getOnGameStatsUpdated() const
bool stopGame(const std::string &gameId, Game *game=nullptr, bool force=false)
void scanForRunningGames(const std::vector< Game * > &games, GameAccessCallback gameAccessCallback)
std::function< void(const std::string &gameId, std::function< void(Game &)>)> GameAccessCallback
bool isGameRunning(const std::string &gameId) const
void setOnNotification(std::function< void(GameProcess::NotificationType, const std::string &)> callback)
std::vector< std::string > getRunningGameIds() const
ProcessSnapshot getRunningProcessSnapshot(const std::string &gameId) const
std::chrono::seconds getGameSessionDuration(const std::string &gameId) const
static GameProcessManager & instance()
Manages a single running game process.
void update()
Check if process is still running and update statistics.
bool stop()
Stop the game process gracefully.
int getTrackedProcessId() const
Get the tracked game process ID.
GameProcess(const Game &game)
Constructor - creates a process for the given game.
int getProcessId() const
Get the process ID.
double getRunningTimeSeconds() const
Get how long the process has been running.
State
Current state of the game process.
@ Running
Process is running normally.
@ Stopping
Process is being stopped (graceful shutdown).
@ Error
Process encountered an error during launch.
@ Stopped
Process has stopped (either normally or was killed).
@ Starting
Process is in the process of starting.
@ NotStarted
Process has not been started yet.
const LaunchInfo & getLastLaunchInfo() const
Get information about what was applied during the last launch.
const std::string & getTrackedProcessName() const
Get the name of the tracked game process.
bool isRunning() const
Check if process is currently running.
bool launch()
Launch the game process.
void notify(NotificationType type, const std::string &message) const
bool kill()
Force kill the game process.
~GameProcess()
Destructor - stops the process if still running.
void attachToRunningProcess(int pid, const std::string &processName="")
Attach to an already-running process.
NotificationType
Type of notification to display.
static GameSessionService & instance()
Get singleton instance.
void onGameStopped()
Called when a game stops running.
void onGameStarted()
Called when a game starts running.
Complete representation of a game in the library.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::string name
Display name shown in UI.
Definition game.h:774
std::string id
Unique identifier (auto-generated or user-specified).
Definition game.h:773
GameStatistics statistics
Play statistics and usage tracking.
Definition game.h:786
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
RAII wrapper for FILE* from popen().
FILE * get() const
Get raw FILE* pointer.
static ProcessResult executeWithOutput(const std::string &command, bool silent=false)
Execute command and capture stdout.
static ProcessResult executeBackground(const std::string &command)
Execute command in background (non-blocking).
static ProcessResult execute(const std::string &command, bool silent=false)
Execute command and check exit code.
static bool isProcessRunning(const std::string &processName)
Check if process is running by name.
static std::vector< std::pair< std::string, std::filesystem::path > > getVersions()
Get cached Proton versions.
static std::string formatEnvVar(const std::string &name, const std::string &value)
Format an environment variable assignment safely.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
static bool isValidEnvName(const std::string &name)
Validate an environment variable name.
static std::vector< std::string > splitArgs(const std::string &args)
Split a shell argument string into tokens, respecting quoting.
static SystemInfoService & instance()
Get singleton instance.
const SystemCapabilities & getCapabilities()
Get complete system capabilities.
bool supportsNTSync()
Check if NTSync is supported (kernel 6.2+ with module loaded).
GameModeAPI & operator=(const GameModeAPI &)=delete
static bool readSteamMinimizedFromDisk()
Read just steamMinimized directly from the settings file.
static bool readUseSteamLaunchByDefaultFromDisk()
Read just useSteamLaunchByDefault directly from the settings file.
@ ScummVM
ScummVM engine.
Definition game.h:86
@ Proton
Proton (Steam's Wine fork).
Definition game.h:84
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:82
@ Wine
Wine compatibility layer.
Definition game.h:83
@ DOSBox
DOSBox emulator.
Definition game.h:85
static time_t parseProcessStartTime(pid_t pid)
static bool isSteamFlatpak()
static std::string getSteamCommand()
constexpr int GAME_DETECTION_INTERVAL_SEC
Interval between game process detection scans.
bool kernelSupportsNTSync()
Check if kernel supports NTSync (kernel 6.14+ or CachyOS backport).
std::string buildGamescopeWrapper(const GameRunnerConfig &config, std::string &modeInfo)
Build the Gamescope wrapper prefix.
std::string detectGPUVendor()
Detect GPU vendor for GPU-specific optimizations.
const std::vector< std::string > & kWineSystemExes()
void addApplicationSpecificFixes(std::ostringstream &cmd, const Game &game)
Add application-specific environment variables for known problematic apps.
void addGPUOptimizations(std::ostringstream &cmd, bool isProton=false)
Add GPU-specific optimization environment variables.
bool isWrapperAvailable(const std::string &name)
Check if a wrapper/tool is available in PATH.
void addSyncEnvironment(std::ostringstream &cmd, const GameRunnerConfig &config, bool isProton=false)
Add synchronization environment variables.
std::string buildWrapperChain(const GameRunnerConfig &config, const std::string &gameId)
Build the wrapper chain for a game launch.
bool kernelSupportsFsync()
Check if kernel supports Fsync (futex2).
bool isSteamGame
True if imported from Steam.
Definition game.h:574
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
Configuration for how to launch and run a game.
Definition game.h:138
bool enableVkBasalt
Enable VkBasalt shader injection.
Definition game.h:188
int gamescopeInternalHeight
Internal render height for FSR upscaling (0 = native).
Definition game.h:198
std::string executablePath
Full path to game executable.
Definition game.h:141
int gamescopeITMSDRNits
ITM SDR nits reference (0 = use default).
Definition game.h:207
bool gamescopeIntegerScaling
Enable integer scaling filter.
Definition game.h:208
bool gamescopeFullscreen
Run in fullscreen mode.
Definition game.h:200
std::string arguments
Command line arguments to pass to game.
Definition game.h:143
int gamescopeHeight
Gamescope output height (0 = native).
Definition game.h:196
bool gamescopeEnableFSR
Enable AMD FSR upscaling.
Definition game.h:202
bool enableMangoHud
Enable MangoHud performance overlay.
Definition game.h:184
std::string winePrefix
WINEPREFIX path (Wine install location).
Definition game.h:167
int gamescopeFSRSharpness
FSR sharpness (0-20, 0 = max sharp).
Definition game.h:203
bool gamescopeEnableVRR
Enable Variable Refresh Rate.
Definition game.h:204
bool enableGamePerformance
Enable game-performance wrapper (CachyOS).
Definition game.h:187
bool enableFsync
Enable Fsync (kernel 5.16+, best performance).
Definition game.h:215
int gamescopeRefreshRate
Refresh rate limit (0 = no limit).
Definition game.h:199
bool autoDetectSync
Auto-detect best sync method (default: true).
Definition game.h:216
bool gamescopeEnableITM
Enable HDR inverse tone mapping for SDR games.
Definition game.h:206
int gamescopeWidth
Gamescope output width (0 = native).
Definition game.h:195
std::string mangoHudConfigFile
Per-game MangoHud config file path (MANGOHUD_CONFIGFILE).
Definition game.h:185
int gamescopeInternalWidth
Internal render width for FSR upscaling (0 = native).
Definition game.h:197
bool enableGameMode
Enable GameMode CPU governor optimization.
Definition game.h:186
bool enableGamescope
Enable Gamescope compositor.
Definition game.h:194
std::string protonVersion
Proton version (e.g., "proton-cachyos-slr").
Definition game.h:170
std::map< std::string, std::string > environmentVariables
Environment variables to set before launching (KEY=VALUE pairs).
Definition game.h:146
bool gamescopeEnableHDR
Enable HDR output.
Definition game.h:205
bool useSteamLaunch
For Steam games: if true, launch via "steam -applaunch" instead of direct Proton.
Definition game.h:161
bool gamescopeBorderless
Borderless window mode.
Definition game.h:201
bool gamescopeForceGrabCursor
Force cursor grab (useful for some games).
Definition game.h:209
Play statistics and usage tracking for a game.
Definition game.h:712
time_t lastExitTime
Unix timestamp of last exit.
Definition game.h:727
std::string lastExitReason
Reason game stopped: "normal", "crash", "timeout", "unknown".
Definition game.h:726
std::string lastProtonVersion
Proton version used in last launch.
Definition game.h:721
std::map< std::string, std::string > lastEnvironmentVars
Environment variables from last launch.
Definition game.h:723
std::string lastLaunchCommand
Full command used for last launch (with env vars).
Definition game.h:720
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
Definition game.h:714
time_t lastPlayed
Unix timestamp of last play session.
Definition game.h:715
int timesLaunched
Number of times game was launched.
Definition game.h:713
int crashCount
Number of times game has crashed.
Definition game.h:728
Result of process execution including exit code and output.
int exitCode
Process exit code (0 = success).
bool success
true if command executed successfully (exit code 0)
std::string output
Captured stdout (if requested).
bool shouldUseGameMode() const
True iff gamemoderun should actually be invoked.
@ Game
Game-specific fixes.