game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_state_sync.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_state_sync.cpp
4// ==============================================================================
5// Automatic game state synchronization service
6// ==============================================================================
7
8#include "game_state_sync.h"
9#include "logger.h"
10#include <chrono>
11#include <filesystem>
12#include <thread>
13#include <utility>
14
15// ==============================================================================
16// Singleton Access
17// ==============================================================================
18
20{
21 static GameStateSync instance;
22 return instance;
23}
24
25// ==============================================================================
26// Constructor / Destructor
27// ==============================================================================
28
29GameStateSync::GameStateSync()
30 : library_(nullptr), steamScanner_(nullptr), shouldStop_(false), requestFullSync_(false)
31{
32 Logger::info("[GameStateSync] Initialized");
33}
34
35GameStateSync::~GameStateSync()
36{
37 stop();
38}
39
40// ==============================================================================
41// Control Methods
42// ==============================================================================
43
45{
46 if (syncThread_.joinable())
47 {
48 Logger::info("[GameStateSync] Already running");
49 return;
50 }
51
52 library_ = library;
53 steamScanner_ = steamScanner;
54 shouldStop_ = false;
55
56 syncThread_ = std::thread(&GameStateSync::syncThreadFunction, this);
57
58 Logger::info("[GameStateSync] Started background sync thread (interval: {}s)",
59 syncIntervalSeconds_);
60}
61
63{
64 if (!syncThread_.joinable())
65 {
66 return;
67 }
68
69 Logger::info("[GameStateSync] Stopping...");
70 shouldStop_ = true;
71
72 if (syncThread_.joinable())
73 {
74 syncThread_.join();
75 }
76
77 Logger::info("[GameStateSync] Stopped");
78}
79
80void GameStateSync::requestImmediateSync(const std::string& gameId)
81{
82 std::lock_guard<std::mutex> lock(gameIdsMutex_);
83 gamesNeedingSync_.insert(gameId);
84}
85
87{
88 requestFullSync_ = true;
89}
90
91// ==============================================================================
92// Configuration
93// ==============================================================================
94
95void GameStateSync::setSyncInterval(int intervalSeconds)
96{
97 syncIntervalSeconds_ = std::max(1, intervalSeconds);
98}
99
101{
102 transitionalStateTimeoutSeconds_ = std::max(5, timeoutSeconds);
103}
104
106{
107 autoRecoveryEnabled_ = enabled;
108}
109
111{
112 std::lock_guard<std::mutex> lock(callbackMutex_);
113 stateChangeCallback_ = std::move(callback);
114}
115
117{
118 std::lock_guard<std::mutex> lock(callbackMutex_);
119 gameUpdateCallback_ = std::move(callback);
120}
121
122// ==============================================================================
123// Statistics
124// ==============================================================================
125
127{
128 std::lock_guard<std::mutex> lock(statsMutex_);
129 return stats_;
130}
131
132// ==============================================================================
133// Main Sync Thread
134// ==============================================================================
135
136void GameStateSync::syncThreadFunction()
137{
138 Logger::info("[GameStateSync] Sync thread started");
139
140 while (!shouldStop_)
141 {
142 try
143 {
144 if (!library_)
145 {
146 std::this_thread::sleep_for(std::chrono::seconds(1));
147 continue;
148 }
149
150 // Get all games or just ones needing sync
151 std::set<std::string> gamesToSync;
152 bool doFullSync = requestFullSync_.exchange(false);
153
154 {
155 std::lock_guard<std::mutex> lock(gameIdsMutex_);
156 gamesToSync = gamesNeedingSync_;
157 gamesNeedingSync_.clear();
158 }
159
160 if (doFullSync || gamesToSync.empty())
161 {
162 // Full sync - check all games.
163 // Collect IDs while the library lock is implicitly held inside getAllGames(),
164 // then look each game up fresh via getGame() to avoid use-after-free if a
165 // game is removed between getAllGames() returning and syncGame() running.
166 std::vector<std::string> gameIds;
167 {
168 auto allGames = library_->getAllGames();
169 gameIds.reserve(allGames.size());
170 for (const auto* g : allGames)
171 gameIds.push_back(g->id);
172 }
173 for (const auto& gid : gameIds)
174 {
175 auto gameOpt = library_->getGame(gid);
176 if (gameOpt.has_value())
177 syncGame(*gameOpt);
178 }
179
180 {
181 std::lock_guard<std::mutex> lock(statsMutex_);
182 stats_.totalSyncCycles++;
183 stats_.lastSyncTime = time(nullptr);
184 }
185 }
186 else
187 {
188 // Partial sync - only requested games
189 for (const auto& gameId : gamesToSync)
190 {
191 auto gameOpt = library_->getGame(gameId);
192 if (gameOpt.has_value())
193 {
194 syncGame(*gameOpt);
195 }
196 }
197
198 {
199 std::lock_guard<std::mutex> lock(statsMutex_);
200 stats_.totalSyncCycles++;
201 stats_.lastSyncTime = time(nullptr);
202 }
203 }
204 }
205 catch (const std::exception& e)
206 {
207 Logger::error("[GameStateSync] Error in sync thread: {}", e.what());
208 }
209
210 // Sleep for configured interval
211 for (int i = 0; i < syncIntervalSeconds_ && !shouldStop_; ++i)
212 {
213 std::this_thread::sleep_for(std::chrono::seconds(1));
214 }
215 }
216
217 Logger::info("[GameStateSync] Sync thread stopped");
218}
219
220// ==============================================================================
221// Sync Individual Game
222// ==============================================================================
223
224void GameStateSync::syncGame(Game* game)
225{
226 if (!game || !autoRecoveryEnabled_)
227 {
228 return;
229 }
230
231 // Check for stuck transitional states
234 {
235 fixTransitionalState(game);
236 }
237
238 // Verify installation status matches reality
239 if (game->metadata.isSteamGame)
240 {
241 // Sync Steam game state
242 if (verifySteamInstallation(game))
243 {
244 // Installation status is correct
245 }
246 }
247 else
248 {
249 // Verify non-Steam game files exist
250 verifyLocalInstallation(game);
251 }
252}
253
254// ==============================================================================
255// Fix Stuck Transitional States
256// ==============================================================================
257
258void GameStateSync::fixTransitionalState(Game* game)
259{
260 // Track when this game entered transitional state
261 std::string gameId = game->id;
262 time_t now = time(nullptr);
263 time_t stateStartTime = 0;
264
265 {
266 std::lock_guard<std::mutex> lock(transitionalStatesMutex_);
267 auto it = transitionalStateStartTimes_.find(gameId);
268 if (it == transitionalStateStartTimes_.end())
269 {
270 // First time seeing this game in transitional state
271 transitionalStateStartTimes_[gameId] = now;
272 return; // Give it time
273 }
274 stateStartTime = it->second;
275 }
276
277 // Check if timeout exceeded
278 double timeInState = difftime(now, stateStartTime);
279 if (timeInState < transitionalStateTimeoutSeconds_)
280 {
281 // Still within timeout, don't fix yet
282 return;
283 }
284
285 // Timeout exceeded - fix the state
286 Logger::info("[GameStateSync] Fixing stuck state for: {} (stuck in {} for {}s)", game->name,
287 game->getStatusName(), static_cast<int>(timeInState));
288
289 GameStatus newStatus;
290
291 // Determine appropriate status based on installation
292 if (game->metadata.isSteamGame)
293 {
294 newStatus =
296 }
297 else
298 {
299 // For non-Steam games, check if executable exists
300 if (!game->runnerConfig.executablePath.empty() &&
301 std::filesystem::exists(game->runnerConfig.executablePath))
302 {
303 newStatus = GameStatus::Installed;
304 }
305 else
306 {
307 newStatus = GameStatus::NotInstalled;
308 }
309 }
310
311 transitionGameState(game, newStatus);
312
313 // Remove from transitional state tracking
314 {
315 std::lock_guard<std::mutex> lock(transitionalStatesMutex_);
316 transitionalStateStartTimes_.erase(gameId);
317 }
318
319 // Update statistics
320 {
321 std::lock_guard<std::mutex> lock(statsMutex_);
322 stats_.gamesFixed++;
323 }
324}
325
326// ==============================================================================
327// Verify Steam Installation
328// ==============================================================================
329
330bool GameStateSync::verifySteamInstallation(Game* game)
331{
332 if (!game->metadata.isSteamGame || !steamScanner_)
333 {
334 return false;
335 }
336
337 // Check if game's steamInstalled flag matches what Steam scanner sees
338 // This is a lightweight check - full rescan happens elsewhere
339
340 GameStatus expectedStatus =
342
343 // Only fix if status is clearly wrong and game is not running
344 if (game->status != expectedStatus && game->status != GameStatus::Running)
345 {
346 // Additional check: don't change status for transitional states that might be valid
349 {
351 "[GameStateSync] Correcting installation status for: {} (was: {}, should be: {})",
352 game->name, game->getStatusName(),
353 (game->metadata.steamInstalled ? "Installed" : "NotInstalled"));
354
355 transitionGameState(game, expectedStatus);
356 }
357 }
358
359 return true;
360}
361
362// ==============================================================================
363// Verify Local Installation
364// ==============================================================================
365
366bool GameStateSync::verifyLocalInstallation(Game* game)
367{
368 // Check if executable path exists
369 bool executableExists = !game->runnerConfig.executablePath.empty() &&
370 std::filesystem::exists(game->runnerConfig.executablePath);
371
372 bool shouldBeInstalled = executableExists || !game->installPath.empty();
373
374 GameStatus expectedStatus =
376
377 // Only fix if clearly wrong and not running
378 if (game->status != expectedStatus && game->status != GameStatus::Running)
379 {
382 {
383 Logger::info("[GameStateSync] Correcting local game status for: {} (executable {})",
384 game->name, (executableExists ? "exists" : "missing"));
385
386 transitionGameState(game, expectedStatus);
387 }
388 }
389
390 return executableExists;
391}
392
393// ==============================================================================
394// State Transition with Callback
395// ==============================================================================
396
397void GameStateSync::transitionGameState(Game* game, GameStatus newStatus)
398{
399 GameStatus oldStatus = game->status;
400
401 if (oldStatus == newStatus)
402 {
403 return;
404 }
405
406 // Copy callbacks under lock, invoke outside
407 StateChangeCallback stateCb;
408 GameUpdateCallback updateCb;
409 {
410 std::lock_guard<std::mutex> lock(callbackMutex_);
411 stateCb = stateChangeCallback_;
412 updateCb = gameUpdateCallback_;
413 }
414
415 // Mutate game status via the execute-under-lock callback when available,
416 // which holds the library controller's mutex and prevents data races with
417 // the main thread. Fall back to direct mutation only when no callback is set
418 // (e.g., in unit tests or if wiring is not complete).
419 if (updateCb)
420 {
421 std::string gameId = game->id;
422 updateCb(gameId, [newStatus](Game& g) { g.status = newStatus; });
423 }
424 else
425 {
426 game->status = newStatus;
427 }
428
429 // Update statistics
430 {
431 std::lock_guard<std::mutex> lock(statsMutex_);
432 stats_.statusChanges++;
433 }
434
435 if (stateCb)
436 {
437 stateCb(game->id, oldStatus, newStatus);
438 }
439
440 Logger::info("[GameStateSync] State transition: {} - {} -> {}", game->name,
441 static_cast<int>(oldStatus), static_cast<int>(newStatus));
442}
Central database for managing all games in the launcher.
void setStateChangeCallback(StateChangeCallback callback)
void requestFullSync()
Request immediate sync of all games.
void setTransitionalStateTimeout(int timeoutSeconds)
Set timeout for transitional states (default: 60 seconds).
void setSyncInterval(int intervalSeconds)
Set sync interval (default: 10 seconds).
void start(GameLibrary *library, SteamLibraryScanner *steamScanner)
Start the background sync thread.
Stats getStats() const
std::function< void(const std::string &gameId, std::function< void(Game &)>)> GameUpdateCallback
void setAutoRecoveryEnabled(bool enabled)
Enable/disable automatic status recovery.
void requestImmediateSync(const std::string &gameId)
Request immediate sync of a specific game.
void stop()
Stop the background sync thread.
void setGameUpdateCallback(GameUpdateCallback callback)
std::function< void(const std::string &gameId, GameStatus oldStatus, GameStatus newStatus)> StateChangeCallback
static GameStateSync & instance()
Complete representation of a game in the library.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::string installPath
Installation directory path.
Definition game.h:819
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
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
GameStatus status
Current installation and execution status.
Definition game.h:778
std::string getStatusName() const
Get human-readable status name.
Definition game.cpp:95
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
Scans Steam installations to discover games.
GameStatus
Current installation and execution status of the game.
Definition game.h:97
@ Installing
Game is being installed.
Definition game.h:103
@ NotInstalled
Game is in library but not installed.
Definition game.h:98
@ Running
Game is currently running.
Definition game.h:101
@ Closing
Game is shutting down (waiting for process to terminate).
Definition game.h:102
@ Updating
Game is being updated.
Definition game.h:104
@ Installed
Game is installed and ready to play.
Definition game.h:99
@ Launching
Game is being launched (waiting for process to start).
Definition game.h:100
bool isSteamGame
True if imported from Steam.
Definition game.h:574
bool steamInstalled
True if Steam game is installed (set during Steam import).
Definition game.h:576
std::string executablePath
Full path to game executable.
Definition game.h:141
@ Game
Game-specific fixes.