game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_library.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_library.h
4// ==============================================================================
5// Game library management - stores and manages all games
6// ==============================================================================
7// The GameLibrary class provides a centralized database of all games in the
8// launcher. It handles:
9// - Loading/saving the entire library to/from disk
10// - Adding, removing, and updating games
11// - Querying games by various criteria (platform, favorites, recently played)
12// - Managing collections (user-defined game groups)
13// - Tracking library statistics (total games, playtime, etc.)
14//
15// ## Storage Format
16// Each game is stored in a separate .game file in the library directory
17// (~/.local/share/gamelauncher/ on Linux). Collections are stored
18// in a separate collections.txt file.
19//
20// ## Performance Considerations
21// - Games are stored in a std::map for O(log n) lookups by ID
22// - Query methods return pointers to avoid copying Game objects
23// - Const-correctness is maintained for read-only operations
24// ==============================================================================
25
26#pragma once
27
28// ==============================================================================
29// Includes
30// ==============================================================================
31
32#include "game.h"
33#include "game_database.h"
34#include <map>
35#include <memory>
36#include <optional>
37#include <string>
38#include <string_view>
39#include <vector>
40
41// ==============================================================================
42// Game Library Class
43// ==============================================================================
44
45/**
46 * @class GameLibrary
47 * @brief Central database for managing all games in the launcher
48 *
49 * The GameLibrary is responsible for persistent storage and retrieval
50 * of all game data. It provides methods for CRUD operations on games,
51 * as well as powerful query capabilities for filtering and sorting.
52 *
53 * ## Thread Safety
54 * This class is NOT thread-safe. External synchronization is required
55 * if accessed from multiple threads.
56 */
58{
59 public:
60 // ==========================================================================
61 // Constructor & Destructor
62 // ==========================================================================
63
64 /**
65 * @brief Constructor - initializes library path
66 *
67 * Determines the platform-specific library storage location:
68 * - Linux: ~/.local/share/gamelauncher/
69 * - Windows: %APPDATA%/gamelauncher/
70 */
72
73 /**
74 * @brief Destructor - cleanup
75 *
76 * Note: The destructor does NOT automatically save to disk.
77 * Call saveToDisk() explicitly before destruction if needed.
78 */
80
81 // ==========================================================================
82 // Library Management
83 // ==========================================================================
84
85 /**
86 * @brief Load library from disk
87 *
88 * Reads all .game files from the library directory and loads them
89 * into memory. Also loads the collections list from collections.txt.
90 * Creates the library directory if it doesn't exist.
91 *
92 * @note This clears any games currently in memory before loading.
93 */
94 void loadFromDisk();
95
96 /**
97 * @brief Save library to disk
98 *
99 * Writes all games to individual .game files in the library directory.
100 * Also saves the collections list to collections.txt.
101 * Creates the library directory if it doesn't exist.
102 */
103 void saveToDisk();
104
105 // ==========================================================================
106 // Game Operations
107 // ==========================================================================
108
109 /**
110 * @brief Add a new game to the library
111 * @param game Game object to add (ID will be generated if empty)
112 * @return The ID assigned to the game
113 *
114 * If the game doesn't have an ID, a unique one will be generated.
115 * The game is added to the in-memory library but NOT saved to disk
116 * until saveToDisk() is called.
117 */
118 std::string addGame(const Game& game);
119
120 /**
121 * @brief Remove a game from the library
122 * @param gameId Unique ID of game to remove
123 * @return True if game was found and removed, false otherwise
124 *
125 * Removes the game from memory AND deletes its .game file from disk.
126 */
127 bool removeGame(const std::string& gameId);
128
129 /**
130 * @brief Update an existing game
131 * @param gameId ID of game to update
132 * @param updatedGame New game data (ID will be preserved)
133 * @return True if game was found and updated, false otherwise
134 *
135 * Updates the game in memory but does NOT save to disk until
136 * saveToDisk() is called.
137 */
138 bool updateGame(const std::string& gameId, const Game& updatedGame);
139
140 /**
141 * @brief Get a game by ID
142 * @param gameId Unique ID of game to retrieve
143 * @return Optional containing pointer to game if found, nullopt otherwise
144 *
145 * Returns a pointer to the game in the library. The pointer remains
146 * valid until the game is removed or the library is destroyed.
147 */
148 std::optional<Game*> getGame(const std::string& gameId);
149
150 /**
151 * @brief Get a game by ID (const version)
152 * @param gameId Unique ID of game to retrieve
153 * @return Optional containing const pointer to game if found, nullopt otherwise
154 */
155 std::optional<const Game*> getGame(const std::string& gameId) const;
156
157 // ==========================================================================
158 // Query Operations
159 // ==========================================================================
160
161 /**
162 * @brief Get all games in the library
163 * @return Vector of pointers to all games
164 *
165 * The returned pointers remain valid until games are removed or
166 * the library is destroyed. No particular order is guaranteed.
167 */
168 std::vector<Game*> getAllGames();
169
170 /**
171 * @brief Get all games in the library (const version)
172 * @return Vector of const pointers to all games
173 */
174 std::vector<const Game*> getAllGames() const;
175
176 /**
177 * @brief Get games filtered by platform
178 * @param platform Platform to filter by
179 * @return Vector of pointers to games matching the platform
180 */
181 std::vector<Game*> getGamesByPlatform(GamePlatform platform);
182
183 /**
184 * @brief Get games filtered by platform (const version)
185 * @param platform Platform to filter by
186 * @return Vector of const pointers to games matching the platform
187 */
188 std::vector<const Game*> getGamesByPlatform(GamePlatform platform) const;
189
190 /**
191 * @brief Get all favorite games
192 * @return Vector of pointers to favorite games
193 */
194 std::vector<Game*> getFavorites();
195
196 /**
197 * @brief Get all favorite games (const version)
198 * @return Vector of const pointers to favorite games
199 */
200 std::vector<const Game*> getFavorites() const;
201
202 /**
203 * @brief Get recently played games
204 * @param count Maximum number of games to return (default: 10)
205 * @return Vector of pointers to recently played games, sorted by
206 * last played time (most recent first)
207 */
208 std::vector<Game*> getRecentlyPlayed(int count = 10);
209
210 /**
211 * @brief Get recently played games (const version)
212 * @param count Maximum number of games to return (default: 10)
213 * @return Vector of const pointers to recently played games
214 */
215 std::vector<const Game*> getRecentlyPlayed(int count = 10) const;
216
217 /**
218 * @brief Get recent play sessions for a game from the database
219 * @param gameId Game ID
220 * @param limit Maximum sessions to return
221 * @return Vector of PlaySession records, most recent first
222 */
223 std::vector<PlaySession> getRecentSessions(const std::string& gameId, int limit = 20) const;
224
225 /**
226 * @brief Get all installed games
227 * @return Vector of pointers to games with status Installed or Running
228 */
229 std::vector<Game*> getInstalledGames();
230
231 /**
232 * @brief Get all installed games (const version)
233 * @return Vector of const pointers to installed games
234 */
235 std::vector<const Game*> getInstalledGames() const;
236
237 /**
238 * @brief Search games by name (case-insensitive substring match)
239 * @param query Search query string
240 * @return Vector of pointers to games whose name contains the query
241 *
242 * Performance: O(n) where n is total number of games.
243 * Uses std::string_view for efficient string handling.
244 */
245 std::vector<Game*> searchGames(std::string_view query);
246
247 /**
248 * @brief Search games by name (const version)
249 * @param query Search query string
250 * @return Vector of const pointers to matching games
251 */
252 std::vector<const Game*> searchGames(std::string_view query) const;
253
254 /**
255 * @brief Get games in a specific collection
256 * @param collectionName Name of collection to query
257 * @return Vector of pointers to games in the collection
258 */
259 std::vector<Game*> getGamesInCollection(const std::string& collectionName);
260
261 /**
262 * @brief Get games in a specific collection (const version)
263 * @param collectionName Name of collection to query
264 * @return Vector of const pointers to games in the collection
265 */
266 std::vector<const Game*> getGamesInCollection(const std::string& collectionName) const;
267
268 // ==========================================================================
269 // Statistics
270 // ==========================================================================
271
272 /**
273 * @brief Get total number of games in library
274 * @return Total game count (includes all statuses)
275 */
276 int getTotalGameCount() const;
277
278 /**
279 * @brief Get number of installed games
280 * @return Count of games with status Installed or Running
281 */
282 int getInstalledGameCount() const;
283
284 /**
285 * @brief Get total play time across all games
286 * @return Total play time in seconds (sum of all game play times)
287 */
288 double getTotalPlayTime() const;
289
290 // ==========================================================================
291 // Image Discovery
292 // ==========================================================================
293
294 /**
295 * @brief Discover and update images for games missing cover art
296 * @return Number of games that had images discovered
297 *
298 * Scans Steam's library cache for images and updates the database.
299 * Should be called in a background thread.
300 */
302
303 /**
304 * @brief Discover images for a specific game
305 * @param gameId ID of game to discover images for
306 * @return True if images were found and updated
307 */
308 bool discoverImagesForGame(const std::string& gameId);
309
310 /**
311 * @brief Refresh images for games with stale/missing image files
312 * @return Number of games that had images refreshed
313 *
314 * Checks if stored image paths still exist on disk. For any that don't,
315 * attempts to re-discover images from Steam's cache. This handles cases
316 * where Steam has updated its cache structure or cleared old images.
317 * Should be called in a background thread.
318 */
319 int refreshStaleImages();
320
321 // ==========================================================================
322 // Collections
323 // ==========================================================================
324
325 /**
326 * @brief Create a new empty collection
327 * @param name Name of collection to create
328 *
329 * Collections are user-defined groups for organizing games.
330 * If a collection with this name already exists, this is a no-op.
331 */
332 void createCollection(const std::string& name);
333
334 /**
335 * @brief Delete a collection
336 * @param name Name of collection to delete
337 *
338 * Removes the collection from the list AND removes all games from
339 * this collection. The games themselves are not deleted, only the
340 * collection membership.
341 */
342 void deleteCollection(const std::string& name);
343
344 /**
345 * @brief Get list of all collection names
346 * @return Vector of collection names (may be empty)
347 */
348 std::vector<std::string> getCollectionNames() const;
349
350 /**
351 * @brief Add a game to a collection
352 * @param gameId ID of game to add
353 * @param collection Name of collection
354 *
355 * If the game is already in the collection, this is a no-op.
356 * If the game doesn't exist, prints an error to stderr.
357 */
358 void addGameToCollection(const std::string& gameId, const std::string& collection);
359
360 /**
361 * @brief Remove a game from a collection
362 * @param gameId ID of game to remove
363 * @param collection Name of collection
364 *
365 * If the game isn't in the collection, this is a no-op.
366 * If the game doesn't exist, prints an error to stderr.
367 */
368 void removeGameFromCollection(const std::string& gameId, const std::string& collection);
369
370 private:
371 // ==========================================================================
372 // Private Helper Methods
373 // ==========================================================================
374
375 // Generate a unique ID for a new game
376 std::string generateUniqueId() const;
377
378 // Get the library directory path (creates if doesn't exist)
379 std::string getLibraryPath() const;
380
381 // Get the file path for a specific game (legacy support)
382 std::string getGameFilePath(const std::string& gameId) const;
383
384 // Invalidate all caches
385 void invalidateCaches();
386
387 // Reload games from database into in-memory cache
388 void reloadFromDatabase();
389
390 // ==========================================================================
391 // Member Variables
392 // ==========================================================================
393
394 // SQLite database for persistent storage
395 std::unique_ptr<GameDatabase> database_;
396
397 // Map of game ID -> Game object (in-memory cache)
398 std::map<std::string, Game> games_;
399
400 // List of collection names
401 std::vector<std::string> collections_;
402
403 // Path to library directory
404 std::string libraryPath_;
405
406 // ==========================================================================
407 // Performance Caches
408 // ==========================================================================
409
410 // Cache for getAllGames() - mutable so it can be updated in const methods
411 mutable std::vector<Game*> cachedAllGames_;
412 mutable std::vector<const Game*> cachedAllGamesConst_;
413 mutable bool allGamesCacheValid_ = false;
414 mutable bool allGamesConstCacheValid_ = false;
415
416 // Cache for recently played games
417 mutable std::vector<Game*> cachedRecentGames_;
418 mutable std::vector<const Game*> cachedRecentGamesConst_;
419 mutable bool recentGamesCacheValid_ = false;
420 mutable bool recentGamesConstCacheValid_ = false;
421 // Separate count sentinels to prevent the two overloads from stomping each
422 // other's cached count (e.g. getRecentlyPlayed(10) then getRecentlyPlayed(5)
423 // would otherwise invalidate the first overload's cache on the next call).
424 mutable int cachedRecentGamesCount_ = 0;
425 mutable int cachedRecentGamesConstCount_ = 0;
426};
std::vector< Game * > getInstalledGames()
Get all installed games.
int refreshStaleImages()
Refresh images for games with stale/missing image files.
std::vector< PlaySession > getRecentSessions(const std::string &gameId, int limit=20) const
Get recent play sessions for a game from the database.
~GameLibrary()
Destructor - cleanup.
std::vector< std::string > getCollectionNames() const
Get list of all collection names.
std::vector< Game * > searchGames(std::string_view query)
Search games by name (case-insensitive substring match).
std::string addGame(const Game &game)
Add a new game to the library.
int discoverMissingImages()
Discover and update images for games missing cover art.
std::vector< Game * > getFavorites()
Get all favorite games.
std::vector< Game * > getGamesByPlatform(GamePlatform platform)
Get games filtered by platform.
std::optional< Game * > getGame(const std::string &gameId)
Get a game by ID.
int getTotalGameCount() const
Get total number of games in library.
std::vector< Game * > getGamesInCollection(const std::string &collectionName)
Get games in a specific collection.
void addGameToCollection(const std::string &gameId, const std::string &collection)
Add a game to a collection.
void loadFromDisk()
Load library from disk.
bool updateGame(const std::string &gameId, const Game &updatedGame)
Update an existing game.
int getInstalledGameCount() const
Get number of installed games.
GameLibrary()
Constructor - initializes library path.
std::vector< Game * > getAllGames()
Get all games in the library.
bool removeGame(const std::string &gameId)
Remove a game from the library.
void deleteCollection(const std::string &name)
Delete a collection.
bool discoverImagesForGame(const std::string &gameId)
Discover images for a specific game.
void removeGameFromCollection(const std::string &gameId, const std::string &collection)
Remove a game from a collection.
void saveToDisk()
Save library to disk.
void createCollection(const std::string &name)
Create a new empty collection.
std::vector< Game * > getRecentlyPlayed(int count=10)
Get recently played games.
double getTotalPlayTime() const
Get total play time across all games.
Complete representation of a game in the library.
Definition game.h:767
GamePlatform
Platform/runner type for executing the game.
Definition game.h:61