game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_process.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_process.h
4// ==============================================================================
5// Game process management - launching and monitoring game processes
6// ==============================================================================
7// This file provides classes for launching and managing game processes:
8//
9// ## GameProcess
10// Represents a single running game process. Handles:
11// - Launching games via different runners (native, Wine, Proton)
12// - Monitoring process state (running, stopped, error)
13// - Tracking play time
14// - Graceful shutdown and force kill
15//
16// ## GameProcessManager (Singleton)
17// Manages all running game processes. Provides:
18// - Centralized process tracking
19// - Process lifecycle management
20// - Automatic cleanup of stopped processes
21//
22// ## Platform Support
23// - Linux: Uses fork/exec for native processes
24// - Windows: Uses CreateProcess API
25// - Wine/Proton: Wraps executables with appropriate command prefixes
26//
27// ## Thread Safety
28// Neither class is thread-safe. All operations should be called from
29// the main thread only.
30// ==============================================================================
31
32#pragma once
33
34// ==============================================================================
35// Includes
36// ==============================================================================
37
38#include "game.h"
39#include <atomic>
40#include <functional>
41#include <map>
42#include <memory>
43#include <mutex>
44#include <string>
45#include <thread>
46#include <vector>
47
48// ==============================================================================
49// Game Process Class
50// ==============================================================================
51
52/**
53 * @class GameProcess
54 * @brief Manages a single running game process
55 *
56 * Creates and monitors a game process, handling platform-specific
57 * launching (native, Wine, Proton) and tracking play time statistics.
58 *
59 * ## Usage Example
60 * @code
61 * Game& myGame = ...; // Get game from library
62 * GameProcess process(myGame);
63 *
64 * // Set up callbacks
65 * process.setOnStateChanged([](GameProcess::State newState) {
66 * std::cout << "State changed to: " << (int)newState << std::endl;
67 * });
68 *
69 * // Launch the game
70 * if (process.launch()) {
71 * // Game started successfully
72 * while (process.isRunning()) {
73 * process.update(); // Call each frame
74 * // ... other work ...
75 * }
76 * }
77 * @endcode
78 */
80{
81 public:
82 // ==========================================================================
83 // Process State
84 // ==========================================================================
85
86 /**
87 * @enum State
88 * @brief Current state of the game process
89 */
90 enum class State
91 {
92 NotStarted, ///< Process has not been started yet
93 Starting, ///< Process is in the process of starting
94 Running, ///< Process is running normally
95 Stopping, ///< Process is being stopped (graceful shutdown)
96 Stopped, ///< Process has stopped (either normally or was killed)
97 Error ///< Process encountered an error during launch
98 };
99
100 // ==========================================================================
101 // Constructor & Destructor
102 // ==========================================================================
103
104 /**
105 * @brief Constructor - creates a process for the given game
106 * @param game Game to launch (will be copied to prevent dangling references)
107 */
108 GameProcess(const Game& game);
109
110 /**
111 * @brief Destructor - stops the process if still running
112 *
113 * Automatically calls stop() if the process is still running.
114 */
115 ~GameProcess();
116
117 // ==========================================================================
118 // Process Control
119 // ==========================================================================
120
121 /**
122 * @brief Launch the game process
123 * @return True if launch was successful, false on error
124 *
125 * Launches the game using the appropriate platform runner:
126 * - Native: Direct execution via fork/exec (Linux) or CreateProcess (Windows)
127 * - Wine: Executes through Wine with WINEPREFIX and other settings
128 * - Proton: Executes through Proton with Steam runtime
129 *
130 * On success, the process state becomes Running and startTime is recorded.
131 * On failure, the process state becomes Error.
132 *
133 * @note This function can only be called when state is NotStarted or Stopped
134 */
135 bool launch();
136
137 /**
138 * @brief Stop the game process gracefully
139 * @return True if stop was initiated successfully
140 *
141 * Sends a termination signal to the process:
142 * - Linux: SIGTERM
143 * - Windows: TerminateProcess
144 *
145 * Updates game statistics (play time, last played) before stopping.
146 * State becomes Stopped after this call.
147 */
148 bool stop();
149
150 /**
151 * @brief Force kill the game process
152 * @return True if kill was successful
153 *
154 * Forcefully terminates the process:
155 * - Linux: SIGKILL
156 * - Windows: TerminateProcess with force flag
157 *
158 * Use this only if stop() fails or hangs.
159 */
160 bool kill();
161
162 /**
163 * @brief Attach to an already-running process
164 * @param pid The process ID of the running game
165 * @param processName Optional name of the executable (e.g., "Wow.exe")
166 *
167 * Used to track games that were launched externally (e.g., via Lutris)
168 * or were already running when the application started.
169 * Sets state to Running and begins tracking.
170 */
171 void attachToRunningProcess(int pid, const std::string& processName = "");
172
173 // ==========================================================================
174 // State Query
175 // ==========================================================================
176
177 /**
178 * @brief Get current process state
179 * @return Current State enum value
180 */
182 {
183 return state_;
184 }
185
186 /**
187 * @brief Check if process is currently running
188 * @return True if state is Running
189 */
190 bool isRunning() const
191 {
192 return state_ == State::Running;
193 }
194
195 /**
196 * @brief Get the process ID
197 * @return Process ID, or -1 if not running
198 */
199 int getProcessId() const
200 {
201 return pid_;
202 }
203
204 /**
205 * @brief Get the tracked game process ID
206 * @return Tracked PID, or -1 if not tracking a separate process
207 *
208 * For launcher games (Battle.net, EA App, etc.), this returns the actual
209 * game process PID which may differ from getProcessId().
210 */
212 {
213 return trackedPid_;
214 }
215
216 /**
217 * @brief Get the name of the tracked game process
218 * @return Process name (e.g., "Wow.exe"), or empty if not tracked
219 */
220 const std::string& getTrackedProcessName() const
221 {
222 return trackedProcessName_;
223 }
224
225 /**
226 * @brief Get how long the process has been running
227 * @return Running time in seconds, or 0 if not running
228 */
229 double getRunningTimeSeconds() const;
230
231 /**
232 * @brief Get information about what was applied during the last launch
233 * @return LaunchInfo structure with applied optimizations
234 */
236 {
237 return lastLaunchInfo_;
238 }
239
240 /**
241 * @brief Get the game associated with this process
242 * @return Reference to the game (copy held by this process)
243 */
244 const Game& getGame() const
245 {
246 return game_;
247 }
248
249 // ==========================================================================
250 // Callbacks
251 // ==========================================================================
252
253 /**
254 * @brief Set callback for state changes
255 * @param callback Function to call when state changes
256 *
257 * The callback is invoked whenever the process state transitions.
258 */
259 void setOnStateChanged(std::function<void(State)> callback)
260 {
261 onStateChanged_ = callback;
262 }
263
264 /**
265 * @brief Set callback for process exit
266 * @param callback Function to call when process exits (receives exit code)
267 *
268 * The callback is invoked when the process terminates naturally.
269 */
270 void setOnExit(std::function<void(int exitCode)> callback)
271 {
272 onExit_ = callback;
273 }
274
275 /**
276 * @enum NotificationType
277 * @brief Type of notification to display
278 */
285
286 /**
287 * @brief Set callback for notifications
288 * @param callback Function to call when a notification should be displayed
289 *
290 * This allows the process to communicate status messages to the UI layer
291 * without depending on any specific notification implementation.
292 */
293 void setOnNotification(std::function<void(NotificationType, const std::string&)> callback)
294 {
295 onNotification_ = callback;
296 }
297
298 // ==========================================================================
299 // Update (call each frame)
300 // ==========================================================================
301
302 /**
303 * @brief Check if process is still running and update statistics
304 *
305 * This should be called every frame (or at least regularly) to:
306 * - Check if the process has exited
307 * - Update play time statistics
308 * - Trigger exit callbacks if process stopped
309 *
310 * Automatically transitions state to Stopped if process has exited.
311 */
312 void update();
313
314 private:
315 // ==========================================================================
316 // Private Methods
317 // ==========================================================================
318
319 void updateState(State newState);
320 std::string buildLaunchCommand() const;
321 std::string buildDirectProtonCommand(const std::string& protonExe);
322 bool launchNative();
323 bool launchWine();
324 bool launchProton();
325 bool launchDOSBox();
326 bool launchScummVM();
327 bool checkProcessRunning();
328
329 // Launch option conflict detection (warnings only, does not block launch)
330 void checkLaunchOptionConflicts();
331
332 // Direct command execution (for Wine/Proton launches that build their own command)
333 bool executeCommand(const std::string& command);
334
335 // Proton-specific helpers
336 std::string findProtonExecutable(const std::string& versionName) const;
337 std::string findProtonPath(const std::string& versionName) const;
338 std::string resolveProtonExecutable() const;
339
340 // Non-Steam Proton launch methods
341 static bool isUmuLauncherAvailable();
342 bool launchProtonWithUmu();
343 bool launchProtonDirect();
344 bool launchProtonSteamGame();
345 bool launchViaSteamApplaunch();
346
347 // Steam-specific helpers
348 static bool isSteamRunning();
349 static bool ensureSteamRunning();
350
351 // Child process tracking helpers (for launcher games like Battle.net, EA App)
352 std::vector<int> getChildProcesses(int parentPid) const;
353 std::string getProcessName(int pid) const;
354 std::string getWineExecutableName(int pid) const; // Extract .exe name from Wine process cmdline
355 bool isExcludedProcess(const std::string& processName) const;
356 int findGameProcess() const;
357
358 // Wine process management
359 void killWinePrefix(bool force) const;
360
361 // ==========================================================================
362 // Member Variables
363 // ==========================================================================
364
365 Game game_; // Copy of game being run (owned by GameProcess to prevent dangling reference)
366 State state_; // Current process state
367 int pid_; // Process ID (-1 if not running)
368 int trackedPid_; // Actual game process PID (may differ from pid_ for launchers)
369 std::string trackedProcessName_; // Name of the tracked game process (e.g., "Wow.exe")
370 time_t startTime_; // Time when process started
371 bool isAttachedProcess_; // True if we attached to an already-running process (vs spawned it)
372 int gamemodePid_; // PID that has an active GameMode API request (-1 if none)
373
374 LaunchInfo lastLaunchInfo_; // Information about applied optimizations from last launch
375
376 std::function<void(State)> onStateChanged_;
377 std::function<void(int)> onExit_;
378 std::function<void(NotificationType, const std::string&)> onNotification_;
379
380 protected:
381 // Helper to emit notifications through callback (if set)
382 void notify(NotificationType type, const std::string& message) const;
383};
384
385// ==============================================================================
386// Game Process Manager (Singleton)
387// ==============================================================================
388
389class GameProcessManager
390{
391 public:
392 // ==========================================================================
393 // Singleton Access
394 // ==========================================================================
395
396 static GameProcessManager& instance();
397
398 // ==========================================================================
399 // Process Management
400 // ==========================================================================
401
402 // Launch a game
403 // Returns true if launch was initiated successfully
404 bool launchGame(const std::string& gameId, Game& game);
405
406 // Stop a running game
407 // Returns true if stop was initiated successfully
408 bool stopGame(const std::string& gameId, Game* game = nullptr, bool force = false);
409
410 // Check if a game is currently running
411 bool isGameRunning(const std::string& gameId) const;
412
413 // Get the running process for a game (returns nullptr if not running)
414 // Note: Returns raw pointer - do not store, only use for immediate access
415 // DEPRECATED: Use getRunningProcessSnapshot() for thread-safe access
416 const GameProcess* getRunningProcess(const std::string& gameId) const;
417
418 // Thread-safe snapshot of process state - copies data under the internal lock
420 {
421 bool found = false;
422 int primaryPid = -1;
423 int trackedPid = -1;
426 };
427 ProcessSnapshot getRunningProcessSnapshot(const std::string& gameId) const;
428
429 // Get list of all running game IDs
430 std::vector<std::string> getRunningGameIds() const;
431
432 // Get the session duration for a running game (works for both Steam and non-Steam games)
433 // Returns 0 if the game is not running or no start time is recorded
434 std::chrono::seconds getGameSessionDuration(const std::string& gameId) const;
435
436 // Get the exit code from the last process exit for a game.
437 // Returns defaultCode if no exit has been recorded for this game ID.
438 int getLastExitCode(const std::string& gameId, int defaultCode = 0) const;
439
440 // Scan system for already-running games from the library.
441 // gameAccessCallback: called with (gameId, updater) — runs the updater on the
442 // Game while holding the library's internal lock. This avoids returning a
443 // bare Game* that can become dangling when the library is modified on another thread.
445 std::function<void(const std::string& gameId, std::function<void(Game&)>)>;
446 void scanForRunningGames(const std::vector<Game*>& games,
447 GameAccessCallback gameAccessCallback);
448
449 // ==========================================================================
450 // Callbacks
451 // ==========================================================================
452
453 // Set callback for notifications. Defined out-of-line in .cpp because
454 // it needs callbacksMutex_, which is declared after this section.
455 //
456 // std::function is not atomic; setter and the detection-thread reader
457 // would race without external synchronisation. callbacksMutex_ pairs
458 // the writes here with snapshot reads in getOnNotification() /
459 // getOnGameStatsUpdated() — same pattern already applied to
460 // SteamProcessMonitor::setStateCallback and SteamDownloadMonitor's
461 // setOn* family.
463 std::function<void(GameProcess::NotificationType, const std::string&)> callback);
464
465 // Set callback for when game statistics are updated.
466 void setOnGameStatsUpdated(std::function<void(const std::string& gameId)> callback);
467
468 // Snapshot helpers — return a copy of the callback under the mutex so
469 // the caller can safely invoke it outside the lock (no re-entry risk
470 // and the std::function can't be torn out from under us mid-call).
471 std::function<void(GameProcess::NotificationType, const std::string&)>
472 getOnNotification() const;
473 std::function<void(const std::string&)> getOnGameStatsUpdated() const;
474
475 // ==========================================================================
476 // Update (call each frame)
477 // ==========================================================================
478
479 // Update all running game processes
480 void update();
481
482 private:
483 // ==========================================================================
484 // Private Constructor (Singleton)
485 // ==========================================================================
486
487 GameProcessManager();
488 ~GameProcessManager();
489 GameProcessManager(const GameProcessManager&) = delete;
490 GameProcessManager& operator=(const GameProcessManager&) = delete;
491
492 // ==========================================================================
493 // Member Variables
494 // ==========================================================================
495
496 // Lock ordering convention to prevent deadlocks:
497 // runningProcessesMutex_ -> steamGamesMutex_ -> steamStartTimesMutex_ -> appIdMapMutex_
498 // Always acquire in this order when multiple locks are needed.
499
500 // Map of game ID -> GameProcess (for non-Steam games)
501 std::map<std::string, std::unique_ptr<GameProcess>> runningProcesses_;
502 mutable std::mutex runningProcessesMutex_;
503
504 // Map of Steam App ID to current game ID for running Steam games (stable across re-imports)
505 std::map<int, std::string> runningSteamGames_;
506 mutable std::mutex steamGamesMutex_;
507
508 // Map of Steam App IDs to their start times (for playtime tracking)
509 std::map<int, time_t> steamGameStartTimes_;
510 mutable std::mutex steamStartTimesMutex_;
511
512 // Map of Steam App IDs to their pre-session baseline playtime (seconds).
513 // Captured when a game starts so heartbeats and exit can compute:
514 // totalPlayTimeSeconds = baseline + sessionTime
515 // This avoids double-counting when heartbeats persist interim playtime.
516 std::map<int, double> steamGameBasePlaytime_;
517
518 // Background thread for continuous game detection
519 std::thread detectionThread_;
520 std::atomic<bool> shouldStopDetection_;
521
522 // Steam App ID → Game ID mapping for background thread (eliminates dangling pointer risk)
523 std::map<int, std::string> steamAppIdToGameId_;
524 std::mutex appIdMapMutex_;
525
526 // Last recorded exit code per game ID (populated via setOnExit callbacks)
527 std::map<std::string, int> lastExitCodes_;
528 mutable std::mutex exitCodesMutex_;
529
530 void storeExitCode(const std::string& gameId, int code);
531
532 // Callback to safely access and update a game by ID while holding the library lock.
533 // Signature: void(gameId, std::function<void(Game&)> updater)
535
536 // Notification callback. Read-modify across threads; protected by
537 // callbacksMutex_. Use getOnNotification() / getOnGameStatsUpdated()
538 // to snapshot before invoking.
539 std::function<void(GameProcess::NotificationType, const std::string&)> onNotification_;
540
541 // Callback for when game statistics are updated and need persistence
542 std::function<void(const std::string& gameId)> onGameStatsUpdated_;
543
544 // Pairs setter writes with snapshot reads. Mutable so const accessors
545 // (getOnNotification / getOnGameStatsUpdated) can take it.
546 mutable std::mutex callbacksMutex_;
547
548 // Heartbeat timer for periodic playtime persistence (crash-safe)
549 time_t lastHeartbeat_ = 0;
550
551 // Heartbeat timer for Steam games in the detection thread
552 time_t lastSteamHeartbeat_ = 0;
553
554 // Helper to emit notifications through callback (if set)
555 void notify(GameProcess::NotificationType type, const std::string& message);
556
557 // Background thread function
558 void detectionThreadFunction();
559
560 // Scan for already-running Wine/Proton games at startup
561 void scanForRunningWineGames(const std::vector<Game*>& games);
562
563 // Helper to poll system for running Steam games and update tracking
564 void pollRunningSteamGames();
565
566 // Helper to check if a specific Steam App ID is running on the system
567 bool isSteamGameRunningOnSystem(int steamAppId) const;
568
569 // Helper to check if Steam client is running
570 bool isSteamRunning() const;
571
572 // Helper to ensure Steam is running (starts it if not)
573 bool ensureSteamRunning();
574
575 // Helper to kill a Steam game by its App ID
576 bool killSteamGame(int steamAppId);
577
578 // Find PIDs of game processes for a Steam App ID by scanning
579 // /proc/<pid>/environ for SteamAppId=<id>. Used as a fallback when
580 // pgrep -f 'reaper SteamLaunch AppId=<id>' finds nothing — some games
581 // (notably MTGA's launcher → game double-spawn pattern) escape Steam's
582 // reaper, leaving the game process alive after the reaper exits. This
583 // catches those orphans. Filters out Wine/Proton helpers (wineserver,
584 // services.exe, etc.) that inherit SteamAppId but aren't the game.
585 std::vector<int> findGamePidsByAppId(int steamAppId) const;
586
587 // Helper to detect why a Steam game exited
588 // Returns: "normal", "crash", "timeout", or "unknown"
589 std::string detectSteamGameExitReason(int steamAppId, time_t startTime) const;
590
591 // Helper to build full launch command with environment variables and wrappers
592 static std::string buildLaunchCommand(const Game& game);
593};
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.
void setOnExit(std::function< void(int exitCode)> callback)
Set callback for process exit.
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.
void setOnNotification(std::function< void(NotificationType, const std::string &)> callback)
Set callback for notifications.
bool launch()
Launch the game process.
void notify(NotificationType type, const std::string &message) const
State getState() const
Get current process state.
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.
void setOnStateChanged(std::function< void(State)> callback)
Set callback for state changes.
NotificationType
Type of notification to display.
const Game & getGame() const
Get the game associated with this process.
Complete representation of a game in the library.
Definition game.h:767
Information about optimizations and settings applied during game launch.
Definition game.h:268