41#include <sys/utsname.h>
65 static GameModeAPI inst;
74 int ret = startForFn_(pid);
77 Logger::info(
"GameMode: requested start for PID {}", pid);
84 Logger::warn(
"GameMode: request_start_for({}) failed: {}", pid, errorStringFn_());
86 Logger::warn(
"GameMode: request_start_for({}) failed (ret={})", pid, ret);
96 int ret = endForFn_(pid);
105 Logger::warn(
"GameMode: request_end_for({}) failed: {}", pid, errorStringFn_());
107 Logger::warn(
"GameMode: request_end_for({}) failed (ret={})", pid, ret);
114 return handle_ !=
nullptr;
120 handle_ = dlopen(
"libgamemode.so.0", RTLD_NOW);
124 handle_ = dlopen(
"libgamemode.so", RTLD_NOW);
129 "GameMode API: libgamemode.so.0 not found ({}), PID-targeted GameMode unavailable",
135 reinterpret_cast<int (*)(pid_t)
>(dlsym(handle_,
"real_gamemode_request_start_for"));
137 reinterpret_cast<int (*)(pid_t)
>(dlsym(handle_,
"real_gamemode_request_end_for"));
139 reinterpret_cast<const char* (*)()
>(dlsym(handle_,
"real_gamemode_error_string"));
141 if (!startForFn_ || !endForFn_)
143 Logger::warn(
"GameMode API: loaded libgamemode.so but missing required symbols");
146 startForFn_ =
nullptr;
148 errorStringFn_ =
nullptr;
152 Logger::info(
"GameMode API: loaded libgamemode.so.0 successfully");
169 void* handle_ =
nullptr;
170 int (*startForFn_)(pid_t) =
nullptr;
171 int (*endForFn_)(pid_t) =
nullptr;
172 const char* (*errorStringFn_)() =
nullptr;
187 std::string statPath =
"/proc/" + std::to_string(pid) +
"/stat";
188 std::ifstream statFile(statPath);
189 if (!statFile.is_open())
193 if (!std::getline(statFile, line))
199 size_t lastParen = line.rfind(
')');
200 if (lastParen == std::string::npos || lastParen + 2 >= line.size())
203 std::istringstream iss(line.substr(lastParen + 2));
213 unsigned long long startTicks = std::stoull(token);
214 std::ifstream uptimeFile(
"/proc/uptime");
215 if (!uptimeFile.is_open())
218 double uptimeSeconds;
219 if (!(uptimeFile >> uptimeSeconds))
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);
248 static std::once_flag flag;
249 static bool flatpak =
false;
254 bool nativeSteamExists = std::filesystem::exists(
"/usr/bin/steam") ||
255 std::filesystem::exists(
"/usr/local/bin/steam");
256 if (!nativeSteamExists)
260 "flatpak info com.valvesoftware.Steam 2>/dev/null");
261 flatpak = result.success;
270 return "flatpak run com.valvesoftware.Steam";
280 : game_(game), state_(
State::NotStarted), pid_(-1), trackedPid_(-1), startTime_(0),
281 isAttachedProcess_(false), gamemodePid_(-1)
306 onNotification_(type, message);
314void GameProcess::checkLaunchOptionConflicts()
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")
325 if (fsrEnabled && dlssEnabled)
328 "Potential conflict: FSR and DLSS are both enabled — they are mutually "
329 "exclusive upscalers, only one will take effect");
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)
340 "Potential conflict: MangoHUD and DXVK HUD are both enabled — overlapping "
341 "overlays may cause visual clutter or performance issues");
348 "Potential conflict: Runner is set to Wine but a Proton version is "
349 "configured — the Proton version will be ignored");
356 "Potential conflict: Runner is set to Native but a Wine prefix is "
357 "configured — the Wine prefix will be ignored");
361 if (config.gamescopeEnableHDR && !config.enableGamescope)
364 "Potential conflict: HDR is enabled but Gamescope is disabled — HDR output "
365 "requires Gamescope on Linux");
377 Logger::error(
"Cannot launch: process already running or starting");
388 bool isSteamManaged = game_.metadata.isSteamGame && game_.metadata.steamAppId > 0;
392 if (game_.runnerConfig.executablePath.empty())
394 Logger::error(
"No executable path configured for game: {}", game_.name);
397 "Cannot launch '" + game_.name +
"': no executable path configured");
401 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
403 Logger::error(
"Executable not found for game '{}': {}", game_.name,
404 game_.runnerConfig.executablePath);
407 "': executable not found at '" +
408 game_.runnerConfig.executablePath +
"'");
417 bool wineFound =
false;
418 if (!game_.runnerConfig.winePath.empty() &&
419 std::filesystem::exists(game_.runnerConfig.winePath))
423 else if (std::filesystem::exists(
"/opt/wine-cachyos/bin/wine"))
441 "Cannot launch '" + game_.name +
442 "': Wine is not installed. Install Wine or configure a custom Wine path.");
450 bool protonAvailable = isUmuLauncherAvailable();
451 if (!protonAvailable)
453 std::string protonPath = findProtonPath(game_.runnerConfig.protonVersion);
454 protonAvailable = !protonPath.empty();
457 if (!protonAvailable)
459 Logger::error(
"Proton not available for game: {}", game_.name);
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.");
473 checkLaunchOptionConflicts();
475 bool success =
false;
481 switch (game_.runner)
484 success = launchNative();
488 success = launchWine();
492 success = launchProton();
496 success = launchDOSBox();
500 success = launchScummVM();
504 Logger::error(
"Unsupported runner for game: {}", game_.name);
509 catch (
const std::filesystem::filesystem_error& e)
511 Logger::error(
"Filesystem error launching game '{}': {}", game_.name, e.what());
515 catch (
const std::exception& e)
517 Logger::error(
"Exception launching game '{}': {}", game_.name, e.what());
523 Logger::error(
"Unknown exception launching game '{}'", game_.name);
530 startTime_ = time(
nullptr);
532 Logger::info(
"Launched game: {} (PID: {})", game_.name, pid_);
539 if (pid_ > 0 && !game_.metadata.isSteamGame)
558 if (game_.runnerConfig.enableGameMode && pid_ > 0)
571 std::string errorMsg =
"Failed to launch: " + game_.name;
572 switch (game_.runner)
575 errorMsg +=
" (Wine not available or executable not found)";
578 errorMsg +=
" (Proton/umu-launcher not available or executable not found)";
581 errorMsg +=
" (check executable path)";
604 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid_);
605 if (hProcess != NULL)
607 TerminateProcess(hProcess, 0);
608 CloseHandle(hProcess);
612 if (trackedPid_ > 0 && trackedPid_ != pid_)
614 Logger::info(
"Stopping tracked game process: PID {} ({})", trackedPid_,
615 trackedProcessName_);
616 ::kill(trackedPid_, SIGTERM);
620 if (!game_.runnerConfig.winePrefix.empty())
622 killWinePrefix(
false);
631 for (
int i = 0; i < 30; ++i)
634 pid_t result = waitpid(pid_, &status, WNOHANG);
639 std::this_thread::sleep_for(std::chrono::milliseconds(100));
645 Logger::warn(
"Process {} did not exit after SIGTERM, sending SIGKILL", pid_);
647 if (waitpid(pid_,
nullptr, 0) < 0 && errno != ECHILD)
649 Logger::warn(
"waitpid after SIGKILL failed for pid {}: {}", pid_, strerror(errno));
658 time_t now = time(
nullptr);
659 double sessionTime = difftime(now, startTime_);
660 if (sessionTime > 0.0)
662 game_.statistics.totalPlayTimeSeconds += sessionTime;
663 game_.statistics.lastPlayed = now;
669 trackedProcessName_.clear();
684 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid_);
685 if (hProcess != NULL)
687 TerminateProcess(hProcess, 1);
688 CloseHandle(hProcess);
692 if (trackedPid_ > 0 && trackedPid_ != pid_)
694 Logger::info(
"Force killing tracked game process: PID {} ({})", trackedPid_,
695 trackedProcessName_);
696 ::kill(trackedPid_, SIGKILL);
700 if (!game_.runnerConfig.winePrefix.empty())
702 killWinePrefix(
true);
711 if (waitpid(pid_, &status, 0) < 0 && errno != ECHILD)
713 Logger::warn(
"waitpid after SIGKILL (kill) failed for pid {}: {}", pid_,
722 time_t now = time(
nullptr);
723 double sessionTime = difftime(now, startTime_);
724 if (sessionTime > 0.0)
726 game_.statistics.totalPlayTimeSeconds += sessionTime;
727 game_.statistics.lastPlayed = now;
733 trackedProcessName_.clear();
747 Logger::error(
"Cannot attach to process: invalid PID {}", pid);
752 isAttachedProcess_ =
true;
757 trackedProcessName_ = processName;
758 startTime_ = time(
nullptr);
767 Logger::debug(
"Recovered actual start time for PID {}: {} seconds ago", pid,
768 time(
nullptr) - startTime_);
774 if (!game_.runnerConfig.excludeProcesses.empty())
776 int gameProc = findGameProcess();
777 if (gameProc > 0 && gameProc != pid)
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())
785 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
786 std::istreambuf_iterator<char>());
789 while (cmdStart < cmdline.size())
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)
800 size_t lastSlash = arg.find_last_of(
"/\\");
802 (lastSlash != std::string::npos) ? arg.substr(lastSlash + 1) : arg;
805 cmdStart = cmdEnd + 1;
808 if (gameProcName.empty())
810 gameProcName = getProcessName(gameProc);
812 trackedPid_ = gameProc;
813 trackedProcessName_ = gameProcName;
821 Logger::debug(
"Updated start time to actual game process: {} seconds ago",
822 time(
nullptr) - startTime_);
826 Logger::info(
"Detected actual game process: PID {} ({}) running under launcher PID {}",
827 trackedPid_, trackedProcessName_, pid);
833 Logger::info(
"Started frame metrics collection for attached game process: PID {}",
843 Logger::info(
"Started frame metrics collection for attached process: PID {}", pid);
848 if (game_.runnerConfig.enableGameMode)
851 static_cast<pid_t
>((trackedPid_ > 0 && trackedPid_ != pid_) ? trackedPid_ : pid_);
853 gamemodePid_ =
static_cast<int>(targetPid);
858 Logger::info(
"Attached to running process: PID {} ({})", pid, processName);
876 std::string statPath =
"/proc/" + std::to_string(pid) +
"/stat";
877 std::ifstream statFile(statPath);
878 if (!statFile.is_open())
882 if (!std::getline(statFile, line))
890 size_t lastParen = line.rfind(
')');
891 if (lastParen == std::string::npos || lastParen + 2 >= line.size())
895 std::istringstream iss(line.substr(lastParen + 2));
898 unsigned long long starttime = 0;
901 while (iss >> field && fieldNum < 20)
908 starttime = std::stoull(field);
922 std::ifstream procStat(
"/proc/stat");
923 if (!procStat.is_open())
927 while (std::getline(procStat, line))
929 if (line.compare(0, 6,
"btime ") == 0)
933 bootTime =
static_cast<time_t
>(std::stoll(line.substr(6)));
947 long ticksPerSec = sysconf(_SC_CLK_TCK);
948 if (ticksPerSec <= 0)
952 time_t processStartTime =
953 bootTime +
static_cast<time_t
>(starttime /
static_cast<unsigned long long>(ticksPerSec));
954 return processStartTime;
969 int targetPid = (trackedPid_ > 0) ? trackedPid_ : pid_;
970 time_t procStartTime = getProcessStartTimeFromProc(targetPid);
972 if (procStartTime > 0)
975 time_t now = time(
nullptr);
976 return difftime(now, procStartTime);
985 time_t now = time(
nullptr);
986 return difftime(now, startTime_);
998 if (!checkProcessRunning())
1009 pid_t result = waitpid(pid_, &status, WNOHANG);
1012 if (WIFEXITED(status))
1014 exitCode = WEXITSTATUS(status);
1016 else if (WIFSIGNALED(status))
1018 exitCode = 128 + WTERMSIG(status);
1019 Logger::warn(
"Game process killed by signal {}", WTERMSIG(status));
1031 time_t now = time(
nullptr);
1032 double sessionTime = difftime(now, startTime_);
1033 if (sessionTime > 0.0)
1035 game_.statistics.totalPlayTimeSeconds += sessionTime;
1036 game_.statistics.lastPlayed = now;
1054void GameProcess::updateState(State newState)
1056 if (state_ != newState)
1069 if (onStateChanged_)
1071 onStateChanged_(newState);
1076std::string GameProcess::buildLaunchCommand()
const
1078 std::ostringstream cmd;
1090 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
1093 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
1099 Logger::warn(
"Skipping invalid environment variable name: {}", key);
1111 bool isSteamManagedLaunch = game_.metadata.isSteamGame && game_.metadata.steamAppId > 0 &&
1112 game_.runnerConfig.executablePath ==
"steam";
1114 if (!isSteamManagedLaunch)
1117 if (game_.metadata.isSteamGame && game_.metadata.steamAppId > 0)
1119 const char* home = std::getenv(
"HOME");
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);
1132 cmd <<
"SteamAppId=" << game_.metadata.steamAppId <<
" ";
1133 cmd <<
"SteamGameId=" << game_.metadata.steamAppId <<
" ";
1140 if (game_.runnerConfig.enableGamePerformance ||
1141 game_.runnerConfig.environmentVariables.count(
"GAME_PERFORMANCE") > 0 ||
1142 game_.runnerConfig.environmentVariables.count(
"USE_GAME_PERFORMANCE") > 0)
1144 cmd <<
"game-performance ";
1147 if (game_.runnerConfig.enableGameMode &&
1150 cmd <<
"gamemoderun ";
1152 else if (game_.runnerConfig.enableGameMode)
1154 Logger::info(
"Skipping gamemoderun — ananicy-cpp.service is active "
1155 "and already manages scheduling");
1165 if (!game_.runnerConfig.arguments.empty())
1176bool GameProcess::isSteamRunning()
1181bool GameProcess::ensureSteamRunning()
1183 if (isSteamRunning())
1195 Logger::info(
"Steam is not running. Starting Steam ({})...",
1196 launchSilent ?
"silent / tray" :
"foreground");
1203 startCmd +=
" -silent";
1208 for (
int i = 0; i < 20; i++)
1210 std::this_thread::sleep_for(std::chrono::milliseconds(500));
1212 if (isSteamRunning())
1216 std::this_thread::sleep_for(std::chrono::seconds(2));
1225bool GameProcess::launchDOSBox()
1228 std::string dosboxBin;
1229 for (
const auto& candidate : {
"dosbox",
"dosbox-staging",
"dosbox-x"})
1234 dosboxBin = candidate;
1239 if (dosboxBin.empty())
1241 Logger::error(
"DOSBox not found. Install dosbox, dosbox-staging, or dosbox-x.");
1243 "DOSBox not found. Install dosbox, dosbox-staging, or dosbox-x.");
1248 std::ostringstream cmd;
1251 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
1253 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
1262 const std::string& exePath = game_.runnerConfig.executablePath;
1263 if (exePath.size() >= 5 && exePath.substr(exePath.size() - 5) ==
".conf")
1277 return executeCommand(cmd.str());
1280bool GameProcess::launchScummVM()
1284 if (!whichResult.success)
1292 std::ostringstream cmd;
1295 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
1297 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
1306 if (!game_.runnerConfig.arguments.empty())
1310 else if (!game_.runnerConfig.workingDirectory.empty())
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.");
1323 return executeCommand(cmd.str());
1326bool GameProcess::launchNative()
1329 if (game_.metadata.isSteamGame)
1331 if (!ensureSteamRunning())
1333 Logger::error(
"Cannot launch Steam game: Steam is not running and failed to start");
1338 std::string command = buildLaunchCommand();
1348 PROCESS_INFORMATION pi;
1349 ZeroMemory(&si,
sizeof(si));
1351 ZeroMemory(&pi,
sizeof(pi));
1354 std::vector<char> cmdLine(command.begin(), command.end());
1355 cmdLine.push_back(
'\0');
1357 if (CreateProcess(NULL, cmdLine.data(), NULL, NULL, FALSE, 0, NULL,
1358 game_.runnerConfig.workingDirectory.empty()
1360 : game_.runnerConfig.workingDirectory.c_str(),
1363 pid_ = pi.dwProcessId;
1364 CloseHandle(pi.hProcess);
1365 CloseHandle(pi.hThread);
1372 std::string workDirCopy = game_.runnerConfig.workingDirectory;
1373 std::string commandCopy = command;
1384 if (!workDirCopy.empty())
1386 if (chdir(workDirCopy.c_str()) != 0)
1388 const char* msg =
"GameLauncher: Failed to change working directory\n";
1389 [[maybe_unused]]
auto _ = write(STDERR_FILENO, msg, strlen(msg));
1399 long maxFd = sysconf(_SC_OPEN_MAX);
1402 for (
long fd = 3; fd < maxFd; ++fd)
1404 close(
static_cast<int>(fd));
1408 execl(
"/bin/sh",
"sh",
"-c", commandCopy.c_str(),
static_cast<char*
>(
nullptr));
1411 const char* msg =
"GameLauncher: Failed to execute command\n";
1412 [[maybe_unused]]
auto _ = write(STDERR_FILENO, msg, strlen(msg));
1424 Logger::error(
"Failed to fork process: {}", strerror(errno));
1430bool GameProcess::executeCommand(
const std::string& command)
1442 PROCESS_INFORMATION pi;
1443 ZeroMemory(&si,
sizeof(si));
1445 ZeroMemory(&pi,
sizeof(pi));
1447 std::vector<char> cmdLine(command.begin(), command.end());
1448 cmdLine.push_back(
'\0');
1450 if (CreateProcess(NULL, cmdLine.data(), NULL, NULL, FALSE, 0, NULL,
1451 game_.runnerConfig.workingDirectory.empty()
1453 : game_.runnerConfig.workingDirectory.c_str(),
1456 pid_ = pi.dwProcessId;
1457 CloseHandle(pi.hProcess);
1458 CloseHandle(pi.hThread);
1477 std::string workDirCopy2 = game_.runnerConfig.workingDirectory;
1479 std::string commandCopy2 = command;
1490 if (!workDirCopy2.empty())
1492 if (chdir(workDirCopy2.c_str()) != 0)
1495 const char* msg =
"GameLauncher: Failed to change working directory\n";
1496 [[maybe_unused]]
auto _ = write(STDERR_FILENO, msg, strlen(msg));
1502 long maxFd = sysconf(_SC_OPEN_MAX);
1505 for (
long fd = 3; fd < maxFd; ++fd)
1507 close(
static_cast<int>(fd));
1511 execl(
"/bin/sh",
"sh",
"-c", commandCopy2.c_str(),
static_cast<char*
>(
nullptr));
1514 const char* msg =
"GameLauncher: Failed to execute command\n";
1515 [[maybe_unused]]
auto _ = write(STDERR_FILENO, msg, strlen(msg));
1527 Logger::error(
"Failed to fork process: {}", strerror(errno));
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",
1563 static std::once_flag flag;
1564 static std::string cached;
1573 for (
const auto& entry : std::filesystem::directory_iterator(
"/sys/class/drm"))
1575 std::string name = entry.path().filename().string();
1576 if (name.find(
"card") == 0 && name.find(
"-") == std::string::npos)
1578 std::filesystem::path vendorPath = entry.path() /
"device" /
"vendor";
1579 if (std::filesystem::exists(vendorPath))
1581 std::ifstream vendorFile(vendorPath);
1582 std::string vendorId;
1583 if (vendorFile >> vendorId)
1585 if (vendorId ==
"0x1002" || vendorId ==
"0x1022")
1590 else if (vendorId ==
"0x10de")
1595 else if (vendorId ==
"0x8086")
1622 static std::once_flag flag;
1623 static bool result =
false;
1625 std::call_once(flag,
1633 if (uname(&uts) == 0)
1635 char* endMajor =
nullptr;
1636 const long major = std::strtol(uts.release, &endMajor, 10);
1637 if (endMajor && *endMajor ==
'.' && endMajor != uts.release)
1639 char* endMinor =
nullptr;
1640 const long minor = std::strtol(endMajor + 1, &endMinor, 10);
1641 if (endMinor && endMinor != endMajor + 1)
1643 result = (major > 5) || (major == 5 && minor >= 16);
1679 std::vector<std::string> paths = {
"/usr/bin/" + name,
"/usr/local/bin/" + name};
1681 const char* home = std::getenv(
"HOME");
1684 paths.push_back(std::string(home) +
"/.local/bin/" + name);
1687 for (
const auto& path : paths)
1689 if (std::filesystem::exists(path))
1721 std::ostringstream gs;
1722 std::ostringstream mode;
1743 if (!mode.str().empty())
1761 gs <<
"--fsr-upscaling ";
1763 if (!mode.str().empty())
1771 gs <<
"-S integer ";
1772 if (!mode.str().empty())
1780 gs <<
"--adaptive-sync ";
1781 if (!mode.str().empty())
1789 gs <<
"--hdr-enabled ";
1790 if (!mode.str().empty())
1798 gs <<
"--hdr-itm-enable ";
1808 gs <<
"--force-grab-cursor ";
1814 gs <<
"--mangoapp ";
1815 Logger::info(
"Using MangoHud via --mangoapp (Gamescope native integration)");
1819 gs <<
"--expose-wayland ";
1824 modeInfo = mode.str().empty() ?
"enabled" : mode.str();
1825 Logger::info(
"Using Gamescope compositor ({})", modeInfo);
1848 std::ostringstream wrappers;
1854 wrappers <<
"game-performance ";
1855 Logger::info(
"Using game-performance wrapper (outermost)");
1863 wrappers <<
"gamemoderun ";
1868 Logger::info(
"Skipping gamemoderun — ananicy-cpp.service is active");
1886 if (!cfgPath.empty())
1892 wrappers <<
"MANGOHUD=1 ";
1893 Logger::info(
"Using MangoHud performance overlay with logging");
1900 wrappers <<
"ENABLE_VKBASALT=1 ";
1904 return wrappers.str();
1927 bool isProton =
false)
1938 cmd <<
"PROTON_USE_NTSYNC=1 ";
1941 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
1942 Logger::info(
"Using NTSync (auto-detected kernel support)");
1946 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
1947 Logger::info(
"Using Fsync (auto-detected kernel support)");
1951 cmd <<
"WINEESYNC=1 ";
1952 Logger::info(
"Using Esync (kernel doesn't support Fsync)");
1957 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
1977 cmd <<
"ENABLE_LAYER_MESA_ANTI_LAG=1 ";
1980 else if (gpu ==
"NVIDIA")
1983 cmd <<
"DXVK_ENABLE_NVAPI=1 ";
1987 cmd <<
"PROTON_FORCE_NVAPI=1 ";
2017 std::string nameLower;
2018 std::string exeLower;
2022 nameLower = game.
name;
2027 Logger::warn(
"Failed to copy game strings for application fix detection");
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)));
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);
2050 Logger::info(
"Detected Battle.net - applying compatibility fixes");
2052 cmd <<
"WINE_SIMULATE_WRITECOPY=1 ";
2054 cmd <<
"WINE_LARGE_ADDRESS_AWARE=1 ";
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);
2068 Logger::info(
"Detected EA App/Origin - applying compatibility fixes");
2070 cmd <<
"WINE_LARGE_ADDRESS_AWARE=1 ";
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);
2083 Logger::info(
"Detected Ubisoft Connect - applying compatibility fixes");
2084 cmd <<
"WINE_LARGE_ADDRESS_AWARE=1 ";
2090 bool isGOGGalaxy = (nameLower.find(
"gog galaxy") != std::string::npos ||
2091 exeLower.find(
"galaxyclient") != std::string::npos);
2095 Logger::info(
"Detected GOG Galaxy - applying compatibility fixes");
2096 cmd <<
"WINE_LARGE_ADDRESS_AWARE=1 ";
2102bool GameProcess::launchWine()
2104 std::ostringstream cmd;
2116 lastLaunchInfo_ = LaunchInfo();
2117 lastLaunchInfo_.runner =
"Wine";
2120 if (game_.runnerConfig.executablePath.empty())
2122 Logger::error(
"No executable path specified for game: {}", game_.name);
2125 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
2127 Logger::error(
"Executable not found: {}", game_.runnerConfig.executablePath);
2132 std::string winePrefix;
2133 if (!game_.runnerConfig.winePrefix.empty())
2135 winePrefix = game_.runnerConfig.winePrefix;
2139 const char* home = std::getenv(
"HOME");
2142 std::string safeName = game_.name;
2143 for (
char& c : safeName)
2145 if (!std::isalnum(
static_cast<unsigned char>(c)))
2148 winePrefix = std::string(home) +
"/Games/wine-prefixes/" + safeName;
2151 lastLaunchInfo_.winePrefix = winePrefix;
2159 bool freshPrefixNeedsInit =
false;
2160 if (!winePrefix.empty())
2164 if (!std::filesystem::exists(winePrefix))
2166 std::filesystem::create_directories(winePrefix);
2167 Logger::info(
"Created Wine prefix directory: {}", winePrefix);
2168 freshPrefixNeedsInit =
true;
2170 else if (!std::filesystem::exists(std::filesystem::path(winePrefix) /
"system.reg"))
2173 freshPrefixNeedsInit =
true;
2176 catch (
const std::exception& e)
2178 Logger::warn(
"Failed to create Wine prefix directory: {}", e.what());
2182 if (freshPrefixNeedsInit && !winePrefix.empty())
2188 const std::string bootCmd =
2190 Logger::info(
"Initialising fresh Wine prefix via wineboot -u …");
2191 const int rc = std::system(bootCmd.c_str());
2194 Logger::warn(
"wineboot -u returned rc={}; continuing with lazy init", rc);
2200 int customEnvCount = 0;
2201 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
2204 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
2210 Logger::warn(
"Skipping invalid environment variable name: {}", key);
2219 lastLaunchInfo_.customEnvVars = customEnvCount;
2222 if (!winePrefix.empty())
2230 cmd <<
"WINEARCH=win64 ";
2233 if (game_.runnerConfig.environmentVariables.find(
"WINEDEBUG") ==
2234 game_.runnerConfig.environmentVariables.end())
2236 cmd <<
"WINEDEBUG=-all ";
2240 if (!game_.runnerConfig.wineDLL.empty())
2248 if (game_.runnerConfig.autoDetectSync)
2252 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
2253 lastLaunchInfo_.syncMethod =
"NTSync";
2254 Logger::info(
"Using NTSync (auto-detected kernel support)");
2258 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
2259 lastLaunchInfo_.syncMethod =
"Fsync";
2260 Logger::info(
"Using Fsync (auto-detected kernel support)");
2264 cmd <<
"WINEESYNC=1 ";
2265 lastLaunchInfo_.syncMethod =
"Esync";
2266 Logger::info(
"Using Esync (kernel doesn't support Fsync)");
2269 else if (game_.runnerConfig.enableFsync)
2271 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
2272 lastLaunchInfo_.syncMethod =
"Fsync";
2278 lastLaunchInfo_.gpuVendor = gpu;
2282 cmd <<
"ENABLE_LAYER_MESA_ANTI_LAG=1 ";
2283 lastLaunchInfo_.amdAntiLag =
true;
2286 else if (gpu ==
"NVIDIA")
2288 cmd <<
"DXVK_ENABLE_NVAPI=1 ";
2289 lastLaunchInfo_.nvidiaNvapi =
true;
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)));
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);
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");
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);
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");
2330 if (game_.runnerConfig.enableDetailedLogging)
2332 cmd <<
"WINEDEBUG=+loaddll,+seh ";
2339 if (game_.runnerConfig.enableGamePerformance &&
isWrapperAvailable(
"game-performance"))
2341 cmd <<
"game-performance ";
2342 lastLaunchInfo_.gamePerformance =
true;
2343 Logger::info(
"Using game-performance wrapper (outermost)");
2348 cmd <<
"gamemoderun ";
2349 lastLaunchInfo_.gameMode =
true;
2354 Logger::info(
"Skipping gamemoderun — ananicy-cpp.service is active");
2359 if (!game_.runnerConfig.enableGamescope)
2362 game_.id, game_.runnerConfig.mangoHudConfigFile);
2363 if (!cfgPath.empty())
2367 if (game_.runnerConfig.enableMangoHud)
2369 cmd <<
"MANGOHUD=1 ";
2370 lastLaunchInfo_.mangoHud =
true;
2371 Logger::info(
"Using MangoHud performance overlay (config: {})", cfgPath);
2375 if (game_.runnerConfig.enableVkBasalt)
2377 cmd <<
"ENABLE_VKBASALT=1 ";
2378 lastLaunchInfo_.vkBasalt =
true;
2383 std::string gamescopeMode;
2385 if (!gamescopeWrapper.empty())
2387 cmd << gamescopeWrapper;
2388 lastLaunchInfo_.gamescope =
true;
2389 lastLaunchInfo_.gamescopeMode = gamescopeMode;
2393 std::string wineBinary =
"wine";
2396 if (!game_.runnerConfig.winePath.empty() &&
2397 std::filesystem::exists(game_.runnerConfig.winePath))
2399 wineBinary = game_.runnerConfig.winePath;
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);
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";
2415 if (std::filesystem::exists(wineLibDir) || std::filesystem::exists(wineLib32Dir))
2417 std::string libPaths;
2418 if (std::filesystem::exists(wineLibDir))
2419 libPaths += wineLibDir.string() +
":";
2420 if (std::filesystem::exists(wineLib32Dir))
2421 libPaths += wineLib32Dir.string() +
":";
2426 else if (std::filesystem::exists(
"/opt/wine-cachyos/bin/wine"))
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";
2439 lastLaunchInfo_.runnerVersion =
"system";
2443 if (game_.runnerConfig.useVirtualDesktop)
2448 << game_.runnerConfig.virtualDesktopWidth <<
"x"
2449 << game_.runnerConfig.virtualDesktopHeight <<
" ";
2460 if (!game_.runnerConfig.arguments.empty())
2467 std::string command = cmd.str();
2471 bool success = executeCommand(command);
2476 std::string summary = lastLaunchInfo_.getSummary(
false);
2483std::string GameProcess::findProtonExecutable(
const std::string& versionName)
const
2486 if (versionName.empty())
2494 for (
const auto& [name, path] : protonPaths)
2496 if (name == versionName && !path.empty())
2498 Logger::info(
"Found Proton version '{}' at: {}", versionName, path.string());
2499 return path.string();
2504 Logger::warn(
"Proton version '{}' not found, falling back to 'proton' from PATH", versionName);
2506 "Proton '" + versionName +
"' not found, using system default");
2510bool GameProcess::isUmuLauncherAvailable()
2514 static std::once_flag flag;
2515 static bool available =
false;
2517 std::call_once(flag,
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"};
2527 for (
const auto& path : umuPaths)
2529 if (!path.empty() && std::filesystem::exists(path))
2538 ProcessResult result =
2551bool GameProcess::launchProton()
2564 if (game_.metadata.isSteamGame && game_.metadata.steamAppId > 0)
2566 return launchProtonSteamGame();
2570 if (isUmuLauncherAvailable())
2572 return launchProtonWithUmu();
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();
2582bool GameProcess::launchProtonWithUmu()
2584 std::ostringstream cmd;
2602 Logger::info(
"Launching non-Steam game with umu-launcher: {}", game_.name);
2605 lastLaunchInfo_ = LaunchInfo();
2606 lastLaunchInfo_.runner =
"umu-launcher (Proton)";
2609 if (game_.runnerConfig.executablePath.empty())
2611 Logger::error(
"No executable path specified for game: {}", game_.name);
2614 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
2616 Logger::error(
"Executable not found: {}", game_.runnerConfig.executablePath);
2621 if (game_.runnerConfig.useVirtualDesktop)
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.");
2629 std::string winePrefix;
2630 const char* home = std::getenv(
"HOME");
2632 if (!game_.runnerConfig.winePrefix.empty())
2634 winePrefix = game_.runnerConfig.winePrefix;
2638 std::string safeName = game_.name;
2639 for (
char& c : safeName)
2641 if (!std::isalnum(
static_cast<unsigned char>(c)))
2644 winePrefix = std::string(home) +
"/Games/umu/" + safeName;
2646 lastLaunchInfo_.winePrefix = winePrefix;
2649 if (!winePrefix.empty())
2653 std::filesystem::path prefixPath(winePrefix);
2654 std::filesystem::path gamesDir = prefixPath.parent_path();
2655 if (!std::filesystem::exists(gamesDir))
2657 std::filesystem::create_directories(gamesDir);
2658 Logger::info(
"Created umu games directory: {}", gamesDir.string());
2661 catch (
const std::exception& e)
2663 Logger::warn(
"Failed to create umu directory: {}", e.what());
2673 int customEnvCount = 0;
2674 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
2676 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
2682 Logger::warn(
"Skipping invalid environment variable name: {}", key);
2689 lastLaunchInfo_.customEnvVars = customEnvCount;
2692 if (!winePrefix.empty())
2699 cmd <<
"WINEARCH=win64 ";
2702 if (game_.runnerConfig.environmentVariables.find(
"WINEDEBUG") ==
2703 game_.runnerConfig.environmentVariables.end())
2705 cmd <<
"WINEDEBUG=-all ";
2709 std::string dllOverrides;
2710 if (!game_.runnerConfig.wineDLL.empty())
2712 dllOverrides = game_.runnerConfig.wineDLL;
2715 if (!dllOverrides.empty())
2717 dllOverrides +=
";winemenubuilder=";
2721 dllOverrides =
"winemenubuilder=";
2729 if (game_.runnerConfig.autoDetectSync)
2734 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
2735 lastLaunchInfo_.syncMethod =
"NTSync";
2737 "Using NTSync (auto-detected kernel support, GE-Proton enables automatically)");
2741 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
2742 lastLaunchInfo_.syncMethod =
"Fsync";
2743 Logger::info(
"Using Fsync (auto-detected kernel support)");
2747 cmd <<
"WINEESYNC=1 ";
2748 lastLaunchInfo_.syncMethod =
"Esync";
2749 Logger::info(
"Using Esync (kernel doesn't support Fsync)");
2752 else if (game_.runnerConfig.enableFsync)
2754 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
2755 lastLaunchInfo_.syncMethod =
"Fsync";
2761 std::string gameId =
"umu-default";
2762 if (game_.metadata.steamAppId > 0)
2764 gameId =
"umu-" + std::to_string(game_.metadata.steamAppId);
2767 auto gameIdIt = game_.runnerConfig.environmentVariables.find(
"GAMEID");
2768 if (gameIdIt != game_.runnerConfig.environmentVariables.end() && !gameIdIt->second.empty())
2770 gameId = gameIdIt->second;
2777 if (!game_.id.empty())
2786 std::string protonPath;
2787 if (!game_.runnerConfig.protonVersion.empty())
2789 protonPath = findProtonPath(game_.runnerConfig.protonVersion);
2790 if (!protonPath.empty())
2793 lastLaunchInfo_.runnerVersion = game_.runnerConfig.protonVersion;
2798 Logger::warn(
"Proton version '{}' not found, umu-launcher will use default",
2799 game_.runnerConfig.protonVersion);
2804 if (game_.runnerConfig.environmentVariables.find(
"PROTON_VERB") ==
2805 game_.runnerConfig.environmentVariables.end())
2807 cmd <<
"PROTON_VERB=waitforexitandrun ";
2811 cmd <<
"PROTON_DXVK_D3D8=1 ";
2817 lastLaunchInfo_.gpuVendor = gpu;
2821 cmd <<
"ENABLE_LAYER_MESA_ANTI_LAG=1 ";
2822 cmd <<
"WINE_FULLSCREEN_FSR=1 ";
2823 lastLaunchInfo_.amdAntiLag =
true;
2824 Logger::info(
"Enabling AMD optimizations (Anti-Lag, FSR)");
2826 else if (gpu ==
"NVIDIA")
2828 cmd <<
"DXVK_ENABLE_NVAPI=1 ";
2829 cmd <<
"PROTON_FORCE_NVAPI=1 ";
2830 cmd <<
"WINE_FULLSCREEN_FSR=1 ";
2831 lastLaunchInfo_.nvidiaNvapi =
true;
2836 if (game_.runnerConfig.enableDetailedLogging)
2838 cmd <<
"PROTON_LOG=1 ";
2839 cmd <<
"UMU_LOG=debug ";
2840 cmd <<
"WINEDEBUG=+loaddll,+seh ";
2845 cmd <<
"UMU_LOG=1 ";
2851 if (game_.runnerConfig.enableGamePerformance &&
isWrapperAvailable(
"game-performance"))
2853 cmd <<
"game-performance ";
2854 lastLaunchInfo_.gamePerformance =
true;
2859 cmd <<
"gamemoderun ";
2860 lastLaunchInfo_.gameMode =
true;
2864 if (!game_.runnerConfig.enableGamescope)
2867 game_.id, game_.runnerConfig.mangoHudConfigFile);
2868 if (!cfgPath.empty())
2872 if (game_.runnerConfig.enableMangoHud)
2874 cmd <<
"MANGOHUD=1 ";
2875 lastLaunchInfo_.mangoHud =
true;
2880 if (game_.runnerConfig.enableVkBasalt)
2882 cmd <<
"ENABLE_VKBASALT=1 ";
2883 lastLaunchInfo_.vkBasalt =
true;
2888 std::string gamescopeMode;
2890 if (!gamescopeWrapper.empty())
2892 cmd << gamescopeWrapper;
2893 lastLaunchInfo_.gamescope =
true;
2894 lastLaunchInfo_.gamescopeMode = gamescopeMode;
2904 if (!game_.runnerConfig.arguments.empty())
2911 std::string command = cmd.str();
2915 bool success = executeCommand(command);
2919 std::string summary = lastLaunchInfo_.getSummary(
false);
2926bool GameProcess::launchProtonDirect()
2928 std::ostringstream cmd;
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.");
2944 if (game_.runnerConfig.executablePath.empty())
2946 Logger::error(
"No executable path specified for game: {}", game_.name);
2949 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
2951 Logger::error(
"Executable not found: {}", game_.runnerConfig.executablePath);
2956 std::string prefixPath;
2957 const char* home = std::getenv(
"HOME");
2959 if (!game_.runnerConfig.winePrefix.empty())
2961 prefixPath = game_.runnerConfig.winePrefix;
2965 std::string safeName = game_.name;
2966 for (
char& c : safeName)
2968 if (!std::isalnum(
static_cast<unsigned char>(c)))
2971 prefixPath = std::string(home) +
"/Games/proton-prefixes/" + safeName;
2975 if (!prefixPath.empty())
2979 if (!std::filesystem::exists(prefixPath))
2981 std::filesystem::create_directories(prefixPath);
2982 Logger::info(
"Created Proton prefix directory: {}", prefixPath);
2985 catch (
const std::exception& e)
2987 Logger::warn(
"Failed to create prefix directory: {}", e.what());
2993 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
2995 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
3001 Logger::warn(
"Skipping invalid environment variable name: {}", key);
3009 if (!prefixPath.empty())
3018 std::filesystem::path steamPath =
3019 std::filesystem::path(home) /
".local" /
"share" /
"Steam";
3020 if (std::filesystem::exists(steamPath))
3026 std::filesystem::path runtimePath = steamPath /
"ubuntu12_32" /
"steam-runtime";
3027 if (std::filesystem::exists(runtimePath))
3044 if (game_.runnerConfig.enableDetailedLogging)
3046 cmd <<
"PROTON_LOG=1 ";
3047 cmd <<
"STEAM_LINUX_RUNTIME_VERBOSE=1 ";
3053 if (!wrapperChain.empty())
3055 cmd << wrapperChain;
3059 std::string gamescopeMode;
3061 if (!gamescopeWrapper.empty())
3063 cmd << gamescopeWrapper;
3064 lastLaunchInfo_.gamescope =
true;
3065 lastLaunchInfo_.gamescopeMode = gamescopeMode;
3069 std::string protonExe;
3072 protonExe = findProtonExecutable(game_.runnerConfig.protonVersion);
3074 catch (
const std::exception& e)
3076 Logger::error(
"Failed to find Proton executable: {}", e.what());
3078 "Failed to find Proton executable. Install Proton via Steam or umu-launcher.");
3087 if (!game_.runnerConfig.arguments.empty())
3094 std::string command = cmd.str();
3098 return executeCommand(command);
3101std::string GameProcess::buildDirectProtonCommand(
const std::string& protonExe)
3103 std::ostringstream cmd;
3126 lastLaunchInfo_ = LaunchInfo{};
3127 lastLaunchInfo_.runner =
"Proton (Direct)";
3130 const char* home = std::getenv(
"HOME");
3137 std::filesystem::path steamPath = std::filesystem::path(home) /
".local" /
"share" /
"Steam";
3140 std::filesystem::path compatDataPath;
3141 std::filesystem::path gamePath = game_.runnerConfig.workingDirectory;
3144 if (!gamePath.empty())
3146 std::filesystem::path searchPath = gamePath;
3147 while (searchPath.has_parent_path() && searchPath.filename() !=
"steamapps")
3149 searchPath = searchPath.parent_path();
3151 if (searchPath.filename() ==
"steamapps")
3153 std::filesystem::path candidate =
3154 searchPath /
"compatdata" / std::to_string(game_.metadata.steamAppId);
3155 if (std::filesystem::exists(candidate))
3157 compatDataPath = candidate;
3163 if (compatDataPath.empty())
3166 steamPath /
"steamapps" /
"compatdata" / std::to_string(game_.metadata.steamAppId);
3171 cmd <<
"SteamAppId=" << game_.metadata.steamAppId <<
" ";
3172 cmd <<
"SteamGameId=" << game_.metadata.steamAppId <<
" ";
3173 lastLaunchInfo_.winePrefix = compatDataPath.string();
3178 if (game_.runnerConfig.winePrefix.empty())
3180 std::filesystem::path pfxPath = compatDataPath /
"pfx";
3181 if (std::filesystem::exists(pfxPath))
3182 game_.runnerConfig.winePrefix = pfxPath.string();
3184 game_.runnerConfig.winePrefix = compatDataPath.string();
3188 std::filesystem::path shaderPath =
3189 steamPath /
"steamapps" /
"shadercache" / std::to_string(game_.metadata.steamAppId);
3193 if (!game_.runnerConfig.enableDetailedLogging)
3195 cmd <<
"WINEDEBUG=-all ";
3199 if (game_.runnerConfig.environmentVariables.find(
"PROTON_VERB") ==
3200 game_.runnerConfig.environmentVariables.end())
3202 cmd <<
"PROTON_VERB=waitforexitandrun ";
3206 cmd <<
"PROTON_DXVK_D3D8=1 ";
3209 if (game_.runnerConfig.autoDetectSync)
3213 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
3214 lastLaunchInfo_.syncMethod =
"NTSync";
3215 Logger::info(
"Using NTSync (auto-detected kernel support)");
3219 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
3220 lastLaunchInfo_.syncMethod =
"Fsync";
3221 Logger::info(
"Using Fsync (auto-detected kernel support)");
3225 cmd <<
"WINEESYNC=1 ";
3226 lastLaunchInfo_.syncMethod =
"Esync";
3227 Logger::info(
"Using Esync (kernel doesn't support Fsync)");
3230 else if (game_.runnerConfig.enableFsync)
3232 cmd <<
"WINEFSYNC=1 WINEESYNC=1 ";
3233 lastLaunchInfo_.syncMethod =
"Fsync";
3239 lastLaunchInfo_.gpuVendor = gpu;
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)");
3248 else if (gpu ==
"NVIDIA")
3250 cmd <<
"DXVK_ENABLE_NVAPI=1 ";
3251 cmd <<
"PROTON_FORCE_NVAPI=1 ";
3252 cmd <<
"WINE_FULLSCREEN_FSR=1 ";
3253 lastLaunchInfo_.nvidiaNvapi =
true;
3258 if (game_.runnerConfig.enableDetailedLogging)
3260 cmd <<
"PROTON_LOG=1 ";
3261 cmd <<
"WINEDEBUG=+loaddll,+seh ";
3266 int customEnvCount = 0;
3267 for (
const auto& [key, value] : game_.runnerConfig.environmentVariables)
3270 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE" || key ==
"MANGOHUD" ||
3271 key ==
"ENABLE_VKBASALT" || key ==
"PROTON_VERB" || key ==
"PROTON_LOG")
3276 Logger::warn(
"Skipping invalid environment variable name: {}", key);
3283 lastLaunchInfo_.customEnvVars = customEnvCount;
3288 if (!game_.runnerConfig.enableGamescope)
3291 game_.id, game_.runnerConfig.mangoHudConfigFile);
3292 if (!cfgPath.empty())
3296 if (game_.runnerConfig.enableMangoHud)
3298 cmd <<
"MANGOHUD=1 ";
3299 lastLaunchInfo_.mangoHud =
true;
3305 if (game_.runnerConfig.enableVkBasalt)
3307 cmd <<
"ENABLE_VKBASALT=1 ";
3308 lastLaunchInfo_.vkBasalt =
true;
3313 if (!game_.id.empty())
3320 if (game_.runnerConfig.enableGamePerformance &&
isWrapperAvailable(
"game-performance"))
3322 cmd <<
"game-performance ";
3323 lastLaunchInfo_.gamePerformance =
true;
3330 cmd <<
"gamemoderun ";
3331 lastLaunchInfo_.gameMode =
true;
3336 std::string gamescopeMode;
3338 if (!gamescopeWrapper.empty())
3340 cmd << gamescopeWrapper;
3341 lastLaunchInfo_.gamescope =
true;
3342 lastLaunchInfo_.gamescopeMode = gamescopeMode;
3346 lastLaunchInfo_.runnerVersion = protonExe;
3353 if (!game_.runnerConfig.arguments.empty())
3363bool GameProcess::launchProtonSteamGame()
3392 const bool steamLaunchByDefault =
3394 if (game_.runnerConfig.useSteamLaunch || game_.runnerConfig.executablePath ==
"steam" ||
3395 steamLaunchByDefault)
3397 Logger::info(
"Launching Steam game via Steam client (App ID: {})",
3398 game_.metadata.steamAppId);
3399 return launchViaSteamApplaunch();
3403 Logger::info(
"Launching Steam Proton game directly (App ID: {}): {}", game_.metadata.steamAppId,
3404 game_.runnerConfig.executablePath);
3408 std::string protonExe = resolveProtonExecutable();
3410 if (protonExe.empty() || !std::filesystem::exists(protonExe))
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();
3419 if (!std::filesystem::exists(game_.runnerConfig.executablePath))
3421 Logger::warn(
"Game executable not found: '{}' — falling back to steam -applaunch",
3422 game_.runnerConfig.executablePath);
3423 return launchViaSteamApplaunch();
3427 if (!ensureSteamRunning())
3429 Logger::error(
"Cannot launch Steam game: Steam is not running and failed to start");
3434 std::string command = buildDirectProtonCommand(protonExe);
3435 if (command.empty())
3437 Logger::error(
"Failed to build direct Proton launch command");
3442 bool success = executeCommand(command);
3446 std::string summary = lastLaunchInfo_.getSummary(
false);
3453bool GameProcess::launchViaSteamApplaunch()
3459 int appId = game_.metadata.steamAppId;
3462 Logger::error(
"Cannot fall back to steam -applaunch: no Steam App ID");
3466 if (!ensureSteamRunning())
3468 Logger::error(
"Cannot launch Steam game: Steam is not running and failed to start");
3472 std::string command =
"steam -applaunch " + std::to_string(appId);
3473 if (!game_.runnerConfig.arguments.empty())
3478 Logger::info(
"Launching via steam -applaunch fallback: {}", command);
3479 lastLaunchInfo_ = LaunchInfo{};
3480 lastLaunchInfo_.runner =
"Steam (managed)";
3482 bool success = executeCommand(command);
3486 "Launched via Steam (App ID: " + std::to_string(appId) +
")");
3491std::string GameProcess::resolveProtonExecutable()
const
3494 const std::string& pv = game_.runnerConfig.protonVersion;
3495 if (!pv.empty() && std::filesystem::exists(pv))
3502 if (!pv.empty() && pv !=
"Proton (Steam-managed)")
3504 std::string dir = findProtonPath(pv);
3507 std::string exe = (std::filesystem::path(dir) /
"proton").
string();
3508 if (std::filesystem::exists(exe))
3510 Logger::info(
"Resolved protonVersion '{}' to: {}", pv, exe);
3517 const std::string& rv = game_.runnerConfig.runnerVersion;
3520 std::string dir = findProtonPath(rv);
3523 std::string exe = (std::filesystem::path(dir) /
"proton").
string();
3524 if (std::filesystem::exists(exe))
3526 Logger::info(
"Resolved runnerVersion '{}' to: {}", rv, exe);
3537 std::vector<std::string> searchTerms;
3538 for (
const std::string& src : {pv, rv})
3540 if (src.empty() || src ==
"Proton (Steam-managed)")
3544 std::string term = src;
3545 auto sysPos = term.find(
" (system)");
3546 if (sysPos != std::string::npos)
3547 term = term.substr(0, sysPos);
3550 searchTerms.push_back(term);
3556 for (
const auto& term : searchTerms)
3558 for (
const auto& [name, path] : protonVersions)
3565 std::string dirName = path.parent_path().filename().string();
3567 if (name.find(term) != std::string::npos || dirName.find(term) != std::string::npos)
3569 std::string exe = path.string();
3570 if (std::filesystem::exists(exe))
3572 Logger::info(
"Partial match: '{}' matched cache entry '{}' → {}", term, name,
3581 bool allTokensMatch =
true;
3582 std::istringstream tokenStream(term);
3585 while (std::getline(tokenStream, token,
'-'))
3590 if (dirName.find(token) == std::string::npos)
3592 allTokensMatch =
false;
3597 if (allTokensMatch && tokenCount >= 2)
3599 std::string exe = path.string();
3600 if (std::filesystem::exists(exe))
3602 Logger::info(
"Token match: all tokens of '{}' found in '{}' → {}", term,
3610 Logger::warn(
"Could not resolve Proton executable from protonVersion='{}', runnerVersion='{}'",
3615std::string GameProcess::findProtonPath(
const std::string& versionName)
const
3617 if (versionName.empty())
3625 for (
const auto& [name, path] : protonPaths)
3627 if (name == versionName && !path.empty())
3630 std::filesystem::path protonDir = path.parent_path();
3631 Logger::info(
"Found Proton path for '{}': {}", versionName, protonDir.string());
3632 return protonDir.string();
3636 Logger::warn(
"Proton version '{}' not found", versionName);
3640bool GameProcess::checkProcessRunning()
3649 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid_);
3650 if (hProcess == NULL)
3656 GetExitCodeProcess(hProcess, &exitCode);
3657 CloseHandle(hProcess);
3659 return (exitCode == STILL_ACTIVE);
3673 if (trackedPid_ > 0 && trackedPid_ != pid_)
3676 if (
::kill(trackedPid_, 0) == 0)
3682 Logger::info(
"Tracked game process {} has exited", trackedPid_);
3691 bool mainProcessRunning =
false;
3693 if (isAttachedProcess_)
3696 mainProcessRunning = (
::kill(pid_, 0) == 0);
3702 pid_t result = waitpid(pid_, &status, WNOHANG);
3703 mainProcessRunning = (result == 0);
3706 if (mainProcessRunning)
3710 if (!game_.runnerConfig.excludeProcesses.empty())
3712 int gameProc = findGameProcess();
3713 if (gameProc > 0 && gameProc != trackedPid_)
3716 std::string newExeName = getWineExecutableName(gameProc);
3717 bool wasNotTracking = (trackedPid_ <= 0 || trackedPid_ == pid_);
3718 trackedPid_ = gameProc;
3719 trackedProcessName_ = newExeName;
3723 Logger::info(
"Found game process to track: PID {} ({}) (launcher: {})",
3724 trackedPid_, trackedProcessName_, pid_);
3728 if (game_.runnerConfig.enableMangoHud)
3733 Logger::info(
"Restarted frame metrics for actual game process: PID {}",
3738 if (game_.runnerConfig.enableGameMode)
3741 if (gamemodePid_ > 0 && gamemodePid_ != trackedPid_)
3744 gamemodePid_ = trackedPid_;
3751 Logger::info(
"Updated tracked process: PID {} ({})", trackedPid_,
3752 trackedProcessName_);
3755 if (game_.runnerConfig.enableGameMode && gamemodePid_ != trackedPid_)
3757 if (gamemodePid_ > 0)
3760 gamemodePid_ = trackedPid_;
3775 bool hasExcludeProcesses = !game_.runnerConfig.excludeProcesses.empty();
3776 bool hasWinePrefix = !game_.runnerConfig.winePrefix.empty();
3778 if (hasExcludeProcesses || isWineGame || hasWinePrefix)
3780 int gameProc = findGameProcess();
3783 if (trackedPid_ != gameProc)
3785 trackedPid_ = gameProc;
3786 trackedProcessName_ = getWineExecutableName(gameProc);
3787 Logger::info(
"Shell/launcher exited, now tracking game process: PID {} ({})",
3788 trackedPid_, trackedProcessName_);
3791 if (game_.runnerConfig.enableGameMode)
3793 if (gamemodePid_ > 0 && gamemodePid_ != trackedPid_)
3796 gamemodePid_ = trackedPid_;
3803 Logger::info(
"Shell/launcher exited and no game processes found");
3816std::vector<int> GameProcess::getChildProcesses(
int parentPid)
const
3818 std::vector<int> children;
3824 for (
const auto& entry : std::filesystem::directory_iterator(
"/proc"))
3826 if (!entry.is_directory())
3829 std::string name = entry.path().filename().string();
3832 bool isPid = !name.empty() && std::all_of(name.begin(), name.end(), ::isdigit);
3836 int pid = std::stoi(name);
3839 std::filesystem::path statPath = entry.path() /
"stat";
3840 if (!std::filesystem::exists(statPath))
3843 std::ifstream statFile(statPath);
3844 if (!statFile.is_open())
3849 if (std::getline(statFile, line))
3852 size_t commEnd = line.rfind(
')');
3853 if (commEnd != std::string::npos && commEnd + 2 < line.size())
3856 std::istringstream iss(line.substr(commEnd + 2));
3859 if (iss >> state >> ppid)
3861 if (ppid == parentPid)
3863 children.push_back(pid);
3870 catch (
const std::exception& e)
3872 Logger::warn(
"Error reading /proc for child processes: {}", e.what());
3879std::string GameProcess::getProcessName(
int pid)
const
3882 std::filesystem::path commPath = std::filesystem::path(
"/proc") / std::to_string(pid) /
"comm";
3886 if (std::filesystem::exists(commPath))
3888 std::ifstream commFile(commPath);
3890 if (std::getline(commFile, name))
3893 while (!name.empty() && (name.back() ==
'\n' || name.back() ==
'\r'))
3901 catch (
const std::exception& e)
3903 Logger::warn(
"Error reading process name for PID {}: {}", pid, e.what());
3910bool GameProcess::isExcludedProcess(
const std::string& processName)
const
3912 if (processName.empty())
3916 std::string nameLower = processName;
3917 for (
char& c : nameLower)
3919 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
3923 std::string nameBase = nameLower;
3924 if (nameBase.size() > 4 && nameBase.substr(nameBase.size() - 4) ==
".exe")
3926 nameBase = nameBase.substr(0, nameBase.size() - 4);
3929 for (
const auto& excluded : game_.runnerConfig.excludeProcesses)
3931 std::string excludedLower = excluded;
3932 for (
char& c : excludedLower)
3934 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
3938 std::string excludeBase = excludedLower;
3939 if (excludeBase.size() > 4 && excludeBase.substr(excludeBase.size() - 4) ==
".exe")
3941 excludeBase = excludeBase.substr(0, excludeBase.size() - 4);
3945 if (nameLower == excludedLower || nameBase == excludeBase)
3952 if (nameLower.find(excludeBase) != std::string::npos)
3958 if (excludeBase.find(nameBase) != std::string::npos && !nameBase.empty())
3967std::string GameProcess::getWineExecutableName(
int pid)
const
3971 auto extractExeFromCmdline = [](
const std::string& cmdline) -> std::string
3974 while (start < cmdline.size())
3976 size_t end = cmdline.find(
'\0', start);
3977 if (end == std::string::npos)
3978 end = cmdline.size();
3980 std::string arg = cmdline.substr(start, end - start);
3983 std::string argLower = arg;
3984 for (
char& c : argLower)
3985 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
3987 if (argLower.find(
".exe") != std::string::npos)
3990 size_t lastSlash = arg.find_last_of(
"/\\");
3991 if (lastSlash != std::string::npos)
3993 return arg.substr(lastSlash + 1);
4004 auto isExcludedLauncher = [
this](
const std::string& exeName) ->
bool
4006 std::string exeNameLower = exeName;
4007 for (
char& c : exeNameLower)
4008 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
4011 std::string exeNameBase = exeNameLower;
4012 if (exeNameBase.size() > 4 && exeNameBase.substr(exeNameBase.size() - 4) ==
".exe")
4014 exeNameBase = exeNameBase.substr(0, exeNameBase.size() - 4);
4018 for (
const auto& excludeProc : game_.runnerConfig.excludeProcesses)
4020 std::string excludeLower = excludeProc;
4021 for (
char& c : excludeLower)
4022 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
4025 std::string excludeBase = excludeLower;
4026 if (excludeBase.size() > 4 && excludeBase.substr(excludeBase.size() - 4) ==
".exe")
4028 excludeBase = excludeBase.substr(0, excludeBase.size() - 4);
4032 if (exeNameLower == excludeLower || exeNameBase == excludeBase)
4037 if (exeNameLower.find(excludeBase) != std::string::npos)
4042 if (excludeBase.find(exeNameBase) != std::string::npos && !exeNameBase.empty())
4053 std::vector<std::string> gameExeCandidates;
4054 std::vector<std::string> launcherCandidates;
4056 if (!game_.runnerConfig.winePrefix.empty())
4060 for (
const auto& entry : std::filesystem::directory_iterator(
"/proc"))
4064 if (!entry.is_directory())
4067 std::string dirName = entry.path().filename().string();
4069 !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
4074 std::filesystem::path environPath = entry.path() /
"environ";
4075 if (!std::filesystem::exists(environPath))
4078 std::ifstream environFile(environPath, std::ios::binary);
4079 if (!environFile.is_open())
4082 constexpr size_t kMaxEnviron = 1u << 20;
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()));
4088 std::string prefixKey =
"WINEPREFIX=";
4089 size_t pos = procEnviron.find(prefixKey);
4090 if (pos == std::string::npos)
4093 size_t valueStart = pos + prefixKey.size();
4094 size_t valueEnd = procEnviron.find(
'\0', valueStart);
4095 if (valueEnd == std::string::npos)
4097 std::string prefixValue = procEnviron.substr(valueStart, valueEnd - valueStart);
4100 while (!prefixValue.empty() && prefixValue.back() ==
'/')
4101 prefixValue.pop_back();
4103 std::string gamePrefix = game_.runnerConfig.winePrefix;
4104 while (!gamePrefix.empty() && gamePrefix.back() ==
'/')
4105 gamePrefix.pop_back();
4109 (prefixValue == gamePrefix) || (prefixValue.find(gamePrefix +
"/") == 0);
4114 std::filesystem::path scanCmdlinePath = entry.path() /
"cmdline";
4115 if (!std::filesystem::exists(scanCmdlinePath))
4118 std::ifstream scanCmdlineFile(scanCmdlinePath, std::ios::binary);
4119 std::string scanCmdline((std::istreambuf_iterator<char>(scanCmdlineFile)),
4120 std::istreambuf_iterator<char>());
4122 std::string exeName = extractExeFromCmdline(scanCmdline);
4123 if (exeName.empty())
4127 std::string exeNameLower = exeName;
4128 for (
char& c : exeNameLower)
4129 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
4131 bool isWineSystemExe =
false;
4134 if (exeNameLower == sysExe)
4136 isWineSystemExe =
true;
4141 if (isWineSystemExe)
4145 if (isExcludedLauncher(exeName))
4148 bool alreadyHave =
false;
4149 for (
const auto& existing : launcherCandidates)
4151 if (existing == exeName)
4160 launcherCandidates.push_back(exeName);
4166 bool alreadyHave =
false;
4167 for (
const auto& existing : gameExeCandidates)
4169 if (existing == exeName)
4178 gameExeCandidates.push_back(exeName);
4189 catch (
const std::exception& e)
4191 Logger::debug(
"Error scanning Wine processes for exe name: {}", e.what());
4196 if (!gameExeCandidates.empty())
4198 Logger::info(
"Detected running game: '{}'", gameExeCandidates[0]);
4199 return gameExeCandidates[0];
4203 if (!launcherCandidates.empty())
4205 Logger::debug(
"No game exe found, using launcher: '{}'", launcherCandidates[0]);
4206 return launcherCandidates[0];
4210 std::filesystem::path cmdlinePath =
4211 std::filesystem::path(
"/proc") / std::to_string(pid) /
"cmdline";
4214 if (std::filesystem::exists(cmdlinePath))
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())
4240 return getProcessName(pid);
4243int GameProcess::findGameProcess()
const
4257 std::vector<int> candidates;
4260 if (!game_.runnerConfig.winePrefix.empty())
4264 for (
const auto& entry : std::filesystem::directory_iterator(
"/proc"))
4268 if (!entry.is_directory())
4271 std::string dirName = entry.path().filename().string();
4273 !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
4277 int pid = std::stoi(dirName);
4280 std::string name = getProcessName(pid);
4286 if (name ==
"wineserver")
4289 bool isWineProcess =
4290 (name ==
"wine" || name ==
"wine64" || name ==
"wine-preloader" ||
4291 name ==
"wine64-preloader" || name.find(
"wine") != std::string::npos);
4297 std::filesystem::path environPath = entry.path() /
"environ";
4298 if (!std::filesystem::exists(environPath))
4301 std::ifstream environFile(environPath, std::ios::binary);
4302 if (!environFile.is_open())
4306 constexpr size_t kMaxEnviron = 1u << 20;
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()));
4313 std::string prefixKey =
"WINEPREFIX=";
4314 size_t pos = procEnviron.find(prefixKey);
4315 if (pos != std::string::npos)
4317 size_t valueStart = pos + prefixKey.size();
4318 size_t valueEnd = procEnviron.find(
'\0', valueStart);
4319 if (valueEnd == std::string::npos)
4321 std::string prefixValue =
4322 procEnviron.substr(valueStart, valueEnd - valueStart);
4325 while (!prefixValue.empty() && prefixValue.back() ==
'/')
4326 prefixValue.pop_back();
4328 std::string gamePrefix = game_.runnerConfig.winePrefix;
4329 while (!gamePrefix.empty() && gamePrefix.back() ==
'/')
4330 gamePrefix.pop_back();
4336 bool prefixMatch = (prefixValue == gamePrefix) ||
4337 (prefixValue.find(gamePrefix +
"/") == 0);
4340 candidates.push_back(pid);
4341 Logger::debug(
"Found Wine process using our prefix: PID {} ({})", pid,
4353 catch (
const std::exception& e)
4355 Logger::warn(
"Error scanning for Wine processes: {}", e.what());
4360 std::set<int> visited;
4361 std::vector<int> toProcess = {pid_};
4363 while (!toProcess.empty())
4365 int current = toProcess.back();
4366 toProcess.pop_back();
4368 if (visited.count(current) > 0)
4370 visited.insert(current);
4372 std::vector<int> children = getChildProcesses(current);
4373 for (
int child : children)
4375 toProcess.push_back(child);
4377 std::string name = getProcessName(child);
4378 if (!name.empty() && !isExcludedProcess(name))
4380 if (
::kill(child, 0) == 0)
4382 candidates.push_back(child);
4383 Logger::debug(
"Found candidate child process: PID {} ({})", child, name);
4390 auto getExeFromCmdline = [](
int pid) -> std::string
4392 std::filesystem::path cmdlinePath =
4393 std::filesystem::path(
"/proc") / std::to_string(pid) /
"cmdline";
4396 if (!std::filesystem::exists(cmdlinePath))
4399 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
4400 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
4401 std::istreambuf_iterator<char>());
4405 while (start < cmdline.size())
4407 size_t end = cmdline.find(
'\0', start);
4408 if (end == std::string::npos)
4409 end = cmdline.size();
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)));
4416 if (argLower.find(
".exe") != std::string::npos)
4418 size_t lastSlash = arg.find_last_of(
"/\\");
4419 if (lastSlash != std::string::npos)
4420 return arg.substr(lastSlash + 1);
4436 std::vector<int> gameCandidates;
4437 std::vector<int> launcherCandidates;
4439 for (
int pid : candidates)
4441 std::string exeName = getExeFromCmdline(pid);
4442 if (exeName.empty())
4445 std::string exeNameLower = exeName;
4446 for (
char& c : exeNameLower)
4447 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
4450 bool isSystemExe =
false;
4453 if (exeNameLower == sysExe)
4463 bool isLauncher =
false;
4464 for (
const auto& excludeProc : game_.runnerConfig.excludeProcesses)
4466 std::string excludeLower = excludeProc;
4467 for (
char& c : excludeLower)
4468 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
4470 if (exeNameLower.find(excludeLower) != std::string::npos)
4473 Logger::debug(
"Found launcher process: PID {} ({})", pid, exeName);
4480 launcherCandidates.push_back(pid);
4484 Logger::debug(
"Found game process candidate: PID {} ({})", pid, exeName);
4485 gameCandidates.push_back(pid);
4490 if (!gameCandidates.empty())
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();
4500 if (!launcherCandidates.empty())
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();
4513void GameProcess::killWinePrefix(
bool force)
const
4516 if (game_.runnerConfig.winePrefix.empty())
4521 int signal = force ? SIGKILL : SIGTERM;
4522 const char* signalName = force ?
"SIGKILL" :
"SIGTERM";
4523 int killedCount = 0;
4527 for (
const auto& entry : std::filesystem::directory_iterator(
"/proc"))
4529 if (!entry.is_directory())
4532 std::string dirName = entry.path().filename().string();
4533 bool isPid = !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
4537 int pid = std::stoi(dirName);
4540 if (pid == getpid())
4544 std::filesystem::path environPath = entry.path() /
"environ";
4545 if (!std::filesystem::exists(environPath))
4548 std::ifstream environFile(environPath, std::ios::binary);
4549 if (!environFile.is_open())
4552 constexpr size_t kMaxEnviron = 1u << 20;
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()));
4558 std::string prefixKey =
"WINEPREFIX=";
4559 size_t pos = procEnviron.find(prefixKey);
4560 if (pos != std::string::npos)
4562 size_t valueStart = pos + prefixKey.size();
4563 size_t valueEnd = procEnviron.find(
'\0', valueStart);
4564 if (valueEnd == std::string::npos)
4566 std::string prefixValue = procEnviron.substr(valueStart, valueEnd - valueStart);
4569 while (!prefixValue.empty() && prefixValue.back() ==
'/')
4570 prefixValue.pop_back();
4572 std::string gamePrefix = game_.runnerConfig.winePrefix;
4573 while (!gamePrefix.empty() && gamePrefix.back() ==
'/')
4574 gamePrefix.pop_back();
4577 (prefixValue == gamePrefix) || (prefixValue.find(gamePrefix +
"/") == 0);
4580 std::string processName = getProcessName(pid);
4581 Logger::debug(
"Sending {} to Wine process: PID {} ({})", signalName, pid,
4589 catch (
const std::exception& e)
4591 Logger::warn(
"Error killing Wine processes: {}", e.what());
4594 if (killedCount > 0)
4596 Logger::info(
"Sent {} to {} Wine processes in prefix: {}", signalName, killedCount,
4597 game_.runnerConfig.winePrefix);
4631 std::lock_guard<std::mutex> lock(callbacksMutex_);
4632 onNotification_ = std::move(callback);
4636 std::function<
void(
const std::string& gameId)> callback)
4638 std::lock_guard<std::mutex> lock(callbacksMutex_);
4639 onGameStatsUpdated_ = std::move(callback);
4645 std::lock_guard<std::mutex> lock(callbacksMutex_);
4646 return onNotification_;
4651 std::lock_guard<std::mutex> lock(callbacksMutex_);
4652 return onGameStatsUpdated_;
4659GameProcessManager::GameProcessManager() : shouldStopDetection_(false)
4661 Logger::info(
"GameProcessManager: Starting background detection thread...");
4663 detectionThread_ = std::thread(&GameProcessManager::detectionThreadFunction,
this);
4666GameProcessManager::~GameProcessManager()
4668 Logger::info(
"GameProcessManager: Stopping background detection thread...");
4670 shouldStopDetection_ =
true;
4673 if (detectionThread_.joinable())
4675 detectionThread_.join();
4685 static GameProcessManager
instance;
4717 if (!ensureSteamRunning())
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");
4736 const bool steamLaunchByDefault =
4743 if (canDirectLaunch)
4745 Logger::info(
"Using direct Proton launch for Steam game (App ID: {})", steamAppId);
4749 auto process = std::make_unique<GameProcess>(game);
4750 process->setOnExit([
this, gameId](
int code) { storeExitCode(gameId, code); });
4751 bool success = process->launch();
4764 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4765 runningProcesses_[gameId] = std::move(process);
4771 Logger::info(
"Direct Proton launch successful for Steam game (App ID: {})",
4777 Logger::warn(
"Direct Proton launch failed for Steam game (App ID: {}), "
4778 "falling back to steam -applaunch",
4787 Logger::info(
"Launching via steam -applaunch (App ID: {})", steamAppId);
4789 std::string command =
"steam -applaunch " + std::to_string(steamAppId);
4812 "Failed to launch Steam game: " + game.
name);
4819 std::lock_guard<std::mutex> lock(steamGamesMutex_);
4820 runningSteamGames_[steamAppId] = gameId;
4825 std::lock_guard<std::mutex> lock(steamStartTimesMutex_);
4826 steamGameStartTimes_[steamAppId] = time(
nullptr);
4839 "Steam game launch command executed. Background thread will detect when it starts.");
4844 auto process = std::make_unique<GameProcess>(game);
4845 process->setOnExit([
this, gameId](
int code) { storeExitCode(gameId, code); });
4848 bool success = process->launch();
4855 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4856 runningProcesses_[gameId] = std::move(process);
4868 std::lock_guard<std::mutex> lock(steamGamesMutex_);
4870 for (
auto it = runningSteamGames_.begin(); it != runningSteamGames_.end(); ++it)
4872 if (it->second == gameId)
4874 steamAppId = it->first;
4876 runningSteamGames_.erase(it);
4884 Logger::info(
"Stopping Steam game: {} (App ID: {})", gameId, steamAppId);
4887 if (game !=
nullptr)
4889 time_t startTime = 0;
4891 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
4892 auto it = steamGameStartTimes_.find(steamAppId);
4893 if (it != steamGameStartTimes_.end())
4895 startTime = it->second;
4896 steamGameStartTimes_.erase(it);
4902 time_t now = time(
nullptr);
4903 double sessionTime = difftime(now, startTime);
4908 static_cast<int>(sessionTime),
4914 bool killed = killSteamGame(steamAppId);
4921 Logger::info(
"Successfully stopped Steam game: {}", gameId);
4925 Logger::warn(
"Failed to stop Steam game (it may have already exited): {}", gameId);
4933 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4934 auto it = runningProcesses_.find(gameId);
4935 if (it == runningProcesses_.end())
4940 bool success = force ? it->second->kill() : it->second->stop();
4946 runningProcesses_.erase(it);
4956 std::lock_guard<std::mutex> lock(steamGamesMutex_);
4958 for (
const auto& [appId, trackedGameId] : runningSteamGames_)
4960 if (trackedGameId == gameId)
4969 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4970 return runningProcesses_.find(gameId) != runningProcesses_.end();
4976 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4977 auto it = runningProcesses_.find(gameId);
4978 if (it != runningProcesses_.end())
4980 return it->second.get();
4988 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
4989 auto it = runningProcesses_.find(gameId);
4990 if (it == runningProcesses_.end())
5004 std::vector<std::string> ids;
5008 std::lock_guard<std::mutex> lock(steamGamesMutex_);
5009 for (
const auto& [appId, gameId] : runningSteamGames_)
5011 ids.push_back(gameId);
5017 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5018 for (
const auto& [
id, process] : runningProcesses_)
5031 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5032 auto it = runningProcesses_.find(gameId);
5033 if (it != runningProcesses_.end() && it->second)
5035 double runningSeconds = it->second->getRunningTimeSeconds();
5036 if (runningSeconds > 0)
5038 return std::chrono::seconds(
static_cast<long long>(runningSeconds));
5045 int matchedSteamAppId = 0;
5047 std::lock_guard<std::mutex> steamLock(steamGamesMutex_);
5048 for (
const auto& [steamAppId,
id] : runningSteamGames_)
5052 matchedSteamAppId = steamAppId;
5058 if (matchedSteamAppId > 0)
5060#ifdef PLATFORM_LINUX
5062 std::string findCmd =
5063 "pgrep -o -f '^/.*reaper SteamLaunch AppId=" + std::to_string(matchedSteamAppId) +
5069 if (fgets(buffer,
sizeof(buffer), pipe.
get()) !=
nullptr)
5071 std::string pidStr(buffer);
5072 pidStr.erase(pidStr.find_last_not_of(
"\n\r") + 1);
5073 if (!pidStr.empty())
5075 int reaperPid = std::stoi(pidStr);
5078 time_t procStartTime = getProcessStartTimeFromProc(reaperPid);
5079 if (procStartTime > 0)
5081 time_t now = time(
nullptr);
5082 double sessionTime = difftime(now, procStartTime);
5083 if (sessionTime > 0)
5085 return std::chrono::seconds(
static_cast<long long>(sessionTime));
5094 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5095 auto timeIt = steamGameStartTimes_.find(matchedSteamAppId);
5096 if (timeIt != steamGameStartTimes_.end() && timeIt->second > 0)
5098 time_t now = time(
nullptr);
5099 double sessionTime = difftime(now, timeIt->second);
5100 return std::chrono::seconds(
static_cast<long long>(sessionTime));
5104 return std::chrono::seconds(0);
5107void GameProcessManager::storeExitCode(
const std::string& gameId,
int code)
5109 std::lock_guard<std::mutex> lock(exitCodesMutex_);
5110 lastExitCodes_[gameId] = code;
5115 std::lock_guard<std::mutex> lock(exitCodesMutex_);
5116 auto it = lastExitCodes_.find(gameId);
5117 return (it != lastExitCodes_.end()) ? it->second : defaultCode;
5124void GameProcessManager::detectionThreadFunction()
5128 while (!shouldStopDetection_)
5131 std::string findCmd =
"pgrep -a -f '/reaper SteamLaunch AppId=' 2>/dev/null";
5135 std::map<int, bool> discoveredAppIds;
5141 while (fgets(buffer,
sizeof(buffer), pipe.get()) !=
nullptr)
5143 std::string line(buffer);
5147 if (line.find(
"reaper SteamLaunch") == std::string::npos)
5155 size_t appIdPos = line.find(
"AppId=");
5156 if (appIdPos != std::string::npos)
5158 constexpr size_t kAppIdPrefix = 6;
5159 const char* numStart = line.c_str() + appIdPos + kAppIdPrefix;
5160 char* end =
nullptr;
5162 const long parsed = std::strtol(numStart, &end, 10);
5163 if (end != numStart && errno == 0 && parsed > 0 &&
5164 parsed <= std::numeric_limits<int>::max())
5166 discoveredAppIds[
static_cast<int>(parsed)] =
true;
5180 std::string envCmd =
"grep -rl 'SteamAppId=' /proc/*/environ 2>/dev/null"
5182 PipeHandle envPipe(envCmd,
"r");
5186 while (fgets(buffer,
sizeof(buffer), envPipe.get()) !=
nullptr)
5188 std::string procPath(buffer);
5190 if (!procPath.empty() && procPath.back() ==
'\n')
5191 procPath.pop_back();
5195 size_t procPos = procPath.find(
"/proc/");
5196 size_t envPos = procPath.find(
"/environ");
5197 if (procPos != std::string::npos && envPos != std::string::npos)
5199 pidStr = procPath.substr(procPos + 6, envPos - procPos - 6);
5203 if (!pidStr.empty())
5205 std::string cmdlinePath =
"/proc/" + pidStr +
"/cmdline";
5206 std::ifstream cmdFile(cmdlinePath, std::ios::binary);
5209 std::string cmdline((std::istreambuf_iterator<char>(cmdFile)),
5210 std::istreambuf_iterator<char>());
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)
5225 if (cmdline.find(helper) != std::string::npos)
5238 std::ifstream envFile(procPath, std::ios::binary);
5241 constexpr size_t kMaxEnviron = 1u << 20;
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)
5251 constexpr size_t kSteamAppIdPrefix = 11;
5252 const char* numStart = envData.c_str() + pos + kSteamAppIdPrefix;
5253 char* end =
nullptr;
5255 const long parsed = std::strtol(numStart, &end, 10);
5256 if (end != numStart && errno == 0 && parsed > 0 &&
5257 parsed <= std::numeric_limits<int>::max())
5259 discoveredAppIds[
static_cast<int>(parsed)] =
true;
5270 std::lock_guard<std::mutex> lock(steamGamesMutex_);
5273 std::vector<int> appIdsToRemove;
5274 for (
const auto& [steamAppId, gameId] : runningSteamGames_)
5276 if (discoveredAppIds.find(steamAppId) == discoveredAppIds.end())
5281 time_t gameStartTime = 0;
5283 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5284 auto it = steamGameStartTimes_.find(steamAppId);
5285 if (it != steamGameStartTimes_.end())
5287 gameStartTime = it->second;
5293 time_t now = time(
nullptr);
5294 double timeSinceLaunch = difftime(now, gameStartTime);
5295 if (timeSinceLaunch < 15.0)
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));
5305 Logger::info(
"[Detection] Game stopped: {} (App ID: {})", gameId,
5307 appIdsToRemove.push_back(steamAppId);
5312 for (
const auto& steamAppId : appIdsToRemove)
5315 std::string gameId = runningSteamGames_[steamAppId];
5324 time_t startTime = 0;
5326 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5327 auto it = steamGameStartTimes_.find(steamAppId);
5328 if (it != steamGameStartTimes_.end())
5330 startTime = it->second;
5331 steamGameStartTimes_.erase(it);
5338 std::string exitReason = detectSteamGameExitReason(steamAppId, startTime);
5341 if (getGameCallback_)
5343 time_t now = time(
nullptr);
5344 double sessionTime = difftime(now, startTime);
5347 double baseline = -1.0;
5348 auto baseIt = steamGameBasePlaytime_.find(steamAppId);
5349 if (baseIt != steamGameBasePlaytime_.end())
5351 baseline = baseIt->second;
5352 steamGameBasePlaytime_.erase(baseIt);
5355 bool statsUpdated =
false;
5360 if (baseline >= 0.0)
5362 baseline + sessionTime;
5371 if (exitReason ==
"crash")
5374 Logger::warn(
"[Detection] Game crashed! Total crashes: {}",
5379 "[Detection] Updated playtime for {}: +{}s (total: {}s) "
5381 game.
name,
static_cast<int>(sessionTime),
5384 statsUpdated =
true;
5398 runningSteamGames_.erase(steamAppId);
5403 std::map<int, std::string> discoveredGames;
5405 std::lock_guard<std::mutex> mapLock(appIdMapMutex_);
5406 for (
const auto& [steamAppId, gameId] : steamAppIdToGameId_)
5409 if (discoveredAppIds.find(steamAppId) != discoveredAppIds.end())
5411 discoveredGames[steamAppId] = gameId;
5417 for (
const auto& [steamAppId, gameId] : discoveredGames)
5419 auto existingEntry = runningSteamGames_.find(steamAppId);
5420 if (existingEntry == runningSteamGames_.end())
5429 std::lock_guard<std::mutex> procLock(runningProcessesMutex_);
5430 if (runningProcesses_.find(gameId) != runningProcesses_.end())
5432 Logger::debug(
"[Detection] Skipping App ID {} — already tracked "
5433 "via direct process for game {}",
5434 steamAppId, gameId);
5440 Logger::info(
"[Detection] Game started: App ID {} -> Game ID {}",
5441 steamAppId, gameId);
5442 runningSteamGames_[steamAppId] = gameId;
5446 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5447 steamGameStartTimes_[steamAppId] = time(
nullptr);
5454 if (getGameCallback_)
5456 int appIdCopy = steamAppId;
5457 getGameCallback_(gameId,
5458 [&, appIdCopy](
Game& game)
5460 steamGameBasePlaytime_[appIdCopy] =
5474 else if (existingEntry->second != gameId)
5477 Logger::info(
"[Detection] Updating game ID for App ID {} from {} to {}",
5478 steamAppId, existingEntry->second, gameId);
5479 existingEntry->second = gameId;
5492 time_t heartbeatNow = time(
nullptr);
5493 if (difftime(heartbeatNow, lastSteamHeartbeat_) >= 60.0)
5495 lastSteamHeartbeat_ = heartbeatNow;
5497 std::lock_guard<std::mutex> steamLock(steamGamesMutex_);
5498 for (
const auto& [steamAppId, gameId] : runningSteamGames_)
5500 time_t startTime = 0;
5502 std::lock_guard<std::mutex> timeLock(steamStartTimesMutex_);
5503 auto it = steamGameStartTimes_.find(steamAppId);
5504 if (it != steamGameStartTimes_.end())
5506 startTime = it->second;
5510 if (startTime <= 0 || !getGameCallback_)
5513 auto baseIt = steamGameBasePlaytime_.find(steamAppId);
5514 if (baseIt == steamGameBasePlaytime_.end())
5517 double sessionTime = difftime(heartbeatNow, startTime);
5518 double newTotal = baseIt->second + sessionTime;
5519 time_t hbNow = heartbeatNow;
5521 bool statsUpdated =
false;
5528 Logger::debug(
"[Heartbeat] Persisted Steam playtime for {} "
5529 "(session: {}s, total: {}s)",
5530 game.
name,
static_cast<int>(sessionTime),
5532 statsUpdated =
true;
5550 std::this_thread::sleep_for(std::chrono::seconds(1));
5561void GameProcessManager::scanForRunningWineGames(
const std::vector<Game*>& games)
5564 Logger::info(
"[Detection] Scanning for already-running Wine/Proton games...");
5568 for (
const auto* game : games)
5583 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5584 if (runningProcesses_.find(game->
id) != runningProcesses_.end())
5589 bool foundRunning =
false;
5591 std::string foundExeName;
5595 for (
const auto& entry : std::filesystem::directory_iterator(
"/proc"))
5597 if (!entry.is_directory())
5600 std::string dirName = entry.path().filename().string();
5602 !dirName.empty() && std::all_of(dirName.begin(), dirName.end(), ::isdigit);
5606 int pid = std::stoi(dirName);
5609 std::filesystem::path environPath = entry.path() /
"environ";
5610 if (!std::filesystem::exists(environPath))
5613 std::ifstream environFile(environPath, std::ios::binary);
5614 if (!environFile.is_open())
5617 constexpr size_t kMaxEnviron = 1u << 20;
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()));
5624 std::string prefixKey =
"WINEPREFIX=";
5625 size_t pos = procEnviron.find(prefixKey);
5626 if (pos == std::string::npos)
5629 size_t valueStart = pos + prefixKey.size();
5630 size_t valueEnd = procEnviron.find(
'\0', valueStart);
5631 if (valueEnd == std::string::npos)
5633 std::string prefixValue = procEnviron.substr(valueStart, valueEnd - valueStart);
5636 while (!prefixValue.empty() && prefixValue.back() ==
'/')
5637 prefixValue.pop_back();
5640 while (!gamePrefix.empty() && gamePrefix.back() ==
'/')
5641 gamePrefix.pop_back();
5648 bool prefixMatch = (prefixValue == gamePrefix) ||
5649 (prefixValue.find(gamePrefix +
"/") == 0) ||
5650 (gamePrefix.find(prefixValue +
"/") == 0);
5655 std::filesystem::path cmdlinePath = entry.path() /
"cmdline";
5656 if (std::filesystem::exists(cmdlinePath))
5658 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
5659 std::string cmdline((std::istreambuf_iterator<char>(cmdlineFile)),
5660 std::istreambuf_iterator<char>());
5664 while (start < cmdline.size())
5666 size_t end = cmdline.find(
'\0', start);
5667 if (end == std::string::npos)
5668 end = cmdline.size();
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)));
5675 if (argLower.find(
".exe") != std::string::npos)
5678 size_t lastSlash = arg.find_last_of(
"/\\");
5679 std::string exeName =
5680 (lastSlash != std::string::npos) ? arg.substr(lastSlash + 1) : arg;
5683 std::string exeLower = exeName;
5684 for (
char& c : exeLower)
5685 c =
static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
5687 bool isSystem =
false;
5690 if (exeLower == sysExe)
5699 foundRunning =
true;
5701 foundExeName = exeName;
5713 catch (
const std::exception& e)
5715 Logger::debug(
"[Detection] Error scanning for Wine games: {}", e.what());
5720 Logger::info(
"[Detection] Found running Wine game: {} (PID: {}, exe: {})", game->
name,
5721 foundPid, foundExeName);
5724 Game gameCopy = *game;
5725 auto process = std::make_unique<GameProcess>(gameCopy);
5726 process->attachToRunningProcess(foundPid, foundExeName);
5729 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5730 runningProcesses_[game->
id] = std::move(process);
5739 Logger::info(
"[Detection] Found {} already-running Wine/Proton games", foundCount);
5751 Logger::info(
"Initializing game library cache for background thread...");
5755 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5756 getGameCallback_ = std::move(getGameCallback);
5761 std::lock_guard<std::mutex> lock(appIdMapMutex_);
5762 steamAppIdToGameId_.clear();
5764 for (
const auto* game : games)
5772 Logger::info(
"[Detection] Registered {} Steam games for detection (total {} games)",
5773 steamAppIdToGameId_.size(), games.size());
5779 std::lock_guard<std::mutex> lock(steamGamesMutex_);
5780 std::lock_guard<std::mutex> mapLock(appIdMapMutex_);
5783 std::vector<std::pair<int, std::string>> updates;
5784 for (
const auto& [steamAppId, gameId] : runningSteamGames_)
5786 auto it = steamAppIdToGameId_.find(steamAppId);
5787 if (it != steamAppIdToGameId_.end())
5790 if (it->second != gameId)
5792 Logger::info(
"Updating tracked game ID for App ID {} from {} to {}", steamAppId,
5793 gameId, it->second);
5794 updates.push_back({steamAppId, it->second});
5802 for (
const auto& [steamAppId, newGameId] : updates)
5804 runningSteamGames_[steamAppId] = newGameId;
5808 Logger::info(
"Game library cache updated with {} games.", games.size());
5809 Logger::info(
"Background detection thread will continuously monitor for running games.");
5813 scanForRunningWineGames(games);
5826 std::vector<std::string> toRemove;
5827 std::vector<std::pair<std::string, GameStatistics>> stoppedGameStats;
5830 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5831 for (
auto& [
id, process] : runningProcesses_)
5833 bool wasRunning = process->isRunning();
5837 if (wasRunning && !process->isRunning())
5840 stoppedGameStats.push_back({id, process->getGame().statistics});
5841 toRemove.push_back(
id);
5846 for (
const auto&
id : toRemove)
5848 runningProcesses_.erase(
id);
5853 for (
size_t i = 0; i < toRemove.size(); i++)
5859 for (
const auto& entry : stoppedGameStats)
5861 const std::string& gameId = entry.first;
5863 if (getGameCallback_)
5865 bool statsUpdated =
false;
5872 Logger::info(
"Updated playtime for {}: total {}s, last played {}", game.
name,
5875 statsUpdated =
true;
5893 time_t now = time(
nullptr);
5894 if (difftime(now, lastHeartbeat_) >= 60.0)
5896 lastHeartbeat_ = now;
5898 std::lock_guard<std::mutex> lock(runningProcessesMutex_);
5899 for (
const auto& procEntry : runningProcesses_)
5901 const std::string&
id = procEntry.first;
5902 const auto& process = procEntry.second;
5904 if (!process->isRunning())
5907 double sessionTime = process->getRunningTimeSeconds();
5908 if (sessionTime <= 0.0 || !getGameCallback_)
5914 double baseline = process->getGame().statistics.totalPlayTimeSeconds;
5915 double newTotal = baseline + sessionTime;
5918 bool statsUpdated =
false;
5925 Logger::debug(
"Heartbeat: persisted playtime for {} (session: {}s, total: {}s)",
5926 game.
name,
static_cast<int>(sessionTime),
5928 statsUpdated =
true;
5946bool GameProcessManager::isSteamRunning()
const
5951bool GameProcessManager::ensureSteamRunning()
5953 if (isSteamRunning())
5975 for (
int i = 0; i < 10; i++)
5977 std::this_thread::sleep_for(std::chrono::seconds(1));
5978 if (isSteamRunning())
5989std::string GameProcessManager::detectSteamGameExitReason(
int steamAppId, time_t startTime)
const
5994 time_t now = time(
nullptr);
5995 double sessionDuration = difftime(now, startTime);
5998 if (sessionDuration < 10.0)
6000 Logger::warn(
"[Exit Detection] Game {} ran for only {} seconds - likely crash", steamAppId,
6001 static_cast<int>(sessionDuration));
6006 if (sessionDuration < 30.0)
6008 Logger::warn(
"[Exit Detection] Game {} ran for {} seconds - possible crash or timeout",
6009 steamAppId,
static_cast<int>(sessionDuration));
6014 Logger::debug(
"[Exit Detection] Game {} ran for {} seconds - normal exit", steamAppId,
6015 static_cast<int>(sessionDuration));
6019bool GameProcessManager::isSteamGameRunningOnSystem(
int steamAppId)
const
6021 if (steamAppId <= 0)
6028 std::string checkCmd =
6029 "tasklist /FI \"IMAGENAME eq steam.exe\" /FO CSV /NH 2>NUL | findstr /C:\"" +
6030 std::to_string(steamAppId) +
"\"";
6044 std::string findCmd =
"pgrep -a -f '/reaper SteamLaunch AppId=' 2>/dev/null";
6045 PipeHandle pipe(findCmd,
"r");
6049 const std::string searchPattern =
6050 "reaper SteamLaunch AppId=" + std::to_string(steamAppId) +
" ";
6051 while (fgets(buffer,
sizeof(buffer), pipe.get()) !=
nullptr)
6053 if (std::string(buffer).find(searchPattern) != std::string::npos)
6063 return !findGamePidsByAppId(steamAppId).empty();
6067void GameProcessManager::pollRunningSteamGames()
6083 std::vector<std::pair<int, std::string>> snapshot;
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);
6091 std::vector<std::pair<int, std::string>> toRemove;
6092 for (
const auto& [appId, gameId] : snapshot)
6094 if (!isSteamGameRunningOnSystem(appId))
6096 Logger::info(
"Steam game stopped: {} (App ID: {})", gameId, appId);
6097 toRemove.emplace_back(appId, gameId);
6101 if (toRemove.empty())
6104 std::lock_guard<std::mutex> lock(steamGamesMutex_);
6105 for (
const auto& [appId, snapshotGameId] : toRemove)
6107 const auto it = runningSteamGames_.find(appId);
6108 if (it != runningSteamGames_.end() && it->second == snapshotGameId)
6110 runningSteamGames_.erase(it);
6121std::vector<int> GameProcessManager::findGamePidsByAppId(
int steamAppId)
const
6123 std::vector<int> pids;
6124#ifdef PLATFORM_LINUX
6125 if (steamAppId <= 0)
6131 const std::string searchTag =
"SteamAppId=" + std::to_string(steamAppId);
6133 DIR* proc = opendir(
"/proc");
6137 struct dirent* entry;
6138 while ((entry = readdir(proc)) !=
nullptr)
6141 const std::string name = entry->d_name;
6143 !std::all_of(name.begin(), name.end(), [](
unsigned char c) { return std::isdigit(c); }))
6150 const std::string envPath =
"/proc/" + name +
"/environ";
6151 std::ifstream envFile(envPath, std::ios::binary);
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()));
6160 const size_t pos = envData.find(searchTag);
6161 if (pos == std::string::npos)
6163 const size_t endPos = pos + searchTag.size();
6166 if (endPos < envData.size() && envData[endPos] !=
'\0')
6172 const std::string cmdlinePath =
"/proc/" + name +
"/cmdline";
6173 std::ifstream cmdFile(cmdlinePath, std::ios::binary);
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)
6188 if (cmdline.find(helper) != std::string::npos)
6200 pids.push_back(std::stoi(name));
6202 catch (
const std::exception&)
6215bool GameProcessManager::killSteamGame(
int steamAppId)
6217 if (steamAppId <= 0)
6222 Logger::info(
"Attempting to kill Steam game with App ID: {}", steamAppId);
6226 std::string killCmd =
6227 "taskkill /F /T /FI \"COMMANDLINE eq *reaper*AppId=" + std::to_string(steamAppId) +
"*\"";
6235 std::string appIdStr = std::to_string(steamAppId);
6236 std::string reaperPidStr;
6240 std::string findCmd =
"pgrep -f 'reaper SteamLaunch AppId=" + appIdStr +
"' 2>/dev/null";
6241 PipeHandle pipe(findCmd,
"r");
6245 if (fgets(buffer,
sizeof(buffer), pipe.get()) !=
nullptr)
6247 reaperPidStr = buffer;
6248 reaperPidStr.erase(reaperPidStr.find_last_not_of(
"\n\r") + 1);
6254 if (reaperPidStr.empty())
6256 std::string findCmd =
"pgrep -f 'SteamLaunch AppId=" + appIdStr +
"' 2>/dev/null";
6257 PipeHandle pipe(findCmd,
"r");
6261 if (fgets(buffer,
sizeof(buffer), pipe.get()) !=
nullptr)
6263 reaperPidStr = buffer;
6264 reaperPidStr.erase(reaperPidStr.find_last_not_of(
"\n\r") + 1);
6274 if (!reaperPidStr.empty())
6276 const int reaperPid = std::stoi(reaperPidStr);
6277 Logger::info(
"Found reaper process at PID: {}", reaperPid);
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);
6286 ::kill(reaperPid, SIGKILL);
6287 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
6300 std::vector<int> orphanPids = findGamePidsByAppId(steamAppId);
6301 if (!orphanPids.empty())
6303 Logger::info(
"Found {} game process(es) via /proc/*/environ scan for App ID {} — "
6305 orphanPids.size(), steamAppId);
6306 for (
int pid : orphanPids)
6308 ::kill(pid, SIGTERM);
6311 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
6314 for (
int pid : orphanPids)
6316 if (::kill(pid, 0) == 0)
6318 Logger::warn(
"Game PID {} survived SIGTERM, sending SIGKILL", pid);
6319 ::kill(pid, SIGKILL);
6322 std::this_thread::sleep_for(std::chrono::milliseconds(500));
6324 else if (reaperPidStr.empty())
6328 Logger::info(
"No reaper or env-tagged process for App ID {} — game already exited",
6339 if (isSteamGameRunningOnSystem(steamAppId))
6341 Logger::warn(
"Game still detected after direct kill — trying steam://gamepadui/killgame/{}",
6343 const std::string steamCmd =
6344 "steam steam://gamepadui/killgame/" + appIdStr +
" 2>/dev/null &";
6346 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
6350 if (isSteamGameRunningOnSystem(steamAppId))
6352 Logger::warn(
"WARNING: Game may still be running after all kill attempts (App ID {})",
6357 Logger::info(
"Successfully stopped Steam game with App ID: {}", steamAppId);
6366std::string GameProcessManager::buildLaunchCommand(
const Game& game)
6368 std::ostringstream cmd;
6383 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE")
6389 Logger::warn(
"Skipping invalid environment variable name: {}", key);
6401 const char* home = std::getenv(
"HOME");
6404 std::filesystem::path steamPath =
6405 std::filesystem::path(home) /
".local" /
"share" /
"Steam";
6406 std::filesystem::path compatDataPath =
6426 cmd <<
"game-performance ";
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.
GameMetadata metadata
Descriptive information and media.
std::string name
Display name shown in UI.
std::string id
Unique identifier (auto-generated or user-specified).
GameStatistics statistics
Play statistics and usage tracking.
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
GameRunnerConfig runnerConfig
How to launch and run the game.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
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.
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).
bool requestStartFor(pid_t pid)
static GameModeAPI & instance()
GameModeAPI(const GameModeAPI &)=delete
bool requestEndFor(pid_t pid)
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.
@ Proton
Proton (Steam's Wine fork).
@ Native
Native Linux executable (no compatibility layer).
@ Wine
Wine compatibility layer.
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.
time_t getProcessStartTimeFromProc(int pid)
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).
std::string trackedProcessName
Configuration for how to launch and run a game.
bool enableVkBasalt
Enable VkBasalt shader injection.
int gamescopeInternalHeight
Internal render height for FSR upscaling (0 = native).
std::string executablePath
Full path to game executable.
int gamescopeITMSDRNits
ITM SDR nits reference (0 = use default).
bool gamescopeIntegerScaling
Enable integer scaling filter.
bool gamescopeFullscreen
Run in fullscreen mode.
std::string arguments
Command line arguments to pass to game.
int gamescopeHeight
Gamescope output height (0 = native).
bool gamescopeEnableFSR
Enable AMD FSR upscaling.
bool enableMangoHud
Enable MangoHud performance overlay.
std::string winePrefix
WINEPREFIX path (Wine install location).
int gamescopeFSRSharpness
FSR sharpness (0-20, 0 = max sharp).
bool gamescopeEnableVRR
Enable Variable Refresh Rate.
bool enableGamePerformance
Enable game-performance wrapper (CachyOS).
bool enableFsync
Enable Fsync (kernel 5.16+, best performance).
int gamescopeRefreshRate
Refresh rate limit (0 = no limit).
bool autoDetectSync
Auto-detect best sync method (default: true).
bool gamescopeEnableITM
Enable HDR inverse tone mapping for SDR games.
int gamescopeWidth
Gamescope output width (0 = native).
std::string mangoHudConfigFile
Per-game MangoHud config file path (MANGOHUD_CONFIGFILE).
int gamescopeInternalWidth
Internal render width for FSR upscaling (0 = native).
bool enableGameMode
Enable GameMode CPU governor optimization.
bool enableGamescope
Enable Gamescope compositor.
std::string protonVersion
Proton version (e.g., "proton-cachyos-slr").
std::map< std::string, std::string > environmentVariables
Environment variables to set before launching (KEY=VALUE pairs).
bool gamescopeEnableHDR
Enable HDR output.
bool useSteamLaunch
For Steam games: if true, launch via "steam -applaunch" instead of direct Proton.
bool gamescopeBorderless
Borderless window mode.
bool gamescopeForceGrabCursor
Force cursor grab (useful for some games).
Play statistics and usage tracking for a game.
time_t lastExitTime
Unix timestamp of last exit.
std::string lastExitReason
Reason game stopped: "normal", "crash", "timeout", "unknown".
std::string lastProtonVersion
Proton version used in last launch.
std::map< std::string, std::string > lastEnvironmentVars
Environment variables from last launch.
std::string lastLaunchCommand
Full command used for last launch (with env vars).
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
time_t lastPlayed
Unix timestamp of last play session.
int timesLaunched
Number of times game was launched.
int crashCount
Number of times game has crashed.
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).
@ Game
Game-specific fixes.