game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
launch_manager.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#include "launch_manager.h"
3#include "frame_metrics.h"
4#include "game_process.h"
5#include "logger.h"
6#include "shell_utils.h"
7#include "steam_constants.h"
8#include "steam_integration.h"
9#include "steam_monitor.h"
10#include <chrono>
11#include <sstream>
12#include <thread>
13#include <utility>
14
15// ==============================================================================
16// Singleton
17// ==============================================================================
18
19GameLaunchManager& GameLaunchManager::instance()
20{
21 static GameLaunchManager instance;
22 return instance;
23}
24
25// ==============================================================================
26// Constructor / Destructor
27// ==============================================================================
28
29GameLaunchManager::GameLaunchManager() : currentState_(LaunchState::IDLE), shouldCancel_(false)
30{
31 Logger::info("[LaunchManager] Initialized");
32}
33
34GameLaunchManager::~GameLaunchManager()
35{
37
38 // Wait for the launch thread to finish before destroying the object
39 if (launchThread_.joinable())
40 {
41 launchThread_.join();
42 }
43}
44
45// ==============================================================================
46// Launch Control
47// ==============================================================================
48
50{
51 // Join any previous launch thread BEFORE acquiring stateMutex_ to avoid deadlock.
52 // The launch thread's transitionTo() also acquires stateMutex_ for callback copy,
53 // so joining while holding the mutex would deadlock.
54 if (launchThread_.joinable())
55 {
56 launchThread_.join();
57 }
58
59 std::lock_guard<std::mutex> lock(stateMutex_);
60
61 // Allow new launches after a previous one completed or failed
62 LaunchState state = currentState_.load();
63 if (state != LaunchState::IDLE && state != LaunchState::COMPLETED &&
64 state != LaunchState::FAILED)
65 {
66 Logger::warn("[LaunchManager] Launch already in progress");
67 return;
68 }
69 currentState_ = LaunchState::IDLE;
70
71 Logger::info("[LaunchManager] Launch requested for: {}", game.name);
72
73 // Store game info
74 currentGame_ = std::make_unique<Game>(game);
75 currentGameId_ = game.id;
76 shouldCancel_ = false;
77
78 // Launch async pipeline in separate thread (tracked, not detached)
79 launchThread_ = std::thread([this]() { performLaunch(); });
80}
81
83{
84 Logger::info("[LaunchManager] Cancel requested");
85 shouldCancel_ = true;
86 stateCV_.notify_all();
87}
88
89// Interruptible sleep — wakes immediately when shouldCancel_ flips. Used in
90// place of std::this_thread::sleep_for() so the destructor's join() doesn't
91// stall up to seconds(N) when the user kills the launcher mid-launch (e.g.
92// systemd reboot triggering the round-4 SIGTERM handler -> QApplication::quit
93// -> singleton destructor -> ~GameLaunchManager). The condition variable is
94// already woken by cancelLaunch() and stateChange transitions.
95//
96// Returns true if the sleep completed without cancellation, false if cancelled.
97bool GameLaunchManager::interruptibleSleep(std::chrono::milliseconds duration)
98{
99 std::unique_lock<std::mutex> lock(stateMutex_);
100 return !stateCV_.wait_for(lock, duration, [this] { return shouldCancel_.load(); });
101}
102
104{
105 return currentState_.load();
106}
107
109{
110 std::lock_guard<std::mutex> lock(stateMutex_);
111 return currentGameId_;
112}
113
115{
116 LaunchState state = currentState_.load();
117 return state != LaunchState::IDLE && state != LaunchState::COMPLETED &&
118 state != LaunchState::FAILED;
119}
120
121// ==============================================================================
122// Callbacks
123// ==============================================================================
124
126{
127 std::lock_guard<std::mutex> lock(stateMutex_);
128 stateCallback_ = std::move(callback);
129}
130
132{
133 std::lock_guard<std::mutex> lock(stateMutex_);
134 completionCallback_ = std::move(callback);
135}
136
137// ==============================================================================
138// Internal Methods
139// ==============================================================================
140
141void GameLaunchManager::transitionTo(LaunchState newState, const std::string& message)
142{
143 LaunchState oldState = currentState_.exchange(newState);
144
145 if (oldState == newState)
146 {
147 return;
148 }
149
150 if (!message.empty())
151 {
152 Logger::info("[LaunchManager] State: {} -> {} ({})", static_cast<int>(oldState),
153 static_cast<int>(newState), message);
154 }
155 else
156 {
157 Logger::info("[LaunchManager] State: {} -> {}", static_cast<int>(oldState),
158 static_cast<int>(newState));
159 }
160
161 // Notify waiting threads
162 stateCV_.notify_all();
163
164 // Copy callback under lock, invoke outside
165 decltype(stateCallback_) callbackCopy;
166 {
167 std::lock_guard<std::mutex> lock(stateMutex_);
168 callbackCopy = stateCallback_;
169 }
170 if (callbackCopy)
171 {
172 callbackCopy(oldState, newState, message);
173 }
174}
175
176void GameLaunchManager::performLaunch()
177{
178 if (!currentGame_)
179 {
180 transitionTo(LaunchState::FAILED, "Game object is null");
181 return;
182 }
183
184 bool success = false;
185 std::string failureReason;
186
187 try
188 {
189 // Stage 1: Check and sync settings if needed
190 transitionTo(LaunchState::CHECKING_SETTINGS, "Checking Steam settings");
191 if (!checkAndSyncSettings())
192 {
193 failureReason = "Settings check failed";
194 goto launch_failed;
195 }
196
197 if (shouldCancel_)
198 {
199 failureReason = "Launch cancelled by user";
200 goto launch_failed;
201 }
202
203 // Stage 2: Wait for Steam if it's a Steam game
204 if (currentGame_->metadata.isSteamGame)
205 {
206 transitionTo(LaunchState::WAITING_FOR_STEAM, "Waiting for Steam");
207 if (!waitForSteam())
208 {
209 failureReason = "Steam failed to start";
210 goto launch_failed;
211 }
212
213 if (shouldCancel_)
214 {
215 failureReason = "Launch cancelled by user";
216 goto launch_failed;
217 }
218 }
219
220 // Stage 3: Execute launch
221 transitionTo(LaunchState::LAUNCHING, "Launching game");
222 if (!executeLaunch())
223 {
224 failureReason = "Failed to execute launch command";
225 goto launch_failed;
226 }
227
228 if (shouldCancel_)
229 {
230 failureReason = "Launch cancelled by user";
231 goto launch_failed;
232 }
233
234 // Stage 4: Verify game started
235 transitionTo(LaunchState::VERIFYING_START, "Verifying game started");
236 if (!verifyGameStarted())
237 {
238 failureReason = "Game process not detected";
239 goto launch_failed;
240 }
241
242 // Success!
243 success = true;
244 transitionTo(LaunchState::RUNNING, "Game launched successfully");
245
246 // Wait a bit then transition to completed. interruptibleSleep wakes
247 // immediately on cancelLaunch() so destructor join doesn't block
248 // for the full duration on shutdown.
249 interruptibleSleep(std::chrono::seconds(2));
250 transitionTo(LaunchState::COMPLETED, "Launch sequence completed");
251 }
252 catch (const std::exception& e)
253 {
254 failureReason = std::string("Exception: ") + e.what();
255 goto launch_failed;
256 }
257
258launch_failed:
259 if (!success)
260 {
261 transitionTo(LaunchState::FAILED, failureReason);
262 }
263
264 // Copy completion callback under lock, invoke outside
265 decltype(completionCallback_) completionCopy;
266 {
267 std::lock_guard<std::mutex> lock(stateMutex_);
268
269 completionCopy = completionCallback_;
270
271 // Clean up
272 currentGame_.reset();
273 currentGameId_.clear();
274 }
275
276 if (completionCopy)
277 {
278 completionCopy(success, success ? "Launch successful" : failureReason);
279 }
280
281 // Return to idle. interruptibleSleep so shutdown doesn't stall here.
282 interruptibleSleep(std::chrono::seconds(1));
283 transitionTo(LaunchState::IDLE, "Ready for next launch");
284}
285
286bool GameLaunchManager::checkAndSyncSettings()
287{
288 // Log launch settings for debugging
289 Logger::info("[LaunchManager] === Launch Settings for: {} ===", currentGame_->name);
290 Logger::info("[LaunchManager] Runner: {} (version: {})",
291 currentGame_->runnerConfig.runnerType.empty()
292 ? "default"
293 : currentGame_->runnerConfig.runnerType,
294 currentGame_->runnerConfig.runnerVersion.empty()
295 ? "default"
296 : currentGame_->runnerConfig.runnerVersion);
297
298 if (!currentGame_->runnerConfig.environmentVariables.empty())
299 {
300 Logger::info("[LaunchManager] Environment variables ({}):",
301 currentGame_->runnerConfig.environmentVariables.size());
302 for (const auto& [key, value] : currentGame_->runnerConfig.environmentVariables)
303 {
304 Logger::info("[LaunchManager] {}={}", key, value);
305 }
306 }
307 else
308 {
309 Logger::info("[LaunchManager] No custom environment variables configured");
310 }
311
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");
318
319 if (!currentGame_->runnerConfig.arguments.empty())
320 {
321 Logger::info("[LaunchManager] Launch arguments: {}", currentGame_->runnerConfig.arguments);
322 }
323 if (!currentGame_->runnerConfig.wineDLL.empty())
324 {
325 Logger::info("[LaunchManager] DLL overrides: {}", currentGame_->runnerConfig.wineDLL);
326 }
327 Logger::info("[LaunchManager] ========================================");
328
329 if (!currentGame_->metadata.isSteamGame)
330 {
331 // Not a Steam game, no sync needed
332 return true;
333 }
334
335 if (currentGame_->runnerConfig.useSteamDefaults)
336 {
337 // Using Steam defaults, no sync needed
338 Logger::info("[LaunchManager] Using Steam defaults, no sync needed");
339 return true;
340 }
341
342 // Build desired launch options
343 std::ostringstream launchOptionsBuilder;
344 const auto& config = currentGame_->runnerConfig;
345
346 // Add custom environment variables as env vars before %command%
347 // Note: Wrappers handle their own env vars, so we skip keys managed by wrappers.
348 // MangoHud: use wrapper only (sets MANGOHUD=1 internally, avoids double-layer injection)
349 // Fsync: Proton auto-detects fsync/esync/ntsync support, explicit WINEFSYNC is redundant
350 // and can conflict with newer Proton versions. Only set if user explicitly added it.
351 // GameMode: use gamemoderun wrapper (applies scheduler optimizations to child processes)
352 for (const auto& [key, value] : config.environmentVariables)
353 {
354 // Skip keys handled by wrapper commands (MangoHud uses wrapper, not env var)
355 // ENABLE_VKBASALT is kept as env var since VkBasalt is a Vulkan layer, not a wrapper
356 // MANGOHUD_CONFIGFILE is injected below from FrameMetricsService — drop any
357 // user-set value here so we don't end up with two competing entries.
358 if (key == "GAME_PERFORMANCE" || key == "USE_GAME_PERFORMANCE" || key == "MANGOHUD" ||
359 key == "MANGOHUD_CONFIGFILE")
360 continue;
361
362 launchOptionsBuilder << key;
363 if (!value.empty())
364 {
365 launchOptionsBuilder << "=" << value;
366 }
367 launchOptionsBuilder << " ";
368 }
369
370 // Inject MANGOHUD_CONFIGFILE so MangoHud (whether activated by our wrapper
371 // or the system implicit Vulkan layer) reads our merged config — preserving
372 // the user's overlay style from ~/.config/MangoHud/MangoHud.conf while
373 // overriding log_duration so the launcher's FPS panel keeps populating
374 // past the user's goverlay-set cutoff. Per MangoHud's src/config.cpp
375 // parseConfigFile, when MANGOHUD_CONFIGFILE is set, enumerate_config_files
376 // is skipped and only this path is parsed. Skip when Gamescope is active
377 // — gamescope's --mangoapp flag uses a different (SysV queue) protocol.
378 if (!config.enableGamescope)
379 {
381 currentGame_->id, config.mangoHudConfigFile);
382 if (!cfgPath.empty())
383 {
384 launchOptionsBuilder << "MANGOHUD_CONFIGFILE=" << ShellUtils::escapeArg(cfgPath) << " ";
385 }
386 }
387
388 // Build wrapper command prefix (these go before %command%)
389 // Order follows CachyOS best practices: game-performance > gamemoderun > mangohud
390 // Outermost wrapper = highest priority for process scheduling
391 std::ostringstream wrapperPrefix;
392
393 // game-performance wrapper (CachyOS specific - outermost for scheduler priority)
394 if (config.enableGamePerformance || config.environmentVariables.count("GAME_PERFORMANCE") > 0 ||
395 config.environmentVariables.count("USE_GAME_PERFORMANCE") > 0)
396 {
397 wrapperPrefix << "game-performance ";
398 }
399
400 // GameMode wrapper (CPU governor + scheduler optimizations)
401 if (config.enableGameMode)
402 {
403 wrapperPrefix << "gamemoderun ";
404 }
405
406 // MangoHud wrapper (performance overlay - use wrapper instead of env var
407 // to properly inject the Vulkan layer without double-application)
408 if (config.enableMangoHud)
409 {
410 wrapperPrefix << "mangohud ";
411 }
412
413 // VkBasalt uses ENABLE_VKBASALT=1 env var (Vulkan layer, not a wrapper binary)
414 // It's handled through config.environmentVariables and not skipped in the env loop above
415
416 // Combine: ENV_VARS wrapper1 wrapper2 %command% ARGS
417 std::string envVars = launchOptionsBuilder.str();
418 std::string wrappers = wrapperPrefix.str();
419
420 std::ostringstream finalOptions;
421 if (!envVars.empty())
422 {
423 finalOptions << envVars;
424 }
425 if (!wrappers.empty())
426 {
427 finalOptions << wrappers;
428 }
429 finalOptions << "%command%";
430
431 // Add launch arguments after %command%
432 if (!config.arguments.empty() && config.arguments.find("-applaunch") == std::string::npos)
433 {
434 // Only add arguments if they're not the steam command itself
435 finalOptions << " " << config.arguments;
436 }
437
438 std::string desiredLaunchOptions = finalOptions.str();
439
440 // Read current Steam settings
441 uint32_t steamAppId = static_cast<uint32_t>(currentGame_->metadata.steamAppId);
442 std::string currentSteamOptions = SteamLibraryScanner::readSteamLaunchOptions(steamAppId);
443 std::string currentProtonVersion = SteamLibraryScanner::readSteamProtonVersion(steamAppId);
444
445 // Determine desired Proton version. config.runnerVersion may be a launcher
446 // display string with suffix annotations like " (system)" — Steam stores
447 // bare directory names in CompatToolMapping, so normalise before comparing.
448 // An empty normalised name signals a Steam-managed sentinel (e.g. "Native
449 // Linux") that we should leave Steam's mapping alone for.
450 std::string desiredProtonVersion = config.runnerVersion;
451 std::string desiredProtonNormalised =
452 SteamLibraryScanner::normalizeProtonName(desiredProtonVersion);
453
454 // Check if settings differ
455 bool launchOptionsMatch = (currentSteamOptions == desiredLaunchOptions);
456 bool protonVersionMatch =
457 desiredProtonNormalised.empty() || currentProtonVersion == desiredProtonNormalised;
458
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);
463
464 if (launchOptionsMatch && protonVersionMatch)
465 {
466 Logger::info("[LaunchManager] Settings match, no sync needed");
467 return true;
468 }
469
470 Logger::info("[LaunchManager] Settings differ, syncing...");
471 if (!launchOptionsMatch)
472 {
473 Logger::info(" Launch options: '{}' -> '{}'", currentSteamOptions, desiredLaunchOptions);
474 }
475 if (!protonVersionMatch)
476 {
477 Logger::info(" Proton version: '{}' -> '{}'", currentProtonVersion, desiredProtonVersion);
478 }
479
480 // Transition to syncing state
481 transitionTo(LaunchState::SYNCING_SETTINGS, "Syncing settings to Steam");
482
483 auto& monitor = SteamProcessMonitor::instance();
484 bool steamWasRunning = monitor.isSteamRunning();
485
486 // Proton version changes require Steam restart (Steam caches CompatToolMapping).
487 // Launch options can be written in-place — Steam reads them per-game at launch time.
488 bool needsSteamRestart = !protonVersionMatch && !desiredProtonVersion.empty();
489
490 if (needsSteamRestart && steamWasRunning)
491 {
492 Logger::info("[LaunchManager] Proton version change requires Steam restart...");
493 monitor.requestSteamShutdown();
494
495 // Wait for Steam to stop
496 if (!monitor.waitForState(SteamProcessMonitor::State::NOT_RUNNING, 15000))
497 {
498 Logger::error("[LaunchManager] Timeout waiting for Steam to stop");
499 return false;
500 }
501
502 // Small delay to ensure Steam has fully released file locks
503 std::this_thread::sleep_for(std::chrono::milliseconds(500));
504 }
505 else if (!steamWasRunning)
506 {
507 Logger::info("[LaunchManager] Steam not running, updating config directly");
508 }
509 else
510 {
511 Logger::info("[LaunchManager] Launch options only — writing in-place (no restart needed)");
512 }
513
514 // Write launch options if needed
515 if (!launchOptionsMatch)
516 {
517 if (!SteamLibraryScanner::writeSteamLaunchOptions(steamAppId, desiredLaunchOptions))
518 {
519 Logger::error("[LaunchManager] Failed to write launch options");
520 if (needsSteamRestart && steamWasRunning)
521 {
522 monitor.requestSteamStart();
523 }
524 return false;
525 }
526 Logger::info("[LaunchManager] Launch options synced successfully");
527 }
528
529 // Write Proton version if needed
530 if (!protonVersionMatch && !desiredProtonVersion.empty())
531 {
532 if (!SteamLibraryScanner::writeSteamProtonVersion(steamAppId, desiredProtonVersion))
533 {
534 Logger::error("[LaunchManager] Failed to write Proton version");
535 if (needsSteamRestart && steamWasRunning)
536 {
537 monitor.requestSteamStart();
538 }
539 return false;
540 }
541 Logger::info("[LaunchManager] Proton version synced successfully");
542 }
543
544 Logger::info("[LaunchManager] All settings synced successfully");
545
546 // Only restart Steam if we shut it down for a Proton version change
547 if (needsSteamRestart && steamWasRunning)
548 {
549 monitor.requestSteamStart();
550 }
551
552 return true;
553}
554
555bool GameLaunchManager::waitForSteam()
556{
557 auto& monitor = SteamProcessMonitor::instance();
558
559 // Check if Steam is already running and initialized
560 if (monitor.getCurrentState() == SteamProcessMonitor::State::RUNNING)
561 {
562 if (monitor.isSteamFullyInitialized())
563 {
564 Logger::info("[LaunchManager] Steam is already running and initialized");
565 return true;
566 }
567 // Steam process is running but not fully initialized yet
568 Logger::info("[LaunchManager] Steam process running, waiting for full initialization...");
569 if (monitor.waitForSteamInitialized(10000))
570 {
571 return true;
572 }
573 Logger::warn("[LaunchManager] Steam did not fully initialize, proceeding anyway...");
574 return true; // Still try to launch
575 }
576
577 // Steam is not running - request start
578 Logger::info("[LaunchManager] Steam not running, requesting start...");
579 monitor.requestSteamStart();
580
581 // Wait for Steam process to be running
582 if (!monitor.waitForState(SteamProcessMonitor::State::RUNNING, 20000))
583 {
584 Logger::error("[LaunchManager] Timeout waiting for Steam to start");
585 return false;
586 }
587
588 // Wait for Steam to be fully initialized (not just process running)
589 Logger::info("[LaunchManager] Steam process started, waiting for full initialization...");
590 if (!monitor.waitForSteamInitialized(15000))
591 {
592 Logger::warn("[LaunchManager] Steam initialization timeout, proceeding anyway...");
593 // Still return true - the process is running, just may not be fully ready
594 // This prevents blocking forever if initialization detection fails
595 }
596
597 return true;
598}
599
600bool GameLaunchManager::executeLaunch()
601{
602 Logger::info("[LaunchManager] Executing launch for game: {}", currentGame_->name);
603
604 // Use GameProcessManager to launch
605 bool launched = GameProcessManager::instance().launchGame(currentGame_->id, *currentGame_);
606
607 if (!launched)
608 {
609 Logger::error("[LaunchManager] GameProcessManager.launchGame() returned false");
610 return false;
611 }
612
613 return true;
614}
615
616bool GameLaunchManager::verifyGameStarted()
617{
618 // For Steam games, the background thread tracks them
619 // For other games, GameProcessManager tracks them
620 // Poll for 5 seconds to see if game appears as running
621
622 Logger::info("[LaunchManager] Verifying game started...");
623
624 // Calculate max iterations based on timeout and poll interval
625 const int maxIterations = static_cast<int>((SteamConstants::GAME_VERIFY_TIMEOUT_SEC * 1000) /
627
628 for (int i = 0; i < maxIterations; i++)
629 {
630 if (shouldCancel_)
631 {
632 Logger::info("[LaunchManager] Verification cancelled by user");
633 return false;
634 }
635
636 if (GameProcessManager::instance().isGameRunning(currentGame_->id))
637 {
638 Logger::info("[LaunchManager] Game confirmed running");
639 return true;
640 }
641
642 std::this_thread::sleep_for(std::chrono::milliseconds(SteamConstants::GAME_VERIFY_POLL_MS));
643 }
644
645 Logger::error("[LaunchManager] Error: Could not verify game started after {} seconds",
647 return false;
648}
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.
Definition game.h:767
std::string name
Display name shown in UI.
Definition game.h:774
std::string id
Unique identifier (auto-generated or user-specified).
Definition game.h:773
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
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.