game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
launch_controller.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// launch_controller.cpp
4// ==============================================================================
5// Thread Safety Design:
6// - All callbacks are invoked OUTSIDE mutex locks to prevent deadlocks
7// - Events are collected inside the lock, then fired after releasing the lock
8// - Pattern: lock -> collect events/copy callbacks -> unlock -> fire callbacks
9// ==============================================================================
10
12#include "game.h"
13#include "game_process.h"
15#include "launch_manager.h"
16#include "logger.h"
17#include "steam_monitor.h"
18
19#include <map>
20#include <mutex>
21
22namespace core
23{
24
25// ==============================================================================
26// Implementation
27// ==============================================================================
28
30{
31 public:
33 {
34 // Set up callbacks from GameProcessManager
36 }
37
38 ~Impl() = default;
39
41 {
42 // Note: GameProcessManager uses a different callback pattern
43 // We'll bridge it here to our event-based system
44 }
45
46 // Callbacks
51
52 mutable std::mutex mutex_;
53
54 // Track active launches for state management
55 std::map<std::string, LaunchState> gameStates_;
56 std::map<std::string, std::chrono::steady_clock::time_point> startTimes_;
57};
58
59// ==============================================================================
60// Constructor / Destructor
61// ==============================================================================
62
63LaunchController::LaunchController() : impl_(std::make_unique<Impl>()) {}
64
66{
67 // Clear the singleton callback so it doesn't fire against our destroyed impl_
69}
70
72LaunchController& LaunchController::operator=(LaunchController&&) noexcept = default;
73
74// ==============================================================================
75// Launch Operations
76// ==============================================================================
77
78bool LaunchController::launchGame(const std::string& gameId, const Game& game)
79{
80 bool alreadyRunning = false;
81 OnLaunchError onLaunchErrorCopy;
82 OnStateChanged onStateChangedCopy;
83 LaunchErrorEvent errorEvent;
84 LaunchStateChangedEvent stateEvent;
85
86 {
87 std::lock_guard<std::mutex> lock(impl_->mutex_);
88
89 // Copy callbacks for use outside lock
90 onLaunchErrorCopy = impl_->onLaunchError_;
91 onStateChangedCopy = impl_->onStateChanged_;
92
93 // Check if already running
95 {
96 alreadyRunning = true;
97 errorEvent.gameId = gameId;
98 errorEvent.errorMessage = "Game is already running";
99 errorEvent.isRecoverable = true;
100 }
101 else
102 {
103 // Update state
104 impl_->gameStates_[gameId] = LaunchState::PreparingLaunch;
105 impl_->startTimes_[gameId] = std::chrono::steady_clock::now();
106
107 stateEvent.gameId = gameId;
108 stateEvent.oldState = LaunchState::Idle;
110 stateEvent.message = "Preparing to launch " + game.name;
111 }
112 }
113
114 // Fire callbacks outside lock
115 if (alreadyRunning)
116 {
117 if (onLaunchErrorCopy)
118 {
119 onLaunchErrorCopy(errorEvent);
120 }
121 return false;
122 }
123
124 if (onStateChangedCopy)
125 {
126 onStateChangedCopy(stateEvent);
127 }
128
129 // Register completion callback so launch failures reach the UI.
130 // (Success is detected in update() via GameProcessManager::isGameRunning.)
132 [this, gameId](bool success, const std::string& message)
133 {
134 if (success)
135 return; // update() handles the running→completed path
136
137 OnLaunchError errCb;
138 LaunchErrorEvent errEvent;
139
140 {
141 std::lock_guard<std::mutex> lock(impl_->mutex_);
142 // Remove stuck PreparingLaunch entry so the slot is freed
143 impl_->gameStates_.erase(gameId);
144 impl_->startTimes_.erase(gameId);
145 errCb = impl_->onLaunchError_;
146 }
147
148 errEvent.gameId = gameId;
149 errEvent.errorMessage = message;
150 errEvent.isRecoverable = false;
151
152 Logger::error("[LaunchController] Launch failed for {}: {}", gameId, message);
153 if (errCb)
154 errCb(errEvent);
155 });
156
157 // Use GameLaunchManager for the actual launch (uses requestLaunch, not launchGame)
159
160 // Note: requestLaunch is async, so we return true to indicate launch was initiated
161 // The actual success/failure will come through the completion callback above
162 return true;
163}
164
165bool LaunchController::stopGame(const std::string& gameId)
166{
167 // Check if game is running (works for both process-tracked and Steam games)
169 {
170 return false;
171 }
172
173 OnStateChanged onStateChangedCopy;
174 LaunchStateChangedEvent stateEvent;
175
176 {
177 std::lock_guard<std::mutex> lock(impl_->mutex_);
178 impl_->gameStates_[gameId] = LaunchState::Stopping;
179 onStateChangedCopy = impl_->onStateChanged_;
180
181 stateEvent.gameId = gameId;
182 stateEvent.oldState = LaunchState::Running;
183 stateEvent.newState = LaunchState::Stopping;
184 stateEvent.message = "Stopping game...";
185 }
186
187 if (onStateChangedCopy)
188 {
189 onStateChangedCopy(stateEvent);
190 }
191
192 // Request graceful stop
194 return true;
195}
196
197bool LaunchController::killGame(const std::string& gameId)
198{
199 // Check if game is running (works for both process-tracked and Steam games)
201 {
202 return false;
203 }
204
205 OnStateChanged onStateChangedCopy;
206 LaunchStateChangedEvent stateEvent;
207
208 {
209 std::lock_guard<std::mutex> lock(impl_->mutex_);
210 impl_->gameStates_[gameId] = LaunchState::Killing;
211 onStateChangedCopy = impl_->onStateChanged_;
212
213 stateEvent.gameId = gameId;
214 stateEvent.oldState = LaunchState::Running;
215 stateEvent.newState = LaunchState::Killing;
216 stateEvent.message = "Force killing game...";
217 }
218
219 if (onStateChangedCopy)
220 {
221 onStateChangedCopy(stateEvent);
222 }
223
224 // Force kill via SIGKILL (not graceful SIGTERM)
225 GameProcessManager::instance().stopGame(gameId, nullptr, true);
226 return true;
227}
228
230{
231 // Stop all running games
233 for (const auto& gameId : runningIds)
234 {
236 }
237}
238
239// ==============================================================================
240// Query Running State
241// ==============================================================================
242
247
248bool LaunchController::isGameRunning(const std::string& gameId) const
249{
251}
252
253LaunchState LaunchController::getGameState(const std::string& gameId) const
254{
255 std::lock_guard<std::mutex> lock(impl_->mutex_);
256
257 auto it = impl_->gameStates_.find(gameId);
258 if (it != impl_->gameStates_.end())
259 {
260 return it->second;
261 }
262
263 // Check with GameProcessManager
265 {
267 }
268
269 return LaunchState::Idle;
270}
271
272std::optional<RunningGameInfo> LaunchController::getRunningGameInfo(const std::string& gameId) const
273{
274 // Use snapshot to copy process data atomically under the internal lock,
275 // avoiding use-after-free if the process is removed by another thread.
277 if (!snap.found)
278 {
279 return std::nullopt;
280 }
281
282 RunningGameInfo info;
283 info.gameId = gameId;
284 info.gameName = snap.trackedProcessName.empty() ? gameId : snap.trackedProcessName;
285 info.primaryPid = snap.primaryPid;
286 info.trackedPid = snap.trackedPid;
287 info.trackedProcessName = snap.trackedProcessName;
288 info.winePrefix = snap.launchInfo.winePrefix;
289 info.protonVersion = snap.launchInfo.runnerVersion;
290 info.gameModeEnabled = snap.launchInfo.gameMode;
291 info.mangoHudEnabled = snap.launchInfo.mangoHud;
292
293 // Get start time from our tracking
294 std::lock_guard<std::mutex> lock(impl_->mutex_);
295 auto timeIt = impl_->startTimes_.find(gameId);
296 if (timeIt != impl_->startTimes_.end())
297 {
298 info.startTime = timeIt->second;
299 }
300 else
301 {
302 info.startTime = std::chrono::steady_clock::now();
303 }
304
305 auto stateIt = impl_->gameStates_.find(gameId);
306 info.state = (stateIt != impl_->gameStates_.end()) ? stateIt->second : LaunchState::Running;
307
308 return info;
309}
310
311std::vector<RunningGameInfo> LaunchController::getAllRunningGames() const
312{
313 std::vector<RunningGameInfo> result;
314
316 for (const auto& gameId : runningIds)
317 {
318 if (auto info = getRunningGameInfo(gameId))
319 {
320 result.push_back(*info);
321 }
322 }
323
324 return result;
325}
326
331
332// ==============================================================================
333// Steam Integration
334// ==============================================================================
335
340
345
347{
348 switch (SteamProcessMonitor::instance().getCurrentState())
349 {
351 return "Not running";
353 return "Starting...";
355 return "Running";
357 return "Stopping...";
358 default:
359 return "Unknown";
360 }
361}
362
363// ==============================================================================
364// Session Statistics
365// ==============================================================================
366
367std::chrono::seconds LaunchController::getSessionDuration(const std::string& gameId) const
368{
369 // Use GameProcessManager's unified method that handles both Steam and non-Steam games
371 if (duration.count() > 0)
372 {
373 return duration;
374 }
375
376 // Fallback to our recorded start times (for games we launched directly)
377 std::lock_guard<std::mutex> lock(impl_->mutex_);
378
379 auto it = impl_->startTimes_.find(gameId);
380 if (it == impl_->startTimes_.end())
381 {
382 return std::chrono::seconds(0);
383 }
384
385 auto now = std::chrono::steady_clock::now();
386 return std::chrono::duration_cast<std::chrono::seconds>(now - it->second);
387}
388
390{
391 std::lock_guard<std::mutex> lock(impl_->mutex_);
392
393 std::chrono::seconds total(0);
394 auto now = std::chrono::steady_clock::now();
395
396 for (const auto& [gameId, startTime] : impl_->startTimes_)
397 {
399 {
400 total += std::chrono::duration_cast<std::chrono::seconds>(now - startTime);
401 }
402 }
403
404 return total;
405}
406
407// ==============================================================================
408// Event Subscriptions
409// ==============================================================================
410
412{
413 std::lock_guard<std::mutex> lock(impl_->mutex_);
414 impl_->onStateChanged_ = std::move(callback);
415}
416
418{
419 std::lock_guard<std::mutex> lock(impl_->mutex_);
420 impl_->onProcessStarted_ = std::move(callback);
421}
422
424{
425 std::lock_guard<std::mutex> lock(impl_->mutex_);
426 impl_->onProcessExited_ = std::move(callback);
427}
428
430{
431 std::lock_guard<std::mutex> lock(impl_->mutex_);
432 impl_->onLaunchError_ = std::move(callback);
433}
434
435// ==============================================================================
436// Background Processing
437// ==============================================================================
438
440{
441 // Poll running processes (check if any have exited)
443
444 // Collect events to fire outside the lock to prevent deadlock
445 std::vector<LaunchStateChangedEvent> stateChangedEvents;
446 std::vector<ProcessStartedEvent> processStartedEvents;
447 std::vector<ProcessExitedEvent> processExitedEvents;
448 OnStateChanged onStateChangedCopy;
449 OnProcessStarted onProcessStartedCopy;
450 OnProcessExited onProcessExitedCopy;
451
452 {
453 std::lock_guard<std::mutex> lock(impl_->mutex_);
454
455 // Copy callbacks for use outside lock
456 onStateChangedCopy = impl_->onStateChanged_;
457 onProcessStartedCopy = impl_->onProcessStarted_;
458 onProcessExitedCopy = impl_->onProcessExited_;
459
460 // Check for state changes in running games
461 std::vector<std::string> toRemove;
462
463 for (auto& [gameId, state] : impl_->gameStates_)
464 {
465 bool isRunning = GameProcessManager::instance().isGameRunning(gameId);
466
467 if (state == LaunchState::PreparingLaunch || state == LaunchState::Launching ||
469 {
470 if (isRunning)
471 {
472 // Game started successfully
473 LaunchState oldState = state;
474 state = LaunchState::Running;
475
476 LaunchStateChangedEvent stateEvent;
477 stateEvent.gameId = gameId;
478 stateEvent.oldState = oldState;
479 stateEvent.newState = LaunchState::Running;
480 stateEvent.message = "Game is running";
481 stateChangedEvents.push_back(stateEvent);
482
484 if (snap.found)
485 {
486 ProcessStartedEvent startEvent;
487 startEvent.gameId = gameId;
488 startEvent.processId = snap.primaryPid;
489 startEvent.processName = snap.trackedProcessName;
490 processStartedEvents.push_back(startEvent);
491 }
492
493 // Activate screensaver inhibition and performance power profile
495 }
496 }
497 else if (state == LaunchState::Running || state == LaunchState::Stopping ||
498 state == LaunchState::Killing)
499 {
500 if (!isRunning)
501 {
502 // Game exited
503 LaunchState oldState = state;
505
506 auto startIt = impl_->startTimes_.find(gameId);
507 std::chrono::seconds duration(0);
508 if (startIt != impl_->startTimes_.end())
509 {
510 auto now = std::chrono::steady_clock::now();
511 duration =
512 std::chrono::duration_cast<std::chrono::seconds>(now - startIt->second);
513 }
514
515 LaunchStateChangedEvent stateEvent;
516 stateEvent.gameId = gameId;
517 stateEvent.oldState = oldState;
518 stateEvent.newState = LaunchState::Completed;
519 stateEvent.message = "Game exited";
520 stateChangedEvents.push_back(stateEvent);
521
522 ProcessExitedEvent exitEvent;
523 exitEvent.gameId = gameId;
525 exitEvent.sessionDuration = duration;
526 processExitedEvents.push_back(exitEvent);
527
528 // Release screensaver inhibition and restore power profile
530
531 toRemove.push_back(gameId);
532 }
533 }
534 }
535
536 // Clean up completed games
537 for (const auto& gameId : toRemove)
538 {
539 impl_->gameStates_.erase(gameId);
540 impl_->startTimes_.erase(gameId);
541 }
542 }
543
544 // Fire callbacks outside the lock to prevent deadlock
545 if (onStateChangedCopy)
546 {
547 for (const auto& event : stateChangedEvents)
548 {
549 onStateChangedCopy(event);
550 }
551 }
552
553 if (onProcessStartedCopy)
554 {
555 for (const auto& event : processStartedEvents)
556 {
557 onProcessStartedCopy(event);
558 }
559 }
560
561 if (onProcessExitedCopy)
562 {
563 for (const auto& event : processExitedEvents)
564 {
565 onProcessExitedCopy(event);
566 }
567 }
568}
569
570} // namespace core
void requestLaunch(const Game &game)
static GameLaunchManager & instance()
void setCompletionCallback(CompletionCallback callback)
int getLastExitCode(const std::string &gameId, int defaultCode=0) const
bool stopGame(const std::string &gameId, Game *game=nullptr, bool force=false)
bool isGameRunning(const std::string &gameId) const
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()
static GameSessionService & instance()
Get singleton instance.
void onGameStopped()
Called when a game stops running.
void onGameStarted()
Called when a game starts running.
Complete representation of a game in the library.
Definition game.h:767
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
State getCurrentState() const
static SteamProcessMonitor & instance()
std::map< std::string, std::chrono::steady_clock::time_point > startTimes_
std::map< std::string, LaunchState > gameStates_
std::chrono::seconds getSessionDuration(const std::string &gameId) const
Get current session duration for a running game.
bool stopGame(const std::string &gameId)
Request graceful stop of a running game.
void setOnProcessStarted(OnProcessStarted callback)
void stopAllGames()
Stop all running games.
std::vector< RunningGameInfo > getAllRunningGames() const
Get all currently running games.
void setOnProcessExited(OnProcessExited callback)
bool killGame(const std::string &gameId)
Force kill a running game.
std::function< void(const LaunchStateChangedEvent &)> OnStateChanged
void setOnLaunchError(OnLaunchError callback)
void setOnStateChanged(OnStateChanged callback)
bool launchGame(const std::string &gameId, const Game &game)
Launch a game Returns true if launch was initiated (doesn't mean success yet).
size_t getRunningGameCount() const
Get the number of running games.
std::optional< RunningGameInfo > getRunningGameInfo(const std::string &gameId) const
Get info about a running game (returns nullopt if not running).
std::chrono::seconds getTotalSessionPlayTime() const
Get total play time recorded for this session.
std::string getSteamStateDescription() const
Get Steam state description.
bool hasRunningGames() const
Check if any game is currently running.
std::function< void(const LaunchErrorEvent &)> OnLaunchError
bool isSteamRunning() const
Check if Steam is running.
void requestSteamStart()
Request Steam to start (async).
void update()
Called periodically to update internal state (process monitoring, etc.) UI layer should call this fro...
LaunchState getGameState(const std::string &gameId) const
Get current launch state for a game.
std::function< void(const ProcessExitedEvent &)> OnProcessExited
bool isGameRunning(const std::string &gameId) const
Check if a specific game is running.
std::function< void(const ProcessStartedEvent &)> OnProcessStarted
std::chrono::seconds sessionDuration
std::chrono::steady_clock::time_point startTime