game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_library_controller.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_library_controller.cpp
4// ==============================================================================
5// Thread Safety Design:
6// - All public getters return copies to prevent data races
7// - Callbacks are invoked OUTSIDE the mutex lock to prevent deadlocks
8// - The pattern is: lock -> copy data + copy callback -> unlock -> invoke callback
9// ==============================================================================
10
12#include "game.h"
13#include "game_library.h"
14
15#include <algorithm>
16#include <mutex>
17
18namespace core
19{
20
21// ==============================================================================
22// Implementation
23// ==============================================================================
24
26{
27 public:
28 Impl() : library_(std::make_unique<GameLibrary>()) {}
29
30 std::unique_ptr<GameLibrary> library_;
31 std::vector<const Game*> filteredGames_;
34 mutable std::mutex mutex_;
35
36 // Callbacks
42
44 {
45 std::vector<const Game*> filteredCopy;
46 OnFilteredListChanged callbackCopy;
47
48 {
49 std::lock_guard<std::mutex> lock(mutex_);
50 filteredGames_.clear();
51
52 // Get all games
53 auto allGames = library_->getAllGames();
54
55 // Apply filters
56 for (const Game* game : allGames)
57 {
58 if (!passesFilter(game))
59 continue;
60 filteredGames_.push_back(game);
61 }
62
63 // Apply sorting
64 sortGames();
65
66 // Copy for callback outside lock
67 filteredCopy = filteredGames_;
68 callbackCopy = onFilteredListChanged_;
69 }
70
71 // Notify listeners outside the lock to prevent deadlock
72 if (callbackCopy)
73 {
74 callbackCopy(filteredCopy);
75 }
76 }
77
78 bool passesFilter(const Game* game) const
79 {
80 if (!game)
81 return false;
82
83 // Search query filter
84 if (!filterOptions_.searchQuery.empty())
85 {
86 std::string nameLower = game->name;
87 std::string queryLower = filterOptions_.searchQuery;
88 std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(),
89 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
90 std::transform(queryLower.begin(), queryLower.end(), queryLower.begin(),
91 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
92
93 if (nameLower.find(queryLower) == std::string::npos)
94 return false;
95 }
96
97 // Platform filter
98 if (filterOptions_.platform.has_value())
99 {
100 if (game->platform != filterOptions_.platform.value())
101 return false;
102 }
103
104 // Status filter
105 if (filterOptions_.status.has_value())
106 {
107 if (game->status != filterOptions_.status.value())
108 return false;
109 }
110
111 // Runner filter
112 if (filterOptions_.runner.has_value())
113 {
114 if (game->runner != filterOptions_.runner.value())
115 return false;
116 }
117
118 // Source filter
119 if (filterOptions_.source.has_value())
120 {
121 if (game->source != filterOptions_.source.value())
122 return false;
123 }
124
125 // Collection filter
126 if (filterOptions_.collection.has_value())
127 {
128 const auto& collections = game->collections;
129 if (std::find(collections.begin(), collections.end(),
130 filterOptions_.collection.value()) == collections.end())
131 return false;
132 }
133
134 // Favorites only
135 if (filterOptions_.favoritesOnly && !game->isFavorite)
136 return false;
137
138 // Installed only - check both status and steamInstalled for Steam games
139 if (filterOptions_.installedOnly)
140 {
141 if (game->metadata.isSteamGame)
142 {
143 if (!game->metadata.steamInstalled)
144 return false;
145 }
146 else if (game->status != GameStatus::Installed)
147 {
148 return false;
149 }
150 }
151
152 // Not installed only - show games that are NOT installed
153 if (filterOptions_.notInstalledOnly)
154 {
155 if (game->metadata.isSteamGame)
156 {
157 if (game->metadata.steamInstalled)
158 return false; // Skip installed Steam games
159 }
160 else if (game->status == GameStatus::Installed || game->status == GameStatus::Running)
161 {
162 return false; // Skip installed non-Steam games
163 }
164 }
165
166 return true;
167 }
168
170 {
171 auto comparator = [this](const Game* a, const Game* b) -> bool
172 {
173 int cmp = 0;
174
175 switch (sortOptions_.field)
176 {
177 case SortField::Name:
178 cmp = a->name.compare(b->name);
179 break;
180
182 cmp = (a->statistics.lastPlayed > b->statistics.lastPlayed) -
183 (a->statistics.lastPlayed < b->statistics.lastPlayed);
184 break;
185
187 cmp = (a->statistics.totalPlayTimeSeconds > b->statistics.totalPlayTimeSeconds) -
188 (a->statistics.totalPlayTimeSeconds < b->statistics.totalPlayTimeSeconds);
189 break;
190
192 cmp = (a->statistics.dateAdded > b->statistics.dateAdded) -
193 (a->statistics.dateAdded < b->statistics.dateAdded);
194 break;
195
197 cmp = static_cast<int>(a->status) - static_cast<int>(b->status);
198 break;
199 }
200
202 cmp = -cmp;
203
204 return cmp < 0;
205 };
206
207 std::sort(filteredGames_.begin(), filteredGames_.end(), comparator);
208 }
209};
210
211// ==============================================================================
212// Constructor / Destructor
213// ==============================================================================
214
215GameLibraryController::GameLibraryController() : impl_(std::make_unique<Impl>()) {}
216
218
221
222// ==============================================================================
223// Library Operations
224// ==============================================================================
225
227{
228 OnLibraryLoaded callbackCopy;
229 LibraryLoadedEvent event;
230
231 {
232 std::lock_guard<std::mutex> lock(impl_->mutex_);
233 impl_->library_->loadFromDisk();
234 event.gameCount = impl_->library_->getAllGames().size();
235 callbackCopy = impl_->onLibraryLoaded_;
236 }
237
238 // Refresh the filtered list BEFORE firing the callback so that any UI
239 // handler that calls getFilteredGames() inside onLibraryLoaded sees a
240 // fully-populated list rather than an empty one.
241 impl_->refreshFilteredList();
242
243 if (callbackCopy)
244 {
245 callbackCopy(event);
246 }
247}
248
250{
251 std::lock_guard<std::mutex> lock(impl_->mutex_);
252 impl_->library_->saveToDisk();
253}
254
256{
257 std::lock_guard<std::mutex> lock(impl_->mutex_);
258 return impl_->library_->getAllGames().size();
259}
260
261const Game* GameLibraryController::getGame(const std::string& gameId) const
262{
263 // LIFETIME NOTE: the returned pointer is valid as long as the entry exists in
264 // the library's internal std::map (stable for non-erased elements). Callers
265 // MUST use the pointer immediately and MUST NOT store it across event-loop
266 // boundaries or yield points — another thread could erase the entry or rebuild
267 // the map (e.g. on library reload) after this lock is released.
268 std::lock_guard<std::mutex> lock(impl_->mutex_);
269 auto result = impl_->library_->getGame(gameId);
270 return result.has_value() ? *result : nullptr;
271}
272
274{
275 // See LIFETIME NOTE on getGame() above.
276 std::lock_guard<std::mutex> lock(impl_->mutex_);
277 auto result = impl_->library_->getGame(gameId);
278 return result.has_value() ? *result : nullptr;
279}
280
281void GameLibraryController::executeWithGame(const std::string& gameId,
282 const std::function<void(Game&)>& updater)
283{
284 std::lock_guard<std::mutex> lock(impl_->mutex_);
285 auto result = impl_->library_->getGame(gameId);
286 if (result.has_value())
287 updater(**result);
288}
289
290// ==============================================================================
291// CRUD Operations
292// ==============================================================================
293
294std::string GameLibraryController::addGame(const Game& game)
295{
296 std::string gameId;
297 OnGameAdded callbackCopy;
298 std::string gameName = game.name;
299
300 {
301 std::lock_guard<std::mutex> lock(impl_->mutex_);
302 gameId = impl_->library_->addGame(game);
303 callbackCopy = impl_->onGameAdded_;
304 }
305
306 if (!gameId.empty())
307 {
308 impl_->refreshFilteredList();
309
310 if (callbackCopy)
311 {
312 GameAddedEvent event;
313 event.gameId = gameId;
314 event.gameName = gameName;
315 callbackCopy(event);
316 }
317 }
318
319 return gameId;
320}
321
322bool GameLibraryController::updateGame(const std::string& gameId, const Game& updatedGame)
323{
324 bool success;
325 OnGameUpdated callbackCopy;
326
327 {
328 std::lock_guard<std::mutex> lock(impl_->mutex_);
329 success = impl_->library_->updateGame(gameId, updatedGame);
330 callbackCopy = impl_->onGameUpdated_;
331 }
332
333 if (success)
334 {
335 impl_->refreshFilteredList();
336
337 if (callbackCopy)
338 {
339 GameUpdatedEvent event;
340 event.gameId = gameId;
341 callbackCopy(event);
342 }
343
344 return true;
345 }
346
347 return false;
348}
349
350bool GameLibraryController::removeGame(const std::string& gameId)
351{
352 std::string gameName;
353 bool success;
354 OnGameRemoved callbackCopy;
355
356 {
357 std::lock_guard<std::mutex> lock(impl_->mutex_);
358 // Get name before removal for event
359 auto result = impl_->library_->getGame(gameId);
360 if (result.has_value())
361 {
362 gameName = (*result)->name;
363 }
364 success = impl_->library_->removeGame(gameId);
365 callbackCopy = impl_->onGameRemoved_;
366 }
367
368 if (success)
369 {
370 impl_->refreshFilteredList();
371
372 if (callbackCopy)
373 {
374 GameRemovedEvent event;
375 event.gameId = gameId;
376 event.gameName = gameName;
377 callbackCopy(event);
378 }
379
380 return true;
381 }
382
383 return false;
384}
385
386std::string GameLibraryController::duplicateGame(const std::string& sourceGameId,
387 const std::string& newName)
388{
389 Game newGame;
390 {
391 std::lock_guard<std::mutex> lock(impl_->mutex_);
392 auto result = impl_->library_->getGame(sourceGameId);
393 if (!result.has_value())
394 return "";
395 newGame = **result; // Copy the game while holding the lock
396 }
397
398 newGame.id.clear(); // Will be assigned by addGame
399 newGame.name = newName;
400 newGame.statistics = GameStatistics{}; // Reset statistics
401
402 return addGame(newGame);
403}
404
405// ==============================================================================
406// Filtering & Sorting
407// ==============================================================================
408
410{
411 {
412 std::lock_guard<std::mutex> lock(impl_->mutex_);
413 impl_->filterOptions_ = options;
414 }
415 impl_->refreshFilteredList();
416}
417
419{
420 std::lock_guard<std::mutex> lock(impl_->mutex_);
421 return impl_->filterOptions_;
422}
423
425{
426 {
427 std::lock_guard<std::mutex> lock(impl_->mutex_);
428 impl_->sortOptions_ = options;
429 }
430 impl_->refreshFilteredList();
431}
432
434{
435 std::lock_guard<std::mutex> lock(impl_->mutex_);
436 return impl_->sortOptions_;
437}
438
439std::vector<const Game*> GameLibraryController::getFilteredGames() const
440{
441 std::lock_guard<std::mutex> lock(impl_->mutex_);
442 return impl_->filteredGames_; // Return copy for thread safety
443}
444
446{
447 impl_->refreshFilteredList();
448}
449
450// ==============================================================================
451// Collections
452// ==============================================================================
453
454std::vector<std::string> GameLibraryController::getCollections() const
455{
456 std::lock_guard<std::mutex> lock(impl_->mutex_);
457 return impl_->library_->getCollectionNames();
458}
459
460bool GameLibraryController::addCollection(const std::string& name)
461{
462 std::lock_guard<std::mutex> lock(impl_->mutex_);
463 impl_->library_->createCollection(name);
464 return true; // createCollection doesn't return status
465}
466
467bool GameLibraryController::removeCollection(const std::string& name)
468{
469 std::lock_guard<std::mutex> lock(impl_->mutex_);
470 impl_->library_->deleteCollection(name);
471 return true; // deleteCollection doesn't return status
472}
473
474bool GameLibraryController::renameCollection(const std::string& /*oldName*/,
475 const std::string& /*newName*/)
476{
477 // Note: GameLibrary doesn't have renameCollection - would need to be implemented
478 // For now, return false to indicate not supported
479 return false;
480}
481
482bool GameLibraryController::addGameToCollection(const std::string& gameId,
483 const std::string& collection)
484{
485 OnGameUpdated callbackCopy;
486 bool added = false;
487
488 {
489 std::lock_guard<std::mutex> lock(impl_->mutex_);
490 auto result = impl_->library_->getGame(gameId);
491 if (result.has_value())
492 {
493 Game* game = *result;
494 auto& collections = game->collections;
495 if (std::find(collections.begin(), collections.end(), collection) == collections.end())
496 {
497 impl_->library_->addGameToCollection(gameId, collection);
498 added = true;
499 callbackCopy = impl_->onGameUpdated_;
500 }
501 }
502 }
503
504 if (added)
505 {
506 // Refresh filtered list so a collection filter reflects the new membership.
507 impl_->refreshFilteredList();
508
509 if (callbackCopy)
510 {
511 GameUpdatedEvent event;
512 event.gameId = gameId;
513 event.fieldChanged = "collections";
514 callbackCopy(event);
515 }
516 }
517
518 return added;
519}
520
522 const std::string& collection)
523{
524 OnGameUpdated callbackCopy;
525 bool removed = false;
526
527 {
528 std::lock_guard<std::mutex> lock(impl_->mutex_);
529 auto result = impl_->library_->getGame(gameId);
530 if (result.has_value())
531 {
532 Game* game = *result;
533 auto& collections = game->collections;
534 auto it = std::find(collections.begin(), collections.end(), collection);
535 if (it != collections.end())
536 {
537 impl_->library_->removeGameFromCollection(gameId, collection);
538 removed = true;
539 callbackCopy = impl_->onGameUpdated_;
540 }
541 }
542 }
543
544 if (removed)
545 {
546 // Refresh filtered list so a collection filter reflects the removed membership.
547 impl_->refreshFilteredList();
548
549 if (callbackCopy)
550 {
551 GameUpdatedEvent event;
552 event.gameId = gameId;
553 event.fieldChanged = "collections";
554 callbackCopy(event);
555 }
556 }
557
558 return removed;
559}
560
561// ==============================================================================
562// Favorites
563// ==============================================================================
564
565void GameLibraryController::toggleFavorite(const std::string& gameId)
566{
567 OnGameUpdated callbackCopy;
568 bool found = false;
569
570 {
571 std::lock_guard<std::mutex> lock(impl_->mutex_);
572 auto result = impl_->library_->getGame(gameId);
573 if (result.has_value())
574 {
575 Game* game = *result;
576 game->isFavorite = !game->isFavorite;
577 // Persist the change so it survives app restart.
578 impl_->library_->updateGame(game->id, *game);
579 found = true;
580 callbackCopy = impl_->onGameUpdated_;
581 }
582 }
583
584 if (found)
585 {
586 impl_->refreshFilteredList();
587
588 if (callbackCopy)
589 {
590 GameUpdatedEvent event;
591 event.gameId = gameId;
592 event.fieldChanged = "isFavorite";
593 callbackCopy(event);
594 }
595 }
596}
597
598bool GameLibraryController::isFavorite(const std::string& gameId) const
599{
600 std::lock_guard<std::mutex> lock(impl_->mutex_);
601 auto result = impl_->library_->getGame(gameId);
602 if (result.has_value())
603 {
604 return (*result)->isFavorite;
605 }
606 return false;
607}
608
609// ==============================================================================
610// Statistics & Queries
611// ==============================================================================
612
614{
615 std::lock_guard<std::mutex> lock(impl_->mutex_);
616 return impl_->library_->getAllGames();
617}
618
619std::vector<const Game*> GameLibraryController::getRecentlyPlayed(int count) const
620{
621 std::lock_guard<std::mutex> lock(impl_->mutex_);
622 auto games = impl_->library_->getRecentlyPlayed(count);
623 std::vector<const Game*> result;
624 result.reserve(games.size());
625 for (const Game* game : games)
626 {
627 result.push_back(game);
628 }
629 return result;
630}
631
632std::vector<PlaySession> GameLibraryController::getRecentSessions(const std::string& gameId,
633 int limit) const
634{
635 std::lock_guard<std::mutex> lock(impl_->mutex_);
636 return impl_->library_->getRecentSessions(gameId, limit);
637}
638
640{
641 std::lock_guard<std::mutex> lock(impl_->mutex_);
642 auto games = impl_->library_->getGamesByPlatform(platform);
643 std::vector<const Game*> result;
644 result.reserve(games.size());
645 for (const Game* game : games)
646 {
647 result.push_back(game);
648 }
649 return result;
650}
651
652std::vector<const Game*> GameLibraryController::getGamesByRunner(GameRunner runner) const
653{
654 std::lock_guard<std::mutex> lock(impl_->mutex_);
655 std::vector<const Game*> result;
656 for (const Game* game : impl_->library_->getAllGames())
657 {
658 if (game->runner == runner)
659 {
660 result.push_back(game);
661 }
662 }
663 return result;
664}
665
666std::vector<const Game*> GameLibraryController::searchGames(const std::string& query) const
667{
668 std::lock_guard<std::mutex> lock(impl_->mutex_);
669 auto games = impl_->library_->searchGames(query);
670 std::vector<const Game*> result;
671 result.reserve(games.size());
672 for (const Game* game : games)
673 {
674 result.push_back(game);
675 }
676 return result;
677}
678
679// ==============================================================================
680// Image Discovery
681// ==============================================================================
682
684{
685 // No controller lock — these are long-running async operations
686 // Race safety is handled inside GameLibrary (results applied single-threaded after futures
687 // complete)
688 return impl_->library_->discoverMissingImages();
689}
690
691bool GameLibraryController::discoverImagesForGame(const std::string& gameId)
692{
693 return impl_->library_->discoverImagesForGame(gameId);
694}
695
697{
698 return impl_->library_->refreshStaleImages();
699}
700
701// ==============================================================================
702// Event Subscriptions
703// ==============================================================================
704
706{
707 std::lock_guard<std::mutex> lock(impl_->mutex_);
708 impl_->onGameAdded_ = std::move(callback);
709}
710
712{
713 std::lock_guard<std::mutex> lock(impl_->mutex_);
714 impl_->onGameRemoved_ = std::move(callback);
715}
716
718{
719 std::lock_guard<std::mutex> lock(impl_->mutex_);
720 impl_->onGameUpdated_ = std::move(callback);
721}
722
724{
725 std::lock_guard<std::mutex> lock(impl_->mutex_);
726 impl_->onLibraryLoaded_ = std::move(callback);
727}
728
730{
731 std::lock_guard<std::mutex> lock(impl_->mutex_);
732 impl_->onFilteredListChanged_ = std::move(callback);
733}
734
735} // namespace core
Central database for managing all games in the launcher.
Complete representation of a game in the library.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::vector< std::string > collections
Collections this game belongs to.
Definition game.h:804
bool isFavorite
Is this marked as a favorite game?
Definition game.h:803
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
GameStatistics statistics
Play statistics and usage tracking.
Definition game.h:786
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
GameStatus status
Current installation and execution status.
Definition game.h:778
GamePlatform platform
Definition game.h:776
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
bool passesFilter(const Game *game) const
std::vector< const Game * > filteredGames_
std::unique_ptr< GameLibrary > library_
void setOnGameRemoved(OnGameRemoved callback)
bool updateGame(const std::string &gameId, const Game &updatedGame)
Update an existing game Returns true on success.
std::vector< PlaySession > getRecentSessions(const std::string &gameId, int limit=20) const
Get recent play sessions for a game from the database.
void setOnFilteredListChanged(OnFilteredListChanged callback)
std::string addGame(const Game &game)
Add a new game to the library Returns the assigned game ID, or empty string on failure.
std::vector< const Game * > getGamesByRunner(GameRunner runner) const
Get games by runner.
std::string duplicateGame(const std::string &sourceGameId, const std::string &newName)
Duplicate a game with a new name Returns the new game's ID, or empty string on failure.
std::vector< std::string > getCollections() const
Get all collection names.
int discoverMissingImages()
Discover and update image paths for games that are missing cover art This should be called in a backg...
bool removeGame(const std::string &gameId)
Remove a game from the library Returns true on success.
bool discoverImagesForGame(const std::string &gameId)
Discover images for a specific game (by Steam App ID) Returns true if images were found and updated.
FilterOptions getFilter() const
Get current filter options (returns copy for thread safety).
void refreshFilteredList()
Force refresh of filtered list (e.g., after external game state change).
const Game * getGame(const std::string &gameId) const
Get a game by ID (returns nullptr if not found).
void loadLibrary()
Load library from disk.
Game * getGameForEdit(const std::string &gameId)
Get mutable game for editing (returns nullptr if not found).
bool removeGameFromCollection(const std::string &gameId, const std::string &collection)
Remove a game from a collection.
std::vector< const Game * > searchGames(const std::string &query) const
Search games by name (substring match).
bool addCollection(const std::string &name)
Add a new collection.
void setSort(const SortOptions &options)
Set sort options and refresh filtered list.
void toggleFavorite(const std::string &gameId)
Toggle favorite status.
std::function< void(const GameRemovedEvent &)> OnGameRemoved
void setOnGameAdded(OnGameAdded callback)
void setFilter(const FilterOptions &options)
Set filter options and refresh filtered list.
bool renameCollection(const std::string &oldName, const std::string &newName)
Rename a collection.
std::vector< const Game * > getFilteredGames() const
Get the currently filtered and sorted game list (returns copy for thread safety).
std::function< void(const GameUpdatedEvent &)> OnGameUpdated
void executeWithGame(const std::string &gameId, const std::function< void(Game &)> &updater)
Execute an update function on a game while holding the library's internal lock.
void saveLibrary()
Save library to disk.
std::vector< Game * > getAllGames()
Get all games (non-const for process tracking).
std::function< void(const GameAddedEvent &)> OnGameAdded
size_t getGameCount() const
Get total game count.
std::vector< const Game * > getRecentlyPlayed(int count=10) const
Get recently played games.
bool removeCollection(const std::string &name)
Remove a collection.
std::function< void(const LibraryLoadedEvent &)> OnLibraryLoaded
std::function< void(const std::vector< const Game * > &)> OnFilteredListChanged
void setOnLibraryLoaded(OnLibraryLoaded callback)
int refreshStaleImages()
Refresh images for games with stale/missing image files Checks if stored paths still exist and re-dis...
SortOptions getSort() const
Get current sort options (returns copy for thread safety).
bool addGameToCollection(const std::string &gameId, const std::string &collection)
Add a game to a collection.
void setOnGameUpdated(OnGameUpdated callback)
std::vector< const Game * > getGamesByPlatform(GamePlatform platform) const
Get games by platform.
bool isFavorite(const std::string &gameId) const
Check if a game is favorited.
GamePlatform
Platform/runner type for executing the game.
Definition game.h:61
@ Running
Game is currently running.
Definition game.h:101
@ Installed
Game is installed and ready to play.
Definition game.h:99
GameRunner
Runner/compatibility layer for executing the game.
Definition game.h:81
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
Play statistics and usage tracking for a game.
Definition game.h:712
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
Definition game.h:714
time_t lastPlayed
Unix timestamp of last play session.
Definition game.h:715
time_t dateAdded
Unix timestamp when added to library.
Definition game.h:716