game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
steam_integration.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// steam_integration.cpp
4// ==============================================================================
5// Implementation of Steam library integration
6// ==============================================================================
7
8#include "steam_integration.h"
9#include "file_handle.h"
10#include "logger.h"
11#include "process_executor.h"
13#include "steam_constants.h"
14#include "steam_paths.h"
15#include "util/shell_utils.h"
16#include <atomic>
17#include <chrono>
18#include <cstring>
19#include <ctime>
20#include <fcntl.h>
21#include <fstream>
22#include <limits>
23#include <mutex>
24#include <regex>
25#include <set>
26#include <signal.h>
27#include <sstream>
28#include <sys/file.h>
29#include <sys/stat.h>
30#include <thread>
31#include <unistd.h>
32#include <unordered_map>
33
34// ==============================================================================
35// Internal helpers
36// ==============================================================================
37
38// Read a VDF/ACF file into a string, returning empty if the file exceeds
39// VDF_MAX_FILE_SIZE. Prevents OOM from corrupt or oversized config files.
40static std::string readVdfContent(std::ifstream& file)
41{
42 file.seekg(0, std::ios::end);
43 const auto sz = file.tellg();
44 if (sz < 0 || static_cast<uintmax_t>(sz) > SteamConstants::VDF_MAX_FILE_SIZE)
45 return {};
46 file.seekg(0, std::ios::beg);
47 return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
48}
49
50// ==============================================================================
51// Steam CDN Image Helper Implementation
52// ==============================================================================
53
54const std::vector<std::string>& SteamCDN::cdnHosts()
55{
56 static const std::vector<std::string> hosts = {
57 "https://cdn.cloudflare.steamstatic.com/steam/apps/", // Primary (CloudFlare)
58 "https://steamcdn-a.akamaihd.net/steam/apps/" // Fallback (Akamai)
59 };
60 return hosts;
61}
62
63std::string SteamCDN::getCacheFilename(ImageType type)
64{
65 switch (type)
66 {
68 return "library_600x900.jpg";
70 return "library_hero.jpg";
71 case ImageType::Logo:
72 return "logo.png";
74 return "header.jpg";
76 return "capsule_616x353.jpg";
77 case ImageType::Icon:
78 return "icon.jpg";
79 default:
80 return "";
81 }
82}
83
84std::filesystem::path SteamCDN::getLibraryCachePath(const std::filesystem::path& libraryPath)
85{
86 return libraryPath / "appcache" / "librarycache";
87}
88
89GameImagePaths SteamCDN::discoverImages(uint32_t appId, const std::filesystem::path& steamRoot)
90{
91 GameImagePaths paths;
92 std::filesystem::path cacheDir = getLibraryCachePath(steamRoot);
93
94 if (!std::filesystem::exists(cacheDir))
95 {
96 Logger::debug("Steam image cache not found at: {}", cacheDir.string());
97 return paths; // Return empty paths
98 }
99
100 std::string appIdStr = std::to_string(appId);
101
102 // Helper lambda to validate an image file
103 // Note: Removed the 50ms sleep delay as it was causing significant slowdowns.
104 // Steam's image files are typically written atomically via rename, so the
105 // size check and header validation should be sufficient.
106 auto validateImageFile = [&](const std::filesystem::path& imagePath,
107 const std::string& filename) -> bool
108 {
109 if (!std::filesystem::exists(imagePath))
110 return false;
111
112 // Check file size
113 std::error_code ec;
114 auto fileSize = std::filesystem::file_size(imagePath, ec);
115 if (ec || fileSize == 0)
116 return false;
117
118 // Minimum reasonable file size check (corrupt files are often tiny)
119 // Logos can be smaller, so use different thresholds
120 constexpr size_t MIN_FILE_SIZE_JPG = 5 * 1024; // 5KB for JPEGs
121 constexpr size_t MIN_FILE_SIZE_PNG = 1 * 1024; // 1KB for PNGs (logos)
122 bool isPng = filename.find(".png") != std::string::npos;
123 size_t minSize = isPng ? MIN_FILE_SIZE_PNG : MIN_FILE_SIZE_JPG;
124
125 if (fileSize < minSize)
126 {
127 return false;
128 }
129
130 // Validate file structure based on type (quick header check)
131 std::ifstream file(imagePath, std::ios::binary);
132 if (!file.is_open())
133 return false;
134
135 unsigned char header[8];
136 file.read(reinterpret_cast<char*>(header), isPng ? 8 : 2);
137 if (!file)
138 return false;
139
140 if (isPng)
141 {
142 // PNG signature: 89 50 4E 47 0D 0A 1A 0A
143 if (header[0] != 0x89 || header[1] != 0x50 || header[2] != 0x4E || header[3] != 0x47)
144 {
145 return false;
146 }
147 }
148 else
149 {
150 // JPEG header (SOI marker: 0xFF 0xD8)
151 if (header[0] != 0xFF || header[1] != 0xD8)
152 {
153 return false;
154 }
155
156 // Check JPEG footer (EOI marker: 0xFF 0xD9)
157 // Only check if file is large enough to potentially have a valid footer
158 if (fileSize > 100)
159 {
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)
164 {
165 return false;
166 }
167 }
168 }
169
170 file.close();
171 return true;
172 };
173
174 // Helper lambda to search for an image with multiple filename variants
175 auto findImage = [&](const std::vector<std::string>& filenames) -> std::string
176 {
177 std::filesystem::path appDir = cacheDir / appIdStr;
178
179 if (std::filesystem::exists(appDir) && std::filesystem::is_directory(appDir))
180 {
181 // FORMAT 1: Files directly in <appId>/ folder (flat format)
182 // e.g., librarycache/622590/library_hero.jpg
183 for (const auto& filename : filenames)
184 {
185 std::filesystem::path imagePath = appDir / filename;
186 if (validateImageFile(imagePath, filename))
187 {
188 Logger::debug("Found image (flat format): {}", imagePath.string());
189 return imagePath.string();
190 }
191 }
192
193 // FORMAT 2: Files in <appId>/<hash>/ subdirectories
194 // e.g., librarycache/578080/a14b88ee.../library_hero.jpg
195 for (const auto& entry : std::filesystem::directory_iterator(appDir))
196 {
197 if (!entry.is_directory())
198 continue;
199
200 for (const auto& filename : filenames)
201 {
202 std::filesystem::path imagePath = entry.path() / filename;
203 if (validateImageFile(imagePath, filename))
204 {
205 Logger::debug("Found image (hash subdir): {}", imagePath.string());
206 return imagePath.string();
207 }
208 }
209 }
210 }
211
212 // FORMAT 3 (LEGACY): Files as <appId>_<filename> directly in cache dir
213 // e.g., librarycache/12345_library_600x900.jpg
214 for (const auto& filename : filenames)
215 {
216 // Try high-res version first (2x)
217 if (filename.find(".jpg") != std::string::npos)
218 {
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))
223 {
224 Logger::debug("Found image (legacy 2x): {}", imagePath.string());
225 return imagePath.string();
226 }
227 }
228
229 // Standard version
230 std::string variant = appIdStr + "_" + filename;
231 std::filesystem::path imagePath = cacheDir / variant;
232 if (validateImageFile(imagePath, variant))
233 {
234 Logger::debug("Found image (legacy): {}", imagePath.string());
235 return imagePath.string();
236 }
237 }
238
239 return "";
240 };
241
242 // Discover all available images with multiple filename variants for each type
243 // Steam uses different filenames in different cache versions
244
245 // Vertical Cover (600x900 portrait)
246 paths.verticalCover = findImage({"library_600x900.jpg", "library_600x900_2x.jpg"});
247
248 // Hero Image (wide banner)
249 paths.heroImage = findImage({"library_hero.jpg", "library_hero_2x.jpg"});
250
251 // Logo (transparent PNG)
252 paths.logo = findImage({"logo.png", "logo_2x.png"});
253
254 // Header (smaller banner, used in list views)
255 paths.header = findImage({"library_header.jpg", "header.jpg", "library_header_2x.jpg"});
256
257 // Capsule (medium banner)
258 paths.capsule = findImage({"library_capsule.jpg", "capsule_616x353.jpg", "capsule_231x87.jpg"});
259
260 // Icon
261 paths.icon = findImage({"icon.jpg", "icon.png"});
262
263 // Log summary
264 int foundCount = 0;
265 if (!paths.verticalCover.empty())
266 foundCount++;
267 if (!paths.heroImage.empty())
268 foundCount++;
269 if (!paths.logo.empty())
270 foundCount++;
271 if (!paths.header.empty())
272 foundCount++;
273 if (!paths.capsule.empty())
274 foundCount++;
275 if (!paths.icon.empty())
276 foundCount++;
277
278 if (foundCount > 0)
279 {
280 Logger::info("Discovered {} images for app {}", foundCount, appIdStr);
281 }
282
283 return paths;
284}
285
286std::string SteamCDN::getCDNUrl(uint32_t appId, ImageType type)
287{
288 std::string filename = getCacheFilename(type);
289 if (filename.empty())
290 return "";
291
292 // Use primary CDN host
293 return cdnHosts()[0] + std::to_string(appId) + "/" + filename;
294}
295
296bool SteamCDN::downloadImage(uint32_t appId, ImageType type, const std::string& outputPath)
297{
298 std::string filename = getCacheFilename(type);
299 if (filename.empty())
300 return false;
301
302 // Try each CDN host
303 for (const auto& host : cdnHosts())
304 {
305 std::string url = host + std::to_string(appId) + "/" + filename;
306 std::string curlCommand = "curl -s -f --max-time 10 -o " +
307 ShellUtils::escapeArg(outputPath) + " " +
308 ShellUtils::escapeArg(url) + " 2>/dev/null";
309
310 ProcessResult result = ProcessExecutor::execute(curlCommand, true);
311
312 if (result.success && std::filesystem::exists(outputPath) &&
313 std::filesystem::file_size(outputPath) > 0)
314 {
315 return true;
316 }
317 }
318
319 // Download failed from all hosts
320 if (std::filesystem::exists(outputPath))
321 {
322 std::filesystem::remove(outputPath);
323 }
324
325 return false;
326}
327
328// ==============================================================================
329// Proton Version Names and Commands
330// ==============================================================================
331
333{
334 switch (version)
335 {
337 return "Proton CachyOS SLR (Recommended)";
339 return "Proton CachyOS (Native)";
341 return "Proton Experimental";
343 return "Proton 9.0";
345 return "Proton 8.0";
347 return "Proton GE (Community)";
349 return "System Default";
351 return "Native Linux";
352 default:
353 return "Unknown";
354 }
355}
356
358{
359 switch (version)
360 {
362 return "proton-cachyos-slr";
364 return "proton-cachyos";
366 return "proton-experimental";
368 return "proton-9.0";
370 return "proton-8.0";
372 return "proton-ge";
374 return "";
376 return "";
377 default:
378 return "";
379 }
380}
381
382// ==============================================================================
383// CachyOS Game Configuration
384// ==============================================================================
385
387{
388 std::ostringstream env;
389
390 // Performance optimizations
391 if (useNTSync)
392 {
393 env << "PROTON_USE_NTSYNC=1 ";
394 }
395 if (useDXVKAsync)
396 {
397 env << "DXVK_ASYNC=1 ";
398 }
400 {
401 env << "__GL_SHADER_DISK_CACHE=1 ";
402 }
404 {
405 env << "__GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 ";
406 }
407
408 // Graphics/Upscaling
409 if (enableFSR)
410 {
411 env << "WINE_FULLSCREEN_FSR=1 ";
412 }
414 {
415 env << "PROTON_DLSS_UPGRADE=1 ";
416 }
418 {
419 env << "PROTON_DLSS_INDICATOR=1 ";
420 }
422 {
423 env << "PROTON_FSR4_UPGRADE=1 ";
424 }
426 {
427 env << "PROTON_FSR4_RDNA3_UPGRADE=1 ";
428 }
430 {
431 env << "PROTON_XESS_UPGRADE=1 ";
432 }
434 {
435 env << "PROTON_NVIDIA_LIBS=1 ";
436 }
437 if (nvidia4000Fix)
438 {
439 env << "PROTON_NVIDIA_LIBS_NO_32BIT=1 ";
440 }
441
442 // Display
443 if (enableGamescope)
444 {
445 env << "ENABLE_GAMESCOPE=1 ";
446 }
447 if (enableHDR)
448 {
449 env << "PROTON_ENABLE_HDR=1 ";
450 }
451 if (enableDXVKHDR)
452 {
453 env << "DXVK_HDR=1 ";
454 }
455 if (enableWayland)
456 {
457 env << "PROTON_ENABLE_WAYLAND=1 ";
458 }
459
460 // Input
461 if (preferSDL)
462 {
463 env << "PROTON_PREFER_SDL=1 ";
464 }
466 {
467 env << "PROTON_NO_STEAMINPUT=1 ";
468 }
469
470 // Debugging
471 if (enableMangoHud)
472 {
473 env << "MANGOHUD=1 ";
474 }
475 if (enableDXVKHud)
476 {
477 env << "DXVK_HUD=compiler ";
478 }
479 if (enableProtonLog)
480 {
481 env << "PROTON_LOG=1 ";
482 }
483 if (fixStuttering)
484 {
485 env << "LD_PRELOAD=\"\" ";
486 }
487
488 // Advanced options
489 if (!protonVerb.empty())
490 {
491 env << "PROTON_VERB=" << ShellUtils::escapeArg(protonVerb) << " ";
492 }
493 if (!radvPerftest.empty())
494 {
495 env << "RADV_PERFTEST=" << ShellUtils::escapeArg(radvPerftest) << " ";
496 }
497
498 return env.str();
499}
500
501// ==============================================================================
502// Steam Game Conversion
503// ==============================================================================
504
506{
507 Game game;
508
509 game.name = name;
510
511 // ==========================================================================
512 // Steam Game Launch Configuration
513 // ==========================================================================
514 // We launch Steam games directly through Proton/native execution for full
515 // control over environment variables, wrappers, and PID tracking. This is
516 // the same approach used by Lutris, Heroic, and other serious launchers.
517 //
518 // For Proton games: <env vars> <wrappers> <proton_path> run <game.exe> <args>
519 // For native games: <env vars> <wrappers> <game_path>/<linux_exe> <args>
520 //
521 // Falls back to "steam -applaunch" if we can't resolve the executable or
522 // Proton path, or if the user explicitly enables the fallback for a game
523 // (e.g., for DRM-protected titles that require Steam's runtime).
524 // ==========================================================================
525
526 bool directLaunchReady = false;
527
528 if (isProtonGame)
529 {
531 game.runnerConfig.runnerType = "proton";
532
533 // Direct Proton launch: requires both game executable and Proton path
534 if (!gameExecutable.empty() && !protonPath.empty() && isInstalled)
535 {
536 // Full path to the game executable within the install directory
537 std::filesystem::path exePath = gamePath / gameExecutable;
538 game.runnerConfig.executablePath = exePath.string();
540 game.runnerConfig.protonVersion = protonPath.string();
541
542 // Set display-friendly runner version
543 std::string protonDir = protonPath.parent_path().filename().string();
544 game.runnerConfig.runnerVersion = protonDir;
545
546 directLaunchReady = true;
547 }
548 else
549 {
550 // Can't resolve direct launch — set reasonable version info anyway
551 if (!protonVersion.empty() && protonVersion != "Unknown (Steam-managed)")
553 else
554 game.runnerConfig.runnerVersion = "Proton";
555 }
556 }
557 else
558 {
560 game.runnerConfig.runnerType = "native";
561 game.runnerConfig.runnerVersion = "";
562
563 // Direct native launch: use the Linux executable if available
564 if (!gameExecutable.empty() && isInstalled)
565 {
566 std::filesystem::path exePath = gamePath / gameExecutable;
567 game.runnerConfig.executablePath = exePath.string();
569 directLaunchReady = true;
570 }
571 }
572
573 // Fall back to steam -applaunch if direct launch can't be set up
574 if (!directLaunchReady)
575 {
576 game.runnerConfig.executablePath = "steam";
577 game.runnerConfig.arguments = "-applaunch " + std::to_string(appId);
578 game.runnerConfig.useSteamLaunch = true;
579 game.runnerConfig.useSteamDefaults = true;
580 }
581
582 game.runnerConfig.workingDirectory = gamePath.string();
583 // Set game source to Steam (where it comes from)
585 // Sync deprecated platform field from runner + source
589 game.installPath = gamePath.string();
590
591 // Store Steam App ID in custom metadata
592 game.metadata.steamAppId = static_cast<int>(appId);
593 game.metadata.isSteamGame = true;
595
596 // Read Steam launch options from localconfig.vdf
598
599 // Import all Steam metadata
606
607 // Copy genres from Steam API if available, otherwise leave existing genres
608 if (!genres.empty())
609 {
610 game.metadata.genres = genres;
611 }
612
613 // Phase 5: Import additional Steam data
616 game.metadata.dlc = dlc;
617
618 // Phase 6: Discover images from Steam's cache
619 // IMPORTANT: Steam stores ALL images in the PRIMARY Steam root's librarycache,
620 // not in individual library folders. Games can be installed anywhere, but
621 // the image cache is always at ~/.steam/steam/appcache/librarycache/
622 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
623 GameImagePaths imagePaths = SteamCDN::discoverImages(appId, steamRoot);
624 game.metadata.imagePaths = imagePaths;
625
626 // Log image discovery results for debugging
627 if (!imagePaths.verticalCover.empty() || !imagePaths.heroImage.empty())
628 {
629 Logger::debug("Images found for {} ({}): cover={}, hero={}", name, appId,
630 imagePaths.verticalCover.empty() ? "no" : "yes",
631 imagePaths.heroImage.empty() ? "no" : "yes");
632 }
633 else
634 {
635 Logger::debug("No images found for {} ({}) in cache: {}", name, appId,
636 (steamRoot / "appcache" / "librarycache").string());
637 }
638
639 // Import Steam's playtime data if available (convert minutes to seconds)
640 if (steamPlaytimeMinutes > 0)
641 {
643 }
644 if (steamLastPlayed > 0)
645 {
647 }
648
649 // Set default CachyOS optimizations for Proton games
650 if (isProtonGame)
651 {
652 // Enable game-performance wrapper by default
653 game.runnerConfig.environmentVariables["GAME_PERFORMANCE"] = "1";
654
655 // Use detected Proton version from Steam, or default to CachyOS SLR
656 if (!protonVersion.empty() && protonVersion != "Unknown (Steam-managed)")
657 {
659 }
660 else
661 {
662 // Fallback to recommended for anti-cheat games
663 game.runnerConfig.protonVersion = "proton-cachyos-slr";
664 }
665 }
666 else
667 {
668 // Native Linux game
669 game.runnerConfig.protonVersion = protonVersion; // Will be "Native Linux"
670 }
671
672 return game;
673}
674
675std::string SteamGame::downloadCoverArt(const std::string& coverArtDir) const
676{
677 // Phase 6: Use Steam's cache directly - no copying or downloading
678 // This method is kept for backwards compatibility but now just discovers
679 // the image path in Steam's cache
680
681 // Cover art cache is always at the primary Steam root, not per-library
683
684 // Return vertical cover if available
685 if (!paths.verticalCover.empty())
686 {
687 Logger::debug("Using Steam cache for cover art: {} ({})", name, appId);
688 return paths.verticalCover;
689 }
690
691 // Fallback: Try to download if not in cache (rare case)
692 std::filesystem::path artDir(coverArtDir);
693 if (!std::filesystem::exists(artDir))
694 {
695 std::filesystem::create_directories(artDir);
696 }
697
698 std::string outputPath = coverArtDir + "/" + std::to_string(appId) + ".jpg";
699
700 // Check if already downloaded in old system
701 if (std::filesystem::exists(outputPath) && std::filesystem::file_size(outputPath) > 0)
702 {
703 return outputPath;
704 }
705
706 // Download from CDN as fallback
708 {
709 Logger::info("Downloaded cover art from CDN: {} ({})", name, appId);
710 return outputPath;
711 }
712
713 return "";
714}
715
716// ==============================================================================
717// ACF Parser Implementation
718// ==============================================================================
719
720std::optional<SteamGame> ACFParser::parseManifest(const std::filesystem::path& acfFilePath,
721 const std::filesystem::path& libraryPath)
722{
723 std::ifstream file(acfFilePath);
724 if (!file.is_open())
725 {
726 Logger::error("Failed to open ACF file: {}", acfFilePath.string());
727 return std::nullopt;
728 }
729
730 std::string content = readVdfContent(file);
731 file.close();
732
733 auto keyValues = parseKeyValues(content);
734
735 SteamGame steamGame;
736
737 // Extract required fields
738 if (keyValues.count("appid"))
739 {
740 try
741 {
742 steamGame.appId = static_cast<uint32_t>(std::stoul(keyValues["appid"]));
743 }
744 catch (...)
745 {
746 Logger::error("Invalid appid in ACF file: {}", acfFilePath.string());
747 return std::nullopt;
748 }
749 }
750 else
751 {
752 Logger::error("Missing appid in ACF file: {}", acfFilePath.string());
753 return std::nullopt;
754 }
755
756 steamGame.name = keyValues.count("name") ? keyValues["name"] : "Unknown Game";
757 steamGame.installDir = keyValues.count("installdir") ? keyValues["installdir"] : "";
758
759 if (steamGame.installDir.empty())
760 {
761 Logger::error("Missing installdir in ACF file: {}", acfFilePath.string());
762 return std::nullopt;
763 }
764
765 // Reject installDir values containing path traversal components
766 if (steamGame.installDir.find("..") != std::string::npos ||
767 steamGame.installDir.find('/') != std::string::npos ||
768 steamGame.installDir.find('\\') != std::string::npos)
769 {
770 Logger::error("[SteamLibraryScanner] Rejected ACF installdir with path traversal: {}",
771 steamGame.installDir);
772 return std::nullopt;
773 }
774
775 steamGame.libraryPath = libraryPath;
776 steamGame.gamePath = libraryPath / "steamapps" / "common" / steamGame.installDir;
777
778 // Parse optional fields
779 if (keyValues.count("SizeOnDisk"))
780 {
781 try
782 {
783 steamGame.sizeOnDisk = std::stoull(keyValues["SizeOnDisk"]);
784 }
785 catch (...)
786 {
787 steamGame.sizeOnDisk = 0;
788 }
789 }
790
791 if (keyValues.count("LastUpdated"))
792 {
793 try
794 {
795 steamGame.lastUpdated = static_cast<time_t>(std::stoll(keyValues["LastUpdated"]));
796 }
797 catch (...)
798 {
799 steamGame.lastUpdated = 0;
800 }
801 }
802
803 // Parse buildid if available
804 if (keyValues.count("buildid"))
805 {
806 steamGame.steamBuildId = keyValues["buildid"];
807 }
808
809 // Parse StateFlags for installation/update status
810 // Steam StateFlags: 4 = fully installed, 1026 = update required, etc.
811 if (keyValues.count("StateFlags"))
812 {
813 try
814 {
815 steamGame.stateFlags = static_cast<uint32_t>(std::stoul(keyValues["StateFlags"]));
816 // StateFlags bit meanings:
817 // 4 = Fully Installed
818 // 2 = Update Required
819 // 1024 = Downloading
820 // etc.
821 steamGame.isDownloading = (steamGame.stateFlags & 1024) != 0;
822 steamGame.isUpdatePending = (steamGame.stateFlags & 2) != 0;
823 }
824 catch (...)
825 {
826 steamGame.stateFlags = 4; // Default to installed
827 }
828 }
829
830 // Parse download/update progress fields
831 if (keyValues.count("BytesDownloaded"))
832 {
833 try
834 {
835 steamGame.bytesDownloaded = std::stoull(keyValues["BytesDownloaded"]);
836 }
837 catch (...)
838 {
839 }
840 }
841 if (keyValues.count("BytesToDownload"))
842 {
843 try
844 {
845 steamGame.bytesToDownload = std::stoull(keyValues["BytesToDownload"]);
846 }
847 catch (...)
848 {
849 }
850 }
851 if (keyValues.count("BytesStaged"))
852 {
853 try
854 {
855 steamGame.bytesStaged = std::stoull(keyValues["BytesStaged"]);
856 }
857 catch (...)
858 {
859 }
860 }
861 if (keyValues.count("BytesToStage"))
862 {
863 try
864 {
865 steamGame.bytesToStage = std::stoull(keyValues["BytesToStage"]);
866 }
867 catch (...)
868 {
869 }
870 }
871
872 // Check if it's a Proton game (has compatdata directory)
873 std::filesystem::path compatDataPath =
874 libraryPath / "steamapps" / "compatdata" / std::to_string(steamGame.appId);
875 steamGame.isProtonGame = std::filesystem::exists(compatDataPath);
876
877 // Set basic Proton version info (detailed detection can be slow, so skip during import)
878 if (steamGame.isProtonGame)
879 {
880 // Just mark as Proton game, actual version can be detected on-demand later
881 steamGame.protonVersion = "Proton (Steam-managed)";
882 }
883 else
884 {
885 steamGame.protonVersion = "Native Linux";
886 }
887
888 return steamGame;
889}
890
891std::string ACFParser::detectProtonVersion(uint32_t appId, const std::filesystem::path& libraryPath)
892{
893 // CompatToolMapping is stored in Steam's global config.vdf, not localconfig.vdf:
894 // ~/.local/share/Steam/config/config.vdf (or equivalent Steam root)
895
896 // Navigate up to Steam root (from library/steamapps back to Steam root)
897 std::filesystem::path steamPath = libraryPath;
898 while (steamPath.has_parent_path() && steamPath.filename() != "Steam")
899 {
900 steamPath = steamPath.parent_path();
901 }
902
903 std::filesystem::path userConfigPath = steamPath / "config" / "config.vdf";
904 if (!std::filesystem::exists(userConfigPath))
905 {
906 return ""; // Can't find config.vdf
907 }
908
909 // Read and parse the config.vdf file
910 std::ifstream file(userConfigPath);
911 if (!file.is_open())
912 {
913 return "";
914 }
915
916 std::string content = readVdfContent(file);
917 file.close();
918
919 // Look for CompatToolMapping section for this appId
920 // Format is:
921 // "CompatToolMapping"
922 // {
923 // "548430" // App ID
924 // {
925 // "name" "proton_experimental"
926 // ...
927 // }
928 // }
929
930 std::string appIdStr = std::to_string(appId);
931 size_t compatToolPos = content.find("\"CompatToolMapping\"");
932 if (compatToolPos == std::string::npos)
933 {
934 return ""; // No compat tool mapping
935 }
936
937 // Find this specific app ID within CompatToolMapping
938 size_t appIdPos = content.find("\"" + appIdStr + "\"", compatToolPos);
939 if (appIdPos == std::string::npos)
940 {
941 return ""; // This app not in compat tool mapping (using Steam default)
942 }
943
944 // Find the "name" field after the app ID
945 size_t namePos = content.find("\"name\"", appIdPos);
946 if (namePos == std::string::npos || namePos > appIdPos + 500)
947 {
948 return ""; // Name not found within reasonable range
949 }
950
951 // Extract the value after "name"
952 size_t valueStart = content.find("\"", namePos + 6);
953 if (valueStart == std::string::npos)
954 {
955 return "";
956 }
957
958 size_t valueEnd = content.find("\"", valueStart + 1);
959 if (valueEnd == std::string::npos)
960 {
961 return "";
962 }
963
964 std::string protonName = content.substr(valueStart + 1, valueEnd - valueStart - 1);
965
966 // Clean up the name to be more human-readable
967 // Examples: "proton_experimental" -> "Proton Experimental"
968 // "proton_8" -> "Proton 8"
969 // "proton-ge-custom" -> "Proton GE Custom"
970
971 if (protonName.find("experimental") != std::string::npos)
972 {
973 return "Proton Experimental";
974 }
975 else if (protonName.find("proton_9") != std::string::npos ||
976 protonName.find("proton 9") != std::string::npos)
977 {
978 return "Proton 9.0";
979 }
980 else if (protonName.find("proton_8") != std::string::npos ||
981 protonName.find("proton 8") != std::string::npos)
982 {
983 return "Proton 8.0";
984 }
985 else if (protonName.find("proton_7") != std::string::npos ||
986 protonName.find("proton 7") != std::string::npos)
987 {
988 return "Proton 7.0";
989 }
990 else if (protonName.find("-ge-") != std::string::npos ||
991 protonName.find("GE") != std::string::npos)
992 {
993 return "Proton GE";
994 }
995 else if (protonName.find("proton") != std::string::npos)
996 {
997 // Generic Proton
998 return "Proton (" + protonName + ")";
999 }
1000
1001 return protonName; // Return raw name if no match
1002}
1003
1004std::map<std::string, std::string> ACFParser::parseKeyValues(const std::string& content)
1005{
1006 std::map<std::string, std::string> keyValues;
1007
1008 // Static regex for better performance - only compiled once
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;
1012
1013 for (; iter != end; ++iter)
1014 {
1015 const std::smatch& match = *iter;
1016 keyValues[match[1].str()] = match[2].str();
1017 }
1018
1019 return keyValues;
1020}
1021
1022std::string ACFParser::extractQuotedValue(const std::string& line)
1023{
1024 size_t first = line.find('"');
1025 if (first == std::string::npos)
1026 return "";
1027
1028 size_t second = line.find('"', first + 1);
1029 if (second == std::string::npos)
1030 return "";
1031
1032 return line.substr(first + 1, second - first - 1);
1033}
1034
1035// ==============================================================================
1036// Steam Library Scanner Implementation
1037// ==============================================================================
1038
1040{
1041 steamPath_ = detectSteamPath();
1042 if (!steamPath_.empty())
1043 {
1044 libraries_ = parseLibraryFolders(steamPath_);
1045 // Always include main Steam library
1046 libraries_.insert(libraries_.begin(), steamPath_);
1047 }
1048}
1049
1051{
1052 std::vector<SteamGame> allGames;
1053
1054 for (const auto& library : libraries_)
1055 {
1056 std::vector<SteamGame> libraryGames = scanLibrary(library);
1057 allGames.insert(allGames.end(), libraryGames.begin(), libraryGames.end());
1058 }
1059
1060 // Read Steam playtime data once for all games
1061 std::map<uint32_t, SteamPlaytimeData> playtimeData = readSteamPlaytimeData();
1062
1063 // Read Cloud Saves data once for all games
1064 std::map<uint32_t, CloudSaveInfo> cloudSaveData = readAllCloudSaveInfo();
1065
1066 // Read Steam user categories once for all games
1067 std::map<uint32_t, std::vector<std::string>> categoriesData = readAllUserCategories();
1068
1069 // Populate playtime data for each game
1070 for (auto& game : allGames)
1071 {
1072 auto it = playtimeData.find(game.appId);
1073 if (it != playtimeData.end())
1074 {
1075 const SteamPlaytimeData& data = it->second;
1076 game.steamPlaytimeMinutes = data.playtimeMinutes;
1077 game.steamLastPlayed = data.lastPlayed;
1078 game.steamPlaytime2Weeks = data.playtime2Weeks;
1079 game.steamLastLaunch = data.lastLaunch;
1080 game.steamLastExit = data.lastExit;
1081 }
1082
1083 // Populate cloud save data
1084 auto cloudIt = cloudSaveData.find(game.appId);
1085 if (cloudIt != cloudSaveData.end())
1086 {
1087 game.cloudSave = cloudIt->second;
1088 }
1089
1090 // Populate user categories
1091 auto catIt = categoriesData.find(game.appId);
1092 if (catIt != categoriesData.end())
1093 {
1094 game.steamUserCategories = catIt->second;
1095 }
1096 }
1097
1098 return allGames;
1099}
1100
1102{
1103 Logger::info("[SteamScanner] Starting scan for all owned games...");
1104
1105 // First, get all installed games with full metadata
1106 std::vector<SteamGame> installedGames = scanAllLibraries();
1107
1108 Logger::info("[SteamScanner] Found {} installed games", installedGames.size());
1109
1110 // Create a set of installed App IDs for quick lookup
1111 std::set<uint32_t> installedAppIds;
1112 for (const auto& game : installedGames)
1113 {
1114 installedAppIds.insert(game.appId);
1115 }
1116
1117 // Parse localconfig.vdf to get all owned App IDs
1118 std::set<uint32_t> ownedAppIds;
1119
1120 // Find Steam userdata directory using SteamPaths for proper Flatpak/Snap support
1121 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
1122 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
1123 {
1124 // Can't find Steam root - just return installed games
1125 return installedGames;
1126 }
1127
1128 std::filesystem::path userdataPath = SteamPaths::getUserDataDirectory();
1129 if (!std::filesystem::exists(userdataPath))
1130 {
1131 return installedGames;
1132 }
1133
1134 // Read localconfig.vdf from the first user directory to get all owned App IDs
1135 for (const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
1136 {
1137 if (!userEntry.is_directory())
1138 continue;
1139
1140 std::filesystem::path configPath = userEntry.path() / "config" / "localconfig.vdf";
1141 if (!std::filesystem::exists(configPath))
1142 continue;
1143
1144 std::ifstream file(configPath);
1145 if (!file.is_open())
1146 continue;
1147
1148 std::string content = readVdfContent(file);
1149 file.close();
1150
1151 // Parse the Apps section to extract all App IDs
1152 size_t appsPos = content.find("\"apps\"");
1153 if (appsPos == std::string::npos)
1154 {
1155 continue;
1156 }
1157
1158 // Find the opening brace for Apps section
1159 size_t appsOpenBrace = content.find('{', appsPos);
1160 if (appsOpenBrace == std::string::npos)
1161 {
1162 continue;
1163 }
1164
1165 // Track brace depth to find the Apps section boundary
1166 int braceDepth = 1;
1167 size_t pos = appsOpenBrace + 1;
1168 size_t appsSectionEnd = content.length();
1169
1170 while (pos < content.length() && braceDepth > 0)
1171 {
1172 if (content[pos] == '{')
1173 braceDepth++;
1174 else if (content[pos] == '}')
1175 {
1176 braceDepth--;
1177 if (braceDepth == 0)
1178 {
1179 appsSectionEnd = pos;
1180 break;
1181 }
1182 }
1183 pos++;
1184 }
1185
1186 // Extract the Apps section
1187 std::string appsSection =
1188 content.substr(appsOpenBrace + 1, appsSectionEnd - appsOpenBrace - 1);
1189
1190 // Parse each App ID using regex
1191 std::regex appIdRegex("\"(\\d+)\"\\s*\\{");
1192 std::sregex_iterator appIdIter(appsSection.begin(), appsSection.end(), appIdRegex);
1193 std::sregex_iterator end;
1194
1195 for (; appIdIter != end; ++appIdIter)
1196 {
1197 const std::smatch& match = *appIdIter;
1198 uint32_t appId = static_cast<uint32_t>(std::stoul(match[1].str()));
1199 ownedAppIds.insert(appId);
1200 }
1201
1202 // We found and parsed a config file, no need to check other users
1203 break;
1204 }
1205
1206 Logger::info("[SteamScanner] Found {} total owned App IDs", ownedAppIds.size());
1207
1208 // Read Steam playtime data once for all games
1209 std::map<uint32_t, SteamPlaytimeData> playtimeData = readSteamPlaytimeData();
1210
1211 // Start with installed games
1212 std::vector<SteamGame> allGames = installedGames;
1213
1214 // Add owned but not installed games (limit to prevent UI overload)
1215 const size_t MAX_UNINSTALLED_GAMES = 100; // Reasonable limit
1216 size_t uninstalledCount = 0;
1217
1218 for (uint32_t appId : ownedAppIds)
1219 {
1220 // Skip if already in installed games
1221 if (installedAppIds.find(appId) != installedAppIds.end())
1222 continue;
1223
1224 // Limit the number of uninstalled games to prevent performance issues
1225 if (uninstalledCount >= MAX_UNINSTALLED_GAMES)
1226 {
1227 Logger::info("[SteamScanner] Reached limit of {} uninstalled games, stopping",
1228 MAX_UNINSTALLED_GAMES);
1229 break;
1230 }
1231
1232 // Create a minimal SteamGame entry for not-installed game
1233 SteamGame game;
1234 game.appId = appId;
1235 game.isInstalled = false;
1236 uninstalledCount++;
1237
1238 // Try to get playtime data
1239 auto playtimeIt = playtimeData.find(appId);
1240 if (playtimeIt != playtimeData.end())
1241 {
1242 // We have playtime data - populate it
1243 const SteamPlaytimeData& data = playtimeIt->second;
1245 game.steamLastPlayed = data.lastPlayed;
1247 game.steamLastLaunch = data.lastLaunch;
1248 game.steamLastExit = data.lastExit;
1249 }
1250
1251 // Try to get the real game name from the pre-loaded cache (instant lookup)
1252 std::string cachedName = fetchGameNameFromCache(appId);
1253 if (!cachedName.empty())
1254 {
1255 game.name = cachedName;
1256 }
1257 else
1258 {
1259 // Use placeholder name - will be fetched async by the app if needed
1260 game.name = "Steam App " + std::to_string(appId);
1261 }
1262
1263 // No installation data
1264 game.installDir = "";
1265 game.libraryPath = "";
1266 game.gamePath = "";
1267 game.sizeOnDisk = 0;
1268 game.lastUpdated = 0;
1269
1270 allGames.push_back(game);
1271 }
1272
1273 Logger::info("[SteamScanner] Scan complete. Total: {} games ({} installed, {} not installed)",
1274 allGames.size(), installedGames.size(), uninstalledCount);
1275
1276 return allGames;
1277}
1278
1279std::vector<std::filesystem::path> SteamLibraryScanner::getLibraryPaths() const
1280{
1281 return libraries_;
1282}
1283
1285{
1286 return !steamPath_.empty();
1287}
1288
1289std::filesystem::path SteamLibraryScanner::detectSteamPath()
1290{
1291 // Use centralized Steam path detection
1293}
1294
1295std::vector<std::filesystem::path>
1296SteamLibraryScanner::parseLibraryFolders(const std::filesystem::path& steamPath)
1297{
1298 std::vector<std::filesystem::path> libraries;
1299
1300 std::filesystem::path libraryFoldersPath = steamPath / "steamapps" / "libraryfolders.vdf";
1301
1302 if (!std::filesystem::exists(libraryFoldersPath))
1303 {
1304 return libraries;
1305 }
1306
1307 std::ifstream file(libraryFoldersPath);
1308 if (!file.is_open())
1309 {
1310 return libraries;
1311 }
1312
1313 std::string line;
1314 std::regex pathRegex("\"path\"\\s+\"([^\"]+)\"");
1315
1316 while (std::getline(file, line))
1317 {
1318 std::smatch match;
1319 if (std::regex_search(line, match, pathRegex))
1320 {
1321 std::string libraryPath = match[1].str();
1322 if (std::filesystem::exists(libraryPath))
1323 {
1324 libraries.push_back(libraryPath);
1325 }
1326 }
1327 }
1328
1329 file.close();
1330 return libraries;
1331}
1332
1333std::vector<SteamGame> SteamLibraryScanner::scanLibrary(const std::filesystem::path& libraryPath)
1334{
1335 std::vector<SteamGame> games;
1336
1337 std::filesystem::path steamappsPath = libraryPath / "steamapps";
1338 if (!std::filesystem::exists(steamappsPath))
1339 {
1340 return games;
1341 }
1342
1343 // Scan for appmanifest files
1344 for (const auto& entry : std::filesystem::directory_iterator(steamappsPath))
1345 {
1346 if (!entry.is_regular_file())
1347 continue;
1348
1349 std::string filename = entry.path().filename().string();
1350
1351 // Check if it's an appmanifest file (C++17 compatible)
1352 if (filename.rfind("appmanifest_", 0) == 0 && filename.size() >= 4 &&
1353 filename.substr(filename.size() - 4) == ".acf")
1354 {
1355 auto steamGame = ACFParser::parseManifest(entry.path(), libraryPath);
1356 if (steamGame.has_value())
1357 {
1358 SteamGame game = steamGame.value();
1359
1360 // Parse DLC information from this ACF file
1361 game.dlc = readDLCFromACF(entry.path(), libraryPath);
1362
1363 games.push_back(game);
1364 }
1365 }
1366 }
1367
1368 return games;
1369}
1370
1371// ==============================================================================
1372// Steam Launch Command Builder
1373// ==============================================================================
1374
1376 const CachyOSGameConfig& config)
1377{
1378 std::ostringstream command;
1379
1380 // Add environment variables
1381 std::string envVars = config.buildEnvVars();
1382 if (!envVars.empty())
1383 {
1384 command << envVars;
1385 }
1386
1387 // Add game-performance wrapper if enabled
1388 if (config.useGamePerformanceWrapper)
1389 {
1390 command << "game-performance ";
1391 }
1392
1393 // Use Steam launch method for Steam games
1394 if (game.metadata.isSteamGame && game.metadata.steamAppId > 0)
1395 {
1396 // Use -applaunch for proper Steam integration and overlay support
1397 // This method ensures Steam overlay works correctly
1398 command << "steam -applaunch " << game.metadata.steamAppId;
1399
1400 // Add any additional launch options if specified
1401 // Note: Steam launch options should be set in Steam's properties for the game
1402 // but we can append them here if needed for testing
1403 }
1404 else
1405 {
1406 // Fallback to direct execution
1407 command << game.runnerConfig.executablePath;
1408 if (!game.runnerConfig.arguments.empty())
1409 {
1410 command << " " << game.runnerConfig.arguments;
1411 }
1412 }
1413
1414 return command.str();
1415}
1416
1417std::string SteamLaunchBuilder::buildSteamURI(uint32_t appId)
1418{
1419 return "steam://rungameid/" + std::to_string(appId);
1420}
1421
1422// ==============================================================================
1423// Steam Launch Options Parser
1424// ==============================================================================
1425
1427{
1429 result.rawString = launchOptions;
1430
1431 if (launchOptions.empty())
1432 {
1433 return result;
1434 }
1435
1436 // Split by spaces, but respect quotes
1437 std::vector<std::string> tokens;
1438 std::string currentToken;
1439 bool inQuotes = false;
1440
1441 for (size_t i = 0; i < launchOptions.length(); i++)
1442 {
1443 char c = launchOptions[i];
1444
1445 if (c == '"')
1446 {
1447 inQuotes = !inQuotes;
1448 }
1449 else if (c == ' ' && !inQuotes)
1450 {
1451 if (!currentToken.empty())
1452 {
1453 tokens.push_back(currentToken);
1454 currentToken.clear();
1455 }
1456 }
1457 else
1458 {
1459 currentToken += c;
1460 }
1461 }
1462
1463 if (!currentToken.empty())
1464 {
1465 tokens.push_back(currentToken);
1466 }
1467
1468 // Parse tokens - everything before %command% is either env vars or wrappers
1469 // Everything after %command% is game arguments
1470 bool afterCommand = false;
1471
1472 for (const auto& token : tokens)
1473 {
1474 if (token == "%command%")
1475 {
1476 afterCommand = true;
1477 continue;
1478 }
1479
1480 if (afterCommand)
1481 {
1482 // Game arguments
1483 result.gameArguments.push_back(token);
1484 }
1485 else
1486 {
1487 // Check if it's an environment variable (contains =)
1488 size_t eqPos = token.find('=');
1489 if (eqPos != std::string::npos && eqPos > 0 && eqPos < token.length() - 1)
1490 {
1491 // It's an environment variable
1492 std::string key = token.substr(0, eqPos);
1493 std::string value = token.substr(eqPos + 1);
1494 result.environmentVariables[key] = value;
1495 }
1496 else
1497 {
1498 // It's a wrapper command
1499 result.wrappers.push_back(token);
1500 }
1501 }
1502 }
1503
1504 return result;
1505}
1506
1508{
1509 return rawString.empty() ||
1510 (environmentVariables.empty() && wrappers.empty() && gameArguments.empty());
1511}
1512
1513// ==============================================================================
1514// Steam Configuration Reading
1515// ==============================================================================
1516
1518{
1519 // Find Steam userdata directory
1520 // Centralised Steam-root detection via SteamPaths — handles native,
1521 // Flatpak (~/.var/app/com.valvesoftware.Steam/...), and Snap layouts.
1522 // Previously every caller hand-rolled `~/.steam/root` + `~/.local/share/Steam`
1523 // fallback, which silently broke for Flatpak users.
1524 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
1525 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
1526 {
1527 Logger::error("Steam root directory not found");
1528 return "";
1529 }
1530
1531 // Find userdata directory - typically there's only one user ID subdirectory
1532 std::filesystem::path userdataPath = steamRoot / "userdata";
1533 if (!std::filesystem::exists(userdataPath))
1534 {
1535 Logger::error("Steam userdata directory not found");
1536 return "";
1537 }
1538
1539 // Look for config in each user directory (usually just one)
1540 for (const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
1541 {
1542 if (!userEntry.is_directory())
1543 continue;
1544
1545 std::filesystem::path configPath = userEntry.path() / "config" / "localconfig.vdf";
1546 if (!std::filesystem::exists(configPath))
1547 continue;
1548
1549 // Parse the VDF file to find launch options
1550 std::ifstream file(configPath);
1551 if (!file.is_open())
1552 continue;
1553
1554 std::string line;
1555 std::string appIdStr = "\"" + std::to_string(appId) + "\"";
1556 bool foundApp = false;
1557 int appBraceDepth = 0;
1558 bool inAppSection = false;
1559
1560 while (std::getline(file, line))
1561 {
1562 // Trim whitespace
1563 size_t start = line.find_first_not_of(" \t");
1564 if (start == std::string::npos)
1565 continue;
1566 std::string trimmed = line.substr(start);
1567
1568 // If we found our app ID, mark it
1569 if (!foundApp && trimmed.find(appIdStr) == 0)
1570 {
1571 foundApp = true;
1572 // Check if there's a brace on the same line or next line
1573 if (line.find('{') != std::string::npos)
1574 {
1575 inAppSection = true;
1576 appBraceDepth = 1;
1577 }
1578 continue;
1579 }
1580
1581 // If we just found the app, look for opening brace
1582 if (foundApp && !inAppSection && line.find('{') != std::string::npos)
1583 {
1584 inAppSection = true;
1585 appBraceDepth = 1;
1586 continue;
1587 }
1588
1589 // Track braces within our app section
1590 if (inAppSection)
1591 {
1592 // Check for LaunchOptions BEFORE brace counting to avoid misidentifying
1593 // a '}' inside the launch option value as a section-closing brace
1594 if (trimmed.find("\"LaunchOptions\"") == 0)
1595 {
1596 // Extract value between quotes after "LaunchOptions"
1597 // Find the position after "LaunchOptions" (length = 15)
1598 size_t keyEnd = line.find("\"LaunchOptions\"") + 15;
1599 // Now find the opening quote of the value
1600 size_t valueStart = line.find('\"', keyEnd);
1601 if (valueStart != std::string::npos)
1602 {
1603 // Find the closing quote by scanning for unescaped '"'
1604 size_t valueEnd = valueStart + 1;
1605 while (valueEnd < line.size())
1606 {
1607 if (line[valueEnd] == '\\')
1608 {
1609 valueEnd += 2; // skip escape sequence
1610 continue;
1611 }
1612 if (line[valueEnd] == '"')
1613 break;
1614 valueEnd++;
1615 }
1616 if (valueEnd < line.size())
1617 {
1618 std::string launchOpts =
1619 line.substr(valueStart + 1, valueEnd - valueStart - 1);
1620 file.close();
1621 return launchOpts;
1622 }
1623 }
1624 file.close();
1625 return "";
1626 }
1627
1628 // Count braces (only for non-key-value lines)
1629 bool inQuote = false;
1630 for (size_t ci = 0; ci < line.size(); ci++)
1631 {
1632 char c = line[ci];
1633 if (c == '"' && (ci == 0 || line[ci - 1] != '\\'))
1634 inQuote = !inQuote;
1635 if (inQuote)
1636 continue;
1637 if (c == '{')
1638 appBraceDepth++;
1639 else if (c == '}')
1640 {
1641 appBraceDepth--;
1642 if (appBraceDepth == 0)
1643 {
1644 // Exited our app section without finding LaunchOptions
1645 file.close();
1646 return "";
1647 }
1648 }
1649 }
1650 }
1651 }
1652
1653 file.close();
1654 }
1655
1656 return ""; // Not found
1657}
1658
1659// ==============================================================================
1660// VDF File Write Helpers
1661// ==============================================================================
1662
1663bool SteamLibraryScanner::isFileLocked(const std::filesystem::path& filePath)
1664{
1665 // Try to open file for reading/writing to check if it's locked
1666 FILE* fp = fopen(filePath.c_str(), "r+");
1667 if (!fp)
1668 {
1669 // Can't open file - might not exist or we lack permissions
1670 // If file doesn't exist, it's not locked
1671 if (!std::filesystem::exists(filePath))
1672 {
1673 return false;
1674 }
1675 // If we can't open for r+ but file exists, try read-only
1676 fp = fopen(filePath.c_str(), "r");
1677 if (!fp)
1678 {
1679 return true; // Can't open at all - assume locked
1680 }
1681 }
1682
1683 // Try to get exclusive write lock (non-blocking)
1684 struct flock fl;
1685 fl.l_type = F_WRLCK; // Write lock
1686 fl.l_whence = SEEK_SET;
1687 fl.l_start = 0;
1688 fl.l_len = 0; // Lock entire file
1689 fl.l_pid = getpid();
1690
1691 // Non-blocking lock attempt - F_SETLK returns immediately
1692 int ret = fcntl(fileno(fp), F_SETLK, &fl);
1693 bool isLocked = (ret == -1 && (errno == EACCES || errno == EAGAIN));
1694
1695 // If we got the lock, release it immediately
1696 if (!isLocked)
1697 {
1698 fl.l_type = F_UNLCK;
1699 fcntl(fileno(fp), F_SETLK, &fl);
1700 }
1701
1702 fclose(fp);
1703 return isLocked;
1704}
1705
1706bool SteamLibraryScanner::validateVDFFile(const std::filesystem::path& filePath)
1707{
1708 // Check file exists and is not empty
1709 if (!std::filesystem::exists(filePath))
1710 {
1711 Logger::error("[VDF Validation] File does not exist: {}", filePath.string());
1712 return false;
1713 }
1714
1715 std::error_code fsEc;
1716 auto fileSize = std::filesystem::file_size(filePath, fsEc);
1717 if (fsEc)
1718 {
1719 Logger::error("[VDF Validation] Cannot get file size: {}", filePath.string());
1720 return false;
1721 }
1722 if (fileSize == 0)
1723 {
1724 Logger::error("[VDF Validation] File is empty: {}", filePath.string());
1725 return false;
1726 }
1727
1728 if (fileSize > SteamConstants::VDF_MAX_FILE_SIZE)
1729 {
1730 Logger::error("[VDF Validation] File exceeds max size: {}", filePath.string());
1731 return false;
1732 }
1733
1734 // Basic structure validation - check for balanced braces
1735 std::ifstream file(filePath);
1736 if (!file.is_open())
1737 {
1738 Logger::error("[VDF Validation] Could not open file for validation: {}", filePath.string());
1739 return false;
1740 }
1741
1742 // Balance check that ignores braces inside quoted values, and also
1743 // honours the `\\` and `\"` escapes inside those values. A launch
1744 // option like `"{ -nohmd }"` is legal KeyValues but the prior naive
1745 // counter rejected it, falsely flagging valid files as corrupt and
1746 // pushing them into the backup-restore path.
1747 int braceCount = 0;
1748 bool inString = false;
1749 bool escapeNext = false;
1750 std::string line;
1751 while (std::getline(file, line))
1752 {
1753 for (char c : line)
1754 {
1755 if (escapeNext)
1756 {
1757 // Consume any character following a backslash without
1758 // changing string-state. Per the KeyValues spec the only
1759 // legal followers are `"`, `\\`, `n`, `t`, `r`, but other
1760 // bytes are tolerated by Steam's parser.
1761 escapeNext = false;
1762 continue;
1763 }
1764 if (inString)
1765 {
1766 if (c == '\\')
1767 escapeNext = true;
1768 else if (c == '"')
1769 inString = false;
1770 continue;
1771 }
1772 // Outside a quoted value:
1773 if (c == '"')
1774 inString = true;
1775 else if (c == '{')
1776 braceCount++;
1777 else if (c == '}')
1778 braceCount--;
1779 }
1780 // KeyValues strings cannot span lines per the spec; getline()
1781 // would have closed the value at the implicit newline. Reset
1782 // inString so a stray opening-quote at end-of-line doesn't
1783 // poison the rest of the file.
1784 inString = false;
1785 escapeNext = false;
1786 }
1787 file.close();
1788
1789 if (braceCount != 0)
1790 {
1791 Logger::error("[VDF Validation] Unbalanced braces in file: {}", filePath.string());
1792 return false;
1793 }
1794
1795 return true;
1796}
1797
1798bool SteamLibraryScanner::writeVDFFileWithRetry(const std::filesystem::path& filePath,
1799 const std::vector<std::string>& lines,
1800 const std::filesystem::path& backupPath)
1801{
1802 const int maxAttempts = 3;
1803
1804 for (int attempt = 0; attempt < maxAttempts; attempt++)
1805 {
1806 if (attempt > 0)
1807 {
1808 Logger::info("[VDF Write] Retry attempt {} of {}", attempt + 1, maxAttempts);
1809 }
1810
1811 // Check if file is locked
1812 if (isFileLocked(filePath))
1813 {
1814 Logger::info("[VDF Write] File is locked, waiting...");
1815 // Wait with exponential backoff
1816 std::this_thread::sleep_for(std::chrono::milliseconds(100 * (1 << attempt)));
1817 continue;
1818 }
1819
1820 // Attempt write
1821 std::ofstream outFile(filePath);
1822 if (!outFile.is_open())
1823 {
1824 Logger::error("[VDF Write] Failed to open file for writing: {}", filePath.string());
1825
1826 // Wait before retry
1827 std::this_thread::sleep_for(std::chrono::milliseconds(100 * (1 << attempt)));
1828 continue;
1829 }
1830
1831 // Write all lines
1832 for (const auto& line : lines)
1833 {
1834 outFile << line << "\n";
1835 }
1836 outFile.close();
1837
1838 // Validate the write
1839 if (validateVDFFile(filePath))
1840 {
1841 Logger::info("[VDF Write] Successfully wrote and validated: {}", filePath.string());
1842 return true;
1843 }
1844
1845 Logger::error("[VDF Write] Validation failed after write attempt {}", attempt + 1);
1846
1847 // Restore from backup if validation failed
1848 if (std::filesystem::exists(backupPath))
1849 {
1850 try
1851 {
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");
1855 }
1856 catch (const std::exception& e)
1857 {
1858 Logger::error("[VDF Write] Failed to restore from backup: {}", e.what());
1859 }
1860 }
1861
1862 // Wait before next attempt
1863 if (attempt < maxAttempts - 1)
1864 {
1865 std::this_thread::sleep_for(std::chrono::milliseconds(100 * (1 << attempt)));
1866 }
1867 }
1868
1869 Logger::error("[VDF Write] Failed to write file after {} attempts: {}", maxAttempts,
1870 filePath.string());
1871 return false;
1872}
1873
1874// Escape a string value for inclusion in a Steam KeyValues / VDF text file.
1875//
1876// Steam's KeyValues format (https://developer.valvesoftware.com/wiki/KeyValues)
1877// supports the following escapes inside double-quoted values:
1878// \\ -> backslash
1879// \" -> double-quote
1880// \n -> newline
1881// \t -> tab
1882// \r -> carriage return
1883// Any other byte passes through. The previous implementation only handled
1884// `"` and `\\`, so a launch option like `DXVK_HUD=devinfo\nfps` (newline) was
1885// written literally — corrupting the file at the next line break. Same for
1886// any tab character that found its way into a name or argument.
1887static std::string vdfEscapeValue(const std::string& s)
1888{
1889 std::string out;
1890 out.reserve(s.size() + 4);
1891 for (char c : s)
1892 {
1893 switch (c)
1894 {
1895 case '\\':
1896 out += "\\\\";
1897 break;
1898 case '"':
1899 out += "\\\"";
1900 break;
1901 case '\n':
1902 out += "\\n";
1903 break;
1904 case '\t':
1905 out += "\\t";
1906 break;
1907 case '\r':
1908 out += "\\r";
1909 break;
1910 default:
1911 out += c;
1912 break;
1913 }
1914 }
1915 return out;
1916}
1917
1918bool SteamLibraryScanner::writeSteamLaunchOptions(uint32_t appId, const std::string& launchOptions)
1919{
1920 // Find Steam userdata directory (Flatpak/Snap-aware via SteamPaths).
1921 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
1922 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
1923 {
1924 Logger::error("Steam root directory not found");
1925 return false;
1926 }
1927
1928 std::filesystem::path userdataPath = steamRoot / "userdata";
1929 if (!std::filesystem::exists(userdataPath))
1930 {
1931 Logger::error("Steam userdata directory not found");
1932 return false;
1933 }
1934
1935 // Look for config in each user directory
1936 for (const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
1937 {
1938 if (!userEntry.is_directory())
1939 continue;
1940
1941 std::filesystem::path configPath = userEntry.path() / "config" / "localconfig.vdf";
1942 if (!std::filesystem::exists(configPath))
1943 continue;
1944
1945 // Read entire file into memory
1946 std::ifstream inFile(configPath);
1947 if (!inFile.is_open())
1948 continue;
1949
1950 std::vector<std::string> lines;
1951 std::string line;
1952 while (std::getline(inFile, line))
1953 {
1954 lines.push_back(line);
1955 }
1956 inFile.close();
1957
1958 // First, find the "apps" section within Software/Valve/Steam
1959 bool inAppsSection = false;
1960 size_t appsLineStart = 0;
1961
1962 for (size_t i = 0; i < lines.size(); i++)
1963 {
1964 size_t start = lines[i].find_first_not_of(" \t");
1965 if (start == std::string::npos)
1966 continue;
1967 std::string trimmed = lines[i].substr(start);
1968
1969 if (trimmed.find("\"apps\"") == 0)
1970 {
1971 inAppsSection = true;
1972 appsLineStart = i;
1973 break;
1974 }
1975 }
1976
1977 if (!inAppsSection)
1978 {
1979 Logger::error("Could not find apps section in localconfig.vdf");
1980 continue;
1981 }
1982
1983 // Now find and update the app section within the apps section
1984 std::string appIdStr = "\"" + std::to_string(appId) + "\"";
1985 bool foundApp = false;
1986 bool modified = false;
1987 int appBraceDepth = 0;
1988 bool inAppSection = false;
1989
1990 for (size_t i = appsLineStart; i < lines.size(); i++)
1991 {
1992 std::string& currentLine = lines[i];
1993
1994 // Trim to check content
1995 size_t start = currentLine.find_first_not_of(" \t");
1996 if (start == std::string::npos)
1997 continue;
1998 std::string trimmed = currentLine.substr(start);
1999
2000 // If we found our app ID (must be after apps section started)
2001 if (!foundApp && trimmed.find(appIdStr) == 0)
2002 {
2003 foundApp = true;
2004 if (currentLine.find('{') != std::string::npos)
2005 {
2006 inAppSection = true;
2007 appBraceDepth = 1;
2008 }
2009 continue;
2010 }
2011
2012 // Look for opening brace after app ID
2013 if (foundApp && !inAppSection && currentLine.find('{') != std::string::npos)
2014 {
2015 inAppSection = true;
2016 appBraceDepth = 1;
2017 continue;
2018 }
2019
2020 // Within our app section
2021 if (inAppSection)
2022 {
2023 // Check for LaunchOptions BEFORE brace counting to avoid misidentifying
2024 // a '}' inside the launch option value as a section-closing brace
2025 if (!modified && trimmed.find("\"LaunchOptions\"") == 0)
2026 {
2027 // Replace this line with updated launch options - preserve indentation
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\"" +
2031 vdfEscapeValue(launchOptions) + "\"";
2032 modified = true;
2033 continue;
2034 }
2035
2036 // Count braces, skipping characters inside quoted strings
2037 bool inQuote = false;
2038 for (size_t ci = 0; ci < currentLine.size(); ci++)
2039 {
2040 char c = currentLine[ci];
2041 if (c == '"' && (ci == 0 || currentLine[ci - 1] != '\\'))
2042 inQuote = !inQuote;
2043 if (inQuote)
2044 continue;
2045 if (c == '{')
2046 appBraceDepth++;
2047 else if (c == '}')
2048 {
2049 appBraceDepth--;
2050 if (appBraceDepth == 0)
2051 {
2052 // End of app section - insert LaunchOptions if not found
2053 if (!modified)
2054 {
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\"" +
2058 vdfEscapeValue(launchOptions) + "\"";
2059 lines.insert(lines.begin() + static_cast<std::ptrdiff_t>(i),
2060 newLine);
2061 modified = true;
2062 }
2063 break;
2064 }
2065 }
2066 }
2067
2068 if (appBraceDepth == 0)
2069 break;
2070 }
2071 }
2072
2073 if (!modified)
2074 {
2075 Logger::error("Could not find app {} in localconfig.vdf", appId);
2076 continue;
2077 }
2078
2079 // ==================================================================
2080 // Create backup before writing
2081 // ==================================================================
2082 std::filesystem::path backupPath = configPath;
2083 backupPath += ".backup";
2084
2085 try
2086 {
2087 std::filesystem::copy_file(configPath, backupPath,
2088 std::filesystem::copy_options::overwrite_existing);
2089 Logger::info("Created backup: {}", backupPath.string());
2090 }
2091 catch (const std::exception& e)
2092 {
2093 Logger::warn("Failed to create backup: {}", e.what());
2094 // Continue anyway - backup is optional
2095 }
2096
2097 // ==================================================================
2098 // Write back to file with retry logic
2099 // ==================================================================
2100 if (!writeVDFFileWithRetry(configPath, lines, backupPath))
2101 {
2102 Logger::error("Failed to write localconfig.vdf after retries");
2103 return false;
2104 }
2105
2106 // Verify final write was successful
2107 if (std::filesystem::file_size(configPath) == 0)
2108 {
2109 Logger::error("Error: Final verification shows empty file! Restoring backup...");
2110
2111 // Restore from backup
2112 if (std::filesystem::exists(backupPath))
2113 {
2114 try
2115 {
2116 std::filesystem::copy_file(backupPath, configPath,
2117 std::filesystem::copy_options::overwrite_existing);
2118 Logger::info("Restored from backup after detecting empty file");
2119 }
2120 catch (const std::exception& e)
2121 {
2122 Logger::error("Failed to restore from backup: {}", e.what());
2123 }
2124 }
2125 return false;
2126 }
2127
2128 Logger::info("Successfully wrote launch options for app {}", appId);
2129 Logger::info("NOTE: Steam must be restarted for changes to take effect");
2130
2131 return true;
2132 }
2133
2134 Logger::error("Could not find localconfig.vdf");
2135 return false;
2136}
2137
2138std::map<uint32_t, SteamLibraryScanner::SteamPlaytimeData>
2140{
2141 std::map<uint32_t, SteamPlaytimeData> playtimeData;
2142
2143 // Find Steam userdata directory (Flatpak/Snap-aware via SteamPaths).
2144 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
2145 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
2146 {
2147 Logger::error("Steam root directory not found");
2148 return playtimeData;
2149 }
2150
2151 std::filesystem::path userdataPath = steamRoot / "userdata";
2152 if (!std::filesystem::exists(userdataPath))
2153 {
2154 Logger::error("Steam userdata directory not found");
2155 return playtimeData;
2156 }
2157
2158 // Read localconfig.vdf from the first user directory
2159 for (const auto& userEntry : std::filesystem::directory_iterator(userdataPath))
2160 {
2161 if (!userEntry.is_directory())
2162 continue;
2163
2164 std::filesystem::path configPath = userEntry.path() / "config" / "localconfig.vdf";
2165 if (!std::filesystem::exists(configPath))
2166 continue;
2167
2168 std::ifstream file(configPath);
2169 if (!file.is_open())
2170 continue;
2171
2172 std::string content = readVdfContent(file);
2173 file.close();
2174
2175 // Parse the Apps section within UserLocalConfigStore
2176 // Format:
2177 // "UserLocalConfigStore"
2178 // {
2179 // "Software"
2180 // {
2181 // "Valve"
2182 // {
2183 // "Steam"
2184 // {
2185 // "Apps"
2186 // {
2187 // "440" // App ID
2188 // {
2189 // "Playtime" "7409"
2190 // "LastPlayed" "1767510428"
2191 // }
2192 // }
2193 // }
2194 // }
2195 // }
2196 // }
2197
2198 // Note: The section is lowercase "apps" not "Apps"
2199 size_t appsPos = content.find("\"apps\"");
2200 if (appsPos == std::string::npos)
2201 {
2202 continue; // No apps section found
2203 }
2204
2205 // Find the opening brace for Apps section
2206 size_t appsOpenBrace = content.find('{', appsPos);
2207 if (appsOpenBrace == std::string::npos)
2208 {
2209 continue;
2210 }
2211
2212 // Track brace depth to find the Apps section boundary
2213 int braceDepth = 1;
2214 size_t pos = appsOpenBrace + 1;
2215 size_t appsSectionEnd = content.length();
2216
2217 while (pos < content.length() && braceDepth > 0)
2218 {
2219 if (content[pos] == '{')
2220 braceDepth++;
2221 else if (content[pos] == '}')
2222 {
2223 braceDepth--;
2224 if (braceDepth == 0)
2225 {
2226 appsSectionEnd = pos;
2227 break;
2228 }
2229 }
2230 pos++;
2231 }
2232
2233 // Extract the Apps section
2234 std::string appsSection =
2235 content.substr(appsOpenBrace + 1, appsSectionEnd - appsOpenBrace - 1);
2236
2237 // Parse each app entry with regex - static for better performance
2238 // Match App ID followed by various playtime fields
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);
2248
2249 std::sregex_iterator appIdIter(appsSection.begin(), appsSection.end(), appIdRegex);
2250 std::sregex_iterator end;
2251
2252 for (; appIdIter != end; ++appIdIter)
2253 {
2254 const std::smatch& match = *appIdIter;
2255 uint32_t appId = static_cast<uint32_t>(std::stoul(match[1].str()));
2256
2257 // Get the substring for this app entry (until next app ID or end of section)
2258 size_t entryStart = static_cast<size_t>(match.position() + match.length());
2259 size_t entryEnd = appsSection.length();
2260
2261 // Find the closing brace for this app entry
2262 int entryBraceDepth = 1;
2263 size_t entryPos = entryStart;
2264 while (entryPos < appsSection.length() && entryBraceDepth > 0)
2265 {
2266 if (appsSection[entryPos] == '{')
2267 entryBraceDepth++;
2268 else if (appsSection[entryPos] == '}')
2269 {
2270 entryBraceDepth--;
2271 if (entryBraceDepth == 0)
2272 {
2273 entryEnd = entryPos;
2274 break;
2275 }
2276 }
2277 entryPos++;
2278 }
2279
2280 std::string appEntry = appsSection.substr(entryStart, entryEnd - entryStart);
2281
2282 // Create data struct
2283 SteamPlaytimeData data;
2284
2285 // Extract all playtime fields
2286 std::smatch playtimeMatch;
2287 if (std::regex_search(appEntry, playtimeMatch, playtimeRegex))
2288 {
2289 data.playtimeMinutes = static_cast<uint32_t>(std::stoul(playtimeMatch[1].str()));
2290 }
2291
2292 std::smatch lastPlayedMatch;
2293 if (std::regex_search(appEntry, lastPlayedMatch, lastPlayedRegex))
2294 {
2295 data.lastPlayed = static_cast<time_t>(std::stoull(lastPlayedMatch[1].str()));
2296 }
2297
2298 std::smatch playtime2wksMatch;
2299 if (std::regex_search(appEntry, playtime2wksMatch, playtime2wksRegex))
2300 {
2301 data.playtime2Weeks = static_cast<uint32_t>(std::stoul(playtime2wksMatch[1].str()));
2302 }
2303
2304 std::smatch lastLaunchMatch;
2305 if (std::regex_search(appEntry, lastLaunchMatch, lastLaunchRegex))
2306 {
2307 data.lastLaunch = static_cast<time_t>(std::stoull(lastLaunchMatch[1].str()));
2308 }
2309
2310 std::smatch lastExitMatch;
2311 if (std::regex_search(appEntry, lastExitMatch, lastExitRegex))
2312 {
2313 data.lastExit = static_cast<time_t>(std::stoull(lastExitMatch[1].str()));
2314 }
2315
2316 // Store the data
2317 playtimeData[appId] = data;
2318 }
2319
2320 // We found and parsed a config file, no need to check other users
2321 break;
2322 }
2323
2324 return playtimeData;
2325}
2326
2327// ==============================================================================
2328// Steam Web API - App Name Cache (FAST batch lookup)
2329// ==============================================================================
2330
2331// Static cache for app names - loaded once, used for all lookups
2332// Using unordered_map for O(1) lookup instead of O(log n)
2333static std::unordered_map<uint32_t, std::string> s_appNameCache;
2334static bool s_appNameCacheLoaded = false;
2335static std::mutex s_appNameCacheMutex;
2336
2337// Helper function to load app names from local appinfo.vdf (binary format)
2338static size_t loadAppNamesFromLocalCache(const std::filesystem::path& steamPath)
2339{
2340 // Path to appinfo.vdf binary cache
2341 std::filesystem::path appinfoPath = steamPath / "appcache" / "appinfo.vdf";
2342
2343 if (!std::filesystem::exists(appinfoPath))
2344 {
2345 Logger::warn("[SteamCache] appinfo.vdf not found at {}", appinfoPath.string());
2346 return 0;
2347 }
2348
2349 // Read the file
2350 std::ifstream file(appinfoPath, std::ios::binary);
2351 if (!file)
2352 {
2353 Logger::warn("[SteamCache] Failed to open appinfo.vdf");
2354 return 0;
2355 }
2356
2357 // Get file size
2358 file.seekg(0, std::ios::end);
2359 size_t fileSize = static_cast<size_t>(file.tellg());
2360 file.seekg(0, std::ios::beg);
2361
2362 if (fileSize < 16)
2363 {
2364 Logger::warn("[SteamCache] appinfo.vdf too small");
2365 return 0;
2366 }
2367
2368 // Read entire file into memory
2369 std::vector<uint8_t> data(fileSize);
2370 file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(fileSize));
2371 file.close();
2372
2373 // Check magic number. v29 (0x07564429, June 2024+) uses a string table for
2374 // keys; v27/v28 (0x07564427/0x07564428) use inline keys. This lightweight
2375 // name-pattern scanner depends on v29's string-index encoding, so older
2376 // formats are recognised but skipped with an actionable message rather
2377 // than a generic "Unknown format" warning.
2378 uint32_t magic;
2379 std::memcpy(&magic, data.data(), sizeof(magic));
2380 if (magic == 0x07564427 || magic == 0x07564428)
2381 {
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.",
2385 magic);
2386 return 0;
2387 }
2388 if (magic != 0x07564429)
2389 {
2390 Logger::warn("[SteamCache] Unknown appinfo.vdf format: 0x{:08x}", magic);
2391 return 0;
2392 }
2393
2394 // Parse app records
2395 // Format: magic(4) + universe(4), then records:
2396 // appid(4) + size(4) + data(size-8 bytes that include header fields)
2397 size_t pos = 8; // Skip header
2398 size_t count = 0;
2399
2400 // Name pattern in VDF binary: 0x01 0x04 0x00 0x00 0x00 followed by null-terminated string
2401 // This is: type=string(01), key_index=4 (which maps to "name")
2402 const uint8_t namePattern[] = {0x01, 0x04, 0x00, 0x00, 0x00};
2403 const size_t patternLen = 5;
2404
2405 while (pos + 8 < fileSize)
2406 {
2407 uint32_t appId;
2408 std::memcpy(&appId, data.data() + pos, sizeof(appId));
2409 if (appId == 0)
2410 break;
2411
2412 uint32_t size;
2413 std::memcpy(&size, data.data() + pos + 4, sizeof(size));
2414
2415 // Skip entries with size 0
2416 if (size == 0)
2417 {
2418 pos += 8;
2419 continue;
2420 }
2421
2422 size_t recordEnd = pos + 8 + size;
2423 if (recordEnd > fileSize)
2424 break;
2425
2426 // Search for name pattern within this record
2427 size_t recordStart = pos;
2428 size_t recordLen = recordEnd - recordStart;
2429
2430 for (size_t i = 0; i + patternLen < recordLen; ++i)
2431 {
2432 if (std::memcmp(data.data() + recordStart + i, namePattern, patternLen) == 0)
2433 {
2434 // Found pattern, read null-terminated string after it
2435 size_t valueStart = recordStart + i + patternLen;
2436 size_t valueEnd = valueStart;
2437
2438 // Find null terminator
2439 while (valueEnd < recordEnd && data[valueEnd] != 0)
2440 {
2441 valueEnd++;
2442 }
2443
2444 if (valueEnd > valueStart && valueEnd - valueStart < 300)
2445 {
2446 std::string name(reinterpret_cast<char*>(data.data() + valueStart),
2447 valueEnd - valueStart);
2448 if (!name.empty())
2449 {
2450 s_appNameCache[appId] = name;
2451 count++;
2452 }
2453 }
2454 break; // Only need first name match per record
2455 }
2456 }
2457
2458 pos = recordEnd;
2459 }
2460
2461 return count;
2462}
2463
2465{
2466 std::lock_guard<std::mutex> lock(s_appNameCacheMutex);
2467
2469 {
2470 return true; // Already loaded
2471 }
2472
2473 // First try loading from local appinfo.vdf cache (instant, no network)
2474 std::filesystem::path steamPath = SteamPaths::getPrimarySteamRoot();
2475 if (!steamPath.empty())
2476 {
2477 Logger::info("[SteamCache] Loading app names from local appinfo.vdf...");
2478 size_t localCount = loadAppNamesFromLocalCache(steamPath);
2479 if (localCount > 0)
2480 {
2481 s_appNameCacheLoaded = true;
2482 Logger::info("[SteamCache] Loaded {} app names from local cache", localCount);
2483 return true;
2484 }
2485 }
2486
2487 // Fallback to Steam Web API
2488 Logger::info("[SteamCache] Loading Steam app name cache from GetAppList API...");
2489
2490 // Use Steam's GetAppList API - returns ALL apps in ONE request
2491 // This is much faster than individual appdetails calls
2492 std::string command = "curl -s -m 30 'https://api.steampowered.com/ISteamApps/GetAppList/v2/'";
2493 PipeHandle pipe(command, "r");
2494
2495 if (!pipe)
2496 {
2497 Logger::error("[SteamCache] Failed to fetch Steam app list");
2498 return false;
2499 }
2500
2501 // Read the response (capped to prevent OOM from oversized API responses)
2502 std::string response;
2503 char buffer[8192];
2504 constexpr size_t kMaxSteamResponse = 32u * 1024 * 1024; // 32 MB (app list is ~12 MB)
2505 // s_appNameCacheMutex is held intentionally to serialize the
2506 // one-time cache load; concurrent loaders would each pay the network
2507 // round-trip. The blocking fgets IS the cache-population work.
2508 // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection) - see comment above.
2509 while (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
2510 {
2511 response += buffer;
2512 if (response.size() > kMaxSteamResponse)
2513 {
2514 Logger::warn("[Steam] App list response too large, truncating");
2515 break;
2516 }
2517 }
2518
2519 // Parse JSON response: {"applist":{"apps":[{"appid":10,"name":"Counter-Strike"},...]}}
2520 // Simple parsing without a JSON library
2521 size_t appsStart = response.find("\"apps\":[");
2522 if (appsStart == std::string::npos)
2523 {
2524 Logger::error("[SteamCache] Invalid response from Steam GetAppList API");
2525 return false;
2526 }
2527
2528 // Parse each app entry
2529 size_t pos = appsStart;
2530 size_t count = 0;
2531
2532 while ((pos = response.find("{\"appid\":", pos)) != std::string::npos)
2533 {
2534 // Extract appid
2535 size_t appidStart = pos + 9;
2536 size_t appidEnd = response.find(',', appidStart);
2537 if (appidEnd == std::string::npos)
2538 break;
2539
2540 uint32_t appId = 0;
2541 try
2542 {
2543 appId = static_cast<uint32_t>(
2544 std::stoul(response.substr(appidStart, appidEnd - appidStart)));
2545 }
2546 catch (...)
2547 {
2548 pos = appidEnd;
2549 continue;
2550 }
2551
2552 // Extract name
2553 size_t namePos = response.find("\"name\":\"", pos);
2554 if (namePos == std::string::npos || namePos > pos + 100)
2555 {
2556 pos = appidEnd;
2557 continue;
2558 }
2559
2560 size_t nameStart = namePos + 8;
2561
2562 // Find the closing quote of the name field by scanning for an unescaped '"'
2563 size_t nameEnd = nameStart;
2564 while (nameEnd < response.size())
2565 {
2566 if (response[nameEnd] == '\\')
2567 {
2568 nameEnd += 2; // skip escape sequence
2569 continue;
2570 }
2571 if (response[nameEnd] == '"')
2572 break;
2573 nameEnd++;
2574 }
2575 if (nameEnd >= response.size())
2576 {
2577 pos = appidEnd;
2578 continue;
2579 }
2580
2581 std::string name = response.substr(nameStart, nameEnd - nameStart);
2582
2583 // Unescape common JSON sequences
2584 size_t escPos = 0;
2585 while ((escPos = name.find("\\\"", escPos)) != std::string::npos)
2586 {
2587 name.replace(escPos, 2, "\"");
2588 escPos++;
2589 }
2590
2591 if (!name.empty())
2592 {
2593 s_appNameCache[appId] = name;
2594 count++;
2595 }
2596
2597 pos = nameEnd;
2598 }
2599
2600 s_appNameCacheLoaded = true;
2601 Logger::info("[SteamCache] Loaded {} app names from API", count);
2602 return true;
2603}
2604
2606{
2607 std::lock_guard<std::mutex> lock(s_appNameCacheMutex);
2608
2609 auto it = s_appNameCache.find(appId);
2610 if (it != s_appNameCache.end())
2611 {
2612 return it->second;
2613 }
2614 return "";
2615}
2616
2618{
2619 std::lock_guard<std::mutex> lock(s_appNameCacheMutex);
2620 return s_appNameCacheLoaded;
2621}
2622
2623// ==============================================================================
2624// Steam Web API - Fetch Game Names (individual lookup - fallback)
2625// ==============================================================================
2626
2628{
2629 // First try the cache (instant)
2630 std::string cachedName = fetchGameNameFromCache(appId);
2631 if (!cachedName.empty())
2632 {
2633 Logger::debug("[SteamAPI] Cache hit for AppID {}: '{}'", appId, cachedName);
2634 return cachedName;
2635 }
2636
2637 // Fallback to individual API call (slow)
2638 // Use Steam's public API to get game details
2639 // API endpoint: https://store.steampowered.com/api/appdetails?appids=<appid>
2640 std::string url =
2641 "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(appId);
2642
2643 Logger::info("[SteamAPI] Fetching game name from API for AppID {}", appId);
2644
2645 // Use curl to fetch the data (reduced timeout from 5s to 3s)
2646 std::string command = "curl -s -m 3 '" + url + "'";
2647 PipeHandle pipe(command, "r");
2648
2649 if (!pipe)
2650 {
2651 Logger::error("[SteamAPI] Failed to open pipe for AppID {}", appId);
2652 return "";
2653 }
2654
2655 // Read the response (capped to prevent OOM from oversized responses)
2656 std::string response;
2657 char buffer[1024];
2658 constexpr size_t kMaxResponse = 1u * 1024 * 1024; // 1 MB
2659 while (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
2660 {
2661 response += buffer;
2662 if (response.size() > kMaxResponse)
2663 {
2664 Logger::warn("[Steam] Game name API response too large, truncating");
2665 break;
2666 }
2667 }
2668 // PipeHandle automatically closes on scope exit
2669
2670 if (response.empty())
2671 {
2672 Logger::error("[SteamAPI] Empty response for AppID {}", appId);
2673 return "";
2674 }
2675
2676 Logger::debug("[SteamAPI] Response length for AppID {}: {} bytes", appId, response.size());
2677
2678 // Parse JSON response to extract game name
2679 // Response format: {"<appid>": {"success": true, "data": {"name": "Game Name", ...}}}
2680
2681 // Check for success: false
2682 if (response.find("\"success\":false") != std::string::npos ||
2683 response.find("\"success\": false") != std::string::npos)
2684 {
2685 Logger::warn("[SteamAPI] API returned success:false for AppID {}", appId);
2686 return "";
2687 }
2688
2689 // Find the "name" field in the JSON
2690 size_t namePos = response.find("\"name\":");
2691 if (namePos == std::string::npos)
2692 {
2693 Logger::warn("[SteamAPI] No 'name' field found in response for AppID {}", appId);
2694 return "";
2695 }
2696
2697 // Find the opening quote of the name value
2698 size_t nameStart = response.find("\"", namePos + 7);
2699 if (nameStart == std::string::npos)
2700 {
2701 Logger::warn("[SteamAPI] Malformed name field for AppID {}", appId);
2702 return "";
2703 }
2704 nameStart++; // Move past the opening quote
2705
2706 // Find the closing quote
2707 size_t nameEnd = response.find("\"", nameStart);
2708 if (nameEnd == std::string::npos)
2709 {
2710 Logger::warn("[SteamAPI] Unclosed name string for AppID {}", appId);
2711 return "";
2712 }
2713
2714 // Extract the name
2715 std::string gameName = response.substr(nameStart, nameEnd - nameStart);
2716
2717 // Unescape common JSON escape sequences
2718 size_t pos = 0;
2719 while ((pos = gameName.find("\\\"", pos)) != std::string::npos)
2720 {
2721 gameName.replace(pos, 2, "\"");
2722 pos++;
2723 }
2724
2725 Logger::info("[SteamAPI] Successfully fetched name for AppID {}: '{}'", appId, gameName);
2726 return gameName;
2727}
2728
2729bool SteamLibraryScanner::fetchSteamMetadata(uint32_t appId, std::string& outType,
2730 std::vector<std::string>& outGenres,
2731 std::vector<std::string>& outCategories)
2732{
2733 std::string outName; // Unused in this overload
2734 return fetchSteamMetadata(appId, outName, outType, outGenres, outCategories);
2735}
2736
2737bool SteamLibraryScanner::fetchSteamMetadata(uint32_t appId, std::string& outName,
2738 std::string& outType,
2739 std::vector<std::string>& outGenres,
2740 std::vector<std::string>& outCategories)
2741{
2742 // Use Steam's public API to get game details
2743 // This single call fetches ALL metadata: name, type, genres, categories
2744 std::string url =
2745 "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(appId);
2746
2747 // Use curl to fetch the data (reduced timeout from 5s to 3s for faster failure)
2748 std::string command = "curl -s -m 3 '" + url + "'";
2749 PipeHandle pipe(command, "r");
2750
2751 if (!pipe)
2752 {
2753 return false;
2754 }
2755
2756 // Read the response (capped to prevent OOM from oversized responses)
2757 std::string response;
2758 char buffer[4096];
2759 constexpr size_t kMaxMetaResponse = 4u * 1024 * 1024; // 4 MB
2760 while (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
2761 {
2762 response += buffer;
2763 if (response.size() > kMaxMetaResponse)
2764 {
2765 Logger::warn("[Steam] Metadata API response too large, truncating");
2766 break;
2767 }
2768 }
2769 // PipeHandle automatically closes on scope exit
2770
2771 // Check if the response indicates success
2772 if (response.find("\"success\":true") == std::string::npos)
2773 {
2774 return false;
2775 }
2776
2777 // Parse name
2778 size_t namePos = response.find("\"name\":\"");
2779 if (namePos != std::string::npos)
2780 {
2781 size_t nameStart = namePos + 8;
2782 size_t nameEnd = response.find("\"", nameStart);
2783 if (nameEnd != std::string::npos)
2784 {
2785 outName = response.substr(nameStart, nameEnd - nameStart);
2786 // Unescape common JSON escape sequences
2787 size_t pos = 0;
2788 while ((pos = outName.find("\\\"", pos)) != std::string::npos)
2789 {
2790 outName.replace(pos, 2, "\"");
2791 pos++;
2792 }
2793 }
2794 }
2795
2796 // Parse type
2797 size_t typePos = response.find("\"type\":\"");
2798 if (typePos != std::string::npos)
2799 {
2800 size_t typeStart = typePos + 8;
2801 size_t typeEnd = response.find("\"", typeStart);
2802 if (typeEnd != std::string::npos)
2803 {
2804 outType = response.substr(typeStart, typeEnd - typeStart);
2805 }
2806 }
2807
2808 // Parse genres array
2809 size_t genresPos = response.find("\"genres\":[");
2810 if (genresPos != std::string::npos)
2811 {
2812 size_t genresEnd = response.find("]", genresPos);
2813 if (genresEnd != std::string::npos)
2814 {
2815 std::string genresSection = response.substr(genresPos, genresEnd - genresPos);
2816
2817 // Extract all "description" fields in genres
2818 size_t pos = 0;
2819 while ((pos = genresSection.find("\"description\":\"", pos)) != std::string::npos)
2820 {
2821 size_t start = pos + 15;
2822 size_t end = genresSection.find("\"", start);
2823 if (end != std::string::npos)
2824 {
2825 outGenres.push_back(genresSection.substr(start, end - start));
2826 pos = end;
2827 }
2828 else
2829 {
2830 break;
2831 }
2832 }
2833 }
2834 }
2835
2836 // Parse categories array
2837 size_t categoriesPos = response.find("\"categories\":[");
2838 if (categoriesPos != std::string::npos)
2839 {
2840 size_t categoriesEnd = response.find("]", categoriesPos);
2841 if (categoriesEnd != std::string::npos)
2842 {
2843 std::string categoriesSection =
2844 response.substr(categoriesPos, categoriesEnd - categoriesPos);
2845
2846 // Extract all "description" fields in categories
2847 size_t pos = 0;
2848 while ((pos = categoriesSection.find("\"description\":\"", pos)) != std::string::npos)
2849 {
2850 size_t start = pos + 15;
2851 size_t end = categoriesSection.find("\"", start);
2852 if (end != std::string::npos)
2853 {
2854 outCategories.push_back(categoriesSection.substr(start, end - start));
2855 pos = end;
2856 }
2857 else
2858 {
2859 break;
2860 }
2861 }
2862 }
2863 }
2864
2865 return !outType.empty(); // Return success if we at least got the type
2866}
2867
2868// ==============================================================================
2869// Steam Process Management
2870// ==============================================================================
2871
2876
2878{
2879 if (!isSteamRunning())
2880 {
2881 // Steam not running, just start it
2883 return result.success;
2884 }
2885
2886 // Steam is running - need to shut it down and restart
2887 Logger::info("Shutting down Steam...");
2888
2889 // Use steam -shutdown for graceful shutdown
2890 ProcessExecutor::execute("steam -shutdown");
2891
2892 // Wait for Steam to shut down (max 10 seconds)
2893 int attempts = 0;
2894 while (isSteamRunning() && attempts < 20)
2895 {
2896 std::this_thread::sleep_for(std::chrono::milliseconds(500));
2897 attempts++;
2898 }
2899
2900 if (isSteamRunning())
2901 {
2902 Logger::error("Failed to shut down Steam gracefully");
2903 return false;
2904 }
2905
2906 Logger::info("Steam shut down, restarting...");
2907
2908 // Wait a moment for cleanup
2909 std::this_thread::sleep_for(std::chrono::seconds(1));
2910
2911 // Restart Steam
2913
2914 Logger::info("Steam restarted");
2915 return true;
2916}
2917
2919{
2920 // Launch the blocking restartSteam() function asynchronously
2921 return std::async(std::launch::async, []() { return SteamLibraryScanner::restartSteam(); });
2922}
2923
2924// ==============================================================================
2925// Proton Version Scanner
2926// ==============================================================================
2927
2928std::vector<std::pair<std::string, std::filesystem::path>> SteamLibraryScanner::scanProtonVersions()
2929{
2930 std::vector<std::pair<std::string, std::filesystem::path>> protonVersions;
2931 std::set<std::string> foundVersions; // Track to avoid duplicates
2932
2933 // Helper lambda to scan a Steam installation directory
2934 auto scanSteamDirectory = [&](const std::filesystem::path& steamPath)
2935 {
2936 if (!std::filesystem::exists(steamPath))
2937 return;
2938
2939 Logger::info("Scanning for Proton in: {}", steamPath.string());
2940
2941 // Scan compatibilitytools.d directory (custom Proton installations like CachyOS, GE-Proton)
2942 std::filesystem::path compatToolsPath = steamPath / SteamConstants::COMPAT_TOOLS_DIR;
2943 if (std::filesystem::exists(compatToolsPath))
2944 {
2945 for (const auto& entry : std::filesystem::directory_iterator(compatToolsPath))
2946 {
2947 if (!entry.is_directory())
2948 continue;
2949
2950 std::filesystem::path protonExe = entry.path() / "proton";
2951 if (std::filesystem::exists(protonExe))
2952 {
2953 std::string displayName = entry.path().filename().string();
2954 if (foundVersions.find(displayName) == foundVersions.end())
2955 {
2956 protonVersions.push_back({displayName, protonExe});
2957 foundVersions.insert(displayName);
2958 }
2959 }
2960 }
2961 }
2962
2963 // Scan steamapps/common for official Proton versions (installed)
2964 std::filesystem::path commonPath =
2966 if (std::filesystem::exists(commonPath))
2967 {
2968 for (const auto& entry : std::filesystem::directory_iterator(commonPath))
2969 {
2970 if (!entry.is_directory())
2971 continue;
2972
2973 std::string dirname = entry.path().filename().string();
2974 // Check if directory name contains "Proton" (case-sensitive)
2975 if (dirname.find("Proton") != std::string::npos)
2976 {
2977 std::filesystem::path protonExe = entry.path() / "proton";
2978 if (std::filesystem::exists(protonExe))
2979 {
2980 if (foundVersions.find(dirname) == foundVersions.end())
2981 {
2982 protonVersions.push_back({dirname, protonExe});
2983 foundVersions.insert(dirname);
2984 }
2985 }
2986 }
2987 }
2988 }
2989 };
2990
2991 // ==========================================================================
2992 // Scan All Steam Installations (using centralized detection)
2993 // ==========================================================================
2994 std::vector<std::filesystem::path> steamRoots = SteamPaths::getAllSteamRoots();
2995 for (const auto& steamPath : steamRoots)
2996 {
2997 scanSteamDirectory(steamPath);
2998 }
2999
3000 // ==========================================================================
3001 // Scan Additional Steam Library Folders
3002 // ==========================================================================
3003 // Parse libraryfolders.vdf to find additional Steam library locations
3004 std::filesystem::path primarySteamRoot = SteamPaths::getPrimarySteamRoot();
3005 if (primarySteamRoot.empty())
3006 {
3007 return protonVersions;
3008 }
3009
3010 std::filesystem::path libraryFoldersVdf =
3012 if (std::filesystem::exists(libraryFoldersVdf))
3013 {
3014 std::ifstream file(libraryFoldersVdf);
3015 std::string line;
3016 while (std::getline(file, line))
3017 {
3018 // Look for "path" entries in the VDF file
3019 // Format: "path" "/mnt/games/SteamLibrary"
3020 size_t pathPos = line.find("\"path\"");
3021 if (pathPos != std::string::npos)
3022 {
3023 // Extract the path value
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)
3027 {
3028 std::string libraryPath =
3029 line.substr(firstQuote + 1, secondQuote - firstQuote - 1);
3030 Logger::info("Found additional Steam library: {}", libraryPath);
3031
3032 // Scan this library's Proton installations
3033 std::filesystem::path libraryProtonPath = std::filesystem::path(libraryPath) /
3036 if (std::filesystem::exists(libraryProtonPath))
3037 {
3038 for (const auto& entry :
3039 std::filesystem::directory_iterator(libraryProtonPath))
3040 {
3041 if (!entry.is_directory())
3042 continue;
3043
3044 std::string dirname = entry.path().filename().string();
3045 if (dirname.find("Proton") != std::string::npos)
3046 {
3047 std::filesystem::path protonExe = entry.path() / "proton";
3048 if (std::filesystem::exists(protonExe))
3049 {
3050 if (foundVersions.find(dirname) == foundVersions.end())
3051 {
3052 protonVersions.push_back({dirname, protonExe});
3053 foundVersions.insert(dirname);
3054 }
3055 }
3056 }
3057 }
3058 }
3059 }
3060 }
3061 }
3062 file.close();
3063 }
3064
3065 // ==========================================================================
3066 // Scan System-wide Proton Installations (if any)
3067 // ==========================================================================
3068 std::vector<std::filesystem::path> systemPaths = {"/usr/share/steam/compatibilitytools.d",
3069 "/opt/steam/compatibilitytools.d"};
3070
3071 for (const auto& systemPath : systemPaths)
3072 {
3073 if (std::filesystem::exists(systemPath))
3074 {
3075 Logger::info("Scanning system-wide Proton directory: {}", systemPath.string());
3076 for (const auto& entry : std::filesystem::directory_iterator(systemPath))
3077 {
3078 if (!entry.is_directory())
3079 continue;
3080
3081 std::filesystem::path protonExe = entry.path() / "proton";
3082 if (std::filesystem::exists(protonExe))
3083 {
3084 std::string displayName = entry.path().filename().string() + " (system)";
3085 if (foundVersions.find(displayName) == foundVersions.end())
3086 {
3087 protonVersions.push_back({displayName, protonExe});
3088 foundVersions.insert(displayName);
3089 }
3090 }
3091 }
3092 }
3093 }
3094
3095 // ==========================================================================
3096 // Add Known Downloadable Proton Versions (for reference)
3097 // ==========================================================================
3098 // These show up in Steam's compatibility tool dropdown but may not be installed yet
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"}};
3103
3104 for (const auto& [displayName, steamName] : knownProtonVersions)
3105 {
3106 // Only add if not already found as installed
3107 if (foundVersions.find(displayName) == foundVersions.end())
3108 {
3109 // Use empty path to indicate it's not installed yet
3110 protonVersions.push_back({displayName + " (not installed)", std::filesystem::path()});
3111 }
3112 }
3113
3114 // ==========================================================================
3115 // Sort by Priority
3116 // ==========================================================================
3117 // Priority: Installed > CachyOS > Experimental > Alphabetically (newest first)
3118 std::sort(protonVersions.begin(), protonVersions.end(),
3119 [](const auto& a, const auto& b)
3120 {
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);
3127
3128 // Installed versions first
3129 if (aInstalled && !bInstalled)
3130 return true;
3131 if (!aInstalled && bInstalled)
3132 return false;
3133
3134 // Among installed: CachyOS first
3135 if (aInstalled && bInstalled)
3136 {
3137 if (aCachyOS && !bCachyOS)
3138 return true;
3139 if (!aCachyOS && bCachyOS)
3140 return false;
3141
3142 // Then Experimental
3143 if (aExperimental && !bExperimental)
3144 return true;
3145 if (!aExperimental && bExperimental)
3146 return false;
3147 }
3148
3149 // Otherwise alphabetically (reverse for newer versions first)
3150 return a.first > b.first;
3151 });
3152
3153 Logger::info("Found {} Proton versions", protonVersions.size());
3154
3155 return protonVersions;
3156}
3157
3158// ==============================================================================
3159// Steam Proton Version Writer
3160// ==============================================================================
3161
3163{
3164 // Find Steam config.vdf file (Flatpak/Snap-aware via SteamPaths).
3165 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
3166 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
3167 {
3168 Logger::error("Steam root directory not found");
3169 return "";
3170 }
3171
3172 std::filesystem::path configPath = steamRoot / "config" / "config.vdf";
3173 if (!std::filesystem::exists(configPath))
3174 {
3175 Logger::error("Steam config.vdf not found");
3176 return "";
3177 }
3178
3179 // Read and parse file looking for app entry in CompatToolMapping
3180 std::ifstream inFile(configPath);
3181 if (!inFile.is_open())
3182 {
3183 Logger::error("Failed to open config.vdf for reading");
3184 return "";
3185 }
3186
3187 bool inCompatToolMapping = false;
3188 bool foundApp = false;
3189 int braceDepth = 0;
3190 std::string appIdStr = "\"" + std::to_string(appId) + "\"";
3191 std::string line;
3192
3193 while (std::getline(inFile, line))
3194 {
3195 size_t start = line.find_first_not_of(" \t");
3196 if (start == std::string::npos)
3197 continue;
3198 std::string trimmed = line.substr(start);
3199
3200 // Find CompatToolMapping section
3201 if (!inCompatToolMapping && trimmed.find("\"CompatToolMapping\"") == 0)
3202 {
3203 inCompatToolMapping = true;
3204 continue;
3205 }
3206
3207 if (inCompatToolMapping)
3208 {
3209 // Track braces
3210 for (char c : line)
3211 {
3212 if (c == '{')
3213 braceDepth++;
3214 else if (c == '}')
3215 {
3216 braceDepth--;
3217 if (braceDepth == 0)
3218 {
3219 // End of section, app not found
3220 return "";
3221 }
3222 }
3223 }
3224
3225 // Look for the app ID
3226 if (!foundApp && trimmed.find(appIdStr) == 0)
3227 {
3228 foundApp = true;
3229 continue;
3230 }
3231
3232 // If we found the app, look for the "name" field
3233 if (foundApp && trimmed.find("\"name\"") == 0)
3234 {
3235 // Parse: "name" "ProtonVersionName"
3236 size_t firstQuote = trimmed.find('"', 6); // After "name"
3237 if (firstQuote != std::string::npos)
3238 {
3239 size_t secondQuote = trimmed.find('"', firstQuote + 1);
3240 if (secondQuote != std::string::npos)
3241 {
3242 return trimmed.substr(firstQuote + 1, secondQuote - firstQuote - 1);
3243 }
3244 }
3245 return "";
3246 }
3247
3248 // If we hit a closing brace after finding the app but before name, something's wrong
3249 if (foundApp && trimmed == "}")
3250 {
3251 return "";
3252 }
3253 }
3254 }
3255
3256 return "";
3257}
3258
3259// ==============================================================================
3260// Proton Path Resolution for Direct Launch
3261// ==============================================================================
3262
3263std::filesystem::path SteamLibraryScanner::resolveProtonPath(uint32_t appId,
3264 std::string& outCompatToolName)
3265{
3266 outCompatToolName.clear();
3267
3268 // Step 1: Check for explicit per-game compat tool mapping
3269 std::string configuredTool = readSteamProtonVersion(appId);
3270 if (!configuredTool.empty())
3271 {
3272 outCompatToolName = configuredTool;
3273 Logger::info("[ProtonResolve] App {} has explicit compat tool: {}", appId, configuredTool);
3274 }
3275
3276 // Step 2: Scan all installed Proton versions
3277 auto protonVersions = scanProtonVersions();
3278 if (protonVersions.empty())
3279 {
3280 Logger::warn("[ProtonResolve] No Proton versions found on system");
3281 return {};
3282 }
3283
3284 // Step 3: If explicit tool configured, try to match it to an installed version
3285 if (!configuredTool.empty())
3286 {
3287 // Compat tool names use patterns like:
3288 // "proton_experimental" -> "Proton - Experimental"
3289 // "proton_10" -> "Proton 10.0"
3290 // "proton_9" -> "Proton 9.0"
3291 // "proton-cachyos-..." -> exact directory name match
3292 // "GE-Proton10-32" -> exact directory name match
3293
3294 for (const auto& [displayName, protonExe] : protonVersions)
3295 {
3296 std::string dirName = protonExe.parent_path().filename().string();
3297
3298 // Exact directory name match (for custom Proton versions)
3299 if (dirName == configuredTool)
3300 return protonExe;
3301
3302 // Map Steam's internal names to directory names
3303 if (configuredTool == "proton_experimental" &&
3304 (dirName == "Proton - Experimental" ||
3305 dirName.find("Proton - Experimental") != std::string::npos))
3306 {
3307 return protonExe;
3308 }
3309
3310 // Pattern: "proton_N" or "proton_N0" -> "Proton N.0"
3311 if (configuredTool.rfind("proton_", 0) == 0)
3312 {
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)
3316 {
3317 return protonExe;
3318 }
3319 }
3320
3321 // Case-insensitive substring match as last resort
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)); });
3328 // Replace underscores/hyphens for comparison
3329 std::replace(lowerTool.begin(), lowerTool.end(), '_', ' ');
3330 std::replace(lowerTool.begin(), lowerTool.end(), '-', ' ');
3331 std::replace(lowerDir.begin(), lowerDir.end(), '-', ' ');
3332
3333 if (lowerDir.find(lowerTool) != std::string::npos ||
3334 lowerTool.find(lowerDir) != std::string::npos)
3335 {
3336 return protonExe;
3337 }
3338 }
3339
3341 "[ProtonResolve] Configured compat tool '{}' not found among installed versions",
3342 configuredTool);
3343 }
3344
3345 // Step 4: No explicit tool or match not found — pick best available
3346 // Priority: latest official stable > experimental > custom (GE, CachyOS)
3347 std::filesystem::path bestPath;
3348 int bestScore = -1;
3349
3350 for (const auto& [displayName, protonExe] : protonVersions)
3351 {
3352 int score = 0;
3353 std::string dirName = protonExe.parent_path().filename().string();
3354
3355 // Official stable versions score highest
3356 // "Proton 10.0" > "Proton 9.0" etc.
3357 if (dirName.rfind("Proton ", 0) == 0 && dirName.find("Experimental") == std::string::npos)
3358 {
3359 score = 100;
3360 // Extract version number for comparison
3361 try
3362 {
3363 double ver = std::stod(dirName.substr(7));
3364 // Clamp before cast to avoid UB from double→int overflow.
3365 double scaled = ver * 10.0;
3366 if (scaled > 10000.0)
3367 scaled = 10000.0;
3368 if (scaled < 0.0)
3369 scaled = 0.0;
3370 score += static_cast<int>(scaled); // Higher version = higher score
3371 }
3372 catch (...)
3373 {
3374 }
3375 }
3376 // Experimental is a good fallback
3377 else if (dirName.find("Experimental") != std::string::npos)
3378 {
3379 score = 90;
3380 }
3381 // Proton Hotfix
3382 else if (dirName.find("Hotfix") != std::string::npos)
3383 {
3384 score = 85;
3385 }
3386 // CachyOS custom Proton
3387 else if (dirName.find("cachyos") != std::string::npos)
3388 {
3389 score = 80;
3390 }
3391 // GE-Proton
3392 else if (dirName.find("GE-Proton") != std::string::npos)
3393 {
3394 score = 75;
3395 }
3396 // System-installed
3397 else if (displayName.find("(system)") != std::string::npos)
3398 {
3399 score = 50;
3400 }
3401 // Unknown custom
3402 else
3403 {
3404 score = 60;
3405 }
3406
3407 if (score > bestScore)
3408 {
3409 bestScore = score;
3410 bestPath = protonExe;
3411 }
3412 }
3413
3414 if (!bestPath.empty())
3415 {
3416 outCompatToolName = bestPath.parent_path().filename().string();
3417 Logger::info("[ProtonResolve] Auto-selected Proton: {} (score {})", outCompatToolName,
3418 bestScore);
3419 }
3420
3421 return bestPath;
3422}
3423
3425{
3426 if (game.appId == 0)
3427 return;
3428
3429 // Load appinfo.vdf for executable discovery, with mtime-based reload.
3430 //
3431 // Steam rewrites appinfo.vdf on game install, update, login, and
3432 // background sync. The previous std::call_once "load once per
3433 // process" pattern silently served stale launch metadata for the
3434 // remainder of the session — if Steam patched a game's executable
3435 // path mid-session, we'd direct-launch the wrong / missing binary.
3436 //
3437 // This loader keeps the parser in a static optional but tracks the
3438 // file's last_write_time, reloading whenever it changes. The mutex
3439 // serialises concurrent access from multiple library-scan threads.
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{};
3444
3445 {
3446 std::lock_guard<std::mutex> lock(s_appInfoMutex);
3447
3448 std::filesystem::path appInfoPath =
3449 SteamPaths::getPrimarySteamRoot() / "appcache" / "appinfo.vdf";
3450 std::error_code mtEc;
3451 auto mtime = std::filesystem::last_write_time(appInfoPath, mtEc);
3452
3453 const bool pathChanged = (s_appInfoPath != appInfoPath);
3454 const bool mtimeChanged = (!mtEc && mtime != s_appInfoMtime);
3455 const bool needLoad = !s_appInfoParser || pathChanged || mtimeChanged;
3456
3457 if (needLoad)
3458 {
3459 SteamAppInfoParser parser;
3460 if (parser.load(appInfoPath))
3461 {
3462 s_appInfoParser.emplace(std::move(parser));
3463 s_appInfoPath = appInfoPath;
3464 if (!mtEc)
3465 s_appInfoMtime = mtime;
3466 }
3467 else
3468 {
3469 Logger::warn("[DirectLaunch] Failed to load appinfo.vdf — "
3470 "will fall back to steam -applaunch");
3471 s_appInfoParser.reset();
3472 }
3473 }
3474 }
3475
3476 // Get executable info from appinfo.vdf
3477 if (s_appInfoParser)
3478 {
3479 auto appInfo = s_appInfoParser->getAppInfo(game.appId);
3480 if (appInfo)
3481 {
3482 if (game.isProtonGame)
3483 {
3484 auto entry = appInfo->getProtonLaunchEntry();
3485 if (entry)
3486 {
3487 game.gameExecutable = entry->executable;
3488 game.gameArguments = entry->arguments;
3489 }
3490 }
3491 else
3492 {
3493 // Native Linux game — try native entry first, then Windows
3494 auto entry = appInfo->getNativeLaunchEntry();
3495 if (!entry)
3496 entry = appInfo->getProtonLaunchEntry();
3497 if (entry)
3498 {
3499 game.gameExecutable = entry->executable;
3500 game.gameArguments = entry->arguments;
3501 }
3502 }
3503
3504 // Also capture type info if not already set
3505 if (game.steamType.empty())
3506 game.steamType = appInfo->type;
3507 }
3508 }
3509
3510 // Resolve Proton path for Proton games
3511 if (game.isProtonGame && !game.gameExecutable.empty())
3512 {
3514 }
3515}
3516
3517std::string SteamLibraryScanner::normalizeProtonName(const std::string& display)
3518{
3519 if (display.empty())
3520 return {};
3521
3522 // Steam-managed sentinel values — leave Steam's choice alone.
3523 if (display == "Native Linux" || display == "Proton" ||
3524 display.find("Steam-managed") != std::string::npos ||
3525 display.find("(not installed)") != std::string::npos)
3526 {
3527 return {};
3528 }
3529
3530 // Strip a single trailing " (annotation)" suffix added for display.
3531 std::string base = display;
3532 if (base.size() > 3 && base.back() == ')')
3533 {
3534 size_t parenPos = base.rfind(" (");
3535 if (parenPos != std::string::npos)
3536 {
3537 base = base.substr(0, parenPos);
3538 }
3539 }
3540
3541 // Map the official-Proton display names to Steam's internal
3542 // CompatToolMapping ids. This is the single source of truth for that
3543 // mapping: both the config dialog and the launch-time sync
3544 // (GameLaunchManager::checkAndSyncSettings) route through here, so writing
3545 // e.g. the literal "Proton Experimental" into config.vdf — which Steam
3546 // does not recognise — cannot happen. Custom tools (proton-cachyos,
3547 // GE-Proton*, wine-staging, …) use their folder name directly and pass
3548 // through unchanged.
3549 if (base == "Proton Experimental")
3550 return "proton_experimental";
3551 if (base == "Proton 9.0")
3552 return "proton_9";
3553 if (base == "Proton 8.0")
3554 return "proton_8";
3555
3556 return base;
3557}
3558
3559bool SteamLibraryScanner::writeSteamProtonVersion(uint32_t appId, const std::string& protonNameRaw)
3560{
3561 const std::string protonName = normalizeProtonName(protonNameRaw);
3562 if (protonName.empty())
3563 {
3564 Logger::info("[Steam] Skipping CompatToolMapping write for AppID {}: '{}' is a "
3565 "Steam-managed sentinel",
3566 appId, protonNameRaw);
3567 return true; // Not an error — caller asked to write a name we shouldn't.
3568 }
3569 if (protonName != protonNameRaw)
3570 {
3571 Logger::info("[Steam] Normalised Proton tool name '{}' -> '{}' for AppID {}", protonNameRaw,
3572 protonName, appId);
3573 }
3574 // Find Steam config.vdf file (Flatpak/Snap-aware via SteamPaths).
3575 std::filesystem::path steamRoot = SteamPaths::getPrimarySteamRoot();
3576 if (steamRoot.empty() || !std::filesystem::exists(steamRoot))
3577 {
3578 Logger::error("Steam root directory not found");
3579 return false;
3580 }
3581
3582 std::filesystem::path configPath = steamRoot / "config" / "config.vdf";
3583 if (!std::filesystem::exists(configPath))
3584 {
3585 Logger::error("Steam config.vdf not found");
3586 return false;
3587 }
3588
3589 // Read entire file
3590 std::ifstream inFile(configPath);
3591 if (!inFile.is_open())
3592 {
3593 Logger::error("Failed to open config.vdf for reading");
3594 return false;
3595 }
3596
3597 std::vector<std::string> lines;
3598 std::string line;
3599 while (std::getline(inFile, line))
3600 {
3601 lines.push_back(line);
3602 }
3603 inFile.close();
3604
3605 // Find CompatToolMapping section
3606 bool inCompatToolMapping = false;
3607 bool foundApp = false;
3608 bool modified = false;
3609 int braceDepth = 0;
3610
3611 for (size_t i = 0; i < lines.size(); i++)
3612 {
3613 size_t start = lines[i].find_first_not_of(" \t");
3614 if (start == std::string::npos)
3615 continue;
3616 std::string trimmed = lines[i].substr(start);
3617
3618 // Find CompatToolMapping section
3619 if (!inCompatToolMapping && trimmed.find("\"CompatToolMapping\"") == 0)
3620 {
3621 inCompatToolMapping = true;
3622 continue;
3623 }
3624
3625 if (inCompatToolMapping)
3626 {
3627 // Track braces to know when we're in the section
3628 for (char c : lines[i])
3629 {
3630 if (c == '{')
3631 braceDepth++;
3632 else if (c == '}')
3633 {
3634 braceDepth--;
3635 if (braceDepth == 0)
3636 {
3637 // End of CompatToolMapping section
3638 if (!foundApp)
3639 {
3640 // Insert new entry before closing brace
3641 size_t indent = lines[i].find_first_not_of(" \t");
3642 std::string indentStr = lines[i].substr(0, indent);
3643
3644 std::vector<std::string> newEntry = {
3645 indentStr + "\t\"" + std::to_string(appId) + "\"",
3646 indentStr + "\t{",
3647 indentStr + "\t\t\"name\"\t\t\"" + vdfEscapeValue(protonName) +
3648 "\"",
3649 indentStr + "\t\t\"config\"\t\t\"\"",
3650 indentStr + "\t\t\"priority\"\t\t\"250\"",
3651 indentStr + "\t}"};
3652
3653 lines.insert(lines.begin() + static_cast<std::ptrdiff_t>(i),
3654 newEntry.begin(), newEntry.end());
3655 modified = true;
3656 }
3657 break;
3658 }
3659 }
3660 }
3661
3662 // Look for existing app entry
3663 std::string appIdStr = "\"" + std::to_string(appId) + "\"";
3664 if (!foundApp && trimmed.find(appIdStr) == 0)
3665 {
3666 foundApp = true;
3667 // Find and update the "name" field
3668 for (size_t j = i + 1; j < lines.size() && j < i + 10; j++)
3669 {
3670 size_t nameStart = lines[j].find_first_not_of(" \t");
3671 if (nameStart != std::string::npos)
3672 {
3673 std::string nameLine = lines[j].substr(nameStart);
3674 if (nameLine.find("\"name\"") == 0)
3675 {
3676 // Update name field
3677 std::string indentStr = lines[j].substr(0, nameStart);
3678 lines[j] =
3679 indentStr + "\"name\"\t\t\"" + vdfEscapeValue(protonName) + "\"";
3680 modified = true;
3681 break;
3682 }
3683 }
3684 }
3685 }
3686
3687 if (braceDepth == 0)
3688 break;
3689 }
3690 }
3691
3692 if (!modified)
3693 {
3694 Logger::error("Could not modify CompatToolMapping for app {}", appId);
3695 return false;
3696 }
3697
3698 // ==================================================================
3699 // Create backup before writing
3700 // ==================================================================
3701 std::filesystem::path backupPath = configPath;
3703
3704 try
3705 {
3706 std::filesystem::copy_file(configPath, backupPath,
3707 std::filesystem::copy_options::overwrite_existing);
3708 Logger::info("Created backup: {}", backupPath.string());
3709 }
3710 catch (const std::exception& e)
3711 {
3712 Logger::warn("Failed to create backup: {}", e.what());
3713 // Continue anyway - backup is optional
3714 }
3715
3716 // ==================================================================
3717 // Write back to file with retry logic
3718 // ==================================================================
3719 if (!writeVDFFileWithRetry(configPath, lines, backupPath))
3720 {
3721 Logger::error("Failed to write config.vdf after retries");
3722 return false;
3723 }
3724
3725 Logger::info("Successfully wrote Proton version '{}' for app {}", protonName, appId);
3726 return true;
3727}
3728// ==============================================================================
3729// Phase 5 Enhancements: Steam Integration Implementation
3730// ==============================================================================
3731// This file contains implementations for:
3732// - Cloud Save info parsing
3733// - User Categories (tags) parsing
3734// - DLC detection from ACF files
3735//
3736// These functions should be added to src/steam_integration.cpp
3737// ==============================================================================
3738
3739// ==============================================================================
3740// Cloud Save Information
3741// ==============================================================================
3742
3743// Helper function to get active Steam user ID
3744static std::string getActiveUserId()
3745{
3746 std::filesystem::path steamPath = SteamPaths::getPrimarySteamRoot();
3747 if (steamPath.empty())
3748 return "";
3749
3750 std::filesystem::path userdataPath = SteamPaths::getUserDataDirectory();
3751 if (!std::filesystem::exists(userdataPath))
3752 return "";
3753
3754 // Find the first user directory
3755 try
3756 {
3757 for (const auto& entry : std::filesystem::directory_iterator(userdataPath))
3758 {
3759 if (entry.is_directory())
3760 {
3761 std::filesystem::path configFile = entry.path() / "config" / "localconfig.vdf";
3762 if (std::filesystem::exists(configFile))
3763 {
3764 return entry.path().filename().string();
3765 }
3766 }
3767 }
3768 }
3769 catch (...)
3770 {
3771 }
3772
3773 return "";
3774}
3775
3776// Helper: find the position of the closing '}' of a VDF section starting at openBrace.
3777// Returns std::string::npos if not found.
3778static size_t findVdfSectionEnd(const std::string& content, size_t openBrace)
3779{
3780 int depth = 0;
3781 for (size_t i = openBrace; i < content.size(); i++)
3782 {
3783 if (content[i] == '{')
3784 depth++;
3785 else if (content[i] == '}')
3786 {
3787 if (--depth == 0)
3788 return i;
3789 }
3790 }
3791 return std::string::npos;
3792}
3793
3795{
3796 CloudSaveInfo info;
3797
3798 // Get user config path
3799 std::filesystem::path steamPath = SteamPaths::getPrimarySteamRoot();
3800 if (steamPath.empty())
3801 {
3802 Logger::warn("Steam installation not found for cloud save info");
3803 return info;
3804 }
3805
3806 std::string userId = getActiveUserId();
3807 if (userId.empty())
3808 {
3809 Logger::warn("No active Steam user found for cloud save info");
3810 return info;
3811 }
3812
3813 std::filesystem::path userConfigPath =
3814 steamPath / "userdata" / userId / "config" / "localconfig.vdf";
3815
3816 if (!std::filesystem::exists(userConfigPath))
3817 {
3818 Logger::debug("localconfig.vdf not found for cloud save info: {}", userConfigPath.string());
3819 return info;
3820 }
3821
3822 // Read entire file
3823 std::ifstream file(userConfigPath);
3824 if (!file.is_open())
3825 {
3826 Logger::error("Failed to open localconfig.vdf for cloud save info");
3827 return info;
3828 }
3829
3830 std::string content = readVdfContent(file);
3831 file.close();
3832
3833 // Parse VDF to find cloud save section for this app
3834 // Structure: "Software" -> "Valve" -> "Steam" -> "Apps" -> "[AppID]" -> "Cloud"
3835
3836 std::string appIdStr = std::to_string(appId);
3837 std::string appSection = "\"" + appIdStr + "\"";
3838
3839 size_t appsPos = content.find("\"apps\"");
3840 if (appsPos == std::string::npos)
3841 return info;
3842
3843 size_t appPos = content.find(appSection, appsPos);
3844 if (appPos == std::string::npos)
3845 return info;
3846
3847 // Find the end of this app's section by brace-counting from its opening '{'
3848 size_t appOpenBrace = content.find('{', appPos + appSection.size());
3849 size_t appSectionEnd = (appOpenBrace != std::string::npos)
3850 ? findVdfSectionEnd(content, appOpenBrace)
3851 : std::string::npos;
3852
3853 // Find the Cloud section within this app
3854 size_t cloudPos = content.find("\"Cloud\"", appPos);
3855 if (cloudPos == std::string::npos ||
3856 (appSectionEnd != std::string::npos && cloudPos > appSectionEnd))
3857 {
3858 // No cloud section or it belongs to next app
3859 return info;
3860 }
3861
3862 // Find the opening brace for Cloud section
3863 size_t bracePos = content.find("{", cloudPos);
3864 if (bracePos == std::string::npos)
3865 return info;
3866
3867 // Parse cloud section
3868 size_t pos = bracePos;
3869 int braceDepth = 1;
3870
3871 while (braceDepth > 0 && ++pos < content.length())
3872 {
3873 if (content[pos] == '{')
3874 braceDepth++;
3875 if (content[pos] == '}')
3876 braceDepth--;
3877
3878 // Look for cloud keys
3879 if (content.substr(pos, 7) == "\"cloud\"")
3880 {
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)
3884 {
3885 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3886 info.supported = (value == "1");
3887 }
3888 }
3889 else if (content.substr(pos, 14) == "\"cloudenabled\"")
3890 {
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)
3894 {
3895 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3896 info.enabled = (value == "1");
3897 }
3898 }
3899 else if (content.substr(pos, 15) == "\"lastsyncstate\"")
3900 {
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)
3904 {
3905 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3906 try
3907 {
3908 info.lastSyncState = std::stoi(value);
3909 }
3910 catch (...)
3911 {
3912 info.lastSyncState = 0;
3913 }
3914 }
3915 }
3916 else if (content.substr(pos, 17) == "\"laststoragesize\"")
3917 {
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)
3921 {
3922 std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);
3923 try
3924 {
3925 info.storageBytes = std::stoull(value);
3926 }
3927 catch (...)
3928 {
3929 info.storageBytes = 0;
3930 }
3931 }
3932 }
3933 }
3934
3935 // Check if cloud save directory exists
3936 if (info.enabled)
3937 {
3938 std::filesystem::path cloudDir = steamPath / "userdata" / userId / appIdStr / "remote";
3939 if (std::filesystem::exists(cloudDir))
3940 {
3941 // Get last write time of cloud directory as last sync time
3942 try
3943 {
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);
3949 }
3950 catch (...)
3951 {
3952 info.lastSyncTime = 0;
3953 }
3954 }
3955 }
3956
3957 return info;
3958}
3959
3960// ==============================================================================
3961// User Categories (Tags)
3962// ==============================================================================
3963
3964std::vector<std::string> SteamLibraryScanner::readSteamUserCategories(uint32_t appId)
3965{
3966 std::vector<std::string> categories;
3967
3968 // Get user config path
3969 std::filesystem::path steamPath = SteamPaths::getPrimarySteamRoot();
3970 if (steamPath.empty())
3971 return categories;
3972
3973 std::string userId = getActiveUserId();
3974 if (userId.empty())
3975 return categories;
3976
3977 std::filesystem::path userConfigPath =
3978 steamPath / "userdata" / userId / "config" / "localconfig.vdf";
3979
3980 if (!std::filesystem::exists(userConfigPath))
3981 return categories;
3982
3983 std::ifstream file(userConfigPath);
3984 if (!file.is_open())
3985 return categories;
3986
3987 std::string content = readVdfContent(file);
3988 file.close();
3989
3990 // Parse VDF to find tags section for this app
3991 // Structure: "Software" -> "Valve" -> "Steam" -> "Apps" -> "[AppID]" -> "tags"
3992
3993 std::string appIdStr = std::to_string(appId);
3994 std::string appSection = "\"" + appIdStr + "\"";
3995
3996 size_t appsPos = content.find("\"apps\"");
3997 if (appsPos == std::string::npos)
3998 return categories;
3999
4000 size_t appPos = content.find(appSection, appsPos);
4001 if (appPos == std::string::npos)
4002 return categories;
4003
4004 // Find the end of this app's section by brace-counting from its opening '{'
4005 size_t appOpenBrace = content.find('{', appPos + appSection.size());
4006 size_t appSectionEnd = (appOpenBrace != std::string::npos)
4007 ? findVdfSectionEnd(content, appOpenBrace)
4008 : std::string::npos;
4009
4010 // Find the tags section within this app
4011 size_t tagsPos = content.find("\"tags\"", appPos);
4012 if (tagsPos == std::string::npos ||
4013 (appSectionEnd != std::string::npos && tagsPos > appSectionEnd))
4014 return categories;
4015
4016 // Find the opening brace for tags section
4017 size_t bracePos = content.find("{", tagsPos);
4018 if (bracePos == std::string::npos)
4019 return categories;
4020
4021 // Parse tags section - format is "0" "TagName1", "1" "TagName2", etc.
4022 size_t pos = bracePos;
4023 int braceDepth = 1;
4024
4025 while (braceDepth > 0 && ++pos < content.length())
4026 {
4027 if (content[pos] == '{')
4028 braceDepth++;
4029 if (content[pos] == '}')
4030 {
4031 braceDepth--;
4032 continue;
4033 }
4034
4035 // Look for quoted strings (tag values)
4036 if (content[pos] == '\"')
4037 {
4038 size_t keyEnd = content.find('\"', pos + 1);
4039 if (keyEnd == std::string::npos)
4040 break;
4041
4042 // Skip the key (index number), find the value
4043 size_t valueStart = content.find('\"', keyEnd + 1);
4044 if (valueStart == std::string::npos)
4045 break;
4046
4047 size_t valueEnd = content.find('\"', valueStart + 1);
4048 if (valueEnd == std::string::npos)
4049 break;
4050
4051 std::string tagValue = content.substr(valueStart + 1, valueEnd - valueStart - 1);
4052 if (!tagValue.empty())
4053 {
4054 categories.push_back(tagValue);
4055 }
4056
4057 pos = valueEnd;
4058 }
4059 }
4060
4061 return categories;
4062}
4063
4064// ==============================================================================
4065// DLC Detection
4066// ==============================================================================
4067
4068std::vector<DLCInfo>
4069SteamLibraryScanner::readDLCFromACF(const std::filesystem::path& acfFilePath,
4070 const std::filesystem::path& /*libraryPath*/)
4071{
4072 std::vector<DLCInfo> dlcList;
4073
4074 std::ifstream file(acfFilePath);
4075 if (!file.is_open())
4076 {
4077 Logger::error("Failed to open ACF file for DLC detection: {}", acfFilePath.string());
4078 return dlcList;
4079 }
4080
4081 std::string content = readVdfContent(file);
4082 file.close();
4083
4084 // Parse InstalledDepots section
4085 // Structure: "AppState" -> "InstalledDepots" -> "[DepotID]" -> "manifest", "size", etc.
4086
4087 size_t depotsPos = content.find("\"InstalledDepots\"");
4088 if (depotsPos == std::string::npos)
4089 return dlcList;
4090
4091 size_t bracePos = content.find("{", depotsPos);
4092 if (bracePos == std::string::npos)
4093 return dlcList;
4094
4095 // Parse each depot
4096 size_t pos = bracePos;
4097 int braceDepth = 1;
4098
4099 while (braceDepth > 0 && ++pos < content.length())
4100 {
4101 if (content[pos] == '{')
4102 braceDepth++;
4103 if (content[pos] == '}')
4104 braceDepth--;
4105
4106 // Look for depot IDs (quoted numbers at depth 2)
4107 if (braceDepth == 2 && content[pos] == '\"')
4108 {
4109 size_t depotIdEnd = content.find('\"', pos + 1);
4110 if (depotIdEnd == std::string::npos)
4111 continue;
4112
4113 std::string depotIdStr = content.substr(pos + 1, depotIdEnd - pos - 1);
4114
4115 // Check if this is a number (depot ID)
4116 bool isNumber =
4117 !depotIdStr.empty() && std::all_of(depotIdStr.begin(), depotIdStr.end(), ::isdigit);
4118
4119 if (isNumber)
4120 {
4121 DLCInfo dlc;
4122 dlc.appId = 0; // We don't have the DLC App ID from depot ID
4123 dlc.installed = true; // It's in InstalledDepots, so it's installed
4124
4125 // Find the size within this depot's section using brace tracking
4126 size_t depotBracePos = content.find("{", depotIdEnd);
4127 if (depotBracePos != std::string::npos)
4128 {
4129 // Track braces to find the end of this depot's section
4130 int depth = 1;
4131 size_t depotSectionEnd = depotBracePos + 1;
4132 while (depotSectionEnd < content.size() && depth > 0)
4133 {
4134 if (content[depotSectionEnd] == '{')
4135 depth++;
4136 else if (content[depotSectionEnd] == '}')
4137 depth--;
4138 depotSectionEnd++;
4139 }
4140
4141 // Search for "size" only within this depot's section boundaries
4142 size_t sizePos = content.find("\"size\"", depotBracePos);
4143 if (sizePos != std::string::npos && sizePos < depotSectionEnd)
4144 {
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;
4149
4150 if (sizeValueStart != std::string::npos &&
4151 sizeValueEnd != std::string::npos && sizeValueEnd > sizeValueStart)
4152 {
4153 std::string sizeStr = content.substr(sizeValueStart + 1,
4154 sizeValueEnd - sizeValueStart - 1);
4155 try
4156 {
4157 dlc.sizeBytes = std::stoull(sizeStr);
4158 }
4159 catch (...)
4160 {
4161 dlc.sizeBytes = 0;
4162 }
4163 }
4164 }
4165 }
4166
4167 dlc.name = "Depot " + depotIdStr; // Default name, would need API call for real name
4168
4169 // Only add if it has significant size (filter out base game depot)
4170 if (dlc.sizeBytes > 0)
4171 {
4172 dlcList.push_back(dlc);
4173 }
4174 }
4175
4176 pos = depotIdEnd;
4177 }
4178 }
4179
4180 return dlcList;
4181}
4182
4183// ==============================================================================
4184// Batch Operations (More Efficient)
4185// ==============================================================================
4186
4187std::map<uint32_t, CloudSaveInfo> SteamLibraryScanner::readAllCloudSaveInfo()
4188{
4189 std::map<uint32_t, CloudSaveInfo> result;
4190
4191 std::filesystem::path steamPath = SteamPaths::getPrimarySteamRoot();
4192 if (steamPath.empty())
4193 return result;
4194
4195 std::string userId = getActiveUserId();
4196 if (userId.empty())
4197 return result;
4198
4199 std::filesystem::path userConfigPath =
4200 steamPath / "userdata" / userId / "config" / "localconfig.vdf";
4201
4202 if (!std::filesystem::exists(userConfigPath))
4203 return result;
4204
4205 std::ifstream file(userConfigPath);
4206 if (!file.is_open())
4207 return result;
4208
4209 std::string content = readVdfContent(file);
4210 file.close();
4211
4212 // Find Apps section
4213 size_t appsPos = content.find("\"apps\"");
4214 if (appsPos == std::string::npos)
4215 return result;
4216
4217 // Parse all app sections
4218 size_t pos = appsPos;
4219 while (true)
4220 {
4221 // Find next app ID
4222 pos = content.find("\"", pos + 1);
4223 if (pos == std::string::npos)
4224 break;
4225
4226 size_t appIdEnd = content.find("\"", pos + 1);
4227 if (appIdEnd == std::string::npos)
4228 break;
4229
4230 std::string appIdStr = content.substr(pos + 1, appIdEnd - pos - 1);
4231
4232 // Check if this is a number (app ID)
4233 bool isNumber =
4234 !appIdStr.empty() && std::all_of(appIdStr.begin(), appIdStr.end(), ::isdigit);
4235
4236 if (isNumber)
4237 {
4238 uint32_t appId = static_cast<uint32_t>(std::stoul(appIdStr));
4239
4240 // Check if this app has a Cloud section within its own VDF block
4241 size_t appOpenBrace = content.find('{', appIdEnd);
4242 size_t appSectionEnd = (appOpenBrace != std::string::npos)
4243 ? findVdfSectionEnd(content, appOpenBrace)
4244 : std::string::npos;
4245 size_t cloudPos = content.find("\"Cloud\"", appIdEnd);
4246
4247 if (cloudPos != std::string::npos &&
4248 (appSectionEnd == std::string::npos || cloudPos < appSectionEnd))
4249 {
4250 // Use the single-app function (it's already implemented above)
4252 if (info.supported)
4253 {
4254 result[appId] = info;
4255 }
4256 }
4257 }
4258
4259 pos = appIdEnd;
4260 }
4261
4262 return result;
4263}
4264
4265std::map<uint32_t, std::vector<std::string>> SteamLibraryScanner::readAllUserCategories()
4266{
4267 std::map<uint32_t, std::vector<std::string>> result;
4268
4269 std::filesystem::path steamPath = SteamPaths::getPrimarySteamRoot();
4270 if (steamPath.empty())
4271 return result;
4272
4273 std::string userId = getActiveUserId();
4274 if (userId.empty())
4275 return result;
4276
4277 std::filesystem::path userConfigPath =
4278 steamPath / "userdata" / userId / "config" / "localconfig.vdf";
4279
4280 if (!std::filesystem::exists(userConfigPath))
4281 return result;
4282
4283 std::ifstream file(userConfigPath);
4284 if (!file.is_open())
4285 return result;
4286
4287 std::string content = readVdfContent(file);
4288 file.close();
4289
4290 // Find Apps section
4291 size_t appsPos = content.find("\"apps\"");
4292 if (appsPos == std::string::npos)
4293 return result;
4294
4295 // Parse all app sections
4296 size_t pos = appsPos;
4297 while (true)
4298 {
4299 // Find next app ID
4300 pos = content.find("\"", pos + 1);
4301 if (pos == std::string::npos)
4302 break;
4303
4304 size_t appIdEnd = content.find("\"", pos + 1);
4305 if (appIdEnd == std::string::npos)
4306 break;
4307
4308 std::string appIdStr = content.substr(pos + 1, appIdEnd - pos - 1);
4309
4310 // Check if this is a number (app ID)
4311 bool isNumber =
4312 !appIdStr.empty() && std::all_of(appIdStr.begin(), appIdStr.end(), ::isdigit);
4313
4314 if (isNumber)
4315 {
4316 uint32_t appId = static_cast<uint32_t>(std::stoul(appIdStr));
4317
4318 // Check if this app has a tags section within its own VDF block
4319 size_t appOpenBrace = content.find('{', appIdEnd);
4320 size_t appSectionEnd = (appOpenBrace != std::string::npos)
4321 ? findVdfSectionEnd(content, appOpenBrace)
4322 : std::string::npos;
4323 size_t tagsPos = content.find("\"tags\"", appIdEnd);
4324
4325 if (tagsPos != std::string::npos &&
4326 (appSectionEnd == std::string::npos || tagsPos < appSectionEnd))
4327 {
4328 // Use the single-app function
4329 std::vector<std::string> categories = readSteamUserCategories(appId);
4330 if (!categories.empty())
4331 {
4332 result[appId] = categories;
4333 }
4334 }
4335 }
4336
4337 pos = appIdEnd;
4338 }
4339
4340 return result;
4341}
4342
4343// ==============================================================================
4344// Force Uninstall Implementation
4345// ==============================================================================
4346
4347bool SteamLibraryScanner::getGameInstallInfo(uint32_t appId, std::string& installDir,
4348 std::filesystem::path& libraryPath)
4349{
4350 SteamLibraryScanner scanner;
4351 auto libraries = scanner.getLibraryPaths();
4352
4353 std::string manifestName = "appmanifest_" + std::to_string(appId) + ".acf";
4354
4355 for (const auto& lib : libraries)
4356 {
4357 auto manifestPath = lib / "steamapps" / manifestName;
4358 if (std::filesystem::exists(manifestPath))
4359 {
4360 // Parse manifest to get installdir
4361 std::ifstream file(manifestPath);
4362 if (!file.is_open())
4363 {
4364 continue;
4365 }
4366
4367 std::string content = readVdfContent(file);
4368 file.close();
4369
4370 // Find installdir value
4371 std::string key = "\"installdir\"";
4372 size_t pos = content.find(key);
4373 if (pos != std::string::npos)
4374 {
4375 size_t valueStart = content.find("\"", pos + key.length());
4376 if (valueStart != std::string::npos)
4377 {
4378 valueStart++;
4379 size_t valueEnd = content.find("\"", valueStart);
4380 if (valueEnd != std::string::npos)
4381 {
4382 installDir = content.substr(valueStart, valueEnd - valueStart);
4383 libraryPath = lib;
4384 return true;
4385 }
4386 }
4387 }
4388 }
4389 }
4390 return false;
4391}
4392
4394{
4395 Logger::info("[SteamLibraryScanner] Requesting Steam uninstall for app {}", appId);
4396
4397 // Use Steam's native uninstall protocol
4398 // This opens Steam's uninstall confirmation dialog
4399 std::string uninstallUrl = "steam://uninstall/" + std::to_string(appId);
4400
4401 // Use fork/exec instead of std::system to avoid shell injection risks
4402 auto launchDetached = [](const char* program, const char* arg) -> bool
4403 {
4404 pid_t pid = fork();
4405 if (pid == 0)
4406 {
4407 // Child: redirect stderr to /dev/null, detach
4408 int devnull = open("/dev/null", O_WRONLY);
4409 if (devnull >= 0)
4410 {
4411 dup2(devnull, STDERR_FILENO);
4412 close(devnull);
4413 }
4414 setsid();
4415 execlp(program, program, arg, nullptr);
4416 _exit(127); // exec failed
4417 }
4418 return pid > 0;
4419 };
4420
4421 // Try xdg-open first (Linux standard)
4422 if (launchDetached("xdg-open", uninstallUrl.c_str()))
4423 {
4424 Logger::info("[SteamLibraryScanner] Sent uninstall request to Steam for app {}", appId);
4425 return true;
4426 }
4427
4428 // Fallback: try steam directly
4429 if (launchDetached("steam", uninstallUrl.c_str()))
4430 {
4431 Logger::info("[SteamLibraryScanner] Sent uninstall request to Steam for app {}", appId);
4432 return true;
4433 }
4434
4435 Logger::error("[SteamLibraryScanner] Failed to send uninstall request for app {}", appId);
4436 return false;
4437}
4438
4440{
4441 Logger::info("[SteamLibraryScanner] Force uninstalling Steam app {}", appId);
4442
4443 std::string installDir;
4444 std::filesystem::path libraryPath;
4445
4446 if (!getGameInstallInfo(appId, installDir, libraryPath))
4447 {
4448 Logger::error("[SteamLibraryScanner] Could not find installation info for app {}", appId);
4449 return false;
4450 }
4451
4452 bool success = true;
4453 std::error_code ec;
4454
4455 // Validate installDir doesn't contain path traversal components.
4456 // Substring check is fast but doesn't defend against symlinks: a
4457 // malicious or compromised ACF could put a benign-looking installdir
4458 // value pointing to a folder that is itself a symlink to anywhere on
4459 // disk. fs::remove_all follows symlinks for directories on POSIX, so
4460 // we'd happily nuke /home or worse.
4461 if (installDir.empty() || installDir.find("..") != std::string::npos ||
4462 installDir.find('/') != std::string::npos || installDir.find('\\') != std::string::npos)
4463 {
4464 Logger::error("[SteamLibraryScanner] Invalid installDir contains path traversal: {}",
4465 installDir);
4466 return false;
4467 }
4468
4469 // 1. Remove the game directory from steamapps/common/.
4470 //
4471 // Containment-check the canonical path is strictly inside
4472 // <libraryPath>/steamapps/common before deleting:
4473 // - weakly_canonical(gamePath) resolves any symlink components
4474 // - we then verify gamePath stays inside the common-dir
4475 // - and refuse if the path itself is a symlink (refuse to follow it
4476 // even into a "valid" location, since the user/Steam never
4477 // creates these via symlink legitimately)
4478 std::filesystem::path commonRoot = libraryPath / "steamapps" / "common";
4479 std::filesystem::path gamePath = commonRoot / installDir;
4480 if (std::filesystem::exists(gamePath))
4481 {
4482 // is_symlink() checks the path itself, not its targets — Steam
4483 // never installs games as symlinks, so refuse out of caution.
4484 if (std::filesystem::is_symlink(gamePath))
4485 {
4486 Logger::error("[SteamLibraryScanner] Refusing to delete '{}': path is a symlink "
4487 "(possible malicious ACF redirecting remove_all)",
4488 gamePath.string());
4489 return false;
4490 }
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)
4495 {
4496 Logger::error("[SteamLibraryScanner] Cannot canonicalize '{}'; refusing remove_all",
4497 gamePath.string());
4498 return false;
4499 }
4500 std::error_code relEc;
4501 auto rel = std::filesystem::relative(canonGame, canonCommon, relEc);
4502 if (relEc || rel.empty() || (*rel.begin()) == "..")
4503 {
4504 Logger::error("[SteamLibraryScanner] Refusing to delete '{}': resolved path "
4505 "escapes steamapps/common (resolved to '{}')",
4506 gamePath.string(), canonGame.string());
4507 return false;
4508 }
4509 Logger::info("[SteamLibraryScanner] Removing game directory: {}", gamePath.string());
4510 std::filesystem::remove_all(gamePath, ec);
4511 if (ec)
4512 {
4513 Logger::error("[SteamLibraryScanner] Failed to remove game directory: {}",
4514 ec.message());
4515 success = false;
4516 }
4517 }
4518
4519 // 2. Remove the Proton prefix from steamapps/compatdata/ (if exists)
4520 std::filesystem::path compatPath =
4521 libraryPath / "steamapps" / "compatdata" / std::to_string(appId);
4522 if (std::filesystem::exists(compatPath))
4523 {
4524 Logger::info("[SteamLibraryScanner] Removing Proton prefix: {}", compatPath.string());
4525 std::filesystem::remove_all(compatPath, ec);
4526 if (ec)
4527 {
4528 Logger::warn("[SteamLibraryScanner] Failed to remove compatdata: {}", ec.message());
4529 // Don't fail the whole operation for this
4530 }
4531 }
4532
4533 // 3. Remove the appmanifest file
4534 std::filesystem::path manifestPath =
4535 libraryPath / "steamapps" / ("appmanifest_" + std::to_string(appId) + ".acf");
4536 if (std::filesystem::exists(manifestPath))
4537 {
4538 Logger::info("[SteamLibraryScanner] Removing appmanifest: {}", manifestPath.string());
4539 std::filesystem::remove(manifestPath, ec);
4540 if (ec)
4541 {
4542 Logger::error("[SteamLibraryScanner] Failed to remove appmanifest: {}", ec.message());
4543 success = false;
4544 }
4545 }
4546
4547 // 4. Remove shader cache if exists
4548 std::filesystem::path shaderCachePath =
4549 libraryPath / "steamapps" / "shadercache" / std::to_string(appId);
4550 if (std::filesystem::exists(shaderCachePath))
4551 {
4552 Logger::info("[SteamLibraryScanner] Removing shader cache: {}", shaderCachePath.string());
4553 std::filesystem::remove_all(shaderCachePath, ec);
4554 if (ec)
4555 {
4556 Logger::warn("[SteamLibraryScanner] Failed to remove shader cache: {}", ec.message());
4557 // Don't fail the whole operation for this
4558 }
4559 }
4560
4561 if (success)
4562 {
4563 Logger::info("[SteamLibraryScanner] Successfully force uninstalled app {}", appId);
4564 }
4565 else
4566 {
4567 Logger::error("[SteamLibraryScanner] Force uninstall of app {} completed with errors",
4568 appId);
4569 }
4570
4571 return success;
4572}
4573
4574// ==============================================================================
4575// SteamDownloadMonitor Implementation
4576// ==============================================================================
4577
4579{
4580 public:
4581 Impl() = default;
4583 {
4584 stop();
4585 }
4586
4587 void start(int pollIntervalMs)
4588 {
4589 // CAS so two near-simultaneous start() calls don't both pass the
4590 // running_ check and spin up two monitor threads. The previous
4591 // load-then-store pattern was a textbook TOCTOU.
4592 bool expected = false;
4593 if (!running_.compare_exchange_strong(expected, true, std::memory_order_acq_rel))
4594 {
4595 return;
4596 }
4597 pollIntervalMs_ = pollIntervalMs;
4598 monitorThread_ = std::thread(&Impl::monitorLoop, this);
4599 }
4600
4601 void stop()
4602 {
4603 running_ = false;
4604 if (monitorThread_.joinable())
4605 {
4606 monitorThread_.join();
4607 }
4608 }
4609
4610 bool isRunning() const
4611 {
4612 return running_;
4613 }
4614
4615 // Setters for the four callback std::function members. Live inside
4616 // Impl so they can take the private mutex_; outer setters delegate.
4617 // Pairs with the mutex-guarded snapshot in pollGames(); std::function
4618 // is not atomic, so concurrent setter+poll-thread read races would
4619 // tear the function-pointer.
4621 {
4622 std::lock_guard<std::mutex> lock(mutex_);
4623 onProgressUpdate_ = std::move(cb);
4624 }
4626 {
4627 std::lock_guard<std::mutex> lock(mutex_);
4628 onStateChange_ = std::move(cb);
4629 }
4631 {
4632 std::lock_guard<std::mutex> lock(mutex_);
4633 onGameLaunch_ = std::move(cb);
4634 }
4636 {
4637 std::lock_guard<std::mutex> lock(mutex_);
4638 onGameExit_ = std::move(cb);
4639 }
4640
4641 void watchGame(uint32_t appId)
4642 {
4643 std::lock_guard<std::mutex> lock(mutex_);
4644 if (watchedGames_.find(appId) == watchedGames_.end())
4645 {
4646 Logger::info("[SteamDownloadMonitor] Starting to watch app {}", appId);
4647 watchedGames_[appId] = SteamDownloadProgress{};
4648 watchedGames_[appId].appId = appId;
4649 }
4650 }
4651
4652 void unwatchGame(uint32_t appId)
4653 {
4654 std::lock_guard<std::mutex> lock(mutex_);
4655 watchedGames_.erase(appId);
4656 lastStates_.erase(appId);
4657 lastRunningPids_.erase(appId);
4658 }
4659
4660 std::vector<uint32_t> getWatchedGames() const
4661 {
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_)
4666 {
4667 result.push_back(pair.first);
4668 }
4669 return result;
4670 }
4671
4673 {
4674 std::lock_guard<std::mutex> lock(mutex_);
4675 auto it = watchedGames_.find(appId);
4676 if (it != watchedGames_.end())
4677 {
4678 return it->second;
4679 }
4680 return SteamDownloadProgress{};
4681 }
4682
4683 // Callbacks
4688
4689 private:
4690 void monitorLoop()
4691 {
4692 while (running_)
4693 {
4694 pollGames();
4695 std::this_thread::sleep_for(std::chrono::milliseconds(pollIntervalMs_));
4696 }
4697 }
4698
4699 void pollGames()
4700 {
4701 // Collect events while holding the lock, then fire callbacks after releasing
4702 // This prevents deadlocks if callbacks try to call watchGame/unwatchGame/getProgress
4703 struct StateChangeEvent
4704 {
4705 uint32_t appId;
4706 uint32_t oldState;
4707 uint32_t newState;
4708 };
4709 struct ProgressEvent
4710 {
4711 uint32_t appId;
4712 SteamDownloadProgress progress;
4713 };
4714 struct LaunchEvent
4715 {
4716 uint32_t appId;
4717 int pid;
4718 };
4719 struct ExitEvent
4720 {
4721 uint32_t appId;
4722 };
4723
4724 std::vector<StateChangeEvent> stateChanges;
4725 std::vector<ProgressEvent> progressUpdates;
4726 std::vector<LaunchEvent> launches;
4727 std::vector<ExitEvent> exits;
4728
4729 // Capture callbacks UNDER the lock — std::function is not atomic
4730 // and the setOnXxx writers run on the GUI thread. Reading these
4731 // pointers without the mutex was a tiny but real data race that
4732 // would tear the std::function's internal pointer between
4733 // poll-thread and GUI-thread interleavings. Move the snapshot
4734 // inside the critical section; callbacks are still invoked
4735 // outside the lock further down (which is the original goal of
4736 // the prior pattern).
4741
4742 {
4743 std::lock_guard<std::mutex> lock(mutex_);
4744 onStateChange = onStateChange_;
4745 onProgressUpdate = onProgressUpdate_;
4746 onGameLaunch = onGameLaunch_;
4747 onGameExit = onGameExit_;
4748
4749 // Periodically refresh library paths (every 60 polls = ~1 minute at 1s interval)
4750 // Note: pollCount_ is a member of Impl, not static, to avoid cross-instance sharing
4751 if (++pollCount_ >= 60)
4752 {
4753 pollCount_ = 0;
4754 cachedLibraryPaths_.clear(); // Force refresh on next findAppManifest call
4755 }
4756
4757 for (auto& [appId, progress] : watchedGames_)
4758 {
4759 // Find the appmanifest file for this game
4760 auto manifestPath = findAppManifest(appId);
4761 if (manifestPath.empty())
4762 {
4763 Logger::debug("[SteamDownloadMonitor] No manifest found for app {}", appId);
4764 // No manifest = not installed or being uninstalled
4765 if (progress.stateFlags != 0)
4766 {
4767 uint32_t oldState = progress.stateFlags;
4768 progress.stateFlags = 0;
4769 progress.stateDescription = "Not Installed";
4770 progress.isComplete = false;
4771
4772 stateChanges.push_back({appId, oldState, 0});
4773 }
4774 continue;
4775 }
4776
4777 Logger::debug("[SteamDownloadMonitor] Found manifest for app {}: {}", appId,
4778 manifestPath.string());
4779
4780 // Parse the manifest for current state
4781 SteamDownloadProgress newProgress = parseManifestProgress(appId, manifestPath);
4782
4783 // Check for state change
4784 auto lastIt = lastStates_.find(appId);
4785 uint32_t lastState = (lastIt != lastStates_.end()) ? lastIt->second : 0;
4786
4787 if (newProgress.stateFlags != lastState)
4788 {
4789 lastStates_[appId] = newProgress.stateFlags;
4790 stateChanges.push_back({appId, lastState, newProgress.stateFlags});
4791 }
4792
4793 // Check for progress update (only if actively downloading/staging, NOT for fully
4794 // installed games)
4795 bool isActivelyInstalling =
4797 (newProgress.stateFlags & SteamStateFlags::Staging) != 0 ||
4798 (newProgress.stateFlags & SteamStateFlags::UpdateRequired) != 0;
4799
4800 bool hasProgressChange = newProgress.bytesDownloaded != progress.bytesDownloaded ||
4801 newProgress.bytesStaged != progress.bytesStaged ||
4802 newProgress.stateFlags != progress.stateFlags;
4803
4804 // Only send progress updates for games that are actively installing/downloading
4805 if (hasProgressChange && isActivelyInstalling)
4806 {
4807 // Preserve speed tracking state from previous progress
4808 newProgress.lastBytesDownloaded = progress.lastBytesDownloaded;
4809 newProgress.lastSpeedUpdate = progress.lastSpeedUpdate;
4810 newProgress.queuePosition = progress.queuePosition;
4811
4812 // Update speed calculation
4813 newProgress.updateSpeed();
4814
4815 Logger::info("[SteamDownloadMonitor] App {} progress: state={} ({}) "
4816 "downloaded={}/{} overall={}% speed={}",
4817 appId, newProgress.stateFlags, newProgress.stateDescription,
4818 newProgress.bytesDownloaded, newProgress.bytesToDownload,
4819 static_cast<int>(newProgress.overallProgress * 100.0),
4820 newProgress.getFormattedSpeed());
4821 progress = newProgress;
4822 progressUpdates.push_back({appId, progress});
4823 }
4824 else
4825 {
4826 // Still update our stored progress state, but don't trigger UI updates
4827 progress = newProgress;
4828 }
4829
4830 // Check for game launch/exit
4832 auto pidIt = lastRunningPids_.find(appId);
4833 int lastPid = (pidIt != lastRunningPids_.end()) ? pidIt->second : -1;
4834
4835 if (pid > 0 && lastPid <= 0)
4836 {
4837 // Game launched
4838 lastRunningPids_[appId] = pid;
4839 launches.push_back({appId, pid});
4840 }
4841 else if (pid <= 0 && lastPid > 0)
4842 {
4843 // Game exited
4844 lastRunningPids_[appId] = -1;
4845 exits.push_back({appId});
4846 }
4847 }
4848 }
4849 // Mutex released - now safe to invoke callbacks
4850
4851 // Fire state change callbacks
4852 for (const auto& event : stateChanges)
4853 {
4854 if (onStateChange)
4855 {
4856 onStateChange(event.appId, event.oldState, event.newState);
4857 }
4858 }
4859
4860 // Fire progress update callbacks
4861 for (const auto& event : progressUpdates)
4862 {
4863 if (onProgressUpdate)
4864 {
4865 Logger::debug("[SteamDownloadMonitor] Calling onProgressUpdate callback for app {}",
4866 event.appId);
4867 onProgressUpdate(event.appId, event.progress);
4868 }
4869 }
4870
4871 // Fire game launch callbacks
4872 for (const auto& event : launches)
4873 {
4874 if (onGameLaunch)
4875 {
4876 onGameLaunch(event.appId, event.pid);
4877 }
4878 }
4879
4880 // Fire game exit callbacks
4881 for (const auto& event : exits)
4882 {
4883 if (onGameExit)
4884 {
4885 onGameExit(event.appId);
4886 }
4887 }
4888 }
4889
4890 std::filesystem::path findAppManifest(uint32_t appId)
4891 {
4892 // Cache library paths to avoid repeated scanning
4893 if (cachedLibraryPaths_.empty())
4894 {
4895 SteamLibraryScanner scanner;
4896 cachedLibraryPaths_ = scanner.getLibraryPaths();
4897 Logger::info("[SteamDownloadMonitor] Loaded {} Steam library paths:",
4898 cachedLibraryPaths_.size());
4899 for (const auto& lib : cachedLibraryPaths_)
4900 {
4901 Logger::info("[SteamDownloadMonitor] - {}", lib.string());
4902 }
4903 }
4904
4905 std::string manifestName = "appmanifest_" + std::to_string(appId) + ".acf";
4906
4907 for (const auto& lib : cachedLibraryPaths_)
4908 {
4909 auto manifestPath = lib / "steamapps" / manifestName;
4910 if (std::filesystem::exists(manifestPath))
4911 {
4912 return manifestPath;
4913 }
4914 }
4915 return {};
4916 }
4917
4918 SteamDownloadProgress parseManifestProgress(uint32_t appId,
4919 const std::filesystem::path& manifestPath)
4920 {
4921 SteamDownloadProgress progress;
4922 progress.appId = appId;
4923
4924 // Get file size first to detect if file is being written
4925 std::error_code ec;
4926 auto fileSize = std::filesystem::file_size(manifestPath, ec);
4927 if (ec || fileSize == 0)
4928 {
4929 // File doesn't exist, is empty, or we can't read size
4930 return progress;
4931 }
4932
4933 std::ifstream file(manifestPath);
4934 if (!file.is_open())
4935 {
4936 return progress;
4937 }
4938
4939 std::string content = readVdfContent(file);
4940 file.close();
4941
4942 // Validate we read the entire file (Steam might be mid-write)
4943 if (content.size() < fileSize)
4944 {
4945 Logger::debug("[SteamDownloadMonitor] Partial read for app {}: got {} of {} bytes",
4946 appId, content.size(), fileSize);
4947 return progress; // Return default, will retry next poll
4948 }
4949
4950 // Basic ACF structure validation - must have "AppState" header
4951 if (content.find("\"AppState\"") == std::string::npos)
4952 {
4953 Logger::debug("[SteamDownloadMonitor] Invalid manifest for app {}: missing AppState",
4954 appId);
4955 return progress;
4956 }
4957
4958 // Parse key values from ACF
4959 auto getValue = [&content](const std::string& key) -> std::string
4960 {
4961 std::string pattern = "\"" + key + "\"";
4962 size_t pos = content.find(pattern);
4963 if (pos == std::string::npos)
4964 return "";
4965
4966 // Find the value after the key (skip whitespace and tabs)
4967 size_t valueStart = content.find("\"", pos + pattern.length());
4968 if (valueStart == std::string::npos)
4969 return "";
4970 valueStart++;
4971
4972 size_t valueEnd = content.find("\"", valueStart);
4973 if (valueEnd == std::string::npos)
4974 return "";
4975
4976 return content.substr(valueStart, valueEnd - valueStart);
4977 };
4978
4979 // Extract progress values - read all at once for consistency
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");
4985
4986 // StateFlags is required - if missing, file is corrupt or incomplete
4987 if (stateFlagsStr.empty())
4988 {
4989 Logger::debug("[SteamDownloadMonitor] No StateFlags in manifest for app {}", appId);
4990 return progress;
4991 }
4992
4993 try
4994 {
4995 progress.stateFlags = static_cast<uint32_t>(std::stoul(stateFlagsStr));
4996
4997 if (!bytesDownloadedStr.empty())
4998 progress.bytesDownloaded = std::stoull(bytesDownloadedStr);
4999 if (!bytesToDownloadStr.empty())
5000 progress.bytesToDownload = std::stoull(bytesToDownloadStr);
5001 if (!bytesStagedStr.empty())
5002 progress.bytesStaged = std::stoull(bytesStagedStr);
5003 if (!bytesToStageStr.empty())
5004 progress.bytesToStage = std::stoull(bytesToStageStr);
5005
5006 // If game is downloading but manifest shows 0 bytes downloaded,
5007 // try to get actual progress by checking the downloading folder size
5009 progress.bytesDownloaded == 0 && progress.bytesToDownload > 0)
5010 {
5011 // Find the downloading folder for this game
5012 std::filesystem::path manifestDir = manifestPath.parent_path();
5013 std::filesystem::path downloadingDir =
5014 manifestDir / "downloading" / std::to_string(appId);
5015
5016 if (std::filesystem::exists(downloadingDir))
5017 {
5018 uint64_t actualBytes = 0;
5019 std::error_code dirEc;
5020 for (const auto& entry : std::filesystem::recursive_directory_iterator(
5021 downloadingDir,
5022 std::filesystem::directory_options::skip_permission_denied, dirEc))
5023 {
5024 if (entry.is_regular_file())
5025 {
5026 std::error_code sizeEc;
5027 auto size = entry.file_size(sizeEc);
5028 if (!sizeEc)
5029 {
5030 actualBytes += size;
5031 }
5032 }
5033 }
5034
5035 if (actualBytes > 0)
5036 {
5037 progress.bytesDownloaded = actualBytes;
5039 "[SteamDownloadMonitor] App {} using folder size: {} bytes downloaded",
5040 appId, actualBytes);
5041 }
5042 }
5043 }
5044
5045 // Sanity check: downloaded bytes shouldn't exceed total
5046 if (progress.bytesToDownload > 0 && progress.bytesDownloaded > progress.bytesToDownload)
5047 {
5048 // Clamp to total (folder might have temp files)
5049 progress.bytesDownloaded = progress.bytesToDownload;
5050 }
5051 }
5052 catch (const std::exception& e)
5053 {
5054 Logger::warn("Error parsing manifest progress for app {}: {}", appId, e.what());
5055 return progress; // Return with just appId set
5056 }
5057
5060 progress.calculateProgress();
5061 return progress;
5062 }
5063
5064 std::atomic<bool> running_{false};
5065 int pollIntervalMs_ = 1000;
5066 int pollCount_ = 0;
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_; // Cache to avoid rescanning
5073};
5074
5075// ==============================================================================
5076// SteamDownloadMonitor Public Interface
5077// ==============================================================================
5078
5079SteamDownloadMonitor::SteamDownloadMonitor() : impl_(std::make_unique<Impl>()) {}
5080
5082
5084SteamDownloadMonitor& SteamDownloadMonitor::operator=(SteamDownloadMonitor&&) noexcept = default;
5085
5086void SteamDownloadMonitor::start(int pollIntervalMs)
5087{
5088 impl_->start(pollIntervalMs);
5089}
5090
5092{
5093 impl_->stop();
5094}
5095
5097{
5098 return impl_->isRunning();
5099}
5100
5102{
5103 impl_->watchGame(appId);
5104}
5105
5107{
5108 impl_->unwatchGame(appId);
5109}
5110
5111std::vector<uint32_t> SteamDownloadMonitor::getWatchedGames() const
5112{
5113 return impl_->getWatchedGames();
5114}
5115
5117{
5118 return impl_->getProgress(appId);
5119}
5120
5122{
5123 // Check Steam's reaper PID tracking
5124 // Steam stores running game PIDs in ~/.steam/steam/steamapps/shadercache/<appid>/pid
5125 // or in the compatdata folder
5126
5127 std::filesystem::path steamPath;
5128
5129 // Try common Steam paths
5130 const char* homeDir = std::getenv("HOME");
5131 if (homeDir)
5132 {
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"};
5137
5138 for (const auto& path : possiblePaths)
5139 {
5140 if (std::filesystem::exists(path))
5141 {
5142 steamPath = path;
5143 break;
5144 }
5145 }
5146 }
5147
5148 if (steamPath.empty())
5149 {
5150 return -1;
5151 }
5152
5153 // Check for reaper process file
5154 auto compatDataPath = steamPath / "steamapps" / "compatdata" / std::to_string(appId);
5155 auto pidFile = compatDataPath / "reaper.pid";
5156
5157 if (std::filesystem::exists(pidFile))
5158 {
5159 std::ifstream file(pidFile);
5160 if (file.is_open())
5161 {
5162 int pid;
5163 if (file >> pid && pid > 0)
5164 {
5165 // `kill(pid, 0)` only confirms a pid IS running; it does NOT
5166 // confirm it's *our* game. After the game exits and Steam
5167 // removes reaper.pid, the kernel can recycle the pid for an
5168 // unrelated process and we'd return its pid as the running
5169 // game (causing the launcher's PID-watcher to follow some
5170 // other process's lifecycle). Verify by reading
5171 // /proc/<pid>/environ and checking for SteamGameId=<appId>
5172 // — this binds the pid to the specific Steam game, not just
5173 // "any process".
5174 if (::kill(pid, 0) == 0)
5175 {
5176 std::ifstream envFile("/proc/" + std::to_string(pid) + "/environ",
5177 std::ios::binary);
5178 if (envFile.is_open())
5179 {
5180 std::string content((std::istreambuf_iterator<char>(envFile)),
5181 std::istreambuf_iterator<char>());
5182 const std::string needle = "SteamGameId=" + std::to_string(appId);
5183 // /proc/<pid>/environ is NUL-separated; we just
5184 // substring-search for the needle which is unique
5185 // enough (Steam uses this exact env name).
5186 if (content.find(needle) != std::string::npos)
5187 {
5188 return pid;
5189 }
5190 }
5191 }
5192 }
5193 }
5194 }
5195
5196 // Alternative: Check /proc for game processes
5197 // Look for processes with Steam's game environment variables
5198 std::string cmd = "pgrep -f 'SteamAppId=" + std::to_string(appId) + "' 2>/dev/null | head -1";
5200 if (result.success && !result.output.empty())
5201 {
5202 try
5203 {
5204 return std::stoi(result.output);
5205 }
5206 catch (...)
5207 {
5208 // Ignore parse errors
5209 }
5210 }
5211
5212 return -1;
5213}
5214
5216{
5217 // Check if Steam's download process is active
5218 // Look for steamwebhelper or steam processes using significant CPU/disk
5219 return !getDownloadingGames().empty();
5220}
5221
5223{
5224 std::vector<uint32_t> downloading;
5225
5226 // Scan all appmanifest files for downloading state
5227 SteamLibraryScanner scanner;
5228 auto libraries = scanner.getLibraryPaths();
5229
5230 for (const auto& lib : libraries)
5231 {
5232 auto steamappsPath = lib / "steamapps";
5233 if (!std::filesystem::exists(steamappsPath))
5234 continue;
5235
5236 for (const auto& entry : std::filesystem::directory_iterator(steamappsPath))
5237 {
5238 if (!entry.is_regular_file())
5239 continue;
5240
5241 std::string filename = entry.path().filename().string();
5242 if (filename.find("appmanifest_") != 0 || filename.find(".acf") == std::string::npos)
5243 continue;
5244
5245 // Extract app ID from filename
5246 size_t start = 12; // length of "appmanifest_"
5247 size_t end = filename.find(".acf");
5248 std::string appIdStr = filename.substr(start, end - start);
5249
5250 try
5251 {
5252 uint32_t appId = static_cast<uint32_t>(std::stoul(appIdStr));
5253
5254 // Read the manifest to check state
5255 std::ifstream file(entry.path());
5256 if (!file.is_open())
5257 continue;
5258
5259 std::string content = readVdfContent(file);
5260 file.close();
5261
5262 // Find StateFlags
5263 size_t pos = content.find("\"StateFlags\"");
5264 if (pos != std::string::npos)
5265 {
5266 size_t valueStart = content.find("\"", pos + 12);
5267 if (valueStart != std::string::npos)
5268 {
5269 valueStart++;
5270 size_t valueEnd = content.find("\"", valueStart);
5271 if (valueEnd != std::string::npos)
5272 {
5273 std::string flagsStr =
5274 content.substr(valueStart, valueEnd - valueStart);
5275 uint32_t flags = static_cast<uint32_t>(std::stoul(flagsStr));
5276
5278 {
5279 downloading.push_back(appId);
5280 }
5281 }
5282 }
5283 }
5284 }
5285 catch (...)
5286 {
5287 // Skip invalid entries
5288 }
5289 }
5290 }
5291
5292 return downloading;
5293}
5294
5296{
5297 SteamDownloadProgress progress;
5298 progress.appId = appId;
5299
5300 // Find the appmanifest file for this game
5301 SteamLibraryScanner scanner;
5302 auto libraries = scanner.getLibraryPaths();
5303
5304 std::filesystem::path manifestPath;
5305 std::string manifestName = "appmanifest_" + std::to_string(appId) + ".acf";
5306
5307 for (const auto& lib : libraries)
5308 {
5309 auto path = lib / "steamapps" / manifestName;
5310 if (std::filesystem::exists(path))
5311 {
5312 manifestPath = path;
5313 break;
5314 }
5315 }
5316
5317 if (manifestPath.empty())
5318 {
5319 // No manifest = game not installed or being installed
5320 progress.stateDescription = "Not Installed";
5321 return progress;
5322 }
5323
5324 // Get file size first to detect if file is being written
5325 std::error_code ec;
5326 auto fileSize = std::filesystem::file_size(manifestPath, ec);
5327 if (ec || fileSize == 0)
5328 {
5329 progress.stateDescription = "Unknown";
5330 return progress;
5331 }
5332
5333 // Read and parse the manifest
5334 std::ifstream file(manifestPath);
5335 if (!file.is_open())
5336 {
5337 return progress;
5338 }
5339
5340 std::string content = readVdfContent(file);
5341 file.close();
5342
5343 // Validate we read the entire file
5344 if (content.size() < fileSize)
5345 {
5346 progress.stateDescription = "Reading...";
5347 return progress; // Steam is still writing
5348 }
5349
5350 // Basic ACF structure validation
5351 if (content.find("\"AppState\"") == std::string::npos)
5352 {
5353 progress.stateDescription = "Invalid";
5354 return progress;
5355 }
5356
5357 // Parse key values from ACF
5358 auto getValue = [&content](const std::string& key) -> std::string
5359 {
5360 std::string pattern = "\"" + key + "\"";
5361 size_t pos = content.find(pattern);
5362 if (pos == std::string::npos)
5363 return "";
5364
5365 // Find the value after the key
5366 size_t valueStart = content.find("\"", pos + pattern.length());
5367 if (valueStart == std::string::npos)
5368 return "";
5369 valueStart++;
5370
5371 size_t valueEnd = content.find("\"", valueStart);
5372 if (valueEnd == std::string::npos)
5373 return "";
5374
5375 return content.substr(valueStart, valueEnd - valueStart);
5376 };
5377
5378 // Extract progress values
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");
5384
5385 // StateFlags is required
5386 if (stateFlagsStr.empty())
5387 {
5388 progress.stateDescription = "Unknown";
5389 return progress;
5390 }
5391
5392 try
5393 {
5394 progress.stateFlags = static_cast<uint32_t>(std::stoul(stateFlagsStr));
5395
5396 if (!bytesDownloadedStr.empty())
5397 progress.bytesDownloaded = std::stoull(bytesDownloadedStr);
5398 if (!bytesToDownloadStr.empty())
5399 progress.bytesToDownload = std::stoull(bytesToDownloadStr);
5400 if (!bytesStagedStr.empty())
5401 progress.bytesStaged = std::stoull(bytesStagedStr);
5402 if (!bytesToStageStr.empty())
5403 progress.bytesToStage = std::stoull(bytesToStageStr);
5404 }
5405 catch (const std::exception& e)
5406 {
5407 Logger::warn("Error parsing manifest for app {}: {}", appId, e.what());
5408 progress.stateDescription = "Parse Error";
5409 return progress;
5410 }
5411
5412 // Set state description based on flags
5415
5416 // Calculate progress percentages
5417 progress.calculateProgress();
5418
5419 return progress;
5420}
5421
5422// All four setters delegate to Impl helpers that acquire the private
5423// mutex_, pairing with the snapshot read in pollGames().
5425{
5426 impl_->setProgressCallback(std::move(callback));
5427}
5428
5430{
5431 impl_->setStateChangeCallback(std::move(callback));
5432}
5433
5435{
5436 impl_->setGameLaunchCallback(std::move(callback));
5437}
5438
5440{
5441 impl_->setGameExitCallback(std::move(callback));
5442}
5443
5444// ==============================================================================
5445// Steam Update Monitor Implementation
5446// ==============================================================================
5447
5449{
5450 public:
5451 std::atomic<bool> running_{false};
5452 std::atomic<bool> shouldStop_{false};
5453 std::thread monitorThread_;
5454 std::mutex mutex_;
5455 std::condition_variable cv_;
5457
5458 // Cached state of all games
5459 std::map<uint32_t, SteamGameUpdateInfo> gameStates_;
5460 std::mutex statesMutex_;
5461
5462 // Callbacks
5466
5468 {
5469 Logger::info("SteamUpdateMonitor: Starting update monitoring thread");
5470
5471 while (!shouldStop_)
5472 {
5473 // Perform scan
5475
5476 // Wait for interval or stop signal
5477 std::unique_lock<std::mutex> lock(mutex_);
5478 cv_.wait_for(lock, std::chrono::seconds(scanIntervalSeconds_),
5479 [this] { return shouldStop_.load(); });
5480 }
5481
5482 Logger::info("SteamUpdateMonitor: Monitor thread stopped");
5483 }
5484
5486 {
5487 SteamLibraryScanner scanner;
5488 if (!scanner.isSteamInstalled())
5489 {
5490 return;
5491 }
5492
5493 std::vector<std::filesystem::path> libraries = scanner.getLibraryPaths();
5494
5495 // Collect all current game states
5496 std::map<uint32_t, SteamGameUpdateInfo> currentStates;
5497
5498 for (const auto& libraryPath : libraries)
5499 {
5500 std::filesystem::path steamappsPath = libraryPath / "steamapps";
5501 if (!std::filesystem::exists(steamappsPath))
5502 continue;
5503
5504 // Scan all appmanifest files
5505 for (const auto& entry : std::filesystem::directory_iterator(steamappsPath))
5506 {
5507 if (!entry.is_regular_file())
5508 continue;
5509
5510 std::string filename = entry.path().filename().string();
5511 if (filename.find("appmanifest_") != 0 ||
5512 filename.find(".acf") == std::string::npos)
5513 continue;
5514
5515 // Parse appmanifest
5516 std::ifstream file(entry.path());
5517 if (!file.is_open())
5518 continue;
5519
5520 std::string content = readVdfContent(file);
5521 file.close();
5522
5523 // Extract App ID using custom delimiter to avoid )" issues
5524 std::regex appIdRegex(R"_r("appid"\s+"(\d+)")_r");
5525 std::smatch appIdMatch;
5526 if (!std::regex_search(content, appIdMatch, appIdRegex))
5527 continue;
5528
5529 // Hardened parse: a malformed manifest with an out-of-range
5530 // value would otherwise throw std::out_of_range /
5531 // std::invalid_argument and abort scanForUpdates mid-iteration,
5532 // leaving cached states partially populated. The other
5533 // stoul/stoull call sites in this file are wrapped in try/catch
5534 // — these three were the missed spots.
5535 uint32_t appId = 0;
5536 try
5537 {
5538 unsigned long parsed = std::stoul(appIdMatch[1].str());
5539 if (parsed > std::numeric_limits<uint32_t>::max())
5540 continue;
5541 appId = static_cast<uint32_t>(parsed);
5542 }
5543 catch (const std::exception&)
5544 {
5545 continue; // skip this manifest, scan rest
5546 }
5547
5548 // Extract game name
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))
5553 {
5554 gameName = nameMatch[1].str();
5555 }
5556
5557 // Extract StateFlags
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))
5562 {
5563 try
5564 {
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);
5568 }
5569 catch (const std::exception&)
5570 { /* leave stateFlags = 0 */
5571 }
5572 }
5573
5574 // Extract BytesToDownload if available
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))
5579 {
5580 try
5581 {
5582 bytesToDownload = std::stoull(bytesMatch[1].str());
5583 }
5584 catch (const std::exception&)
5585 { /* leave 0 */
5586 }
5587 }
5588
5589 // Build update info
5591 info.appId = appId;
5592 info.gameName = gameName;
5593 info.stateFlags = stateFlags;
5594 info.needsUpdate = SteamStateFlags::needsUpdate(stateFlags);
5596 info.updateSizeBytes = bytesToDownload;
5597 info.detectedAt = std::time(nullptr);
5598
5599 currentStates[appId] = info;
5600 }
5601 }
5602
5603 // Compare with cached states and fire callbacks
5604 {
5605 std::lock_guard<std::mutex> lock(statesMutex_);
5606
5607 for (const auto& [appId, info] : currentStates)
5608 {
5609 auto it = gameStates_.find(appId);
5610
5611 if (it == gameStates_.end())
5612 {
5613 // New game found - check if it needs update
5614 if (info.needsUpdate && onUpdateAvailable_)
5615 {
5616 Logger::info("SteamUpdateMonitor: New update available for {} ({})",
5617 info.gameName, appId);
5618 onUpdateAvailable_(info);
5619 }
5620 }
5621 else
5622 {
5623 const auto& oldInfo = it->second;
5624
5625 // Check for state transitions
5626 if (!oldInfo.needsUpdate && info.needsUpdate)
5627 {
5628 // Newly detected update
5630 {
5631 Logger::info("SteamUpdateMonitor: Update detected for {} ({})",
5632 info.gameName, appId);
5633 onUpdateAvailable_(info);
5634 }
5635 }
5636 else if (!oldInfo.isDownloading && info.isDownloading)
5637 {
5638 // Download started
5639 if (onUpdateStarted_)
5640 {
5641 Logger::info("SteamUpdateMonitor: Update started for {} ({})",
5642 info.gameName, appId);
5643 onUpdateStarted_(info);
5644 }
5645 }
5646 else if ((oldInfo.needsUpdate || oldInfo.isDownloading) && !info.needsUpdate &&
5647 !info.isDownloading &&
5648 SteamStateFlags::isFullyInstalled(info.stateFlags))
5649 {
5650 // Update completed
5652 {
5653 Logger::info("SteamUpdateMonitor: Update completed for {} ({})",
5654 info.gameName, appId);
5655 onUpdateCompleted_(appId, info.gameName);
5656 }
5657 }
5658 }
5659 }
5660
5661 // Update cached states
5662 gameStates_ = std::move(currentStates);
5663 }
5664 }
5665};
5666
5672
5673SteamUpdateMonitor::SteamUpdateMonitor() : impl_(std::make_unique<Impl>()) {}
5674
5675SteamUpdateMonitor::~SteamUpdateMonitor()
5676{
5677 stop();
5678}
5679
5680void SteamUpdateMonitor::start(int scanIntervalSeconds)
5681{
5682 // CAS to atomically check-and-set the running flag. The previous
5683 // load-then-store pattern would let two near-simultaneous start()
5684 // calls both pass the check and spawn two monitor threads.
5685 bool expected = false;
5686 if (!impl_->running_.compare_exchange_strong(expected, true, std::memory_order_acq_rel))
5687 {
5688 Logger::warn("SteamUpdateMonitor: Already running");
5689 return;
5690 }
5691
5692 impl_->scanIntervalSeconds_ = scanIntervalSeconds;
5693 impl_->shouldStop_ = false;
5694
5695 impl_->monitorThread_ = std::thread(&Impl::monitorLoop, impl_.get());
5696
5697 Logger::info("SteamUpdateMonitor: Started with {} second interval", scanIntervalSeconds);
5698}
5699
5701{
5702 if (!impl_->running_)
5703 return;
5704
5705 impl_->shouldStop_ = true;
5706 impl_->cv_.notify_all();
5707
5708 if (impl_->monitorThread_.joinable())
5709 {
5710 impl_->monitorThread_.join();
5711 }
5712
5713 impl_->running_ = false;
5714 Logger::info("SteamUpdateMonitor: Stopped");
5715}
5716
5718{
5719 return impl_->running_;
5720}
5721
5722std::vector<SteamGameUpdateInfo> SteamUpdateMonitor::scanNow()
5723{
5724 impl_->scanForUpdates();
5725 return getGamesNeedingUpdate();
5726}
5727
5728std::vector<SteamGameUpdateInfo> SteamUpdateMonitor::getGamesNeedingUpdate() const
5729{
5730 std::vector<SteamGameUpdateInfo> result;
5731 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5732
5733 for (const auto& [appId, info] : impl_->gameStates_)
5734 {
5735 if (info.needsUpdate || info.isDownloading)
5736 {
5737 result.push_back(info);
5738 }
5739 }
5740
5741 return result;
5742}
5743
5745{
5746 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5747 size_t count = 0;
5748
5749 for (const auto& [appId, info] : impl_->gameStates_)
5750 {
5751 if (info.needsUpdate)
5752 {
5753 count++;
5754 }
5755 }
5756
5757 return count;
5758}
5759
5761{
5762 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5763 impl_->gameStates_.clear();
5764 Logger::info("SteamUpdateMonitor: Cache cleared");
5765}
5766
5767// All three setters take the same statesMutex_ that scanForUpdates() holds
5768// while reading the callbacks (line ~5400). std::function is not atomic;
5769// without the lock the scan thread could read a torn function-pointer.
5771{
5772 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5773 impl_->onUpdateAvailable_ = std::move(callback);
5774}
5775
5777{
5778 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5779 impl_->onUpdateStarted_ = std::move(callback);
5780}
5781
5783{
5784 std::lock_guard<std::mutex> lock(impl_->statesMutex_);
5785 impl_->onUpdateCompleted_ = std::move(callback);
5786}
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.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::string installPath
Installation directory path.
Definition game.h:819
std::string name
Display name shown in UI.
Definition game.h:774
void syncPlatformFromRunner()
Sync the deprecated platform field from the current runner and source.
Definition game.h:912
GameStatistics statistics
Play statistics and usage tracking.
Definition game.h:786
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
GameStatus status
Current installation and execution status.
Definition game.h:778
uint64_t installSizeBytes
Installation size in bytes.
Definition game.h:820
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
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.
Definition shell_utils.h:65
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 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::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.
Definition game.h:41
ImageType
Types of game images available.
Definition game.h:478
@ HeroImage
Wide banner/hero image (landscape).
Definition game.h:480
@ Capsule
Store capsule image (616x353).
Definition game.h:483
@ VerticalCover
Vertical cover art (600x900, portrait).
Definition game.h:479
@ Icon
Small square icon.
Definition game.h:484
@ Logo
Game logo with transparency (PNG).
Definition game.h:481
@ Header
Small header image (460x215).
Definition game.h:482
@ NotInstalled
Game is in library but not installed.
Definition game.h:98
@ Installed
Game is installed and ready to play.
Definition game.h:99
@ Proton
Proton (Steam's Wine fork).
Definition game.h:84
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:82
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.
Definition game.h:517
uint64_t storageBytes
Cloud storage used in bytes.
Definition game.h:521
time_t lastSyncTime
Last successful sync timestamp.
Definition game.h:522
bool enabled
Cloud saves enabled for this game.
Definition game.h:518
bool supported
Game supports Steam Cloud.
Definition game.h:519
int lastSyncState
0=synced, 1=uploading, 2=downloading, 3=error
Definition game.h:520
Information about downloadable content (DLC).
Definition game.h:536
int appId
Steam App ID of the DLC.
Definition game.h:537
bool installed
True if DLC is installed.
Definition game.h:539
uint64_t sizeBytes
Installation size in bytes.
Definition game.h:540
std::string name
DLC display name.
Definition game.h:538
Paths to various game image assets.
Definition game.h:496
std::string header
Small header image (header.jpg, 460x215).
Definition game.h:500
std::string capsule
Store capsule image (capsule_616x353.jpg).
Definition game.h:501
std::string logo
Game logo with transparency (logo.png).
Definition game.h:499
std::string icon
Small square icon (icon.jpg).
Definition game.h:502
std::string verticalCover
Vertical cover art (library_600x900.jpg).
Definition game.h:497
std::string heroImage
Wide banner/hero image (library_hero.jpg).
Definition game.h:498
time_t steamLastLaunch
Last launch timestamp from Steam.
Definition game.h:580
std::vector< std::string > steamCategories
Steam categories (Single-player, Multi-player, etc.).
Definition game.h:584
bool isSteamGame
True if imported from Steam.
Definition game.h:574
bool steamInstalled
True if Steam game is installed (set during Steam import).
Definition game.h:576
time_t steamLastExit
Last exit timestamp from Steam.
Definition game.h:581
std::string steamType
Steam app type: game, dlc, demo, tool, music, etc.
Definition game.h:582
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
GameImagePaths imagePaths
Paths to all available image assets.
Definition game.h:562
CloudSaveInfo cloudSave
Steam Cloud save information.
Definition game.h:596
std::string steamBuildId
Steam build ID.
Definition game.h:578
uint32_t steamPlaytime2Weeks
Playtime in last 2 weeks (minutes).
Definition game.h:579
std::string steamLaunchOptions
Steam launch options from localconfig.vdf.
Definition game.h:577
std::vector< std::string > steamUserCategories
User-defined categories from Steam (tags section).
Definition game.h:595
std::vector< DLCInfo > dlc
Installed DLC for this game.
Definition game.h:597
std::vector< std::string > genres
Game genres (RPG, FPS, Strategy, etc.).
Definition game.h:566
std::string executablePath
Full path to game executable.
Definition game.h:141
bool useSteamDefaults
For Steam games: if true, don't sync custom env vars/wrappers to Steam's VDF files.
Definition game.h:155
std::string workingDirectory
Working directory for game execution.
Definition game.h:142
std::string arguments
Command line arguments to pass to game.
Definition game.h:143
std::string runnerVersion
Runner version: "wine-8.0", "proton-8.0-5", etc.
Definition game.h:140
std::string runnerType
Runner type: "wine", "proton", "native", etc.
Definition game.h:139
std::string protonVersion
Proton version (e.g., "proton-cachyos-slr").
Definition game.h:170
std::map< std::string, std::string > environmentVariables
Environment variables to set before launching (KEY=VALUE pairs).
Definition game.h:146
bool useSteamLaunch
For Steam games: if true, launch via "steam -applaunch" instead of direct Proton.
Definition game.h:161
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
Definition game.h:714
time_t lastPlayed
Unix timestamp of last play session.
Definition game.h:715
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.