32#include <unordered_map>
42 file.seekg(0, std::ios::end);
43 const auto sz = file.tellg();
46 file.seekg(0, std::ios::beg);
47 return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
54const std::vector<std::string>& SteamCDN::cdnHosts()
56 static const std::vector<std::string> hosts = {
57 "https://cdn.cloudflare.steamstatic.com/steam/apps/",
58 "https://steamcdn-a.akamaihd.net/steam/apps/"
63std::string SteamCDN::getCacheFilename(
ImageType type)
68 return "library_600x900.jpg";
70 return "library_hero.jpg";
76 return "capsule_616x353.jpg";
86 return libraryPath /
"appcache" /
"librarycache";
94 if (!std::filesystem::exists(cacheDir))
96 Logger::debug(
"Steam image cache not found at: {}", cacheDir.string());
100 std::string appIdStr = std::to_string(appId);
106 auto validateImageFile = [&](
const std::filesystem::path& imagePath,
107 const std::string& filename) ->
bool
109 if (!std::filesystem::exists(imagePath))
114 auto fileSize = std::filesystem::file_size(imagePath, ec);
115 if (ec || fileSize == 0)
120 constexpr size_t MIN_FILE_SIZE_JPG = 5 * 1024;
121 constexpr size_t MIN_FILE_SIZE_PNG = 1 * 1024;
122 bool isPng = filename.find(
".png") != std::string::npos;
123 size_t minSize = isPng ? MIN_FILE_SIZE_PNG : MIN_FILE_SIZE_JPG;
125 if (fileSize < minSize)
131 std::ifstream file(imagePath, std::ios::binary);
135 unsigned char header[8];
136 file.read(
reinterpret_cast<char*
>(header), isPng ? 8 : 2);
143 if (header[0] != 0x89 || header[1] != 0x50 || header[2] != 0x4E || header[3] != 0x47)
151 if (header[0] != 0xFF || header[1] != 0xD8)
160 file.seekg(-2, std::ios::end);
161 unsigned char footer[2];
162 file.read(
reinterpret_cast<char*
>(footer), 2);
163 if (!file || footer[0] != 0xFF || footer[1] != 0xD9)
175 auto findImage = [&](
const std::vector<std::string>& filenames) -> std::string
177 std::filesystem::path appDir = cacheDir / appIdStr;
179 if (std::filesystem::exists(appDir) && std::filesystem::is_directory(appDir))
183 for (
const auto& filename : filenames)
185 std::filesystem::path imagePath = appDir / filename;
186 if (validateImageFile(imagePath, filename))
188 Logger::debug(
"Found image (flat format): {}", imagePath.string());
189 return imagePath.string();
195 for (
const auto& entry : std::filesystem::directory_iterator(appDir))
197 if (!entry.is_directory())
200 for (
const auto& filename : filenames)
202 std::filesystem::path imagePath = entry.path() / filename;
203 if (validateImageFile(imagePath, filename))
205 Logger::debug(
"Found image (hash subdir): {}", imagePath.string());
206 return imagePath.string();
214 for (
const auto& filename : filenames)
217 if (filename.find(
".jpg") != std::string::npos)
219 std::string base = filename.substr(0, filename.length() - 4);
220 std::string variant2x = appIdStr +
"_" + base +
"_2x.jpg";
221 std::filesystem::path imagePath = cacheDir / variant2x;
222 if (validateImageFile(imagePath, variant2x))
224 Logger::debug(
"Found image (legacy 2x): {}", imagePath.string());
225 return imagePath.string();
230 std::string variant = appIdStr +
"_" + filename;
231 std::filesystem::path imagePath = cacheDir / variant;
232 if (validateImageFile(imagePath, variant))
234 Logger::debug(
"Found image (legacy): {}", imagePath.string());
235 return imagePath.string();
246 paths.
verticalCover = findImage({
"library_600x900.jpg",
"library_600x900_2x.jpg"});
249 paths.
heroImage = findImage({
"library_hero.jpg",
"library_hero_2x.jpg"});
252 paths.
logo = findImage({
"logo.png",
"logo_2x.png"});
255 paths.
header = findImage({
"library_header.jpg",
"header.jpg",
"library_header_2x.jpg"});
258 paths.
capsule = findImage({
"library_capsule.jpg",
"capsule_616x353.jpg",
"capsule_231x87.jpg"});
261 paths.
icon = findImage({
"icon.jpg",
"icon.png"});
269 if (!paths.
logo.empty())
271 if (!paths.
header.empty())
275 if (!paths.
icon.empty())
280 Logger::info(
"Discovered {} images for app {}", foundCount, appIdStr);
288 std::string filename = getCacheFilename(type);
289 if (filename.empty())
293 return cdnHosts()[0] + std::to_string(appId) +
"/" + filename;
298 std::string filename = getCacheFilename(type);
299 if (filename.empty())
303 for (
const auto& host : cdnHosts())
305 std::string url = host + std::to_string(appId) +
"/" + filename;
306 std::string curlCommand =
"curl -s -f --max-time 10 -o " +
312 if (result.
success && std::filesystem::exists(outputPath) &&
313 std::filesystem::file_size(outputPath) > 0)
320 if (std::filesystem::exists(outputPath))
322 std::filesystem::remove(outputPath);
337 return "Proton CachyOS SLR (Recommended)";
339 return "Proton CachyOS (Native)";
341 return "Proton Experimental";
347 return "Proton GE (Community)";
349 return "System Default";
351 return "Native Linux";
362 return "proton-cachyos-slr";
364 return "proton-cachyos";
366 return "proton-experimental";
388 std::ostringstream env;
393 env <<
"PROTON_USE_NTSYNC=1 ";
397 env <<
"DXVK_ASYNC=1 ";
401 env <<
"__GL_SHADER_DISK_CACHE=1 ";
405 env <<
"__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 ";
411 env <<
"WINE_FULLSCREEN_FSR=1 ";
415 env <<
"PROTON_DLSS_UPGRADE=1 ";
419 env <<
"PROTON_DLSS_INDICATOR=1 ";
423 env <<
"PROTON_FSR4_UPGRADE=1 ";
427 env <<
"PROTON_FSR4_RDNA3_UPGRADE=1 ";
431 env <<
"PROTON_XESS_UPGRADE=1 ";
435 env <<
"PROTON_NVIDIA_LIBS=1 ";
439 env <<
"PROTON_NVIDIA_LIBS_NO_32BIT=1 ";
445 env <<
"ENABLE_GAMESCOPE=1 ";
449 env <<
"PROTON_ENABLE_HDR=1 ";
453 env <<
"DXVK_HDR=1 ";
457 env <<
"PROTON_ENABLE_WAYLAND=1 ";
463 env <<
"PROTON_PREFER_SDL=1 ";
467 env <<
"PROTON_NO_STEAMINPUT=1 ";
473 env <<
"MANGOHUD=1 ";
477 env <<
"DXVK_HUD=compiler ";
481 env <<
"PROTON_LOG=1 ";
485 env <<
"LD_PRELOAD=\"\" ";
526 bool directLaunchReady =
false;
543 std::string protonDir =
protonPath.parent_path().filename().string();
546 directLaunchReady =
true;
569 directLaunchReady =
true;
574 if (!directLaunchReady)
631 imagePaths.
heroImage.empty() ?
"no" :
"yes");
636 (steamRoot /
"appcache" /
"librarycache").
string());
692 std::filesystem::path artDir(coverArtDir);
693 if (!std::filesystem::exists(artDir))
695 std::filesystem::create_directories(artDir);
698 std::string outputPath = coverArtDir +
"/" + std::to_string(
appId) +
".jpg";
701 if (std::filesystem::exists(outputPath) && std::filesystem::file_size(outputPath) > 0)
721 const std::filesystem::path& libraryPath)
723 std::ifstream file(acfFilePath);
726 Logger::error(
"Failed to open ACF file: {}", acfFilePath.string());
733 auto keyValues = parseKeyValues(content);
738 if (keyValues.count(
"appid"))
742 steamGame.
appId =
static_cast<uint32_t
>(std::stoul(keyValues[
"appid"]));
746 Logger::error(
"Invalid appid in ACF file: {}", acfFilePath.string());
752 Logger::error(
"Missing appid in ACF file: {}", acfFilePath.string());
756 steamGame.
name = keyValues.count(
"name") ? keyValues[
"name"] :
"Unknown Game";
757 steamGame.
installDir = keyValues.count(
"installdir") ? keyValues[
"installdir"] :
"";
761 Logger::error(
"Missing installdir in ACF file: {}", acfFilePath.string());
766 if (steamGame.
installDir.find(
"..") != std::string::npos ||
767 steamGame.
installDir.find(
'/') != std::string::npos ||
768 steamGame.
installDir.find(
'\\') != std::string::npos)
770 Logger::error(
"[SteamLibraryScanner] Rejected ACF installdir with path traversal: {}",
779 if (keyValues.count(
"SizeOnDisk"))
783 steamGame.
sizeOnDisk = std::stoull(keyValues[
"SizeOnDisk"]);
791 if (keyValues.count(
"LastUpdated"))
795 steamGame.
lastUpdated =
static_cast<time_t
>(std::stoll(keyValues[
"LastUpdated"]));
804 if (keyValues.count(
"buildid"))
811 if (keyValues.count(
"StateFlags"))
815 steamGame.
stateFlags =
static_cast<uint32_t
>(std::stoul(keyValues[
"StateFlags"]));
831 if (keyValues.count(
"BytesDownloaded"))
841 if (keyValues.count(
"BytesToDownload"))
851 if (keyValues.count(
"BytesStaged"))
855 steamGame.
bytesStaged = std::stoull(keyValues[
"BytesStaged"]);
861 if (keyValues.count(
"BytesToStage"))
865 steamGame.
bytesToStage = std::stoull(keyValues[
"BytesToStage"]);
873 std::filesystem::path compatDataPath =
874 libraryPath /
"steamapps" /
"compatdata" / std::to_string(steamGame.
appId);
875 steamGame.
isProtonGame = std::filesystem::exists(compatDataPath);
897 std::filesystem::path steamPath = libraryPath;
898 while (steamPath.has_parent_path() && steamPath.filename() !=
"Steam")
900 steamPath = steamPath.parent_path();
903 std::filesystem::path userConfigPath = steamPath /
"config" /
"config.vdf";
904 if (!std::filesystem::exists(userConfigPath))
910 std::ifstream file(userConfigPath);
930 std::string appIdStr = std::to_string(appId);
931 size_t compatToolPos = content.find(
"\"CompatToolMapping\"");
932 if (compatToolPos == std::string::npos)
938 size_t appIdPos = content.find(
"\"" + appIdStr +
"\"", compatToolPos);
939 if (appIdPos == std::string::npos)
945 size_t namePos = content.find(
"\"name\"", appIdPos);
946 if (namePos == std::string::npos || namePos > appIdPos + 500)
952 size_t valueStart = content.find(
"\"", namePos + 6);
953 if (valueStart == std::string::npos)
958 size_t valueEnd = content.find(
"\"", valueStart + 1);
959 if (valueEnd == std::string::npos)
964 std::string protonName = content.substr(valueStart + 1, valueEnd - valueStart - 1);
971 if (protonName.find(
"experimental") != std::string::npos)
973 return "Proton Experimental";
975 else if (protonName.find(
"proton_9") != std::string::npos ||
976 protonName.find(
"proton 9") != std::string::npos)
980 else if (protonName.find(
"proton_8") != std::string::npos ||
981 protonName.find(
"proton 8") != std::string::npos)
985 else if (protonName.find(
"proton_7") != std::string::npos ||
986 protonName.find(
"proton 7") != std::string::npos)
990 else if (protonName.find(
"-ge-") != std::string::npos ||
991 protonName.find(
"GE") != std::string::npos)
995 else if (protonName.find(
"proton") != std::string::npos)
998 return "Proton (" + protonName +
")";
1004std::map<std::string, std::string> ACFParser::parseKeyValues(
const std::string& content)
1006 std::map<std::string, std::string> keyValues;
1009 static const std::regex keyValueRegex(
"\"([^\"]+)\"\\s+\"([^\"]+)\"", std::regex::optimize);
1010 std::sregex_iterator iter(content.begin(), content.end(), keyValueRegex);
1011 std::sregex_iterator end;
1013 for (; iter != end; ++iter)
1015 const std::smatch& match = *iter;
1016 keyValues[match[1].str()] = match[2].str();
1022std::string ACFParser::extractQuotedValue(
const std::string& line)
1024 size_t first = line.find(
'"');
1025 if (first == std::string::npos)
1028 size_t second = line.find(
'"', first + 1);
1029 if (second == std::string::npos)
1032 return line.substr(first + 1, second - first - 1);
1041 steamPath_ = detectSteamPath();
1042 if (!steamPath_.empty())
1044 libraries_ = parseLibraryFolders(steamPath_);
1046 libraries_.insert(libraries_.begin(), steamPath_);
1052 std::vector<SteamGame> allGames;
1054 for (
const auto& library : libraries_)
1056 std::vector<SteamGame> libraryGames = scanLibrary(library);
1057 allGames.insert(allGames.end(), libraryGames.begin(), libraryGames.end());
1070 for (
auto& game : allGames)
1072 auto it = playtimeData.find(game.appId);
1073 if (it != playtimeData.end())
1080 game.steamLastExit = data.
lastExit;
1084 auto cloudIt = cloudSaveData.find(game.appId);
1085 if (cloudIt != cloudSaveData.end())
1087 game.cloudSave = cloudIt->second;
1091 auto catIt = categoriesData.find(game.appId);
1092 if (catIt != categoriesData.end())
1094 game.steamUserCategories = catIt->second;
1103 Logger::info(
"[SteamScanner] Starting scan for all owned games...");
1108 Logger::info(
"[SteamScanner] Found {} installed games", installedGames.size());
1111 std::set<uint32_t> installedAppIds;
1112 for (
const auto& game : installedGames)
1114 installedAppIds.insert(game.appId);
1118 std::set<uint32_t> ownedAppIds;
1122 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
1125 return installedGames;
1129 if (!std::filesystem::exists(userdataPath))
1131 return installedGames;
1135 for (
const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
1137 if (!userEntry.is_directory())
1140 std::filesystem::path configPath = userEntry.path() /
"config" /
"localconfig.vdf";
1141 if (!std::filesystem::exists(configPath))
1144 std::ifstream file(configPath);
1145 if (!file.is_open())
1152 size_t appsPos = content.find(
"\"apps\"");
1153 if (appsPos == std::string::npos)
1159 size_t appsOpenBrace = content.find(
'{', appsPos);
1160 if (appsOpenBrace == std::string::npos)
1167 size_t pos = appsOpenBrace + 1;
1168 size_t appsSectionEnd = content.length();
1170 while (pos < content.length() && braceDepth > 0)
1172 if (content[pos] ==
'{')
1174 else if (content[pos] ==
'}')
1177 if (braceDepth == 0)
1179 appsSectionEnd = pos;
1187 std::string appsSection =
1188 content.substr(appsOpenBrace + 1, appsSectionEnd - appsOpenBrace - 1);
1191 std::regex appIdRegex(
"\"(\\d+)\"\\s*\\{");
1192 std::sregex_iterator appIdIter(appsSection.begin(), appsSection.end(), appIdRegex);
1193 std::sregex_iterator end;
1195 for (; appIdIter != end; ++appIdIter)
1197 const std::smatch& match = *appIdIter;
1198 uint32_t appId =
static_cast<uint32_t
>(std::stoul(match[1].str()));
1199 ownedAppIds.insert(appId);
1206 Logger::info(
"[SteamScanner] Found {} total owned App IDs", ownedAppIds.size());
1212 std::vector<SteamGame> allGames = installedGames;
1215 const size_t MAX_UNINSTALLED_GAMES = 100;
1216 size_t uninstalledCount = 0;
1218 for (uint32_t appId : ownedAppIds)
1221 if (installedAppIds.find(appId) != installedAppIds.end())
1225 if (uninstalledCount >= MAX_UNINSTALLED_GAMES)
1227 Logger::info(
"[SteamScanner] Reached limit of {} uninstalled games, stopping",
1228 MAX_UNINSTALLED_GAMES);
1239 auto playtimeIt = playtimeData.find(appId);
1240 if (playtimeIt != playtimeData.end())
1253 if (!cachedName.empty())
1255 game.
name = cachedName;
1260 game.
name =
"Steam App " + std::to_string(appId);
1270 allGames.push_back(game);
1273 Logger::info(
"[SteamScanner] Scan complete. Total: {} games ({} installed, {} not installed)",
1274 allGames.size(), installedGames.size(), uninstalledCount);
1286 return !steamPath_.empty();
1289std::filesystem::path SteamLibraryScanner::detectSteamPath()
1295std::vector<std::filesystem::path>
1296SteamLibraryScanner::parseLibraryFolders(
const std::filesystem::path& steamPath)
1298 std::vector<std::filesystem::path> libraries;
1300 std::filesystem::path libraryFoldersPath = steamPath /
"steamapps" /
"libraryfolders.vdf";
1302 if (!std::filesystem::exists(libraryFoldersPath))
1307 std::ifstream file(libraryFoldersPath);
1308 if (!file.is_open())
1314 std::regex pathRegex(
"\"path\"\\s+\"([^\"]+)\"");
1316 while (std::getline(file, line))
1319 if (std::regex_search(line, match, pathRegex))
1321 std::string libraryPath = match[1].str();
1322 if (std::filesystem::exists(libraryPath))
1324 libraries.push_back(libraryPath);
1333std::vector<SteamGame> SteamLibraryScanner::scanLibrary(
const std::filesystem::path& libraryPath)
1335 std::vector<SteamGame> games;
1337 std::filesystem::path steamappsPath = libraryPath /
"steamapps";
1338 if (!std::filesystem::exists(steamappsPath))
1344 for (
const auto& entry : std::filesystem::directory_iterator(steamappsPath))
1346 if (!entry.is_regular_file())
1349 std::string filename = entry.path().filename().string();
1352 if (filename.rfind(
"appmanifest_", 0) == 0 && filename.size() >= 4 &&
1353 filename.substr(filename.size() - 4) ==
".acf")
1356 if (steamGame.has_value())
1358 SteamGame game = steamGame.value();
1363 games.push_back(game);
1378 std::ostringstream command;
1382 if (!envVars.empty())
1390 command <<
"game-performance ";
1414 return command.str();
1419 return "steam://rungameid/" + std::to_string(appId);
1431 if (launchOptions.empty())
1437 std::vector<std::string> tokens;
1438 std::string currentToken;
1439 bool inQuotes =
false;
1441 for (
size_t i = 0; i < launchOptions.length(); i++)
1443 char c = launchOptions[i];
1447 inQuotes = !inQuotes;
1449 else if (c ==
' ' && !inQuotes)
1451 if (!currentToken.empty())
1453 tokens.push_back(currentToken);
1454 currentToken.clear();
1463 if (!currentToken.empty())
1465 tokens.push_back(currentToken);
1470 bool afterCommand =
false;
1472 for (
const auto& token : tokens)
1474 if (token ==
"%command%")
1476 afterCommand =
true;
1488 size_t eqPos = token.find(
'=');
1489 if (eqPos != std::string::npos && eqPos > 0 && eqPos < token.length() - 1)
1492 std::string key = token.substr(0, eqPos);
1493 std::string value = token.substr(eqPos + 1);
1525 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
1532 std::filesystem::path userdataPath = steamRoot /
"userdata";
1533 if (!std::filesystem::exists(userdataPath))
1540 for (
const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
1542 if (!userEntry.is_directory())
1545 std::filesystem::path configPath = userEntry.path() /
"config" /
"localconfig.vdf";
1546 if (!std::filesystem::exists(configPath))
1550 std::ifstream file(configPath);
1551 if (!file.is_open())
1555 std::string appIdStr =
"\"" + std::to_string(appId) +
"\"";
1556 bool foundApp =
false;
1557 int appBraceDepth = 0;
1558 bool inAppSection =
false;
1560 while (std::getline(file, line))
1563 size_t start = line.find_first_not_of(
" \t");
1564 if (start == std::string::npos)
1566 std::string trimmed = line.substr(start);
1569 if (!foundApp && trimmed.find(appIdStr) == 0)
1573 if (line.find(
'{') != std::string::npos)
1575 inAppSection =
true;
1582 if (foundApp && !inAppSection && line.find(
'{') != std::string::npos)
1584 inAppSection =
true;
1594 if (trimmed.find(
"\"LaunchOptions\"") == 0)
1598 size_t keyEnd = line.find(
"\"LaunchOptions\"") + 15;
1600 size_t valueStart = line.find(
'\"', keyEnd);
1601 if (valueStart != std::string::npos)
1604 size_t valueEnd = valueStart + 1;
1605 while (valueEnd < line.size())
1607 if (line[valueEnd] ==
'\\')
1612 if (line[valueEnd] ==
'"')
1616 if (valueEnd < line.size())
1618 std::string launchOpts =
1619 line.substr(valueStart + 1, valueEnd - valueStart - 1);
1629 bool inQuote =
false;
1630 for (
size_t ci = 0; ci < line.size(); ci++)
1633 if (c ==
'"' && (ci == 0 || line[ci - 1] !=
'\\'))
1642 if (appBraceDepth == 0)
1663bool SteamLibraryScanner::isFileLocked(
const std::filesystem::path& filePath)
1666 FILE* fp = fopen(filePath.c_str(),
"r+");
1671 if (!std::filesystem::exists(filePath))
1676 fp = fopen(filePath.c_str(),
"r");
1685 fl.l_type = F_WRLCK;
1686 fl.l_whence = SEEK_SET;
1689 fl.l_pid = getpid();
1692 int ret = fcntl(fileno(fp), F_SETLK, &fl);
1693 bool isLocked = (ret == -1 && (errno == EACCES || errno == EAGAIN));
1698 fl.l_type = F_UNLCK;
1699 fcntl(fileno(fp), F_SETLK, &fl);
1706bool SteamLibraryScanner::validateVDFFile(
const std::filesystem::path& filePath)
1709 if (!std::filesystem::exists(filePath))
1711 Logger::error(
"[VDF Validation] File does not exist: {}", filePath.string());
1715 std::error_code fsEc;
1716 auto fileSize = std::filesystem::file_size(filePath, fsEc);
1719 Logger::error(
"[VDF Validation] Cannot get file size: {}", filePath.string());
1724 Logger::error(
"[VDF Validation] File is empty: {}", filePath.string());
1730 Logger::error(
"[VDF Validation] File exceeds max size: {}", filePath.string());
1735 std::ifstream file(filePath);
1736 if (!file.is_open())
1738 Logger::error(
"[VDF Validation] Could not open file for validation: {}", filePath.string());
1748 bool inString =
false;
1749 bool escapeNext =
false;
1751 while (std::getline(file, line))
1789 if (braceCount != 0)
1791 Logger::error(
"[VDF Validation] Unbalanced braces in file: {}", filePath.string());
1798bool SteamLibraryScanner::writeVDFFileWithRetry(
const std::filesystem::path& filePath,
1799 const std::vector<std::string>& lines,
1800 const std::filesystem::path& backupPath)
1802 const int maxAttempts = 3;
1804 for (
int attempt = 0; attempt < maxAttempts; attempt++)
1808 Logger::info(
"[VDF Write] Retry attempt {} of {}", attempt + 1, maxAttempts);
1812 if (isFileLocked(filePath))
1814 Logger::info(
"[VDF Write] File is locked, waiting...");
1816 std::this_thread::sleep_for(std::chrono::milliseconds(100 * (1 << attempt)));
1821 std::ofstream outFile(filePath);
1822 if (!outFile.is_open())
1824 Logger::error(
"[VDF Write] Failed to open file for writing: {}", filePath.string());
1827 std::this_thread::sleep_for(std::chrono::milliseconds(100 * (1 << attempt)));
1832 for (
const auto& line : lines)
1834 outFile << line <<
"\n";
1839 if (validateVDFFile(filePath))
1841 Logger::info(
"[VDF Write] Successfully wrote and validated: {}", filePath.string());
1845 Logger::error(
"[VDF Write] Validation failed after write attempt {}", attempt + 1);
1848 if (std::filesystem::exists(backupPath))
1852 std::filesystem::copy_file(backupPath, filePath,
1853 std::filesystem::copy_options::overwrite_existing);
1854 Logger::info(
"[VDF Write] Restored from backup after validation failure");
1856 catch (
const std::exception& e)
1858 Logger::error(
"[VDF Write] Failed to restore from backup: {}", e.what());
1863 if (attempt < maxAttempts - 1)
1865 std::this_thread::sleep_for(std::chrono::milliseconds(100 * (1 << attempt)));
1869 Logger::error(
"[VDF Write] Failed to write file after {} attempts: {}", maxAttempts,
1890 out.reserve(s.size() + 4);
1922 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
1928 std::filesystem::path userdataPath = steamRoot /
"userdata";
1929 if (!std::filesystem::exists(userdataPath))
1936 for (
const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
1938 if (!userEntry.is_directory())
1941 std::filesystem::path configPath = userEntry.path() /
"config" /
"localconfig.vdf";
1942 if (!std::filesystem::exists(configPath))
1946 std::ifstream inFile(configPath);
1947 if (!inFile.is_open())
1950 std::vector<std::string> lines;
1952 while (std::getline(inFile, line))
1954 lines.push_back(line);
1959 bool inAppsSection =
false;
1960 size_t appsLineStart = 0;
1962 for (
size_t i = 0; i < lines.size(); i++)
1964 size_t start = lines[i].find_first_not_of(
" \t");
1965 if (start == std::string::npos)
1967 std::string trimmed = lines[i].substr(start);
1969 if (trimmed.find(
"\"apps\"") == 0)
1971 inAppsSection =
true;
1979 Logger::error(
"Could not find apps section in localconfig.vdf");
1984 std::string appIdStr =
"\"" + std::to_string(appId) +
"\"";
1985 bool foundApp =
false;
1986 bool modified =
false;
1987 int appBraceDepth = 0;
1988 bool inAppSection =
false;
1990 for (
size_t i = appsLineStart; i < lines.size(); i++)
1992 std::string& currentLine = lines[i];
1995 size_t start = currentLine.find_first_not_of(
" \t");
1996 if (start == std::string::npos)
1998 std::string trimmed = currentLine.substr(start);
2001 if (!foundApp && trimmed.find(appIdStr) == 0)
2004 if (currentLine.find(
'{') != std::string::npos)
2006 inAppSection =
true;
2013 if (foundApp && !inAppSection && currentLine.find(
'{') != std::string::npos)
2015 inAppSection =
true;
2025 if (!modified && trimmed.find(
"\"LaunchOptions\"") == 0)
2028 size_t indent = currentLine.find_first_not_of(
" \t");
2029 std::string indentStr = currentLine.substr(0, indent);
2030 lines[i] = indentStr +
"\"LaunchOptions\"\t\t\"" +
2037 bool inQuote =
false;
2038 for (
size_t ci = 0; ci < currentLine.size(); ci++)
2040 char c = currentLine[ci];
2041 if (c ==
'"' && (ci == 0 || currentLine[ci - 1] !=
'\\'))
2050 if (appBraceDepth == 0)
2055 size_t lineIndent = currentLine.find_first_not_of(
" \t");
2056 std::string indentStr = currentLine.substr(0, lineIndent);
2057 std::string newLine = indentStr +
"\t\"LaunchOptions\"\t\t\"" +
2059 lines.insert(lines.begin() +
static_cast<std::ptrdiff_t
>(i),
2068 if (appBraceDepth == 0)
2075 Logger::error(
"Could not find app {} in localconfig.vdf", appId);
2082 std::filesystem::path backupPath = configPath;
2083 backupPath +=
".backup";
2087 std::filesystem::copy_file(configPath, backupPath,
2088 std::filesystem::copy_options::overwrite_existing);
2089 Logger::info(
"Created backup: {}", backupPath.string());
2091 catch (
const std::exception& e)
2100 if (!writeVDFFileWithRetry(configPath, lines, backupPath))
2102 Logger::error(
"Failed to write localconfig.vdf after retries");
2107 if (std::filesystem::file_size(configPath) == 0)
2109 Logger::error(
"Error: Final verification shows empty file! Restoring backup...");
2112 if (std::filesystem::exists(backupPath))
2116 std::filesystem::copy_file(backupPath, configPath,
2117 std::filesystem::copy_options::overwrite_existing);
2118 Logger::info(
"Restored from backup after detecting empty file");
2120 catch (
const std::exception& e)
2122 Logger::error(
"Failed to restore from backup: {}", e.what());
2128 Logger::info(
"Successfully wrote launch options for app {}", appId);
2129 Logger::info(
"NOTE: Steam must be restarted for changes to take effect");
2138std::map<uint32_t, SteamLibraryScanner::SteamPlaytimeData>
2141 std::map<uint32_t, SteamPlaytimeData> playtimeData;
2145 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
2148 return playtimeData;
2151 std::filesystem::path userdataPath = steamRoot /
"userdata";
2152 if (!std::filesystem::exists(userdataPath))
2155 return playtimeData;
2159 for (
const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
2161 if (!userEntry.is_directory())
2164 std::filesystem::path configPath = userEntry.path() /
"config" /
"localconfig.vdf";
2165 if (!std::filesystem::exists(configPath))
2168 std::ifstream file(configPath);
2169 if (!file.is_open())
2199 size_t appsPos = content.find(
"\"apps\"");
2200 if (appsPos == std::string::npos)
2206 size_t appsOpenBrace = content.find(
'{', appsPos);
2207 if (appsOpenBrace == std::string::npos)
2214 size_t pos = appsOpenBrace + 1;
2215 size_t appsSectionEnd = content.length();
2217 while (pos < content.length() && braceDepth > 0)
2219 if (content[pos] ==
'{')
2221 else if (content[pos] ==
'}')
2224 if (braceDepth == 0)
2226 appsSectionEnd = pos;
2234 std::string appsSection =
2235 content.substr(appsOpenBrace + 1, appsSectionEnd - appsOpenBrace - 1);
2239 static const std::regex appIdRegex(
"\"(\\d+)\"\\s*\\{", std::regex::optimize);
2240 static const std::regex playtimeRegex(
"\"Playtime\"\\s+\"(\\d+)\"", std::regex::optimize);
2241 static const std::regex lastPlayedRegex(
"\"LastPlayed\"\\s+\"(\\d+)\"",
2242 std::regex::optimize);
2243 static const std::regex playtime2wksRegex(
"\"Playtime2wks\"\\s+\"(\\d+)\"",
2244 std::regex::optimize);
2245 static const std::regex lastLaunchRegex(
"\"lastlaunch\"\\s+\"(\\d+)\"",
2246 std::regex::optimize);
2247 static const std::regex lastExitRegex(
"\"lastexit\"\\s+\"(\\d+)\"", std::regex::optimize);
2249 std::sregex_iterator appIdIter(appsSection.begin(), appsSection.end(), appIdRegex);
2250 std::sregex_iterator end;
2252 for (; appIdIter != end; ++appIdIter)
2254 const std::smatch& match = *appIdIter;
2255 uint32_t appId =
static_cast<uint32_t
>(std::stoul(match[1].str()));
2258 size_t entryStart =
static_cast<size_t>(match.position() + match.length());
2259 size_t entryEnd = appsSection.length();
2262 int entryBraceDepth = 1;
2263 size_t entryPos = entryStart;
2264 while (entryPos < appsSection.length() && entryBraceDepth > 0)
2266 if (appsSection[entryPos] ==
'{')
2268 else if (appsSection[entryPos] ==
'}')
2271 if (entryBraceDepth == 0)
2273 entryEnd = entryPos;
2280 std::string appEntry = appsSection.substr(entryStart, entryEnd - entryStart);
2286 std::smatch playtimeMatch;
2287 if (std::regex_search(appEntry, playtimeMatch, playtimeRegex))
2289 data.
playtimeMinutes =
static_cast<uint32_t
>(std::stoul(playtimeMatch[1].str()));
2292 std::smatch lastPlayedMatch;
2293 if (std::regex_search(appEntry, lastPlayedMatch, lastPlayedRegex))
2295 data.
lastPlayed =
static_cast<time_t
>(std::stoull(lastPlayedMatch[1].str()));
2298 std::smatch playtime2wksMatch;
2299 if (std::regex_search(appEntry, playtime2wksMatch, playtime2wksRegex))
2301 data.
playtime2Weeks =
static_cast<uint32_t
>(std::stoul(playtime2wksMatch[1].str()));
2304 std::smatch lastLaunchMatch;
2305 if (std::regex_search(appEntry, lastLaunchMatch, lastLaunchRegex))
2307 data.
lastLaunch =
static_cast<time_t
>(std::stoull(lastLaunchMatch[1].str()));
2310 std::smatch lastExitMatch;
2311 if (std::regex_search(appEntry, lastExitMatch, lastExitRegex))
2313 data.
lastExit =
static_cast<time_t
>(std::stoull(lastExitMatch[1].str()));
2317 playtimeData[appId] = data;
2324 return playtimeData;
2341 std::filesystem::path appinfoPath = steamPath /
"appcache" /
"appinfo.vdf";
2343 if (!std::filesystem::exists(appinfoPath))
2345 Logger::warn(
"[SteamCache] appinfo.vdf not found at {}", appinfoPath.string());
2350 std::ifstream file(appinfoPath, std::ios::binary);
2353 Logger::warn(
"[SteamCache] Failed to open appinfo.vdf");
2358 file.seekg(0, std::ios::end);
2359 size_t fileSize =
static_cast<size_t>(file.tellg());
2360 file.seekg(0, std::ios::beg);
2369 std::vector<uint8_t> data(fileSize);
2370 file.read(
reinterpret_cast<char*
>(data.data()),
static_cast<std::streamsize
>(fileSize));
2379 std::memcpy(&magic, data.data(),
sizeof(magic));
2380 if (magic == 0x07564427 || magic == 0x07564428)
2382 Logger::warn(
"[SteamCache] Legacy appinfo.vdf format 0x{:08x} detected. "
2383 "Update your Steam client for appinfo metadata; ACF manifests "
2384 "remain the authoritative install source.",
2388 if (magic != 0x07564429)
2390 Logger::warn(
"[SteamCache] Unknown appinfo.vdf format: 0x{:08x}", magic);
2402 const uint8_t namePattern[] = {0x01, 0x04, 0x00, 0x00, 0x00};
2403 const size_t patternLen = 5;
2405 while (pos + 8 < fileSize)
2408 std::memcpy(&appId, data.data() + pos,
sizeof(appId));
2413 std::memcpy(&size, data.data() + pos + 4,
sizeof(size));
2422 size_t recordEnd = pos + 8 + size;
2423 if (recordEnd > fileSize)
2427 size_t recordStart = pos;
2428 size_t recordLen = recordEnd - recordStart;
2430 for (
size_t i = 0; i + patternLen < recordLen; ++i)
2432 if (std::memcmp(data.data() + recordStart + i, namePattern, patternLen) == 0)
2435 size_t valueStart = recordStart + i + patternLen;
2436 size_t valueEnd = valueStart;
2439 while (valueEnd < recordEnd && data[valueEnd] != 0)
2444 if (valueEnd > valueStart && valueEnd - valueStart < 300)
2446 std::string name(
reinterpret_cast<char*
>(data.data() + valueStart),
2447 valueEnd - valueStart);
2475 if (!steamPath.empty())
2477 Logger::info(
"[SteamCache] Loading app names from local appinfo.vdf...");
2482 Logger::info(
"[SteamCache] Loaded {} app names from local cache", localCount);
2488 Logger::info(
"[SteamCache] Loading Steam app name cache from GetAppList API...");
2492 std::string command =
"curl -s -m 30 'https://api.steampowered.com/ISteamApps/GetAppList/v2/'";
2497 Logger::error(
"[SteamCache] Failed to fetch Steam app list");
2502 std::string response;
2504 constexpr size_t kMaxSteamResponse = 32u * 1024 * 1024;
2509 while (fgets(buffer,
sizeof(buffer), pipe.
get()) !=
nullptr)
2512 if (response.size() > kMaxSteamResponse)
2514 Logger::warn(
"[Steam] App list response too large, truncating");
2521 size_t appsStart = response.find(
"\"apps\":[");
2522 if (appsStart == std::string::npos)
2524 Logger::error(
"[SteamCache] Invalid response from Steam GetAppList API");
2529 size_t pos = appsStart;
2532 while ((pos = response.find(
"{\"appid\":", pos)) != std::string::npos)
2535 size_t appidStart = pos + 9;
2536 size_t appidEnd = response.find(
',', appidStart);
2537 if (appidEnd == std::string::npos)
2543 appId =
static_cast<uint32_t
>(
2544 std::stoul(response.substr(appidStart, appidEnd - appidStart)));
2553 size_t namePos = response.find(
"\"name\":\"", pos);
2554 if (namePos == std::string::npos || namePos > pos + 100)
2560 size_t nameStart = namePos + 8;
2563 size_t nameEnd = nameStart;
2564 while (nameEnd < response.size())
2566 if (response[nameEnd] ==
'\\')
2571 if (response[nameEnd] ==
'"')
2575 if (nameEnd >= response.size())
2581 std::string name = response.substr(nameStart, nameEnd - nameStart);
2585 while ((escPos = name.find(
"\\\"", escPos)) != std::string::npos)
2587 name.replace(escPos, 2,
"\"");
2601 Logger::info(
"[SteamCache] Loaded {} app names from API", count);
2631 if (!cachedName.empty())
2633 Logger::debug(
"[SteamAPI] Cache hit for AppID {}: '{}'", appId, cachedName);
2641 "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(appId);
2643 Logger::info(
"[SteamAPI] Fetching game name from API for AppID {}", appId);
2646 std::string command =
"curl -s -m 3 '" + url +
"'";
2651 Logger::error(
"[SteamAPI] Failed to open pipe for AppID {}", appId);
2656 std::string response;
2658 constexpr size_t kMaxResponse = 1u * 1024 * 1024;
2659 while (fgets(buffer,
sizeof(buffer), pipe.
get()) !=
nullptr)
2662 if (response.size() > kMaxResponse)
2664 Logger::warn(
"[Steam] Game name API response too large, truncating");
2670 if (response.empty())
2672 Logger::error(
"[SteamAPI] Empty response for AppID {}", appId);
2676 Logger::debug(
"[SteamAPI] Response length for AppID {}: {} bytes", appId, response.size());
2682 if (response.find(
"\"success\":false") != std::string::npos ||
2683 response.find(
"\"success\": false") != std::string::npos)
2685 Logger::warn(
"[SteamAPI] API returned success:false for AppID {}", appId);
2690 size_t namePos = response.find(
"\"name\":");
2691 if (namePos == std::string::npos)
2693 Logger::warn(
"[SteamAPI] No 'name' field found in response for AppID {}", appId);
2698 size_t nameStart = response.find(
"\"", namePos + 7);
2699 if (nameStart == std::string::npos)
2701 Logger::warn(
"[SteamAPI] Malformed name field for AppID {}", appId);
2707 size_t nameEnd = response.find(
"\"", nameStart);
2708 if (nameEnd == std::string::npos)
2710 Logger::warn(
"[SteamAPI] Unclosed name string for AppID {}", appId);
2715 std::string gameName = response.substr(nameStart, nameEnd - nameStart);
2719 while ((pos = gameName.find(
"\\\"", pos)) != std::string::npos)
2721 gameName.replace(pos, 2,
"\"");
2725 Logger::info(
"[SteamAPI] Successfully fetched name for AppID {}: '{}'", appId, gameName);
2730 std::vector<std::string>& outGenres,
2731 std::vector<std::string>& outCategories)
2733 std::string outName;
2738 std::string& outType,
2739 std::vector<std::string>& outGenres,
2740 std::vector<std::string>& outCategories)
2745 "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(appId);
2748 std::string command =
"curl -s -m 3 '" + url +
"'";
2757 std::string response;
2759 constexpr size_t kMaxMetaResponse = 4u * 1024 * 1024;
2760 while (fgets(buffer,
sizeof(buffer), pipe.
get()) !=
nullptr)
2763 if (response.size() > kMaxMetaResponse)
2765 Logger::warn(
"[Steam] Metadata API response too large, truncating");
2772 if (response.find(
"\"success\":true") == std::string::npos)
2778 size_t namePos = response.find(
"\"name\":\"");
2779 if (namePos != std::string::npos)
2781 size_t nameStart = namePos + 8;
2782 size_t nameEnd = response.find(
"\"", nameStart);
2783 if (nameEnd != std::string::npos)
2785 outName = response.substr(nameStart, nameEnd - nameStart);
2788 while ((pos = outName.find(
"\\\"", pos)) != std::string::npos)
2790 outName.replace(pos, 2,
"\"");
2797 size_t typePos = response.find(
"\"type\":\"");
2798 if (typePos != std::string::npos)
2800 size_t typeStart = typePos + 8;
2801 size_t typeEnd = response.find(
"\"", typeStart);
2802 if (typeEnd != std::string::npos)
2804 outType = response.substr(typeStart, typeEnd - typeStart);
2809 size_t genresPos = response.find(
"\"genres\":[");
2810 if (genresPos != std::string::npos)
2812 size_t genresEnd = response.find(
"]", genresPos);
2813 if (genresEnd != std::string::npos)
2815 std::string genresSection = response.substr(genresPos, genresEnd - genresPos);
2819 while ((pos = genresSection.find(
"\"description\":\"", pos)) != std::string::npos)
2821 size_t start = pos + 15;
2822 size_t end = genresSection.find(
"\"", start);
2823 if (end != std::string::npos)
2825 outGenres.push_back(genresSection.substr(start, end - start));
2837 size_t categoriesPos = response.find(
"\"categories\":[");
2838 if (categoriesPos != std::string::npos)
2840 size_t categoriesEnd = response.find(
"]", categoriesPos);
2841 if (categoriesEnd != std::string::npos)
2843 std::string categoriesSection =
2844 response.substr(categoriesPos, categoriesEnd - categoriesPos);
2848 while ((pos = categoriesSection.find(
"\"description\":\"", pos)) != std::string::npos)
2850 size_t start = pos + 15;
2851 size_t end = categoriesSection.find(
"\"", start);
2852 if (end != std::string::npos)
2854 outCategories.push_back(categoriesSection.substr(start, end - start));
2865 return !outType.empty();
2896 std::this_thread::sleep_for(std::chrono::milliseconds(500));
2909 std::this_thread::sleep_for(std::chrono::seconds(1));
2930 std::vector<std::pair<std::string, std::filesystem::path>> protonVersions;
2931 std::set<std::string> foundVersions;
2934 auto scanSteamDirectory = [&](
const std::filesystem::path& steamPath)
2936 if (!std::filesystem::exists(steamPath))
2939 Logger::info(
"Scanning for Proton in: {}", steamPath.string());
2943 if (std::filesystem::exists(compatToolsPath))
2945 for (
const auto& entry : std::filesystem::directory_iterator(compatToolsPath))
2947 if (!entry.is_directory())
2950 std::filesystem::path protonExe = entry.path() /
"proton";
2951 if (std::filesystem::exists(protonExe))
2953 std::string displayName = entry.path().filename().string();
2954 if (foundVersions.find(displayName) == foundVersions.end())
2956 protonVersions.push_back({displayName, protonExe});
2957 foundVersions.insert(displayName);
2964 std::filesystem::path commonPath =
2966 if (std::filesystem::exists(commonPath))
2968 for (
const auto& entry : std::filesystem::directory_iterator(commonPath))
2970 if (!entry.is_directory())
2973 std::string dirname = entry.path().filename().string();
2975 if (dirname.find(
"Proton") != std::string::npos)
2977 std::filesystem::path protonExe = entry.path() /
"proton";
2978 if (std::filesystem::exists(protonExe))
2980 if (foundVersions.find(dirname) == foundVersions.end())
2982 protonVersions.push_back({dirname, protonExe});
2983 foundVersions.insert(dirname);
2995 for (
const auto& steamPath : steamRoots)
2997 scanSteamDirectory(steamPath);
3005 if (primarySteamRoot.empty())
3007 return protonVersions;
3010 std::filesystem::path libraryFoldersVdf =
3012 if (std::filesystem::exists(libraryFoldersVdf))
3014 std::ifstream file(libraryFoldersVdf);
3016 while (std::getline(file, line))
3020 size_t pathPos = line.find(
"\"path\"");
3021 if (pathPos != std::string::npos)
3024 size_t firstQuote = line.find(
'"', pathPos + 6);
3025 size_t secondQuote = line.find(
'"', firstQuote + 1);
3026 if (firstQuote != std::string::npos && secondQuote != std::string::npos)
3028 std::string libraryPath =
3029 line.substr(firstQuote + 1, secondQuote - firstQuote - 1);
3030 Logger::info(
"Found additional Steam library: {}", libraryPath);
3033 std::filesystem::path libraryProtonPath = std::filesystem::path(libraryPath) /
3036 if (std::filesystem::exists(libraryProtonPath))
3038 for (
const auto& entry :
3039 std::filesystem::directory_iterator(libraryProtonPath))
3041 if (!entry.is_directory())
3044 std::string dirname = entry.path().filename().string();
3045 if (dirname.find(
"Proton") != std::string::npos)
3047 std::filesystem::path protonExe = entry.path() /
"proton";
3048 if (std::filesystem::exists(protonExe))
3050 if (foundVersions.find(dirname) == foundVersions.end())
3052 protonVersions.push_back({dirname, protonExe});
3053 foundVersions.insert(dirname);
3068 std::vector<std::filesystem::path> systemPaths = {
"/usr/share/steam/compatibilitytools.d",
3069 "/opt/steam/compatibilitytools.d"};
3071 for (
const auto& systemPath : systemPaths)
3073 if (std::filesystem::exists(systemPath))
3075 Logger::info(
"Scanning system-wide Proton directory: {}", systemPath.string());
3076 for (
const auto& entry : std::filesystem::directory_iterator(systemPath))
3078 if (!entry.is_directory())
3081 std::filesystem::path protonExe = entry.path() /
"proton";
3082 if (std::filesystem::exists(protonExe))
3084 std::string displayName = entry.path().filename().string() +
" (system)";
3085 if (foundVersions.find(displayName) == foundVersions.end())
3087 protonVersions.push_back({displayName, protonExe});
3088 foundVersions.insert(displayName);
3099 std::vector<std::pair<std::string, std::string>> knownProtonVersions = {
3100 {
"Proton 9.0 (Beta)",
"proton_90"}, {
"Proton 8.0",
"proton_80"},
3101 {
"Proton 7.0",
"proton_70"}, {
"Proton 6.3",
"proton_63"},
3102 {
"Proton 5.13",
"proton_513"}, {
"Proton 5.0",
"proton_50"}};
3104 for (
const auto& [displayName, steamName] : knownProtonVersions)
3107 if (foundVersions.find(displayName) == foundVersions.end())
3110 protonVersions.push_back({displayName +
" (not installed)", std::filesystem::path()});
3118 std::sort(protonVersions.begin(), protonVersions.end(),
3119 [](
const auto& a,
const auto& b)
3121 bool aInstalled = !a.second.empty();
3122 bool bInstalled = !b.second.empty();
3123 bool aCachyOS = (a.first.find(
"cachyos") != std::string::npos);
3124 bool bCachyOS = (b.first.find(
"cachyos") != std::string::npos);
3125 bool aExperimental = (a.first.find(
"Experimental") != std::string::npos);
3126 bool bExperimental = (b.first.find(
"Experimental") != std::string::npos);
3129 if (aInstalled && !bInstalled)
3131 if (!aInstalled && bInstalled)
3135 if (aInstalled && bInstalled)
3137 if (aCachyOS && !bCachyOS)
3139 if (!aCachyOS && bCachyOS)
3143 if (aExperimental && !bExperimental)
3145 if (!aExperimental && bExperimental)
3150 return a.first > b.first;
3153 Logger::info(
"Found {} Proton versions", protonVersions.size());
3155 return protonVersions;
3166 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
3172 std::filesystem::path configPath = steamRoot /
"config" /
"config.vdf";
3173 if (!std::filesystem::exists(configPath))
3180 std::ifstream inFile(configPath);
3181 if (!inFile.is_open())
3187 bool inCompatToolMapping =
false;
3188 bool foundApp =
false;
3190 std::string appIdStr =
"\"" + std::to_string(appId) +
"\"";
3193 while (std::getline(inFile, line))
3195 size_t start = line.find_first_not_of(
" \t");
3196 if (start == std::string::npos)
3198 std::string trimmed = line.substr(start);
3201 if (!inCompatToolMapping && trimmed.find(
"\"CompatToolMapping\"") == 0)
3203 inCompatToolMapping =
true;
3207 if (inCompatToolMapping)
3217 if (braceDepth == 0)
3226 if (!foundApp && trimmed.find(appIdStr) == 0)
3233 if (foundApp && trimmed.find(
"\"name\"") == 0)
3236 size_t firstQuote = trimmed.find(
'"', 6);
3237 if (firstQuote != std::string::npos)
3239 size_t secondQuote = trimmed.find(
'"', firstQuote + 1);
3240 if (secondQuote != std::string::npos)
3242 return trimmed.substr(firstQuote + 1, secondQuote - firstQuote - 1);
3249 if (foundApp && trimmed ==
"}")
3264 std::string& outCompatToolName)
3266 outCompatToolName.clear();
3270 if (!configuredTool.empty())
3272 outCompatToolName = configuredTool;
3273 Logger::info(
"[ProtonResolve] App {} has explicit compat tool: {}", appId, configuredTool);
3278 if (protonVersions.empty())
3280 Logger::warn(
"[ProtonResolve] No Proton versions found on system");
3285 if (!configuredTool.empty())
3294 for (
const auto& [displayName, protonExe] : protonVersions)
3296 std::string dirName = protonExe.parent_path().filename().string();
3299 if (dirName == configuredTool)
3303 if (configuredTool ==
"proton_experimental" &&
3304 (dirName ==
"Proton - Experimental" ||
3305 dirName.find(
"Proton - Experimental") != std::string::npos))
3311 if (configuredTool.rfind(
"proton_", 0) == 0)
3313 std::string numPart = configuredTool.substr(7);
3314 if (dirName.find(
"Proton " + numPart) != std::string::npos ||
3315 dirName.find(
"Proton " + numPart +
".0") != std::string::npos)
3322 std::string lowerTool = configuredTool;
3323 std::string lowerDir = dirName;
3324 std::transform(lowerTool.begin(), lowerTool.end(), lowerTool.begin(),
3325 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
3326 std::transform(lowerDir.begin(), lowerDir.end(), lowerDir.begin(),
3327 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
3329 std::replace(lowerTool.begin(), lowerTool.end(),
'_',
' ');
3330 std::replace(lowerTool.begin(), lowerTool.end(),
'-',
' ');
3331 std::replace(lowerDir.begin(), lowerDir.end(),
'-',
' ');
3333 if (lowerDir.find(lowerTool) != std::string::npos ||
3334 lowerTool.find(lowerDir) != std::string::npos)
3341 "[ProtonResolve] Configured compat tool '{}' not found among installed versions",
3347 std::filesystem::path bestPath;
3350 for (
const auto& [displayName, protonExe] : protonVersions)
3353 std::string dirName = protonExe.parent_path().filename().string();
3357 if (dirName.rfind(
"Proton ", 0) == 0 && dirName.find(
"Experimental") == std::string::npos)
3363 double ver = std::stod(dirName.substr(7));
3365 double scaled = ver * 10.0;
3366 if (scaled > 10000.0)
3370 score +=
static_cast<int>(scaled);
3377 else if (dirName.find(
"Experimental") != std::string::npos)
3382 else if (dirName.find(
"Hotfix") != std::string::npos)
3387 else if (dirName.find(
"cachyos") != std::string::npos)
3392 else if (dirName.find(
"GE-Proton") != std::string::npos)
3397 else if (displayName.find(
"(system)") != std::string::npos)
3407 if (score > bestScore)
3410 bestPath = protonExe;
3414 if (!bestPath.empty())
3416 outCompatToolName = bestPath.parent_path().filename().string();
3417 Logger::info(
"[ProtonResolve] Auto-selected Proton: {} (score {})", outCompatToolName,
3426 if (game.
appId == 0)
3440 static std::mutex s_appInfoMutex;
3441 static std::optional<SteamAppInfoParser> s_appInfoParser;
3442 static std::filesystem::file_time_type s_appInfoMtime{};
3443 static std::filesystem::path s_appInfoPath{};
3446 std::lock_guard<std::mutex> lock(s_appInfoMutex);
3448 std::filesystem::path appInfoPath =
3450 std::error_code mtEc;
3451 auto mtime = std::filesystem::last_write_time(appInfoPath, mtEc);
3453 const bool pathChanged = (s_appInfoPath != appInfoPath);
3454 const bool mtimeChanged = (!mtEc && mtime != s_appInfoMtime);
3455 const bool needLoad = !s_appInfoParser || pathChanged || mtimeChanged;
3460 if (parser.
load(appInfoPath))
3462 s_appInfoParser.emplace(std::move(parser));
3463 s_appInfoPath = appInfoPath;
3465 s_appInfoMtime = mtime;
3469 Logger::warn(
"[DirectLaunch] Failed to load appinfo.vdf — "
3470 "will fall back to steam -applaunch");
3471 s_appInfoParser.reset();
3477 if (s_appInfoParser)
3479 auto appInfo = s_appInfoParser->getAppInfo(game.
appId);
3484 auto entry = appInfo->getProtonLaunchEntry();
3494 auto entry = appInfo->getNativeLaunchEntry();
3496 entry = appInfo->getProtonLaunchEntry();
3519 if (display.empty())
3523 if (display ==
"Native Linux" || display ==
"Proton" ||
3524 display.find(
"Steam-managed") != std::string::npos ||
3525 display.find(
"(not installed)") != std::string::npos)
3531 std::string base = display;
3532 if (base.size() > 3 && base.back() ==
')')
3534 size_t parenPos = base.rfind(
" (");
3535 if (parenPos != std::string::npos)
3537 base = base.substr(0, parenPos);
3549 if (base ==
"Proton Experimental")
3550 return "proton_experimental";
3551 if (base ==
"Proton 9.0")
3553 if (base ==
"Proton 8.0")
3562 if (protonName.empty())
3564 Logger::info(
"[Steam] Skipping CompatToolMapping write for AppID {}: '{}' is a "
3565 "Steam-managed sentinel",
3566 appId, protonNameRaw);
3569 if (protonName != protonNameRaw)
3571 Logger::info(
"[Steam] Normalised Proton tool name '{}' -> '{}' for AppID {}", protonNameRaw,
3576 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
3582 std::filesystem::path configPath = steamRoot /
"config" /
"config.vdf";
3583 if (!std::filesystem::exists(configPath))
3590 std::ifstream inFile(configPath);
3591 if (!inFile.is_open())
3597 std::vector<std::string> lines;
3599 while (std::getline(inFile, line))
3601 lines.push_back(line);
3606 bool inCompatToolMapping =
false;
3607 bool foundApp =
false;
3608 bool modified =
false;
3611 for (
size_t i = 0; i < lines.size(); i++)
3613 size_t start = lines[i].find_first_not_of(
" \t");
3614 if (start == std::string::npos)
3616 std::string trimmed = lines[i].substr(start);
3619 if (!inCompatToolMapping && trimmed.find(
"\"CompatToolMapping\"") == 0)
3621 inCompatToolMapping =
true;
3625 if (inCompatToolMapping)
3628 for (
char c : lines[i])
3635 if (braceDepth == 0)
3641 size_t indent = lines[i].find_first_not_of(
" \t");
3642 std::string indentStr = lines[i].substr(0, indent);
3644 std::vector<std::string> newEntry = {
3645 indentStr +
"\t\"" + std::to_string(appId) +
"\"",
3649 indentStr +
"\t\t\"config\"\t\t\"\"",
3650 indentStr +
"\t\t\"priority\"\t\t\"250\"",
3653 lines.insert(lines.begin() +
static_cast<std::ptrdiff_t
>(i),
3654 newEntry.begin(), newEntry.end());
3663 std::string appIdStr =
"\"" + std::to_string(appId) +
"\"";
3664 if (!foundApp && trimmed.find(appIdStr) == 0)
3668 for (
size_t j = i + 1; j < lines.size() && j < i + 10; j++)
3670 size_t nameStart = lines[j].find_first_not_of(
" \t");
3671 if (nameStart != std::string::npos)
3673 std::string nameLine = lines[j].substr(nameStart);
3674 if (nameLine.find(
"\"name\"") == 0)
3677 std::string indentStr = lines[j].substr(0, nameStart);
3679 indentStr +
"\"name\"\t\t\"" +
vdfEscapeValue(protonName) +
"\"";
3687 if (braceDepth == 0)
3694 Logger::error(
"Could not modify CompatToolMapping for app {}", appId);
3701 std::filesystem::path backupPath = configPath;
3706 std::filesystem::copy_file(configPath, backupPath,
3707 std::filesystem::copy_options::overwrite_existing);
3708 Logger::info(
"Created backup: {}", backupPath.string());
3710 catch (
const std::exception& e)
3719 if (!writeVDFFileWithRetry(configPath, lines, backupPath))
3725 Logger::info(
"Successfully wrote Proton version '{}' for app {}", protonName, appId);
3747 if (steamPath.empty())
3751 if (!std::filesystem::exists(userdataPath))
3757 for (
const auto& entry : std::filesystem::directory_iterator(userdataPath))
3759 if (entry.is_directory())
3761 std::filesystem::path configFile = entry.path() /
"config" /
"localconfig.vdf";
3762 if (std::filesystem::exists(configFile))
3764 return entry.path().filename().string();
3781 for (
size_t i = openBrace; i < content.size(); i++)
3783 if (content[i] ==
'{')
3785 else if (content[i] ==
'}')
3791 return std::string::npos;
3800 if (steamPath.empty())
3802 Logger::warn(
"Steam installation not found for cloud save info");
3809 Logger::warn(
"No active Steam user found for cloud save info");
3813 std::filesystem::path userConfigPath =
3814 steamPath /
"userdata" / userId /
"config" /
"localconfig.vdf";
3816 if (!std::filesystem::exists(userConfigPath))
3818 Logger::debug(
"localconfig.vdf not found for cloud save info: {}", userConfigPath.string());
3823 std::ifstream file(userConfigPath);
3824 if (!file.is_open())
3826 Logger::error(
"Failed to open localconfig.vdf for cloud save info");
3836 std::string appIdStr = std::to_string(appId);
3837 std::string appSection =
"\"" + appIdStr +
"\"";
3839 size_t appsPos = content.find(
"\"apps\"");
3840 if (appsPos == std::string::npos)
3843 size_t appPos = content.find(appSection, appsPos);
3844 if (appPos == std::string::npos)
3848 size_t appOpenBrace = content.find(
'{', appPos + appSection.size());
3849 size_t appSectionEnd = (appOpenBrace != std::string::npos)
3851 : std::string::npos;
3854 size_t cloudPos = content.find(
"\"Cloud\"", appPos);
3855 if (cloudPos == std::string::npos ||
3856 (appSectionEnd != std::string::npos && cloudPos > appSectionEnd))
3863 size_t bracePos = content.find(
"{", cloudPos);
3864 if (bracePos == std::string::npos)
3868 size_t pos = bracePos;
3871 while (braceDepth > 0 && ++pos < content.length())
3873 if (content[pos] ==
'{')
3875 if (content[pos] ==
'}')
3879 if (content.substr(pos, 7) ==
"\"cloud\"")
3881 size_t valueStart = content.find(
"\"", pos + 7);
3882 size_t valueEnd = content.find(
"\"", valueStart + 1);
3883 if (valueStart != std::string::npos && valueEnd != std::string::npos)
3885 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3889 else if (content.substr(pos, 14) ==
"\"cloudenabled\"")
3891 size_t valueStart = content.find(
"\"", pos + 14);
3892 size_t valueEnd = content.find(
"\"", valueStart + 1);
3893 if (valueStart != std::string::npos && valueEnd != std::string::npos)
3895 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3896 info.
enabled = (value ==
"1");
3899 else if (content.substr(pos, 15) ==
"\"lastsyncstate\"")
3901 size_t valueStart = content.find(
"\"", pos + 15);
3902 size_t valueEnd = content.find(
"\"", valueStart + 1);
3903 if (valueStart != std::string::npos && valueEnd != std::string::npos)
3905 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3916 else if (content.substr(pos, 17) ==
"\"laststoragesize\"")
3918 size_t valueStart = content.find(
"\"", pos + 17);
3919 size_t valueEnd = content.find(
"\"", valueStart + 1);
3920 if (valueStart != std::string::npos && valueEnd != std::string::npos)
3922 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3938 std::filesystem::path cloudDir = steamPath /
"userdata" / userId / appIdStr /
"remote";
3939 if (std::filesystem::exists(cloudDir))
3944 auto ftime = std::filesystem::last_write_time(cloudDir);
3945 auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
3946 ftime - std::filesystem::file_time_type::clock::now() +
3947 std::chrono::system_clock::now());
3948 info.
lastSyncTime = std::chrono::system_clock::to_time_t(sctp);
3966 std::vector<std::string> categories;
3970 if (steamPath.empty())
3977 std::filesystem::path userConfigPath =
3978 steamPath /
"userdata" / userId /
"config" /
"localconfig.vdf";
3980 if (!std::filesystem::exists(userConfigPath))
3983 std::ifstream file(userConfigPath);
3984 if (!file.is_open())
3993 std::string appIdStr = std::to_string(appId);
3994 std::string appSection =
"\"" + appIdStr +
"\"";
3996 size_t appsPos = content.find(
"\"apps\"");
3997 if (appsPos == std::string::npos)
4000 size_t appPos = content.find(appSection, appsPos);
4001 if (appPos == std::string::npos)
4005 size_t appOpenBrace = content.find(
'{', appPos + appSection.size());
4006 size_t appSectionEnd = (appOpenBrace != std::string::npos)
4008 : std::string::npos;
4011 size_t tagsPos = content.find(
"\"tags\"", appPos);
4012 if (tagsPos == std::string::npos ||
4013 (appSectionEnd != std::string::npos && tagsPos > appSectionEnd))
4017 size_t bracePos = content.find(
"{", tagsPos);
4018 if (bracePos == std::string::npos)
4022 size_t pos = bracePos;
4025 while (braceDepth > 0 && ++pos < content.length())
4027 if (content[pos] ==
'{')
4029 if (content[pos] ==
'}')
4036 if (content[pos] ==
'\"')
4038 size_t keyEnd = content.find(
'\"', pos + 1);
4039 if (keyEnd == std::string::npos)
4043 size_t valueStart = content.find(
'\"', keyEnd + 1);
4044 if (valueStart == std::string::npos)
4047 size_t valueEnd = content.find(
'\"', valueStart + 1);
4048 if (valueEnd == std::string::npos)
4051 std::string tagValue = content.substr(valueStart + 1, valueEnd - valueStart - 1);
4052 if (!tagValue.empty())
4054 categories.push_back(tagValue);
4070 const std::filesystem::path& )
4072 std::vector<DLCInfo> dlcList;
4074 std::ifstream file(acfFilePath);
4075 if (!file.is_open())
4077 Logger::error(
"Failed to open ACF file for DLC detection: {}", acfFilePath.string());
4087 size_t depotsPos = content.find(
"\"InstalledDepots\"");
4088 if (depotsPos == std::string::npos)
4091 size_t bracePos = content.find(
"{", depotsPos);
4092 if (bracePos == std::string::npos)
4096 size_t pos = bracePos;
4099 while (braceDepth > 0 && ++pos < content.length())
4101 if (content[pos] ==
'{')
4103 if (content[pos] ==
'}')
4107 if (braceDepth == 2 && content[pos] ==
'\"')
4109 size_t depotIdEnd = content.find(
'\"', pos + 1);
4110 if (depotIdEnd == std::string::npos)
4113 std::string depotIdStr = content.substr(pos + 1, depotIdEnd - pos - 1);
4117 !depotIdStr.empty() && std::all_of(depotIdStr.begin(), depotIdStr.end(), ::isdigit);
4126 size_t depotBracePos = content.find(
"{", depotIdEnd);
4127 if (depotBracePos != std::string::npos)
4131 size_t depotSectionEnd = depotBracePos + 1;
4132 while (depotSectionEnd < content.size() && depth > 0)
4134 if (content[depotSectionEnd] ==
'{')
4136 else if (content[depotSectionEnd] ==
'}')
4142 size_t sizePos = content.find(
"\"size\"", depotBracePos);
4143 if (sizePos != std::string::npos && sizePos < depotSectionEnd)
4145 size_t sizeValueStart = content.find(
"\"", sizePos + 6);
4146 size_t sizeValueEnd = (sizeValueStart != std::string::npos)
4147 ? content.find(
"\"", sizeValueStart + 1)
4148 : std::string::npos;
4150 if (sizeValueStart != std::string::npos &&
4151 sizeValueEnd != std::string::npos && sizeValueEnd > sizeValueStart)
4153 std::string sizeStr = content.substr(sizeValueStart + 1,
4154 sizeValueEnd - sizeValueStart - 1);
4167 dlc.
name =
"Depot " + depotIdStr;
4172 dlcList.push_back(dlc);
4189 std::map<uint32_t, CloudSaveInfo> result;
4192 if (steamPath.empty())
4199 std::filesystem::path userConfigPath =
4200 steamPath /
"userdata" / userId /
"config" /
"localconfig.vdf";
4202 if (!std::filesystem::exists(userConfigPath))
4205 std::ifstream file(userConfigPath);
4206 if (!file.is_open())
4213 size_t appsPos = content.find(
"\"apps\"");
4214 if (appsPos == std::string::npos)
4218 size_t pos = appsPos;
4222 pos = content.find(
"\"", pos + 1);
4223 if (pos == std::string::npos)
4226 size_t appIdEnd = content.find(
"\"", pos + 1);
4227 if (appIdEnd == std::string::npos)
4230 std::string appIdStr = content.substr(pos + 1, appIdEnd - pos - 1);
4234 !appIdStr.empty() && std::all_of(appIdStr.begin(), appIdStr.end(), ::isdigit);
4238 uint32_t appId =
static_cast<uint32_t
>(std::stoul(appIdStr));
4241 size_t appOpenBrace = content.find(
'{', appIdEnd);
4242 size_t appSectionEnd = (appOpenBrace != std::string::npos)
4244 : std::string::npos;
4245 size_t cloudPos = content.find(
"\"Cloud\"", appIdEnd);
4247 if (cloudPos != std::string::npos &&
4248 (appSectionEnd == std::string::npos || cloudPos < appSectionEnd))
4254 result[appId] = info;
4267 std::map<uint32_t, std::vector<std::string>> result;
4270 if (steamPath.empty())
4277 std::filesystem::path userConfigPath =
4278 steamPath /
"userdata" / userId /
"config" /
"localconfig.vdf";
4280 if (!std::filesystem::exists(userConfigPath))
4283 std::ifstream file(userConfigPath);
4284 if (!file.is_open())
4291 size_t appsPos = content.find(
"\"apps\"");
4292 if (appsPos == std::string::npos)
4296 size_t pos = appsPos;
4300 pos = content.find(
"\"", pos + 1);
4301 if (pos == std::string::npos)
4304 size_t appIdEnd = content.find(
"\"", pos + 1);
4305 if (appIdEnd == std::string::npos)
4308 std::string appIdStr = content.substr(pos + 1, appIdEnd - pos - 1);
4312 !appIdStr.empty() && std::all_of(appIdStr.begin(), appIdStr.end(), ::isdigit);
4316 uint32_t appId =
static_cast<uint32_t
>(std::stoul(appIdStr));
4319 size_t appOpenBrace = content.find(
'{', appIdEnd);
4320 size_t appSectionEnd = (appOpenBrace != std::string::npos)
4322 : std::string::npos;
4323 size_t tagsPos = content.find(
"\"tags\"", appIdEnd);
4325 if (tagsPos != std::string::npos &&
4326 (appSectionEnd == std::string::npos || tagsPos < appSectionEnd))
4330 if (!categories.empty())
4332 result[appId] = categories;
4348 std::filesystem::path& libraryPath)
4353 std::string manifestName =
"appmanifest_" + std::to_string(appId) +
".acf";
4355 for (
const auto& lib : libraries)
4357 auto manifestPath = lib /
"steamapps" / manifestName;
4358 if (std::filesystem::exists(manifestPath))
4361 std::ifstream file(manifestPath);
4362 if (!file.is_open())
4371 std::string key =
"\"installdir\"";
4372 size_t pos = content.find(key);
4373 if (pos != std::string::npos)
4375 size_t valueStart = content.find(
"\"", pos + key.length());
4376 if (valueStart != std::string::npos)
4379 size_t valueEnd = content.find(
"\"", valueStart);
4380 if (valueEnd != std::string::npos)
4382 installDir = content.substr(valueStart, valueEnd - valueStart);
4395 Logger::info(
"[SteamLibraryScanner] Requesting Steam uninstall for app {}", appId);
4399 std::string uninstallUrl =
"steam://uninstall/" + std::to_string(appId);
4402 auto launchDetached = [](
const char* program,
const char* arg) ->
bool
4408 int devnull = open(
"/dev/null", O_WRONLY);
4411 dup2(devnull, STDERR_FILENO);
4415 execlp(program, program, arg,
nullptr);
4422 if (launchDetached(
"xdg-open", uninstallUrl.c_str()))
4424 Logger::info(
"[SteamLibraryScanner] Sent uninstall request to Steam for app {}", appId);
4429 if (launchDetached(
"steam", uninstallUrl.c_str()))
4431 Logger::info(
"[SteamLibraryScanner] Sent uninstall request to Steam for app {}", appId);
4435 Logger::error(
"[SteamLibraryScanner] Failed to send uninstall request for app {}", appId);
4441 Logger::info(
"[SteamLibraryScanner] Force uninstalling Steam app {}", appId);
4443 std::string installDir;
4444 std::filesystem::path libraryPath;
4448 Logger::error(
"[SteamLibraryScanner] Could not find installation info for app {}", appId);
4452 bool success =
true;
4461 if (installDir.empty() || installDir.find(
"..") != std::string::npos ||
4462 installDir.find(
'/') != std::string::npos || installDir.find(
'\\') != std::string::npos)
4464 Logger::error(
"[SteamLibraryScanner] Invalid installDir contains path traversal: {}",
4478 std::filesystem::path commonRoot = libraryPath /
"steamapps" /
"common";
4479 std::filesystem::path gamePath = commonRoot / installDir;
4480 if (std::filesystem::exists(gamePath))
4484 if (std::filesystem::is_symlink(gamePath))
4486 Logger::error(
"[SteamLibraryScanner] Refusing to delete '{}': path is a symlink "
4487 "(possible malicious ACF redirecting remove_all)",
4491 std::error_code canonEc1, canonEc2;
4492 auto canonGame = std::filesystem::weakly_canonical(gamePath, canonEc1);
4493 auto canonCommon = std::filesystem::weakly_canonical(commonRoot, canonEc2);
4494 if (canonEc1 || canonEc2)
4496 Logger::error(
"[SteamLibraryScanner] Cannot canonicalize '{}'; refusing remove_all",
4500 std::error_code relEc;
4501 auto rel = std::filesystem::relative(canonGame, canonCommon, relEc);
4502 if (relEc || rel.empty() || (*rel.begin()) ==
"..")
4504 Logger::error(
"[SteamLibraryScanner] Refusing to delete '{}': resolved path "
4505 "escapes steamapps/common (resolved to '{}')",
4506 gamePath.string(), canonGame.string());
4509 Logger::info(
"[SteamLibraryScanner] Removing game directory: {}", gamePath.string());
4510 std::filesystem::remove_all(gamePath, ec);
4513 Logger::error(
"[SteamLibraryScanner] Failed to remove game directory: {}",
4520 std::filesystem::path compatPath =
4521 libraryPath /
"steamapps" /
"compatdata" / std::to_string(appId);
4522 if (std::filesystem::exists(compatPath))
4524 Logger::info(
"[SteamLibraryScanner] Removing Proton prefix: {}", compatPath.string());
4525 std::filesystem::remove_all(compatPath, ec);
4528 Logger::warn(
"[SteamLibraryScanner] Failed to remove compatdata: {}", ec.message());
4534 std::filesystem::path manifestPath =
4535 libraryPath /
"steamapps" / (
"appmanifest_" + std::to_string(appId) +
".acf");
4536 if (std::filesystem::exists(manifestPath))
4538 Logger::info(
"[SteamLibraryScanner] Removing appmanifest: {}", manifestPath.string());
4539 std::filesystem::remove(manifestPath, ec);
4542 Logger::error(
"[SteamLibraryScanner] Failed to remove appmanifest: {}", ec.message());
4548 std::filesystem::path shaderCachePath =
4549 libraryPath /
"steamapps" /
"shadercache" / std::to_string(appId);
4550 if (std::filesystem::exists(shaderCachePath))
4552 Logger::info(
"[SteamLibraryScanner] Removing shader cache: {}", shaderCachePath.string());
4553 std::filesystem::remove_all(shaderCachePath, ec);
4556 Logger::warn(
"[SteamLibraryScanner] Failed to remove shader cache: {}", ec.message());
4563 Logger::info(
"[SteamLibraryScanner] Successfully force uninstalled app {}", appId);
4567 Logger::error(
"[SteamLibraryScanner] Force uninstall of app {} completed with errors",
4592 bool expected =
false;
4593 if (!running_.compare_exchange_strong(expected,
true, std::memory_order_acq_rel))
4597 pollIntervalMs_ = pollIntervalMs;
4598 monitorThread_ = std::thread(&Impl::monitorLoop,
this);
4604 if (monitorThread_.joinable())
4606 monitorThread_.join();
4622 std::lock_guard<std::mutex> lock(mutex_);
4627 std::lock_guard<std::mutex> lock(mutex_);
4632 std::lock_guard<std::mutex> lock(mutex_);
4637 std::lock_guard<std::mutex> lock(mutex_);
4643 std::lock_guard<std::mutex> lock(mutex_);
4644 if (watchedGames_.find(appId) == watchedGames_.end())
4646 Logger::info(
"[SteamDownloadMonitor] Starting to watch app {}", appId);
4648 watchedGames_[appId].
appId = appId;
4654 std::lock_guard<std::mutex> lock(mutex_);
4655 watchedGames_.erase(appId);
4656 lastStates_.erase(appId);
4657 lastRunningPids_.erase(appId);
4662 std::lock_guard<std::mutex> lock(mutex_);
4663 std::vector<uint32_t> result;
4664 result.reserve(watchedGames_.size());
4665 for (
const auto& pair : watchedGames_)
4667 result.push_back(pair.first);
4674 std::lock_guard<std::mutex> lock(mutex_);
4675 auto it = watchedGames_.find(appId);
4676 if (it != watchedGames_.end())
4695 std::this_thread::sleep_for(std::chrono::milliseconds(pollIntervalMs_));
4703 struct StateChangeEvent
4709 struct ProgressEvent
4724 std::vector<StateChangeEvent> stateChanges;
4725 std::vector<ProgressEvent> progressUpdates;
4726 std::vector<LaunchEvent> launches;
4727 std::vector<ExitEvent> exits;
4743 std::lock_guard<std::mutex> lock(mutex_);
4751 if (++pollCount_ >= 60)
4754 cachedLibraryPaths_.clear();
4757 for (
auto& [appId, progress] : watchedGames_)
4760 auto manifestPath = findAppManifest(appId);
4761 if (manifestPath.empty())
4763 Logger::debug(
"[SteamDownloadMonitor] No manifest found for app {}", appId);
4765 if (progress.stateFlags != 0)
4767 uint32_t oldState = progress.stateFlags;
4768 progress.stateFlags = 0;
4769 progress.stateDescription =
"Not Installed";
4770 progress.isComplete =
false;
4772 stateChanges.push_back({appId, oldState, 0});
4777 Logger::debug(
"[SteamDownloadMonitor] Found manifest for app {}: {}", appId,
4778 manifestPath.string());
4781 SteamDownloadProgress newProgress = parseManifestProgress(appId, manifestPath);
4784 auto lastIt = lastStates_.find(appId);
4785 uint32_t lastState = (lastIt != lastStates_.end()) ? lastIt->second : 0;
4790 stateChanges.push_back({appId, lastState, newProgress.
stateFlags});
4795 bool isActivelyInstalling =
4800 bool hasProgressChange = newProgress.
bytesDownloaded != progress.bytesDownloaded ||
4801 newProgress.
bytesStaged != progress.bytesStaged ||
4802 newProgress.
stateFlags != progress.stateFlags;
4805 if (hasProgressChange && isActivelyInstalling)
4815 Logger::info(
"[SteamDownloadMonitor] App {} progress: state={} ({}) "
4816 "downloaded={}/{} overall={}% speed={}",
4821 progress = newProgress;
4822 progressUpdates.push_back({appId, progress});
4827 progress = newProgress;
4832 auto pidIt = lastRunningPids_.find(appId);
4833 int lastPid = (pidIt != lastRunningPids_.end()) ? pidIt->second : -1;
4835 if (pid > 0 && lastPid <= 0)
4838 lastRunningPids_[appId] = pid;
4839 launches.push_back({appId, pid});
4841 else if (pid <= 0 && lastPid > 0)
4844 lastRunningPids_[appId] = -1;
4845 exits.push_back({appId});
4852 for (
const auto& event : stateChanges)
4856 onStateChange(event.appId, event.oldState, event.newState);
4861 for (
const auto& event : progressUpdates)
4863 if (onProgressUpdate)
4865 Logger::debug(
"[SteamDownloadMonitor] Calling onProgressUpdate callback for app {}",
4867 onProgressUpdate(event.appId, event.progress);
4872 for (
const auto& event : launches)
4876 onGameLaunch(event.appId, event.pid);
4881 for (
const auto& event : exits)
4885 onGameExit(event.appId);
4890 std::filesystem::path findAppManifest(uint32_t appId)
4893 if (cachedLibraryPaths_.empty())
4895 SteamLibraryScanner scanner;
4897 Logger::info(
"[SteamDownloadMonitor] Loaded {} Steam library paths:",
4898 cachedLibraryPaths_.size());
4899 for (
const auto& lib : cachedLibraryPaths_)
4901 Logger::info(
"[SteamDownloadMonitor] - {}", lib.string());
4905 std::string manifestName =
"appmanifest_" + std::to_string(appId) +
".acf";
4907 for (
const auto& lib : cachedLibraryPaths_)
4909 auto manifestPath = lib /
"steamapps" / manifestName;
4910 if (std::filesystem::exists(manifestPath))
4912 return manifestPath;
4918 SteamDownloadProgress parseManifestProgress(uint32_t appId,
4919 const std::filesystem::path& manifestPath)
4921 SteamDownloadProgress progress;
4922 progress.
appId = appId;
4926 auto fileSize = std::filesystem::file_size(manifestPath, ec);
4927 if (ec || fileSize == 0)
4933 std::ifstream file(manifestPath);
4934 if (!file.is_open())
4943 if (content.size() < fileSize)
4945 Logger::debug(
"[SteamDownloadMonitor] Partial read for app {}: got {} of {} bytes",
4946 appId, content.size(), fileSize);
4951 if (content.find(
"\"AppState\"") == std::string::npos)
4953 Logger::debug(
"[SteamDownloadMonitor] Invalid manifest for app {}: missing AppState",
4959 auto getValue = [&content](
const std::string& key) -> std::string
4961 std::string pattern =
"\"" + key +
"\"";
4962 size_t pos = content.find(pattern);
4963 if (pos == std::string::npos)
4967 size_t valueStart = content.find(
"\"", pos + pattern.length());
4968 if (valueStart == std::string::npos)
4972 size_t valueEnd = content.find(
"\"", valueStart);
4973 if (valueEnd == std::string::npos)
4976 return content.substr(valueStart, valueEnd - valueStart);
4980 std::string stateFlagsStr = getValue(
"StateFlags");
4981 std::string bytesDownloadedStr = getValue(
"BytesDownloaded");
4982 std::string bytesToDownloadStr = getValue(
"BytesToDownload");
4983 std::string bytesStagedStr = getValue(
"BytesStaged");
4984 std::string bytesToStageStr = getValue(
"BytesToStage");
4987 if (stateFlagsStr.empty())
4989 Logger::debug(
"[SteamDownloadMonitor] No StateFlags in manifest for app {}", appId);
4995 progress.
stateFlags =
static_cast<uint32_t
>(std::stoul(stateFlagsStr));
4997 if (!bytesDownloadedStr.empty())
4999 if (!bytesToDownloadStr.empty())
5001 if (!bytesStagedStr.empty())
5002 progress.
bytesStaged = std::stoull(bytesStagedStr);
5003 if (!bytesToStageStr.empty())
5012 std::filesystem::path manifestDir = manifestPath.parent_path();
5013 std::filesystem::path downloadingDir =
5014 manifestDir /
"downloading" / std::to_string(appId);
5016 if (std::filesystem::exists(downloadingDir))
5018 uint64_t actualBytes = 0;
5019 std::error_code dirEc;
5020 for (
const auto& entry : std::filesystem::recursive_directory_iterator(
5022 std::filesystem::directory_options::skip_permission_denied, dirEc))
5024 if (entry.is_regular_file())
5026 std::error_code sizeEc;
5027 auto size = entry.file_size(sizeEc);
5030 actualBytes += size;
5035 if (actualBytes > 0)
5039 "[SteamDownloadMonitor] App {} using folder size: {} bytes downloaded",
5040 appId, actualBytes);
5052 catch (
const std::exception& e)
5054 Logger::warn(
"Error parsing manifest progress for app {}: {}", appId, e.what());
5064 std::atomic<bool> running_{
false};
5065 int pollIntervalMs_ = 1000;
5067 std::thread monitorThread_;
5068 mutable std::mutex mutex_;
5069 std::map<uint32_t, SteamDownloadProgress> watchedGames_;
5070 std::map<uint32_t, uint32_t> lastStates_;
5071 std::map<uint32_t, int> lastRunningPids_;
5072 std::vector<std::filesystem::path> cachedLibraryPaths_;
5088 impl_->start(pollIntervalMs);
5098 return impl_->isRunning();
5103 impl_->watchGame(appId);
5108 impl_->unwatchGame(appId);
5113 return impl_->getWatchedGames();
5118 return impl_->getProgress(appId);
5127 std::filesystem::path steamPath;
5130 const char* homeDir = std::getenv(
"HOME");
5133 std::vector<std::filesystem::path> possiblePaths = {
5134 std::filesystem::path(homeDir) /
".steam" /
"steam",
5135 std::filesystem::path(homeDir) /
".local" /
"share" /
"Steam",
5136 std::filesystem::path(homeDir) /
".steam" /
"root"};
5138 for (
const auto& path : possiblePaths)
5140 if (std::filesystem::exists(path))
5148 if (steamPath.empty())
5154 auto compatDataPath = steamPath /
"steamapps" /
"compatdata" / std::to_string(appId);
5155 auto pidFile = compatDataPath /
"reaper.pid";
5157 if (std::filesystem::exists(pidFile))
5159 std::ifstream file(pidFile);
5163 if (file >> pid && pid > 0)
5174 if (::kill(pid, 0) == 0)
5176 std::ifstream envFile(
"/proc/" + std::to_string(pid) +
"/environ",
5178 if (envFile.is_open())
5180 std::string content((std::istreambuf_iterator<char>(envFile)),
5181 std::istreambuf_iterator<char>());
5182 const std::string needle =
"SteamGameId=" + std::to_string(appId);
5186 if (content.find(needle) != std::string::npos)
5198 std::string cmd =
"pgrep -f 'SteamAppId=" + std::to_string(appId) +
"' 2>/dev/null | head -1";
5204 return std::stoi(result.
output);
5224 std::vector<uint32_t> downloading;
5230 for (
const auto& lib : libraries)
5232 auto steamappsPath = lib /
"steamapps";
5233 if (!std::filesystem::exists(steamappsPath))
5236 for (
const auto& entry : std::filesystem::directory_iterator(steamappsPath))
5238 if (!entry.is_regular_file())
5241 std::string filename = entry.path().filename().string();
5242 if (filename.find(
"appmanifest_") != 0 || filename.find(
".acf") == std::string::npos)
5247 size_t end = filename.find(
".acf");
5248 std::string appIdStr = filename.substr(
start, end -
start);
5252 uint32_t appId =
static_cast<uint32_t
>(std::stoul(appIdStr));
5255 std::ifstream file(entry.path());
5256 if (!file.is_open())
5263 size_t pos = content.find(
"\"StateFlags\"");
5264 if (pos != std::string::npos)
5266 size_t valueStart = content.find(
"\"", pos + 12);
5267 if (valueStart != std::string::npos)
5270 size_t valueEnd = content.find(
"\"", valueStart);
5271 if (valueEnd != std::string::npos)
5273 std::string flagsStr =
5274 content.substr(valueStart, valueEnd - valueStart);
5275 uint32_t flags =
static_cast<uint32_t
>(std::stoul(flagsStr));
5279 downloading.push_back(appId);
5298 progress.
appId = appId;
5304 std::filesystem::path manifestPath;
5305 std::string manifestName =
"appmanifest_" + std::to_string(appId) +
".acf";
5307 for (
const auto& lib : libraries)
5309 auto path = lib /
"steamapps" / manifestName;
5310 if (std::filesystem::exists(path))
5312 manifestPath = path;
5317 if (manifestPath.empty())
5326 auto fileSize = std::filesystem::file_size(manifestPath, ec);
5327 if (ec || fileSize == 0)
5334 std::ifstream file(manifestPath);
5335 if (!file.is_open())
5344 if (content.size() < fileSize)
5351 if (content.find(
"\"AppState\"") == std::string::npos)
5358 auto getValue = [&content](
const std::string& key) -> std::string
5360 std::string pattern =
"\"" + key +
"\"";
5361 size_t pos = content.find(pattern);
5362 if (pos == std::string::npos)
5366 size_t valueStart = content.find(
"\"", pos + pattern.length());
5367 if (valueStart == std::string::npos)
5371 size_t valueEnd = content.find(
"\"", valueStart);
5372 if (valueEnd == std::string::npos)
5375 return content.substr(valueStart, valueEnd - valueStart);
5379 std::string stateFlagsStr = getValue(
"StateFlags");
5380 std::string bytesDownloadedStr = getValue(
"BytesDownloaded");
5381 std::string bytesToDownloadStr = getValue(
"BytesToDownload");
5382 std::string bytesStagedStr = getValue(
"BytesStaged");
5383 std::string bytesToStageStr = getValue(
"BytesToStage");
5386 if (stateFlagsStr.empty())
5394 progress.
stateFlags =
static_cast<uint32_t
>(std::stoul(stateFlagsStr));
5396 if (!bytesDownloadedStr.empty())
5398 if (!bytesToDownloadStr.empty())
5400 if (!bytesStagedStr.empty())
5401 progress.
bytesStaged = std::stoull(bytesStagedStr);
5402 if (!bytesToStageStr.empty())
5405 catch (
const std::exception& e)
5407 Logger::warn(
"Error parsing manifest for app {}: {}", appId, e.what());
5426 impl_->setProgressCallback(std::move(callback));
5431 impl_->setStateChangeCallback(std::move(callback));
5436 impl_->setGameLaunchCallback(std::move(callback));
5441 impl_->setGameExitCallback(std::move(callback));
5469 Logger::info(
"SteamUpdateMonitor: Starting update monitoring thread");
5477 std::unique_lock<std::mutex> lock(
mutex_);
5482 Logger::info(
"SteamUpdateMonitor: Monitor thread stopped");
5493 std::vector<std::filesystem::path> libraries = scanner.
getLibraryPaths();
5496 std::map<uint32_t, SteamGameUpdateInfo> currentStates;
5498 for (
const auto& libraryPath : libraries)
5500 std::filesystem::path steamappsPath = libraryPath /
"steamapps";
5501 if (!std::filesystem::exists(steamappsPath))
5505 for (
const auto& entry : std::filesystem::directory_iterator(steamappsPath))
5507 if (!entry.is_regular_file())
5510 std::string filename = entry.path().filename().string();
5511 if (filename.find(
"appmanifest_") != 0 ||
5512 filename.find(
".acf") == std::string::npos)
5516 std::ifstream file(entry.path());
5517 if (!file.is_open())
5524 std::regex appIdRegex(R
"_r("appid"\s+"(\d+)")_r");
5525 std::smatch appIdMatch;
5526 if (!std::regex_search(content, appIdMatch, appIdRegex))
5538 unsigned long parsed = std::stoul(appIdMatch[1].str());
5539 if (parsed > std::numeric_limits<uint32_t>::max())
5541 appId =
static_cast<uint32_t
>(parsed);
5543 catch (
const std::exception&)
5549 std::string gameName;
5550 std::regex nameRegex(R
"_r("name"\s+"([^"]+)")_r");
5551 std::smatch nameMatch;
5552 if (std::regex_search(content, nameMatch, nameRegex))
5554 gameName = nameMatch[1].str();
5558 uint32_t stateFlags = 0;
5559 std::regex stateRegex(R
"_r("StateFlags"\s+"(\d+)")_r");
5560 std::smatch stateMatch;
5561 if (std::regex_search(content, stateMatch, stateRegex))
5565 unsigned long parsed = std::stoul(stateMatch[1].str());
5566 if (parsed <= std::numeric_limits<uint32_t>::max())
5567 stateFlags =
static_cast<uint32_t
>(parsed);
5569 catch (
const std::exception&)
5575 uint64_t bytesToDownload = 0;
5576 std::regex bytesRegex(R
"_r("BytesToDownload"\s+"(\d+)")_r");
5577 std::smatch bytesMatch;
5578 if (std::regex_search(content, bytesMatch, bytesRegex))
5582 bytesToDownload = std::stoull(bytesMatch[1].str());
5584 catch (
const std::exception&)
5599 currentStates[appId] = info;
5607 for (
const auto& [appId, info] : currentStates)
5616 Logger::info(
"SteamUpdateMonitor: New update available for {} ({})",
5617 info.gameName, appId);
5623 const auto& oldInfo = it->second;
5626 if (!oldInfo.needsUpdate && info.needsUpdate)
5631 Logger::info(
"SteamUpdateMonitor: Update detected for {} ({})",
5632 info.gameName, appId);
5636 else if (!oldInfo.isDownloading && info.isDownloading)
5641 Logger::info(
"SteamUpdateMonitor: Update started for {} ({})",
5642 info.gameName, appId);
5646 else if ((oldInfo.needsUpdate || oldInfo.isDownloading) && !info.needsUpdate &&
5647 !info.isDownloading &&
5653 Logger::info(
"SteamUpdateMonitor: Update completed for {} ({})",
5654 info.gameName, appId);
5675SteamUpdateMonitor::~SteamUpdateMonitor()
5685 bool expected =
false;
5686 if (!impl_->running_.compare_exchange_strong(expected,
true, std::memory_order_acq_rel))
5692 impl_->scanIntervalSeconds_ = scanIntervalSeconds;
5693 impl_->shouldStop_ =
false;
5697 Logger::info(
"SteamUpdateMonitor: Started with {} second interval", scanIntervalSeconds);
5702 if (!impl_->running_)
5705 impl_->shouldStop_ =
true;
5706 impl_->cv_.notify_all();
5708 if (impl_->monitorThread_.joinable())
5710 impl_->monitorThread_.join();
5713 impl_->running_ =
false;
5719 return impl_->running_;
5724 impl_->scanForUpdates();
5730 std::vector<SteamGameUpdateInfo> result;
5731 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5733 for (
const auto& [appId, info] : impl_->gameStates_)
5735 if (info.needsUpdate || info.isDownloading)
5737 result.push_back(info);
5746 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5749 for (
const auto& [appId, info] : impl_->gameStates_)
5751 if (info.needsUpdate)
5762 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5763 impl_->gameStates_.clear();
5772 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5773 impl_->onUpdateAvailable_ = std::move(callback);
5778 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5779 impl_->onUpdateStarted_ = std::move(callback);
5784 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5785 impl_->onUpdateCompleted_ = std::move(callback);
static std::optional< SteamGame > parseManifest(const std::filesystem::path &acfFilePath, const std::filesystem::path &libraryPath)
Parse ACF file to extract game metadata.
static std::string detectProtonVersion(uint32_t appId, const std::filesystem::path &libraryPath)
Detect Proton version for a Steam game from appmanifest UserConfig.
Complete representation of a game in the library.
GameMetadata metadata
Descriptive information and media.
std::string installPath
Installation directory path.
std::string name
Display name shown in UI.
void syncPlatformFromRunner()
Sync the deprecated platform field from the current runner and source.
GameStatistics statistics
Play statistics and usage tracking.
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
GameRunnerConfig runnerConfig
How to launch and run the game.
GameStatus status
Current installation and execution status.
uint64_t installSizeBytes
Installation size in bytes.
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).
RAII wrapper for FILE* from popen().
FILE * get() const
Get raw FILE* pointer.
static ProcessResult executeWithOutput(const std::string &command, bool silent=false)
Execute command and capture stdout.
static ProcessResult executeBackground(const std::string &command)
Execute command in background (non-blocking).
static ProcessResult execute(const std::string &command, bool silent=false)
Execute command and check exit code.
static bool isProcessRunning(const std::string &processName)
Check if process is running by name.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Parses Steam's binary appinfo.vdf cache file.
bool load(const std::filesystem::path &path)
Load and index an appinfo.vdf file.
static std::string getCDNUrl(uint32_t appId, ImageType type)
Build CDN URL for a specific image type.
static bool downloadImage(uint32_t appId, ImageType type, const std::string &outputPath)
Download image from Steam CDN (fallback only).
static GameImagePaths discoverImages(uint32_t appId, const std::filesystem::path &steamRoot)
Find all available images for a Steam game.
static std::filesystem::path getLibraryCachePath(const std::filesystem::path &steamRoot)
Get path to Steam's library cache directory.
void setGameExitCallback(SteamDownloadMonitor::GameExitCallback cb)
void setGameLaunchCallback(SteamDownloadMonitor::GameLaunchCallback cb)
void watchGame(uint32_t appId)
void unwatchGame(uint32_t appId)
void start(int pollIntervalMs)
SteamDownloadMonitor::ProgressCallback onProgressUpdate_
std::vector< uint32_t > getWatchedGames() const
SteamDownloadMonitor::GameExitCallback onGameExit_
void setStateChangeCallback(SteamDownloadMonitor::StateChangeCallback cb)
SteamDownloadProgress getProgress(uint32_t appId) const
SteamDownloadMonitor::StateChangeCallback onStateChange_
SteamDownloadMonitor::GameLaunchCallback onGameLaunch_
void setProgressCallback(SteamDownloadMonitor::ProgressCallback cb)
Monitors Steam download/install progress for games.
void setOnStateChange(StateChangeCallback callback)
void stop()
Stop all monitoring.
static std::vector< uint32_t > getDownloadingGames()
Get list of all games currently downloading.
std::function< void(uint32_t appId, uint32_t oldState, uint32_t newState)> StateChangeCallback
static int getRunningGamePid(uint32_t appId)
Check if a Steam game is currently running (by app ID).
static bool isSteamDownloading()
Check if Steam is actively downloading/updating anything.
std::function< void(uint32_t appId, int pid)> GameLaunchCallback
void setOnGameExit(GameExitCallback callback)
void start(int pollIntervalMs=1000)
Start monitoring Steam downloads.
std::function< void(uint32_t appId)> GameExitCallback
bool isRunning() const
Check if monitor is running.
void watchGame(uint32_t appId)
Add a game to the watch list for progress updates.
static SteamDownloadProgress readGameState(uint32_t appId)
Read current state of a game directly from its appmanifest.
std::function< void(uint32_t appId, const SteamDownloadProgress &progress)> ProgressCallback
void setOnProgressUpdate(ProgressCallback callback)
void unwatchGame(uint32_t appId)
Remove a game from the watch list.
void setOnGameLaunch(GameLaunchCallback callback)
std::vector< uint32_t > getWatchedGames() const
Get list of currently watched game IDs.
SteamDownloadProgress getProgress(uint32_t appId) const
Get current progress for a game (immediate snapshot).
static std::string buildSteamURI(uint32_t appId)
Build Steam launch URI.
static std::string buildLaunchCommand(const Game &game, const CachyOSGameConfig &config)
Build launch command for Steam game.
Scans Steam installations to discover games.
bool isSteamInstalled() const
Check if Steam is installed on this system.
static CloudSaveInfo readSteamCloudSaveInfo(uint32_t appId)
Read Steam Cloud save information for a game from localconfig.vdf.
static std::vector< std::pair< std::string, std::filesystem::path > > scanProtonVersions()
Scan for all installed Proton versions.
static std::map< uint32_t, SteamPlaytimeData > readSteamPlaytimeData()
Read Steam playtime statistics for all games from localconfig.vdf.
static std::string normalizeProtonName(const std::string &display)
Strip launcher-side display annotations from a Proton name.
static std::vector< DLCInfo > readDLCFromACF(const std::filesystem::path &acfFilePath, const std::filesystem::path &libraryPath)
Read DLC information from appmanifest ACF file.
static std::string fetchGameNameFromCache(uint32_t appId)
Get game name from pre-loaded cache (instant).
static bool restartSteam()
Attempt to gracefully restart Steam (blocking).
static bool loadAppNameCache()
Load Steam app name cache from GetAppList API.
static std::map< uint32_t, std::vector< std::string > > readAllUserCategories()
Read all user categories for all games at once (batch operation).
static std::string fetchGameNameFromSteamAPI(uint32_t appId)
Fetch game name from Steam Web API.
static bool isAppNameCacheLoaded()
Check if app name cache is loaded.
static bool requestUninstallGame(uint32_t appId)
Request Steam to uninstall a game via steam:// protocol.
static bool forceUninstallGame(uint32_t appId)
Force uninstall a Steam game by directly removing files.
static bool writeSteamProtonVersion(uint32_t appId, const std::string &protonName)
Write Proton compatibility tool mapping for a game to config.vdf.
static std::future< bool > restartSteamAsync()
Attempt to gracefully restart Steam asynchronously.
static bool getGameInstallInfo(uint32_t appId, std::string &installDir, std::filesystem::path &libraryPath)
Get installation info for a Steam game.
std::vector< SteamGame > scanAllLibraries()
Scan all Steam libraries for installed games.
std::vector< SteamGame > scanAllOwnedGames()
Scan for all owned Steam games (installed and not installed).
std::vector< std::filesystem::path > getLibraryPaths() const
Get list of detected Steam library paths.
static std::string readSteamProtonVersion(uint32_t appId)
Read Proton compatibility tool mapping for a game from config.vdf.
static bool isSteamRunning()
Check if Steam is currently running.
static std::filesystem::path resolveProtonPath(uint32_t appId, std::string &outCompatToolName)
Resolve Proton executable path for a game.
static std::map< uint32_t, CloudSaveInfo > readAllCloudSaveInfo()
Read all cloud save info for all games at once (batch operation).
static void populateDirectLaunchInfo(SteamGame &game)
Populate a SteamGame with direct-launch information.
static bool writeSteamLaunchOptions(uint32_t appId, const std::string &launchOptions)
Write Steam launch options for a game to localconfig.vdf.
static std::vector< std::string > readSteamUserCategories(uint32_t appId)
Read user-defined categories (tags) for a game from localconfig.vdf.
static std::string readSteamLaunchOptions(uint32_t appId)
Read Steam launch options for a game from localconfig.vdf.
SteamLibraryScanner()
Constructor - auto-detects Steam installation.
static bool fetchSteamMetadata(uint32_t appId, std::string &outType, std::vector< std::string > &outGenres, std::vector< std::string > &outCategories)
Fetch enhanced metadata from Steam Web API (type, genres, categories).
static std::filesystem::path getUserDataDirectory()
Get Steam userdata directory.
static std::vector< std::filesystem::path > getAllSteamRoots()
Get all possible Steam installation directories.
static std::filesystem::path getPrimarySteamRoot()
Get primary Steam installation directory.
UpdateStartedCallback onUpdateStarted_
UpdateCompletedCallback onUpdateCompleted_
UpdateAvailableCallback onUpdateAvailable_
std::condition_variable cv_
std::atomic< bool > shouldStop_
std::atomic< bool > running_
std::thread monitorThread_
std::map< uint32_t, SteamGameUpdateInfo > gameStates_
void clearCache()
Clear cached update states (force fresh detection).
static SteamUpdateMonitor & instance()
void setOnUpdateCompleted(UpdateCompletedCallback callback)
Set callback for when an update completes.
void setOnUpdateStarted(UpdateStartedCallback callback)
Set callback for when an update starts downloading.
void setOnUpdateAvailable(UpdateAvailableCallback callback)
Set callback for when a new update is detected.
SteamUpdateMonitor(const SteamUpdateMonitor &)=delete
bool isRunning() const
Check if monitor is running.
void stop()
Stop monitoring.
std::function< void(uint32_t appId, const std::string &gameName)> UpdateCompletedCallback
std::function< void(const SteamGameUpdateInfo &info)> UpdateStartedCallback
std::vector< SteamGameUpdateInfo > scanNow()
Force an immediate scan for updates.
size_t getUpdateCount() const
Get count of games needing updates.
std::vector< SteamGameUpdateInfo > getGamesNeedingUpdate() const
Get all games currently needing updates.
void start(int scanIntervalSeconds=300)
Start monitoring for updates.
std::function< void(const SteamGameUpdateInfo &info)> UpdateAvailableCallback
@ Steam
Steam store/platform.
ImageType
Types of game images available.
@ HeroImage
Wide banner/hero image (landscape).
@ Capsule
Store capsule image (616x353).
@ VerticalCover
Vertical cover art (600x900, portrait).
@ Logo
Game logo with transparency (PNG).
@ Header
Small header image (460x215).
@ NotInstalled
Game is in library but not installed.
@ Installed
Game is installed and ready to play.
@ Proton
Proton (Steam's Wine fork).
@ Native
Native Linux executable (no compatibility layer).
constexpr const char * VDF_BACKUP_SUFFIX
Suffix for backup configuration files.
constexpr const char * LIBRARY_FOLDERS_VDF
File containing library folder paths.
constexpr const char * CONFIG_DIR
Directory containing global Steam configuration.
constexpr const char * COMMON_DIR
Directory containing installed games (within steamapps).
constexpr const char * COMPAT_TOOLS_DIR
Directory containing compatibility tools.
constexpr const char * STEAMAPPS_DIR
Directory containing installed games.
constexpr size_t VDF_MAX_FILE_SIZE
Maximum VDF file size to read (safety limit: 10 MB).
std::string getStateDescription(uint32_t flags)
Get human-readable state description.
bool isFullyInstalled(uint32_t flags)
Check if a game is fully installed.
bool needsUpdate(uint32_t flags)
Check if a game needs an update.
constexpr uint32_t UpdateRequired
Update available (not yet started).
bool isDownloading(uint32_t flags)
Check if a game is currently downloading or updating.
constexpr uint32_t Staging
Staging files after download.
static std::string getActiveUserId()
static bool s_appNameCacheLoaded
static std::mutex s_appNameCacheMutex
static std::string vdfEscapeValue(const std::string &s)
static std::string readVdfContent(std::ifstream &file)
std::string getProtonVersionCommand(ProtonVersion version)
Get command/path for Proton version.
const char * getProtonVersionName(ProtonVersion version)
Get human-readable name for Proton version.
static size_t findVdfSectionEnd(const std::string &content, size_t openBrace)
static std::unordered_map< uint32_t, std::string > s_appNameCache
static size_t loadAppNamesFromLocalCache(const std::filesystem::path &steamPath)
ProtonVersion
Available Proton compatibility layer versions.
@ Proton8
Official Proton 8.0.
@ ProtonCachyOS
proton-cachyos (native, no SLR)
@ ProtonGE
Proton GE (community).
@ ProtonCachyOSSLR
proton-cachyos-slr (recommended for anti-cheat)
@ NativeLinux
Native Linux build (no Proton).
@ Proton9
Official Proton 9.0.
@ ProtonExperimental
Official Proton Experimental.
@ SystemDefault
Use Steam's default selection.
CachyOS-specific gaming configuration options.
std::string radvPerftest
RADV_PERFTEST (comma-separated, e.g., "rt,nggc,sam").
bool nvidia4000Fix
PROTON_NVIDIA_LIBS_NO_32BIT (RTX 4000+).
bool useLocalShaderCache
__GL_SHADER_DISK_CACHE=1 (NVIDIA shader cache)
bool enableWayland
PROTON_ENABLE_WAYLAND (experimental, breaks overlay).
bool enableMangoHud
MANGOHUD=1 (performance overlay).
bool enableFSR
WINE_FULLSCREEN_FSR=1 (AMD upscaling).
bool enableDLSSIndicator
PROTON_DLSS_INDICATOR (show DLSS status).
bool useGamePerformanceWrapper
Use game-performance CPU governor wrapper.
bool enableFSR4Upgrade
PROTON_FSR4_UPGRADE (AMD upscaling v4).
bool skipShaderCacheCleanup
__GL_SHADER_DISK_CACHE_SKIP_CLEANUP (NVIDIA)
bool enableGamescope
ENABLE_GAMESCOPE (microcompositor).
bool disableSteamInput
PROTON_NO_STEAMINPUT (disable Steam Input).
bool enableDXVKHDR
DXVK_HDR=1 (DXVK HDR support).
bool enableProtonLog
PROTON_LOG=1 (verbose logging).
bool enableDLSSUpgrade
PROTON_DLSS_UPGRADE (auto-upgrade DLSS).
bool useNTSync
PROTON_USE_NTSYNC=1 (GE-Proton auto-enables).
bool useDXVKAsync
DXVK_ASYNC=1 (async shader compilation).
bool enableFSR4RDNA3Upgrade
PROTON_FSR4_RDNA3_UPGRADE (AMD RDNA3 optimized upscaling).
bool enableNvidiaLibs
PROTON_NVIDIA_LIBS (PhysX/CUDA support).
bool enableXeSSUpgrade
PROTON_XESS_UPGRADE (Intel Arc upscaling).
std::string protonVerb
PROTON_VERB (e.g., "waitforexitandrun").
bool fixStuttering
LD_PRELOAD="" (disables Steam overlay).
std::string buildEnvVars() const
Build environment variable string for launch.
bool preferSDL
PROTON_PREFER_SDL (controller detection workaround).
bool enableHDR
PROTON_ENABLE_HDR (requires Gamescope/Wayland).
bool enableDXVKHud
DXVK_HUD=compiler (show shader compilation).
Information about Steam Cloud save synchronization.
uint64_t storageBytes
Cloud storage used in bytes.
time_t lastSyncTime
Last successful sync timestamp.
bool enabled
Cloud saves enabled for this game.
bool supported
Game supports Steam Cloud.
int lastSyncState
0=synced, 1=uploading, 2=downloading, 3=error
Information about downloadable content (DLC).
int appId
Steam App ID of the DLC.
bool installed
True if DLC is installed.
uint64_t sizeBytes
Installation size in bytes.
std::string name
DLC display name.
Paths to various game image assets.
std::string header
Small header image (header.jpg, 460x215).
std::string capsule
Store capsule image (capsule_616x353.jpg).
std::string logo
Game logo with transparency (logo.png).
std::string icon
Small square icon (icon.jpg).
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.
bool useSteamDefaults
For Steam games: if true, don't sync custom env vars/wrappers to Steam's VDF files.
std::string workingDirectory
Working directory for game execution.
std::string arguments
Command line arguments to pass to game.
std::string runnerVersion
Runner version: "wine-8.0", "proton-8.0-5", etc.
std::string runnerType
Runner type: "wine", "proton", "native", etc.
std::string protonVersion
Proton version (e.g., "proton-cachyos-slr").
std::map< std::string, std::string > environmentVariables
Environment variables to set before launching (KEY=VALUE pairs).
bool useSteamLaunch
For Steam games: if true, launch via "steam -applaunch" instead of direct Proton.
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
time_t lastPlayed
Unix timestamp of last play session.
Parsed components from Steam launch options string.
bool isEmpty() const
Check if launch options string is empty or only whitespace.
std::vector< std::string > wrappers
Wrapper commands (e.g., game-performance, mangohud).
static ParsedSteamLaunchOptions parse(const std::string &launchOptions)
Parse Steam launch options string.
std::vector< std::string > gameArguments
Arguments after command%.
std::map< std::string, std::string > environmentVariables
Environment variables (KEY=VALUE).
std::string rawString
Original launch options string.
Result of process execution including exit code and output.
bool success
true if command executed successfully (exit code 0)
std::string output
Captured stdout (if requested).
Real-time download/installation progress for a Steam game.
uint64_t bytesToStage
Total bytes to stage.
std::string stateDescription
Human-readable state.
std::string getFormattedSpeed() const
Get formatted download speed string.
uint32_t appId
Steam App ID.
std::chrono::steady_clock::time_point lastSpeedUpdate
Time of last speed update.
uint64_t bytesToDownload
Total bytes to download.
uint64_t lastBytesDownloaded
Previous bytes downloaded for speed calc.
uint64_t bytesStaged
Bytes staged for installation.
void calculateProgress()
Calculate progress percentages from byte values.
void updateSpeed()
Update download speed calculation Should be called periodically with new progress data.
uint64_t bytesDownloaded
Bytes downloaded so far.
bool isComplete
Installation complete.
int queuePosition
Position in download queue (0 = active, 1+ = queued).
uint32_t stateFlags
Current StateFlags.
double overallProgress
Combined progress (0.0 to 1.0).
Information about a game's update status.
Metadata for a Steam game parsed from appmanifest ACF file.
std::string downloadCoverArt(const std::string &coverArtDir) const
Download cover art from Steam CDN.
std::filesystem::path libraryPath
Steam library root path.
uint64_t bytesDownloaded
Bytes downloaded so far.
std::string installDir
Installation directory name.
std::string gameExecutable
Game exe relative to install dir (e.g., "FSD.exe").
time_t steamLastExit
Last exit timestamp from Steam autocloud.
std::string steamType
App type: "game", "dlc", "demo", "tool", "music", etc.
std::string name
Game name.
time_t steamLastPlayed
Last played timestamp from Steam.
bool isInstalled
True if game is installed (has appmanifest), false if owned but not installed.
std::vector< std::string > genres
Game genres from Steam API.
std::vector< DLCInfo > dlc
Installed DLC for this game.
uint32_t steamPlaytime2Weeks
Playtime in last 2 weeks (in minutes).
std::vector< std::string > categories
Steam categories (Single-player, Multi-player, etc.).
uint32_t steamPlaytimeMinutes
Total playtime from Steam (in minutes).
bool isProtonGame
Requires Proton (Windows game).
time_t steamLastLaunch
Last launch timestamp from Steam autocloud.
std::filesystem::path gamePath
Full path to game directory.
Game toGame() const
Convert SteamGame to Game object for library.
std::vector< std::string > steamUserCategories
User-defined categories/tags from Steam.
uint32_t appId
Steam App ID.
uint32_t stateFlags
Steam StateFlags from appmanifest.
bool isUpdatePending
Update available but not yet started.
CloudSaveInfo cloudSave
Steam Cloud save information.
time_t lastUpdated
Last update timestamp.
std::string steamBuildId
Steam build ID from appmanifest.
bool isDownloading
Currently downloading/updating.
uint64_t bytesToStage
Total bytes to stage.
std::string compatToolName
Raw compat tool name from Steam config (e.g., "proton_experimental").
uint64_t bytesToDownload
Total bytes to download.
std::string protonVersion
Detected Proton/compatibility tool version from Steam.
std::string gameArguments
Default launch arguments from Steam (e.g., "-nohmd").
uint64_t bytesStaged
Bytes staged for installation.
uint64_t sizeOnDisk
Installation size in bytes.
std::filesystem::path protonPath
Resolved path to proton executable.
Steam playtime and usage statistics from localconfig.vdf.