game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_library.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_library.cpp
4// ==============================================================================
5// Implementation of GameLibrary class
6// ==============================================================================
7
8#include "game_library.h"
9#include "logger.h"
10#include "steam_integration.h"
11#include "steam_paths.h"
12#include <algorithm>
13#include <ctime>
14#include <filesystem>
15#include <fstream>
16#include <future>
17#include <mutex>
18#include <random>
19#include <sstream>
20
21namespace fs = std::filesystem;
22
23// ==============================================================================
24// Constructor & Destructor
25// ==============================================================================
26
28{
29 // Get library path (will create directory if it doesn't exist)
30 libraryPath_ = getLibraryPath();
31
32 // Initialize SQLite database
33 database_ = std::make_unique<GameDatabase>();
34 std::string dbPath = libraryPath_ + "/games.db";
35
36 if (!database_->open(dbPath))
37 {
38 Logger::error("Failed to open game database: {}", database_->lastError());
39 }
40}
41
42// Database will be closed automatically by unique_ptr destructor.
44
45// ==============================================================================
46// Library Management
47// ==============================================================================
48
50{
51 games_.clear();
52 collections_.clear();
53 invalidateCaches();
54
55 // Create library directory if it doesn't exist
56 if (!fs::exists(libraryPath_))
57 {
58 fs::create_directories(libraryPath_);
59 Logger::info("Created library directory: {}", libraryPath_);
60 return;
61 }
62
63 // Load games from SQLite database into in-memory cache
64 reloadFromDatabase();
65
66 // Load collections from database
67 collections_ = database_->getCollections();
68
69 Logger::info("Loaded {} games from database", games_.size());
70}
71
73{
74 // Sync all in-memory games to database in a single transaction for atomicity and performance
75 int savedCount = 0;
76 int failedCount = 0;
77
78 database_->beginTransaction();
79
80 for (const auto& [id, game] : games_)
81 {
82 bool ok;
83 if (database_->gameExists(id))
84 {
85 ok = database_->updateGame(game);
86 }
87 else
88 {
89 ok = database_->insertGame(game);
90 }
91
92 if (ok)
93 {
94 savedCount++;
95 }
96 else
97 {
98 Logger::error("Failed to save game {}: {}", id, database_->lastError());
99 failedCount++;
100 }
101 }
102
103 if (failedCount > 0)
104 {
105 // Roll back on any failure to preserve atomicity
106 database_->rollbackTransaction();
107 Logger::error("Rolled back save: {} games failed to save", failedCount);
108 }
109 else
110 {
111 database_->commitTransaction();
112 Logger::info("Saved {} games to database", savedCount);
113 }
114}
115
116// ==============================================================================
117// Game Operations
118// ==============================================================================
119
120std::string GameLibrary::addGame(const Game& game)
121{
122 // Check for duplicates before inserting
123 for (const auto& [existingId, existing] : games_)
124 {
125 // Duplicate by Steam App ID
126 if (game.metadata.steamAppId > 0 &&
127 existing.metadata.steamAppId == game.metadata.steamAppId)
128 {
129 Logger::warn("Duplicate game skipped (Steam App ID {}): {} already exists as {}",
130 game.metadata.steamAppId, game.name, existing.name);
131 return existingId; // Return existing ID instead of failing
132 }
133
134 // Duplicate by executable path (non-empty, non-steam)
135 if (!game.runnerConfig.executablePath.empty() &&
136 game.runnerConfig.executablePath != "steam" &&
137 !existing.runnerConfig.executablePath.empty() &&
138 existing.runnerConfig.executablePath != "steam")
139 {
140 // Canonicalize both paths to catch symlink/relative duplicates
141 std::string newExe = game.runnerConfig.executablePath;
142 std::string existExe = existing.runnerConfig.executablePath;
143 try
144 {
145 newExe = fs::canonical(newExe).string();
146 }
147 catch (...)
148 {
149 }
150 try
151 {
152 existExe = fs::canonical(existExe).string();
153 }
154 catch (...)
155 {
156 }
157 if (newExe == existExe)
158 {
159 Logger::warn("Duplicate game skipped (same executable): {} already exists as {}",
160 game.name, existing.name);
161 return existingId;
162 }
163 }
164
165 // Duplicate by name (case-insensitive) when one is Steam and the other isn't
166 // This catches cases where .desktop files or native scans find Steam games
167 if (!game.name.empty() && !existing.name.empty())
168 {
169 std::string newName = game.name;
170 std::string existName = existing.name;
171 // Normalize: lowercase and strip trademark symbols
172 auto normalize = [](std::string s)
173 {
174 // Remove TM/registered symbols
175 std::string result;
176 for (size_t i = 0; i < s.size(); ++i)
177 {
178 unsigned char c = static_cast<unsigned char>(s[i]);
179 // Skip UTF-8 trademark sequences (™ = E2 84 A2, ® = C2 AE)
180 if (c == 0xE2 && i + 2 < s.size() &&
181 static_cast<unsigned char>(s[i + 1]) == 0x84 &&
182 static_cast<unsigned char>(s[i + 2]) == 0xA2)
183 {
184 i += 2;
185 continue;
186 }
187 if (c == 0xC2 && i + 1 < s.size() &&
188 static_cast<unsigned char>(s[i + 1]) == 0xAE)
189 {
190 i += 1;
191 continue;
192 }
193 result += static_cast<char>(std::tolower(c));
194 }
195 // Trim trailing whitespace
196 while (!result.empty() && result.back() == ' ')
197 result.pop_back();
198 return result;
199 };
200
201 if (normalize(newName) == normalize(existName) && game.source != existing.source)
202 {
203 Logger::warn("Duplicate game skipped (same name, different source): "
204 "{} ({}) already exists as {} ({})",
205 game.name, static_cast<int>(game.source), existing.name,
206 static_cast<int>(existing.source));
207 return existingId;
208 }
209 }
210 }
211
212 // Generate unique ID if game doesn't have one
213 std::string id = game.id;
214 if (id.empty())
215 {
216 id = generateUniqueId();
217 }
218
219 // Create a copy and set the ID
220 Game newGame = game;
221 newGame.id = id;
222
223 // Ensure dateAdded is set for new imports
224 if (newGame.statistics.dateAdded == 0)
225 {
226 newGame.statistics.dateAdded = std::time(nullptr);
227 }
228
229 // Insert into database
230 if (!database_->insertGame(newGame))
231 {
232 Logger::error("Failed to add game to database: {}", database_->lastError());
233 return "";
234 }
235
236 // Add to in-memory cache
237 games_[id] = newGame;
238 invalidateCaches();
239
240 Logger::info("Added game to library: {} (ID: {})", newGame.name, id);
241
242 return id;
243}
244
245bool GameLibrary::removeGame(const std::string& gameId)
246{
247 auto it = games_.find(gameId);
248 if (it == games_.end())
249 {
250 Logger::error("Game not found: {}", gameId);
251 return false;
252 }
253
254 // Remove from database
255 if (!database_->deleteGame(gameId))
256 {
257 Logger::error("Failed to delete game from database: {}", database_->lastError());
258 return false;
259 }
260
261 // Also remove legacy .game file if it exists (for migration cleanup)
262 std::string filepath = getGameFilePath(gameId);
263 if (fs::exists(filepath))
264 {
265 fs::remove(filepath);
266 }
267
268 // Remove from in-memory cache
269 games_.erase(it);
270 invalidateCaches();
271
272 Logger::info("Removed game from library: {}", gameId);
273
274 return true;
275}
276
277bool GameLibrary::updateGame(const std::string& gameId, const Game& updatedGame)
278{
279 auto it = games_.find(gameId);
280 if (it == games_.end())
281 {
282 Logger::error("Game not found: {}", gameId);
283 return false;
284 }
285
286 // Update the game (preserve the ID)
287 Game updated = updatedGame;
288 updated.id = gameId;
289
290 // Update in database
291 if (!database_->updateGame(updated))
292 {
293 Logger::error("Failed to update game in database: {}", database_->lastError());
294 return false;
295 }
296
297 // Update in-memory cache
298 games_[gameId] = updated;
299 invalidateCaches();
300
301 Logger::info("Updated game: {}", gameId);
302
303 return true;
304}
305
306std::optional<Game*> GameLibrary::getGame(const std::string& gameId)
307{
308 auto it = games_.find(gameId);
309 if (it == games_.end())
310 {
311 return std::nullopt;
312 }
313
314 return &(it->second);
315}
316
317std::optional<const Game*> GameLibrary::getGame(const std::string& gameId) const
318{
319 auto it = games_.find(gameId);
320 if (it == games_.end())
321 {
322 return std::nullopt;
323 }
324
325 return &(it->second);
326}
327
328// ==============================================================================
329// Query Operations
330// ==============================================================================
331
332std::vector<Game*> GameLibrary::getAllGames()
333{
334 if (!allGamesCacheValid_)
335 {
336 cachedAllGames_.clear();
337 for (auto& [id, game] : games_)
338 {
339 cachedAllGames_.push_back(&game);
340 }
341 allGamesCacheValid_ = true;
342 }
343 return cachedAllGames_;
344}
345
346std::vector<const Game*> GameLibrary::getAllGames() const
347{
348 if (!allGamesConstCacheValid_)
349 {
350 cachedAllGamesConst_.clear();
351 for (const auto& [id, game] : games_)
352 {
353 cachedAllGamesConst_.push_back(&game);
354 }
355 allGamesConstCacheValid_ = true;
356 }
357 return cachedAllGamesConst_;
358}
359
361{
362 std::vector<Game*> result;
363 for (auto& [id, game] : games_)
364 {
365 if (game.platform == platform)
366 {
367 result.push_back(&game);
368 }
369 }
370 return result;
371}
372
374{
375 std::vector<const Game*> result;
376 for (const auto& [id, game] : games_)
377 {
378 if (game.platform == platform)
379 {
380 result.push_back(&game);
381 }
382 }
383 return result;
384}
385
386std::vector<Game*> GameLibrary::getFavorites()
387{
388 std::vector<Game*> result;
389 for (auto& [id, game] : games_)
390 {
391 if (game.isFavorite)
392 {
393 result.push_back(&game);
394 }
395 }
396 return result;
397}
398
399std::vector<const Game*> GameLibrary::getFavorites() const
400{
401 std::vector<const Game*> result;
402 for (const auto& [id, game] : games_)
403 {
404 if (game.isFavorite)
405 {
406 result.push_back(&game);
407 }
408 }
409 return result;
410}
411
412std::vector<Game*> GameLibrary::getRecentlyPlayed(int count)
413{
414 // Rebuild cache if invalid or count changed
415 if (!recentGamesCacheValid_ || cachedRecentGamesCount_ != count)
416 {
417 cachedRecentGames_.clear();
418
419 // Get all games that have been played
420 for (auto& [id, game] : games_)
421 {
422 if (game.statistics.lastPlayed > 0)
423 {
424 cachedRecentGames_.push_back(&game);
425 }
426 }
427
428 // Sort by last played time (most recent first)
429 std::sort(cachedRecentGames_.begin(), cachedRecentGames_.end(), [](Game* a, Game* b)
430 { return a->statistics.lastPlayed > b->statistics.lastPlayed; });
431
432 // Limit to requested count. Guard negative counts, which would
433 // otherwise cast to a huge size_t and skip truncation entirely,
434 // returning the full list.
435 const size_t limit = count > 0 ? static_cast<size_t>(count) : 0;
436 if (cachedRecentGames_.size() > limit)
437 {
438 cachedRecentGames_.resize(limit);
439 }
440
441 recentGamesCacheValid_ = true;
442 cachedRecentGamesCount_ = count;
443 }
444
445 return cachedRecentGames_;
446}
447
448std::vector<const Game*> GameLibrary::getRecentlyPlayed(int count) const
449{
450 // Rebuild cache if invalid or count changed (separate flag from the non-const overload)
451 if (!recentGamesConstCacheValid_ || cachedRecentGamesConstCount_ != count)
452 {
453 cachedRecentGamesConst_.clear();
454
455 // Get all games that have been played
456 for (const auto& [id, game] : games_)
457 {
458 if (game.statistics.lastPlayed > 0)
459 {
460 cachedRecentGamesConst_.push_back(&game);
461 }
462 }
463
464 // Sort by last played time (most recent first)
465 std::sort(cachedRecentGamesConst_.begin(), cachedRecentGamesConst_.end(),
466 [](const Game* a, const Game* b)
467 { return a->statistics.lastPlayed > b->statistics.lastPlayed; });
468
469 // Limit to requested count (guard negative counts — see the non-const
470 // overload above).
471 const size_t limit = count > 0 ? static_cast<size_t>(count) : 0;
472 if (cachedRecentGamesConst_.size() > limit)
473 {
474 cachedRecentGamesConst_.resize(limit);
475 }
476
477 recentGamesConstCacheValid_ = true;
478 cachedRecentGamesConstCount_ = count;
479 }
480
481 return cachedRecentGamesConst_;
482}
483
484std::vector<PlaySession> GameLibrary::getRecentSessions(const std::string& gameId, int limit) const
485{
486 if (database_)
487 {
488 return database_->getRecentSessions(gameId, limit);
489 }
490 return {};
491}
492
494{
495 std::vector<Game*> result;
496 for (auto& [id, game] : games_)
497 {
498 if (game.status == GameStatus::Installed || game.status == GameStatus::Running)
499 {
500 result.push_back(&game);
501 }
502 }
503 return result;
504}
505
506std::vector<const Game*> GameLibrary::getInstalledGames() const
507{
508 std::vector<const Game*> result;
509 for (const auto& [id, game] : games_)
510 {
511 if (game.status == GameStatus::Installed || game.status == GameStatus::Running)
512 {
513 result.push_back(&game);
514 }
515 }
516 return result;
517}
518
519std::vector<Game*> GameLibrary::searchGames(std::string_view query)
520{
521 std::vector<Game*> result;
522
523 std::string lowerQuery(query);
524 std::transform(lowerQuery.begin(), lowerQuery.end(), lowerQuery.begin(),
525 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
526
527 auto containsQuery = [&lowerQuery](const std::string& field)
528 {
529 std::string lower = field;
530 std::transform(lower.begin(), lower.end(), lower.begin(),
531 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
532 return lower.find(lowerQuery) != std::string::npos;
533 };
534
535 for (auto& [id, game] : games_)
536 {
537 if (containsQuery(game.name) || containsQuery(game.metadata.developer) ||
538 containsQuery(game.metadata.publisher) || containsQuery(game.metadata.description))
539 {
540 result.push_back(&game);
541 }
542 }
543
544 return result;
545}
546
547std::vector<const Game*> GameLibrary::searchGames(std::string_view query) const
548{
549 std::vector<const Game*> result;
550
551 std::string lowerQuery(query);
552 std::transform(lowerQuery.begin(), lowerQuery.end(), lowerQuery.begin(),
553 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
554
555 auto containsQuery = [&lowerQuery](const std::string& field)
556 {
557 std::string lower = field;
558 std::transform(lower.begin(), lower.end(), lower.begin(),
559 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
560 return lower.find(lowerQuery) != std::string::npos;
561 };
562
563 for (const auto& [id, game] : games_)
564 {
565 if (containsQuery(game.name) || containsQuery(game.metadata.developer) ||
566 containsQuery(game.metadata.publisher) || containsQuery(game.metadata.description))
567 {
568 result.push_back(&game);
569 }
570 }
571
572 return result;
573}
574
575std::vector<Game*> GameLibrary::getGamesInCollection(const std::string& collectionName)
576{
577 std::vector<Game*> result;
578 for (auto& [id, game] : games_)
579 {
580 // Check if game has this collection
581 auto it = std::find(game.collections.begin(), game.collections.end(), collectionName);
582 if (it != game.collections.end())
583 {
584 result.push_back(&game);
585 }
586 }
587 return result;
588}
589
590std::vector<const Game*> GameLibrary::getGamesInCollection(const std::string& collectionName) const
591{
592 std::vector<const Game*> result;
593 for (const auto& [id, game] : games_)
594 {
595 // Check if game has this collection
596 auto it = std::find(game.collections.begin(), game.collections.end(), collectionName);
597 if (it != game.collections.end())
598 {
599 result.push_back(&game);
600 }
601 }
602 return result;
603}
604
605// ==============================================================================
606// Statistics
607// ==============================================================================
608
610{
611 return static_cast<int>(games_.size());
612}
613
615{
616 int count = 0;
617 for (const auto& [id, game] : games_)
618 {
619 if (game.status == GameStatus::Installed || game.status == GameStatus::Running)
620 {
621 count++;
622 }
623 }
624 return count;
625}
626
628{
629 double total = 0.0;
630 for (const auto& [id, game] : games_)
631 {
632 total += game.statistics.totalPlayTimeSeconds;
633 }
634 return total;
635}
636
637// ==============================================================================
638// Image Discovery
639// ==============================================================================
640
642{
643 // Get games missing cover art from database
644 auto gamesWithoutCover = database_->getGamesWithoutCoverArt();
645
646 if (gamesWithoutCover.empty())
647 {
648 return 0;
649 }
650
651 Logger::info("Discovering images for {} games...", gamesWithoutCover.size());
652
653 // Use parallel discovery for better performance
654 // Limit concurrency to avoid overwhelming the filesystem
655 constexpr size_t MAX_CONCURRENT = 8;
656
657 // Pre-fetch Steam root path (same for all games)
658 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
659
660 // Collect results from async tasks (no shared state access in lambdas)
661 struct ImageResult
662 {
663 std::string gameId;
664 GameImagePaths images;
665 };
666 std::mutex resultsMutex;
667 std::vector<ImageResult> results;
668
669 // Process games in batches using async
670 std::vector<std::future<void>> futures;
671
672 for (const auto& game : gamesWithoutCover)
673 {
674 // Wait if we have too many concurrent tasks
675 if (futures.size() >= MAX_CONCURRENT)
676 {
677 // Wait for at least one to complete
678 futures.front().wait();
679 futures.erase(futures.begin());
680 }
681
682 futures.push_back(std::async(
683 std::launch::async,
684 [&resultsMutex, &results, steamRootCopy = steamRoot, gameId = game.id,
685 steamAppId = game.metadata.steamAppId, this]()
686 {
687 if (steamAppId <= 0)
688 return;
689
690 // Discover images from Steam's cache
691 GameImagePaths images =
692 SteamCDN::discoverImages(static_cast<uint32_t>(steamAppId), steamRootCopy);
693
694 // Check if we found any images
695 if (images.verticalCover.empty() && images.heroImage.empty() &&
696 images.header.empty())
697 {
698 return;
699 }
700
701 // Update database (thread-safe via database mutex)
702 if (database_->updateGameImages(gameId, images))
703 {
704 std::lock_guard<std::mutex> lock(resultsMutex);
705 results.push_back({gameId, std::move(images)});
706 }
707 }));
708 }
709
710 // Wait for all remaining tasks to complete
711 for (auto& future : futures)
712 {
713 future.wait();
714 }
715
716 // Apply results to in-memory cache (single-threaded, no races)
717 for (const auto& result : results)
718 {
719 auto it = games_.find(result.gameId);
720 if (it != games_.end())
721 {
722 it->second.metadata.imagePaths = result.images;
723 }
724 }
725
726 int count = static_cast<int>(results.size());
727 if (count > 0)
728 {
729 Logger::info("Discovered images for {} games", count);
730 }
731
732 return count;
733}
734
735bool GameLibrary::discoverImagesForGame(const std::string& gameId)
736{
737 auto it = games_.find(gameId);
738 if (it == games_.end())
739 {
740 return false;
741 }
742
743 Game& game = it->second;
744
745 // Only discover for Steam games
746 if (game.metadata.steamAppId <= 0)
747 {
748 return false;
749 }
750
751 // Use SteamCDN to discover images from Steam's cache
753 static_cast<uint32_t>(game.metadata.steamAppId), SteamPaths::getPrimarySteamRoot());
754
755 // Check if we found any images
756 if (images.verticalCover.empty() && images.heroImage.empty() && images.header.empty())
757 {
758 return false;
759 }
760
761 // Update database with discovered images
762 if (!database_->updateGameImages(gameId, images))
763 {
764 Logger::error("Failed to update images for game {}: {}", gameId, database_->lastError());
765 return false;
766 }
767
768 // Update in-memory cache
769 game.metadata.imagePaths = images;
770
771 Logger::debug("Discovered images for {} ({})", game.name, game.metadata.steamAppId);
772 return true;
773}
774
776{
777 // Find all Steam games that have image paths stored
778 std::vector<std::pair<std::string, int>> gamesToRefresh; // (gameId, steamAppId)
779
780 for (const auto& [gameId, game] : games_)
781 {
782 if (game.metadata.steamAppId <= 0)
783 continue;
784
785 const auto& paths = game.metadata.imagePaths;
786 bool hasStoredPaths = !paths.verticalCover.empty() || !paths.heroImage.empty() ||
787 !paths.header.empty() || !paths.capsule.empty();
788
789 if (!hasStoredPaths)
790 continue;
791
792 // Check if any stored paths no longer exist on disk
793 bool needsRefresh = false;
794 if (!paths.verticalCover.empty() && !fs::exists(paths.verticalCover))
795 needsRefresh = true;
796 else if (!paths.heroImage.empty() && !fs::exists(paths.heroImage))
797 needsRefresh = true;
798 else if (!paths.header.empty() && !fs::exists(paths.header))
799 needsRefresh = true;
800
801 if (needsRefresh)
802 {
803 gamesToRefresh.emplace_back(gameId, game.metadata.steamAppId);
804 }
805 }
806
807 if (gamesToRefresh.empty())
808 {
809 return 0;
810 }
811
812 Logger::info("Refreshing stale images for {} games...", gamesToRefresh.size());
813
814 // Use parallel refresh similar to discoverMissingImages
815 constexpr size_t MAX_CONCURRENT = 8;
816 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
817
818 struct ImageResult
819 {
820 std::string gameId;
821 GameImagePaths images;
822 };
823 std::mutex resultsMutex;
824 std::vector<ImageResult> results;
825
826 std::vector<std::future<void>> futures;
827
828 for (const auto& entry : gamesToRefresh)
829 {
830 if (futures.size() >= MAX_CONCURRENT)
831 {
832 futures.front().wait();
833 futures.erase(futures.begin());
834 }
835
836 std::string gameId = entry.first;
837 int steamAppId = entry.second;
838
839 futures.push_back(std::async(
840 std::launch::async,
841 [&resultsMutex, &results, steamRootCopy = steamRoot, gameId, steamAppId, this]()
842 {
843 GameImagePaths images =
844 SteamCDN::discoverImages(static_cast<uint32_t>(steamAppId), steamRootCopy);
845
846 if (images.verticalCover.empty() && images.heroImage.empty() &&
847 images.header.empty())
848 {
849 return;
850 }
851
852 if (database_->updateGameImages(gameId, images))
853 {
854 std::lock_guard<std::mutex> lock(resultsMutex);
855 results.push_back({gameId, std::move(images)});
856 }
857 }));
858 }
859
860 for (auto& future : futures)
861 {
862 future.wait();
863 }
864
865 // Apply results to in-memory cache (single-threaded, no races)
866 for (const auto& result : results)
867 {
868 auto it = games_.find(result.gameId);
869 if (it != games_.end())
870 {
871 it->second.metadata.imagePaths = result.images;
872 }
873 }
874
875 int count = static_cast<int>(results.size());
876 if (count > 0)
877 {
878 Logger::info("Refreshed images for {} games", count);
879 }
880
881 return count;
882}
883
884// ==============================================================================
885// Collections
886// ==============================================================================
887
888void GameLibrary::createCollection(const std::string& name)
889{
890 // Check if collection already exists
891 auto it = std::find(collections_.begin(), collections_.end(), name);
892 if (it != collections_.end())
893 {
894 Logger::info("Collection already exists: {}", name);
895 return;
896 }
897
898 collections_.push_back(name);
899 database_->addCollection(name);
900 Logger::info("Created collection: {}", name);
901}
902
903void GameLibrary::deleteCollection(const std::string& name)
904{
905 // Remove from collections list
906 auto it = std::find(collections_.begin(), collections_.end(), name);
907 if (it != collections_.end())
908 {
909 collections_.erase(it);
910 }
911
912 // Remove from all games
913 for (auto& [id, game] : games_)
914 {
915 auto gameIt = std::find(game.collections.begin(), game.collections.end(), name);
916 if (gameIt != game.collections.end())
917 {
918 game.collections.erase(gameIt);
919 }
920 }
921
922 database_->removeCollection(name);
923 Logger::info("Deleted collection: {}", name);
924}
925
926std::vector<std::string> GameLibrary::getCollectionNames() const
927{
928 return collections_;
929}
930
931void GameLibrary::addGameToCollection(const std::string& gameId, const std::string& collection)
932{
933 auto gameOpt = getGame(gameId);
934 if (!gameOpt)
935 {
936 Logger::error("Game not found: {}", gameId);
937 return;
938 }
939
940 Game* game = *gameOpt;
941
942 // Check if already in collection
943 auto it = std::find(game->collections.begin(), game->collections.end(), collection);
944 if (it != game->collections.end())
945 {
946 Logger::info("Game already in collection");
947 return;
948 }
949
950 game->collections.push_back(collection);
951 database_->addGameToCollection(gameId, collection);
952 Logger::info("Added game to collection: {}", collection);
953}
954
955void GameLibrary::removeGameFromCollection(const std::string& gameId, const std::string& collection)
956{
957 auto gameOpt = getGame(gameId);
958 if (!gameOpt)
959 {
960 Logger::error("Game not found: {}", gameId);
961 return;
962 }
963
964 Game* game = *gameOpt;
965
966 auto it = std::find(game->collections.begin(), game->collections.end(), collection);
967 if (it != game->collections.end())
968 {
969 game->collections.erase(it);
970 database_->removeGameFromCollection(gameId, collection);
971 Logger::info("Removed game from collection: {}", collection);
972 }
973}
974
975// ==============================================================================
976// Private Helper Methods
977// ==============================================================================
978
979std::string GameLibrary::generateUniqueId() const
980{
981 std::random_device rd;
982 std::mt19937 gen(rd());
983 std::uniform_int_distribution<uint64_t> dis(100000, 999999999);
984
985 for (int attempt = 0; attempt < 10; ++attempt)
986 {
987 std::ostringstream oss;
988 oss << "game_" << std::time(nullptr) << "_" << dis(gen);
989 std::string id = oss.str();
990
991 // Ensure no collision with existing games
992 if (games_.find(id) == games_.end())
993 return id;
994 }
995
996 // Fallback: extremely unlikely to reach here
997 std::ostringstream oss;
998 oss << "game_" << std::time(nullptr) << "_" << dis(gen) << "_" << dis(gen);
999 return oss.str();
1000}
1001
1002std::string GameLibrary::getLibraryPath() const
1003{
1004 // Use ~/.local/share/gamelauncher/ on Linux
1005 // or %APPDATA%/gamelauncher/ on Windows
1006
1007#ifdef _WIN32
1008 const char* appdata = std::getenv("APPDATA");
1009 if (appdata)
1010 {
1011 return std::string(appdata) + "/gamelauncher";
1012 }
1013 return "./library";
1014#else
1015 const char* home = std::getenv("HOME");
1016 if (home)
1017 {
1018 return std::string(home) + "/.local/share/gamelauncher";
1019 }
1020 return "./library";
1021#endif
1022}
1023
1024std::string GameLibrary::getGameFilePath(const std::string& gameId) const
1025{
1026 // Validate gameId: only alphanumeric, hyphens, and underscores are allowed.
1027 // IDs are UUIDs generated internally, so this is defense-in-depth against
1028 // crafted IDs (e.g., "../../../etc") from corrupt or malicious database content.
1029 for (char c : gameId)
1030 {
1031 if (!std::isalnum(static_cast<unsigned char>(c)) && c != '-' && c != '_')
1032 {
1033 Logger::error("GameLibrary: Rejected invalid game ID for file path: '{}'", gameId);
1034 return "";
1035 }
1036 }
1037 return libraryPath_ + "/" + gameId + ".game";
1038}
1039
1040void GameLibrary::invalidateCaches()
1041{
1042 allGamesCacheValid_ = false;
1043 allGamesConstCacheValid_ = false;
1044 recentGamesCacheValid_ = false;
1045 recentGamesConstCacheValid_ = false;
1046}
1047
1048void GameLibrary::reloadFromDatabase()
1049{
1050 games_.clear();
1051 invalidateCaches();
1052
1053 // Get all games from database
1054 std::vector<Game> dbGames = database_->getAllGames();
1055 for (auto& game : dbGames)
1056 {
1057 games_[game.id] = std::move(game);
1058 }
1059}
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
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::vector< std::string > collections
Collections this game belongs to.
Definition game.h:804
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
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static GameImagePaths discoverImages(uint32_t appId, const std::filesystem::path &steamRoot)
Find all available images for a Steam game.
static std::filesystem::path getPrimarySteamRoot()
Get primary Steam installation directory.
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
Paths to various game image assets.
Definition game.h:496
std::string header
Small header image (header.jpg, 460x215).
Definition game.h:500
std::string verticalCover
Vertical cover art (library_600x900.jpg).
Definition game.h:497
std::string heroImage
Wide banner/hero image (library_hero.jpg).
Definition game.h:498
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
GameImagePaths imagePaths
Paths to all available image assets.
Definition game.h:562
std::string executablePath
Full path to game executable.
Definition game.h:141
time_t dateAdded
Unix timestamp when added to library.
Definition game.h:716