21namespace fs = std::filesystem;
30 libraryPath_ = getLibraryPath();
33 database_ = std::make_unique<GameDatabase>();
34 std::string dbPath = libraryPath_ +
"/games.db";
36 if (!database_->open(dbPath))
38 Logger::error(
"Failed to open game database: {}", database_->lastError());
56 if (!fs::exists(libraryPath_))
58 fs::create_directories(libraryPath_);
59 Logger::info(
"Created library directory: {}", libraryPath_);
67 collections_ = database_->getCollections();
69 Logger::info(
"Loaded {} games from database", games_.size());
78 database_->beginTransaction();
80 for (
const auto& [
id, game] : games_)
83 if (database_->gameExists(
id))
85 ok = database_->updateGame(game);
89 ok = database_->insertGame(game);
98 Logger::error(
"Failed to save game {}: {}",
id, database_->lastError());
106 database_->rollbackTransaction();
107 Logger::error(
"Rolled back save: {} games failed to save", failedCount);
111 database_->commitTransaction();
123 for (
const auto& [existingId, existing] : games_)
129 Logger::warn(
"Duplicate game skipped (Steam App ID {}): {} already exists as {}",
137 !existing.runnerConfig.executablePath.empty() &&
138 existing.runnerConfig.executablePath !=
"steam")
142 std::string existExe = existing.runnerConfig.executablePath;
145 newExe = fs::canonical(newExe).string();
152 existExe = fs::canonical(existExe).string();
157 if (newExe == existExe)
159 Logger::warn(
"Duplicate game skipped (same executable): {} already exists as {}",
160 game.
name, existing.name);
167 if (!game.
name.empty() && !existing.name.empty())
169 std::string newName = game.
name;
170 std::string existName = existing.name;
172 auto normalize = [](std::string s)
176 for (
size_t i = 0; i < s.size(); ++i)
178 unsigned char c =
static_cast<unsigned char>(s[i]);
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)
187 if (c == 0xC2 && i + 1 < s.size() &&
188 static_cast<unsigned char>(s[i + 1]) == 0xAE)
193 result +=
static_cast<char>(std::tolower(c));
196 while (!result.empty() && result.back() ==
' ')
201 if (normalize(newName) == normalize(existName) && game.
source != existing.source)
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));
213 std::string
id = game.
id;
216 id = generateUniqueId();
230 if (!database_->insertGame(newGame))
232 Logger::error(
"Failed to add game to database: {}", database_->lastError());
237 games_[id] = newGame;
247 auto it = games_.find(gameId);
248 if (it == games_.end())
255 if (!database_->deleteGame(gameId))
257 Logger::error(
"Failed to delete game from database: {}", database_->lastError());
262 std::string filepath = getGameFilePath(gameId);
263 if (fs::exists(filepath))
265 fs::remove(filepath);
279 auto it = games_.find(gameId);
280 if (it == games_.end())
287 Game updated = updatedGame;
291 if (!database_->updateGame(updated))
293 Logger::error(
"Failed to update game in database: {}", database_->lastError());
298 games_[gameId] = updated;
308 auto it = games_.find(gameId);
309 if (it == games_.end())
314 return &(it->second);
319 auto it = games_.find(gameId);
320 if (it == games_.end())
325 return &(it->second);
334 if (!allGamesCacheValid_)
336 cachedAllGames_.clear();
337 for (
auto& [
id, game] : games_)
339 cachedAllGames_.push_back(&game);
341 allGamesCacheValid_ =
true;
343 return cachedAllGames_;
348 if (!allGamesConstCacheValid_)
350 cachedAllGamesConst_.clear();
351 for (
const auto& [
id, game] : games_)
353 cachedAllGamesConst_.push_back(&game);
355 allGamesConstCacheValid_ =
true;
357 return cachedAllGamesConst_;
362 std::vector<Game*> result;
363 for (
auto& [
id, game] : games_)
367 result.push_back(&game);
375 std::vector<const Game*> result;
376 for (
const auto& [
id, game] : games_)
380 result.push_back(&game);
388 std::vector<Game*> result;
389 for (
auto& [
id, game] : games_)
393 result.push_back(&game);
401 std::vector<const Game*> result;
402 for (
const auto& [
id, game] : games_)
406 result.push_back(&game);
415 if (!recentGamesCacheValid_ || cachedRecentGamesCount_ != count)
417 cachedRecentGames_.clear();
420 for (
auto& [
id, game] : games_)
422 if (game.statistics.lastPlayed > 0)
424 cachedRecentGames_.push_back(&game);
429 std::sort(cachedRecentGames_.begin(), cachedRecentGames_.end(), [](
Game* a,
Game* b)
430 { return a->statistics.lastPlayed > b->statistics.lastPlayed; });
435 const size_t limit = count > 0 ?
static_cast<size_t>(count) : 0;
436 if (cachedRecentGames_.size() > limit)
438 cachedRecentGames_.resize(limit);
441 recentGamesCacheValid_ =
true;
442 cachedRecentGamesCount_ = count;
445 return cachedRecentGames_;
451 if (!recentGamesConstCacheValid_ || cachedRecentGamesConstCount_ != count)
453 cachedRecentGamesConst_.clear();
456 for (
const auto& [
id, game] : games_)
458 if (game.statistics.lastPlayed > 0)
460 cachedRecentGamesConst_.push_back(&game);
465 std::sort(cachedRecentGamesConst_.begin(), cachedRecentGamesConst_.end(),
467 { return a->statistics.lastPlayed > b->statistics.lastPlayed; });
471 const size_t limit = count > 0 ?
static_cast<size_t>(count) : 0;
472 if (cachedRecentGamesConst_.size() > limit)
474 cachedRecentGamesConst_.resize(limit);
477 recentGamesConstCacheValid_ =
true;
478 cachedRecentGamesConstCount_ = count;
481 return cachedRecentGamesConst_;
488 return database_->getRecentSessions(gameId, limit);
495 std::vector<Game*> result;
496 for (
auto& [
id, game] : games_)
500 result.push_back(&game);
508 std::vector<const Game*> result;
509 for (
const auto& [
id, game] : games_)
513 result.push_back(&game);
521 std::vector<Game*> result;
523 std::string lowerQuery(query);
524 std::transform(lowerQuery.begin(), lowerQuery.end(), lowerQuery.begin(),
525 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
527 auto containsQuery = [&lowerQuery](
const std::string& field)
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;
535 for (
auto& [
id, game] : games_)
537 if (containsQuery(game.name) || containsQuery(game.metadata.developer) ||
538 containsQuery(game.metadata.publisher) || containsQuery(game.metadata.description))
540 result.push_back(&game);
549 std::vector<const Game*> result;
551 std::string lowerQuery(query);
552 std::transform(lowerQuery.begin(), lowerQuery.end(), lowerQuery.begin(),
553 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
555 auto containsQuery = [&lowerQuery](
const std::string& field)
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;
563 for (
const auto& [
id, game] : games_)
565 if (containsQuery(game.name) || containsQuery(game.metadata.developer) ||
566 containsQuery(game.metadata.publisher) || containsQuery(game.metadata.description))
568 result.push_back(&game);
577 std::vector<Game*> result;
578 for (
auto& [
id, game] : games_)
581 auto it = std::find(game.collections.begin(), game.collections.end(), collectionName);
582 if (it != game.collections.end())
584 result.push_back(&game);
592 std::vector<const Game*> result;
593 for (
const auto& [
id, game] : games_)
596 auto it = std::find(game.collections.begin(), game.collections.end(), collectionName);
597 if (it != game.collections.end())
599 result.push_back(&game);
611 return static_cast<int>(games_.size());
617 for (
const auto& [
id, game] : games_)
630 for (
const auto& [
id, game] : games_)
632 total += game.statistics.totalPlayTimeSeconds;
644 auto gamesWithoutCover = database_->getGamesWithoutCoverArt();
646 if (gamesWithoutCover.empty())
651 Logger::info(
"Discovering images for {} games...", gamesWithoutCover.size());
655 constexpr size_t MAX_CONCURRENT = 8;
666 std::mutex resultsMutex;
667 std::vector<ImageResult> results;
670 std::vector<std::future<void>> futures;
672 for (
const auto& game : gamesWithoutCover)
675 if (futures.size() >= MAX_CONCURRENT)
678 futures.front().wait();
679 futures.erase(futures.begin());
682 futures.push_back(std::async(
684 [&resultsMutex, &results, steamRootCopy = steamRoot, gameId = game.id,
685 steamAppId = game.metadata.steamAppId,
this]()
691 GameImagePaths images =
692 SteamCDN::discoverImages(static_cast<uint32_t>(steamAppId), steamRootCopy);
695 if (images.verticalCover.empty() && images.heroImage.empty() &&
696 images.header.empty())
702 if (database_->updateGameImages(gameId, images))
704 std::lock_guard<std::mutex> lock(resultsMutex);
705 results.push_back({gameId, std::move(images)});
711 for (
auto& future : futures)
717 for (
const auto& result : results)
719 auto it = games_.find(result.gameId);
720 if (it != games_.end())
722 it->second.metadata.imagePaths = result.images;
726 int count =
static_cast<int>(results.size());
737 auto it = games_.find(gameId);
738 if (it == games_.end())
743 Game& game = it->second;
762 if (!database_->updateGameImages(gameId, images))
764 Logger::error(
"Failed to update images for game {}: {}", gameId, database_->lastError());
778 std::vector<std::pair<std::string, int>> gamesToRefresh;
780 for (
const auto& [gameId, game] : games_)
782 if (game.metadata.steamAppId <= 0)
785 const auto& paths = game.metadata.imagePaths;
786 bool hasStoredPaths = !paths.verticalCover.empty() || !paths.heroImage.empty() ||
787 !paths.header.empty() || !paths.capsule.empty();
793 bool needsRefresh =
false;
794 if (!paths.verticalCover.empty() && !fs::exists(paths.verticalCover))
796 else if (!paths.heroImage.empty() && !fs::exists(paths.heroImage))
798 else if (!paths.header.empty() && !fs::exists(paths.header))
803 gamesToRefresh.emplace_back(gameId, game.metadata.steamAppId);
807 if (gamesToRefresh.empty())
812 Logger::info(
"Refreshing stale images for {} games...", gamesToRefresh.size());
815 constexpr size_t MAX_CONCURRENT = 8;
823 std::mutex resultsMutex;
824 std::vector<ImageResult> results;
826 std::vector<std::future<void>> futures;
828 for (
const auto& entry : gamesToRefresh)
830 if (futures.size() >= MAX_CONCURRENT)
832 futures.front().wait();
833 futures.erase(futures.begin());
836 std::string gameId = entry.first;
837 int steamAppId = entry.second;
839 futures.push_back(std::async(
841 [&resultsMutex, &results, steamRootCopy = steamRoot, gameId, steamAppId,
this]()
852 if (database_->updateGameImages(gameId, images))
854 std::lock_guard<std::mutex> lock(resultsMutex);
855 results.push_back({gameId, std::move(images)});
860 for (
auto& future : futures)
866 for (
const auto& result : results)
868 auto it = games_.find(result.gameId);
869 if (it != games_.end())
871 it->second.metadata.imagePaths = result.images;
875 int count =
static_cast<int>(results.size());
891 auto it = std::find(collections_.begin(), collections_.end(), name);
892 if (it != collections_.end())
898 collections_.push_back(name);
899 database_->addCollection(name);
906 auto it = std::find(collections_.begin(), collections_.end(), name);
907 if (it != collections_.end())
909 collections_.erase(it);
913 for (
auto& [
id, game] : games_)
915 auto gameIt = std::find(game.collections.begin(), game.collections.end(), name);
916 if (gameIt != game.collections.end())
918 game.collections.erase(gameIt);
922 database_->removeCollection(name);
933 auto gameOpt =
getGame(gameId);
940 Game* game = *gameOpt;
951 database_->addGameToCollection(gameId, collection);
952 Logger::info(
"Added game to collection: {}", collection);
957 auto gameOpt =
getGame(gameId);
964 Game* game = *gameOpt;
970 database_->removeGameFromCollection(gameId, collection);
971 Logger::info(
"Removed game from collection: {}", collection);
979std::string GameLibrary::generateUniqueId()
const
981 std::random_device rd;
982 std::mt19937 gen(rd());
983 std::uniform_int_distribution<uint64_t> dis(100000, 999999999);
985 for (
int attempt = 0; attempt < 10; ++attempt)
987 std::ostringstream oss;
988 oss <<
"game_" << std::time(
nullptr) <<
"_" << dis(gen);
989 std::string
id = oss.str();
992 if (games_.find(
id) == games_.end())
997 std::ostringstream oss;
998 oss <<
"game_" << std::time(
nullptr) <<
"_" << dis(gen) <<
"_" << dis(gen);
1002std::string GameLibrary::getLibraryPath()
const
1008 const char* appdata = std::getenv(
"APPDATA");
1011 return std::string(appdata) +
"/gamelauncher";
1015 const char* home = std::getenv(
"HOME");
1018 return std::string(home) +
"/.local/share/gamelauncher";
1024std::string GameLibrary::getGameFilePath(
const std::string& gameId)
const
1029 for (
char c : gameId)
1031 if (!std::isalnum(
static_cast<unsigned char>(c)) && c !=
'-' && c !=
'_')
1033 Logger::error(
"GameLibrary: Rejected invalid game ID for file path: '{}'", gameId);
1037 return libraryPath_ +
"/" + gameId +
".game";
1040void GameLibrary::invalidateCaches()
1042 allGamesCacheValid_ =
false;
1043 allGamesConstCacheValid_ =
false;
1044 recentGamesCacheValid_ =
false;
1045 recentGamesConstCacheValid_ =
false;
1048void GameLibrary::reloadFromDatabase()
1054 std::vector<Game> dbGames = database_->getAllGames();
1055 for (
auto& game : dbGames)
1057 games_[game.id] = std::move(game);
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.
GameMetadata metadata
Descriptive information and media.
std::vector< std::string > collections
Collections this game belongs to.
std::string name
Display name shown in UI.
std::string id
Unique identifier (auto-generated or user-specified).
GameStatistics statistics
Play statistics and usage tracking.
GameRunnerConfig runnerConfig
How to launch and run the game.
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
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.
@ Running
Game is currently running.
@ Installed
Game is installed and ready to play.
Paths to various game image assets.
std::string header
Small header image (header.jpg, 460x215).
std::string verticalCover
Vertical cover art (library_600x900.jpg).
std::string heroImage
Wide banner/hero image (library_hero.jpg).
std::string executablePath
Full path to game executable.
time_t dateAdded
Unix timestamp when added to library.