29GameLaunchManager::GameLaunchManager() : currentState_(LaunchState::IDLE), shouldCancel_(false)
34GameLaunchManager::~GameLaunchManager()
39 if (launchThread_.joinable())
54 if (launchThread_.joinable())
59 std::lock_guard<std::mutex> lock(stateMutex_);
66 Logger::warn(
"[LaunchManager] Launch already in progress");
74 currentGame_ = std::make_unique<Game>(game);
75 currentGameId_ = game.
id;
76 shouldCancel_ =
false;
79 launchThread_ = std::thread([
this]() { performLaunch(); });
86 stateCV_.notify_all();
97bool GameLaunchManager::interruptibleSleep(std::chrono::milliseconds duration)
99 std::unique_lock<std::mutex> lock(stateMutex_);
100 return !stateCV_.wait_for(lock, duration, [
this] {
return shouldCancel_.load(); });
105 return currentState_.load();
110 std::lock_guard<std::mutex> lock(stateMutex_);
111 return currentGameId_;
127 std::lock_guard<std::mutex> lock(stateMutex_);
128 stateCallback_ = std::move(callback);
133 std::lock_guard<std::mutex> lock(stateMutex_);
134 completionCallback_ = std::move(callback);
141void GameLaunchManager::transitionTo(LaunchState newState,
const std::string& message)
143 LaunchState oldState = currentState_.exchange(newState);
145 if (oldState == newState)
150 if (!message.empty())
152 Logger::info(
"[LaunchManager] State: {} -> {} ({})",
static_cast<int>(oldState),
153 static_cast<int>(newState), message);
157 Logger::info(
"[LaunchManager] State: {} -> {}",
static_cast<int>(oldState),
158 static_cast<int>(newState));
162 stateCV_.notify_all();
165 decltype(stateCallback_) callbackCopy;
167 std::lock_guard<std::mutex> lock(stateMutex_);
168 callbackCopy = stateCallback_;
172 callbackCopy(oldState, newState, message);
176void GameLaunchManager::performLaunch()
184 bool success =
false;
185 std::string failureReason;
191 if (!checkAndSyncSettings())
193 failureReason =
"Settings check failed";
199 failureReason =
"Launch cancelled by user";
204 if (currentGame_->metadata.isSteamGame)
209 failureReason =
"Steam failed to start";
215 failureReason =
"Launch cancelled by user";
222 if (!executeLaunch())
224 failureReason =
"Failed to execute launch command";
230 failureReason =
"Launch cancelled by user";
236 if (!verifyGameStarted())
238 failureReason =
"Game process not detected";
249 interruptibleSleep(std::chrono::seconds(2));
252 catch (
const std::exception& e)
254 failureReason = std::string(
"Exception: ") + e.what();
265 decltype(completionCallback_) completionCopy;
267 std::lock_guard<std::mutex> lock(stateMutex_);
269 completionCopy = completionCallback_;
272 currentGame_.reset();
273 currentGameId_.clear();
278 completionCopy(success, success ?
"Launch successful" : failureReason);
282 interruptibleSleep(std::chrono::seconds(1));
286bool GameLaunchManager::checkAndSyncSettings()
289 Logger::info(
"[LaunchManager] === Launch Settings for: {} ===", currentGame_->name);
290 Logger::info(
"[LaunchManager] Runner: {} (version: {})",
291 currentGame_->runnerConfig.runnerType.empty()
293 : currentGame_->runnerConfig.runnerType,
294 currentGame_->runnerConfig.runnerVersion.empty()
296 : currentGame_->runnerConfig.runnerVersion);
298 if (!currentGame_->runnerConfig.environmentVariables.empty())
300 Logger::info(
"[LaunchManager] Environment variables ({}):",
301 currentGame_->runnerConfig.environmentVariables.size());
302 for (
const auto& [key, value] : currentGame_->runnerConfig.environmentVariables)
309 Logger::info(
"[LaunchManager] No custom environment variables configured");
313 "[LaunchManager] Wrappers: GameMode={}, MangoHud={}, game-performance={}, VkBasalt={}",
314 currentGame_->runnerConfig.enableGameMode ?
"yes" :
"no",
315 currentGame_->runnerConfig.enableMangoHud ?
"yes" :
"no",
316 currentGame_->runnerConfig.enableGamePerformance ?
"yes" :
"no",
317 currentGame_->runnerConfig.enableVkBasalt ?
"yes" :
"no");
319 if (!currentGame_->runnerConfig.arguments.empty())
321 Logger::info(
"[LaunchManager] Launch arguments: {}", currentGame_->runnerConfig.arguments);
323 if (!currentGame_->runnerConfig.wineDLL.empty())
325 Logger::info(
"[LaunchManager] DLL overrides: {}", currentGame_->runnerConfig.wineDLL);
327 Logger::info(
"[LaunchManager] ========================================");
329 if (!currentGame_->metadata.isSteamGame)
335 if (currentGame_->runnerConfig.useSteamDefaults)
338 Logger::info(
"[LaunchManager] Using Steam defaults, no sync needed");
343 std::ostringstream launchOptionsBuilder;
344 const auto& config = currentGame_->runnerConfig;
352 for (
const auto& [key, value] : config.environmentVariables)
358 if (key ==
"GAME_PERFORMANCE" || key ==
"USE_GAME_PERFORMANCE" || key ==
"MANGOHUD" ||
359 key ==
"MANGOHUD_CONFIGFILE")
362 launchOptionsBuilder << key;
365 launchOptionsBuilder <<
"=" << value;
367 launchOptionsBuilder <<
" ";
378 if (!config.enableGamescope)
381 currentGame_->id, config.mangoHudConfigFile);
382 if (!cfgPath.empty())
391 std::ostringstream wrapperPrefix;
394 if (config.enableGamePerformance || config.environmentVariables.count(
"GAME_PERFORMANCE") > 0 ||
395 config.environmentVariables.count(
"USE_GAME_PERFORMANCE") > 0)
397 wrapperPrefix <<
"game-performance ";
401 if (config.enableGameMode)
403 wrapperPrefix <<
"gamemoderun ";
408 if (config.enableMangoHud)
410 wrapperPrefix <<
"mangohud ";
417 std::string envVars = launchOptionsBuilder.str();
418 std::string wrappers = wrapperPrefix.str();
420 std::ostringstream finalOptions;
421 if (!envVars.empty())
423 finalOptions << envVars;
425 if (!wrappers.empty())
427 finalOptions << wrappers;
429 finalOptions <<
"%command%";
432 if (!config.arguments.empty() && config.arguments.find(
"-applaunch") == std::string::npos)
435 finalOptions <<
" " << config.arguments;
438 std::string desiredLaunchOptions = finalOptions.str();
441 uint32_t steamAppId =
static_cast<uint32_t
>(currentGame_->metadata.steamAppId);
450 std::string desiredProtonVersion = config.runnerVersion;
451 std::string desiredProtonNormalised =
455 bool launchOptionsMatch = (currentSteamOptions == desiredLaunchOptions);
456 bool protonVersionMatch =
457 desiredProtonNormalised.empty() || currentProtonVersion == desiredProtonNormalised;
459 Logger::info(
"[LaunchManager] Launch options: current='{}' desired='{}'", currentSteamOptions,
460 desiredLaunchOptions);
461 Logger::info(
"[LaunchManager] Proton version: current='{}' desired='{}'", currentProtonVersion,
462 desiredProtonVersion.empty() ?
"(default)" : desiredProtonVersion);
464 if (launchOptionsMatch && protonVersionMatch)
466 Logger::info(
"[LaunchManager] Settings match, no sync needed");
470 Logger::info(
"[LaunchManager] Settings differ, syncing...");
471 if (!launchOptionsMatch)
473 Logger::info(
" Launch options: '{}' -> '{}'", currentSteamOptions, desiredLaunchOptions);
475 if (!protonVersionMatch)
477 Logger::info(
" Proton version: '{}' -> '{}'", currentProtonVersion, desiredProtonVersion);
484 bool steamWasRunning = monitor.isSteamRunning();
488 bool needsSteamRestart = !protonVersionMatch && !desiredProtonVersion.empty();
490 if (needsSteamRestart && steamWasRunning)
492 Logger::info(
"[LaunchManager] Proton version change requires Steam restart...");
493 monitor.requestSteamShutdown();
498 Logger::error(
"[LaunchManager] Timeout waiting for Steam to stop");
503 std::this_thread::sleep_for(std::chrono::milliseconds(500));
505 else if (!steamWasRunning)
507 Logger::info(
"[LaunchManager] Steam not running, updating config directly");
511 Logger::info(
"[LaunchManager] Launch options only — writing in-place (no restart needed)");
515 if (!launchOptionsMatch)
519 Logger::error(
"[LaunchManager] Failed to write launch options");
520 if (needsSteamRestart && steamWasRunning)
522 monitor.requestSteamStart();
526 Logger::info(
"[LaunchManager] Launch options synced successfully");
530 if (!protonVersionMatch && !desiredProtonVersion.empty())
534 Logger::error(
"[LaunchManager] Failed to write Proton version");
535 if (needsSteamRestart && steamWasRunning)
537 monitor.requestSteamStart();
541 Logger::info(
"[LaunchManager] Proton version synced successfully");
544 Logger::info(
"[LaunchManager] All settings synced successfully");
547 if (needsSteamRestart && steamWasRunning)
549 monitor.requestSteamStart();
555bool GameLaunchManager::waitForSteam()
562 if (monitor.isSteamFullyInitialized())
564 Logger::info(
"[LaunchManager] Steam is already running and initialized");
568 Logger::info(
"[LaunchManager] Steam process running, waiting for full initialization...");
569 if (monitor.waitForSteamInitialized(10000))
573 Logger::warn(
"[LaunchManager] Steam did not fully initialize, proceeding anyway...");
578 Logger::info(
"[LaunchManager] Steam not running, requesting start...");
579 monitor.requestSteamStart();
584 Logger::error(
"[LaunchManager] Timeout waiting for Steam to start");
589 Logger::info(
"[LaunchManager] Steam process started, waiting for full initialization...");
590 if (!monitor.waitForSteamInitialized(15000))
592 Logger::warn(
"[LaunchManager] Steam initialization timeout, proceeding anyway...");
600bool GameLaunchManager::executeLaunch()
602 Logger::info(
"[LaunchManager] Executing launch for game: {}", currentGame_->name);
609 Logger::error(
"[LaunchManager] GameProcessManager.launchGame() returned false");
616bool GameLaunchManager::verifyGameStarted()
622 Logger::info(
"[LaunchManager] Verifying game started...");
628 for (
int i = 0; i < maxIterations; i++)
632 Logger::info(
"[LaunchManager] Verification cancelled by user");
645 Logger::error(
"[LaunchManager] Error: Could not verify game started after {} seconds",
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.
std::function< void(LaunchState oldState, LaunchState newState, const std::string &message)> StateCallback
void requestLaunch(const Game &game)
LaunchState getCurrentState() const
std::function< void(bool success, const std::string &message)> CompletionCallback
void setStateCallback(StateCallback callback)
static GameLaunchManager & instance()
void setCompletionCallback(CompletionCallback callback)
std::string getCurrentGameId() const
bool isLaunchInProgress() const
bool launchGame(const std::string &gameId, Game &game)
static GameProcessManager & instance()
Complete representation of a game in the library.
std::string name
Display name shown in UI.
std::string id
Unique identifier (auto-generated or user-specified).
static void info(const std::string &message, Args &&... args)
Log info message (general information).
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).
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
static std::string normalizeProtonName(const std::string &display)
Strip launcher-side display annotations from a Proton name.
static bool writeSteamProtonVersion(uint32_t appId, const std::string &protonName)
Write Proton compatibility tool mapping for a game to config.vdf.
static std::string readSteamProtonVersion(uint32_t appId)
Read Proton compatibility tool mapping for a game from config.vdf.
static bool writeSteamLaunchOptions(uint32_t appId, const std::string &launchOptions)
Write Steam launch options for a game to localconfig.vdf.
static std::string readSteamLaunchOptions(uint32_t appId)
Read Steam launch options for a game from localconfig.vdf.
static SteamProcessMonitor & instance()
constexpr int GAME_VERIFY_TIMEOUT_SEC
Maximum time to wait for game process to appear after launch.
constexpr int GAME_VERIFY_POLL_MS
Polling interval when verifying game has started.