game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_scanner_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_scanner_service.cpp
4// ==============================================================================
5// Game scanner service implementation
6// ==============================================================================
7
10#include "logger.h"
11
12#include <algorithm>
13#include <cstdlib>
14#include <filesystem>
15#include <fstream>
16#include <functional>
17#include <future>
18#include <mutex>
19#include <nlohmann/json.hpp>
20#include <regex>
21#include <sstream>
22#include <vector>
23
24namespace fs = std::filesystem;
25
26namespace
27{
28std::vector<std::shared_ptr<std::future<void>>> activeFutures_;
29std::mutex futuresMutex_;
30
31void storeFuture(std::shared_ptr<std::future<void>> f)
32{
33 std::lock_guard<std::mutex> lock(futuresMutex_);
34 activeFutures_.erase(std::remove_if(activeFutures_.begin(), activeFutures_.end(),
35 [](const std::shared_ptr<std::future<void>>& fu)
36 {
37 return fu->wait_for(std::chrono::seconds(0)) ==
38 std::future_status::ready;
39 }),
40 activeFutures_.end());
41 activeFutures_.push_back(std::move(f));
42}
43
44// Verify a relative-or-absolute executable path resolves inside an install
45// root. Mirrors the defense-in-depth pattern in gog_integration.cpp's
46// launchGame check: a plain `component == ".."` scan misses symlinks
47// resolving outside the root and misses absolute paths that bypass the
48// install dir entirely. weakly_canonical resolves symlinks and "."/"..",
49// then `fs::relative` produces a path whose first component is ".." iff
50// the resolved target escaped the base.
51//
52// @returns the resolved absolute path on success, or an empty path if the
53// containment check fails (caller decides whether to log + reject).
54fs::path resolveContainedExecutable(const std::string& installPath, const std::string& executable)
55{
56 if (installPath.empty() || executable.empty())
57 return {};
58
59 std::error_code ec1, ec2;
60 const fs::path candidate = fs::path(installPath) / executable;
61 const fs::path canonCand = fs::weakly_canonical(candidate, ec1);
62 const fs::path canonBase = fs::weakly_canonical(fs::path(installPath), ec2);
63 if (ec1 || ec2)
64 return {};
65
66 std::error_code relEc;
67 const fs::path rel = fs::relative(canonCand, canonBase, relEc);
68 if (relEc || rel.empty() || *rel.begin() == "..")
69 return {};
70
71 return canonCand;
72}
73} // namespace
74
75// Static member definitions
76std::vector<std::string> GameScannerService::customScanDirs_;
77std::mutex GameScannerService::customScanDirsMutex_;
78
79void GameScannerService::setCustomScanDirectories(const std::vector<std::string>& dirs)
80{
81 std::lock_guard<std::mutex> lock(customScanDirsMutex_);
82 customScanDirs_ = dirs;
83}
84
85// ==============================================================================
86// ScannedGame Implementation
87// ==============================================================================
88
90{
91 // Generate ID based on executable path hash
92 std::hash<std::string> hasher;
93 size_t hash = hasher(executablePath);
94 std::ostringstream oss;
95 oss << std::hex << hash;
96 id = oss.str();
97}
98
100{
101 Game game;
102
103 game.name = name;
104 game.source = source;
105 game.runner = runner;
106
107 // Derive platform from runner (GamePlatform is deprecated, kept for backward compat)
109
110 // Runner configuration
116
117 // Set runner version appropriately - for Proton, use protonVersion field
119 {
121 game.runnerConfig.runnerType = "proton";
122 }
123 else if (runner == GameRunner::Wine)
124 {
126 game.runnerConfig.runnerType = "wine";
127 }
128 else
129 {
130 game.runnerConfig.runnerType = "native";
131 }
132
133 // DLL overrides go to wineDLL field
134 if (!dllOverrides.empty())
135 {
136 std::string overrides;
137 for (const auto& [dll, mode] : dllOverrides)
138 {
139 if (!overrides.empty())
140 overrides += ";";
141 overrides += dll + "=" + mode;
142 }
143 game.runnerConfig.wineDLL = overrides;
144 }
145
146 // Copy exclude processes list
148
149 // Metadata - use imagePaths for artwork
150 if (!iconPath.empty())
151 {
153 }
154 if (!coverPath.empty())
155 {
157 }
158 if (!bannerPath.empty())
159 {
161 }
162
163 // Store IDs
164 if (steamAppId > 0)
165 {
167 }
168 // Note: GOG ID is not stored in GameMetadata - only Steam ID is supported
169
170 // Scanned games are installed by definition (we found them on disk)
172
173 // Set install path and size
174 game.installPath = installDir;
176
177 return game;
178}
179
180// ==============================================================================
181// Helper Functions
182// ==============================================================================
183
184std::string GameScannerService::getHomeDir()
185{
186 const char* home = std::getenv("HOME");
187 return home ? home : "";
188}
189
190std::string GameScannerService::expandPath(const std::string& path)
191{
192 if (path.empty())
193 return path;
194
195 std::string result = path;
196
197 // Expand ~
198 if (result[0] == '~')
199 {
200 std::string home = getHomeDir();
201 if (!home.empty())
202 {
203 result = home + result.substr(1);
204 }
205 }
206
207 // Expand $HOME
208 size_t pos = result.find("$HOME");
209 if (pos != std::string::npos)
210 {
211 std::string home = getHomeDir();
212 result.replace(pos, 5, home);
213 }
214
215 return result;
216}
217
218uint64_t GameScannerService::getDirectorySize(const std::string& path)
219{
220 uint64_t totalSize = 0;
221 try
222 {
223 for (const auto& entry :
224 fs::recursive_directory_iterator(path, fs::directory_options::skip_permission_denied))
225 {
226 if (entry.is_regular_file())
227 {
228 totalSize += entry.file_size();
229 }
230 }
231 }
232 catch (...)
233 {
234 // Ignore errors
235 }
236 return totalSize;
237}
238
239time_t GameScannerService::getLastModified(const std::string& path)
240{
241 try
242 {
243 auto ftime = fs::last_write_time(path);
244 auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
245 ftime - fs::file_time_type::clock::now() + std::chrono::system_clock::now());
246 return std::chrono::system_clock::to_time_t(sctp);
247 }
248 catch (...)
249 {
250 return 0;
251 }
252}
253
254// ==============================================================================
255// JSON Parsing Helpers
256// ==============================================================================
257
258std::string GameScannerService::extractJsonString(const std::string& json, const std::string& key)
259{
260 std::string searchKey = "\"" + key + "\"";
261 size_t keyPos = json.find(searchKey);
262 if (keyPos == std::string::npos)
263 return "";
264
265 size_t colonPos = json.find(':', keyPos + searchKey.length());
266 if (colonPos == std::string::npos)
267 return "";
268
269 size_t valueStart = json.find_first_not_of(" \t\n\r", colonPos + 1);
270 if (valueStart == std::string::npos)
271 return "";
272
273 if (json[valueStart] == '"')
274 {
275 size_t valueEnd = json.find('"', valueStart + 1);
276 if (valueEnd == std::string::npos)
277 return "";
278 return json.substr(valueStart + 1, valueEnd - valueStart - 1);
279 }
280
281 return "";
282}
283
284int GameScannerService::extractJsonInt(const std::string& json, const std::string& key)
285{
286 std::string searchKey = "\"" + key + "\"";
287 size_t keyPos = json.find(searchKey);
288 if (keyPos == std::string::npos)
289 return 0;
290
291 size_t colonPos = json.find(':', keyPos + searchKey.length());
292 if (colonPos == std::string::npos)
293 return 0;
294
295 size_t valueStart = json.find_first_not_of(" \t\n\r", colonPos + 1);
296 if (valueStart == std::string::npos)
297 return 0;
298
299 size_t valueEnd = json.find_first_of(",}\n\r", valueStart);
300 std::string valueStr = json.substr(valueStart, valueEnd - valueStart);
301
302 try
303 {
304 return std::stoi(valueStr);
305 }
306 catch (...)
307 {
308 return 0;
309 }
310}
311
312bool GameScannerService::extractJsonBool(const std::string& json, const std::string& key)
313{
314 std::string searchKey = "\"" + key + "\"";
315 size_t keyPos = json.find(searchKey);
316 if (keyPos == std::string::npos)
317 return false;
318
319 size_t colonPos = json.find(':', keyPos + searchKey.length());
320 if (colonPos == std::string::npos)
321 return false;
322
323 size_t valueStart = json.find_first_not_of(" \t\n\r", colonPos + 1);
324 if (valueStart == std::string::npos)
325 return false;
326
327 return json.substr(valueStart, 4) == "true";
328}
329
330// ==============================================================================
331// Source Availability Checks
332// ==============================================================================
333
335{
336 std::string gamesDir = LutrisConfigParser::getGamesDirectory();
337 return !gamesDir.empty() && fs::exists(gamesDir);
338}
339
341{
342 return fs::exists(expandPath("~/.local/share/bottles/bottles")) ||
343 fs::exists(expandPath("~/.var/app/com.usebottles.bottles/data/bottles/bottles"));
344}
345
347{
348 return fs::exists(expandPath("~/.config/heroic")) ||
349 fs::exists(expandPath("~/.var/app/com.heroicgameslauncher.hgl/config/heroic"));
350}
351
353{
354 std::string legendaryDir = expandPath("~/.config/legendary");
355 return fs::exists(legendaryDir);
356}
357
358// ==============================================================================
359// Source Display Names and Icons
360// ==============================================================================
361
363{
364 switch (source)
365 {
367 return "Steam";
368 case GameSource::GOG:
369 return "GOG";
370 case GameSource::Epic:
371 return "Epic Games";
372 case GameSource::Itch:
373 return "itch.io";
375 return "Lutris";
377 return "Flatpak";
379 return "Local";
380 default:
381 return "Unknown";
382 }
383}
384
386{
387 switch (source)
388 {
390 return "🎮";
391 case GameSource::GOG:
392 return "🌌";
393 case GameSource::Epic:
394 return "🎯";
395 case GameSource::Itch:
396 return "🎲";
398 return "🍷";
400 return "📦";
402 return "🐧";
403 default:
404 return "❓";
405 }
406}
407
408// ==============================================================================
409// Lutris Scanner
410// ==============================================================================
411
412std::vector<ScannedGame> GameScannerService::scanLutris()
413{
414 std::vector<ScannedGame> games;
415
416 std::string gamesDir = LutrisConfigParser::getGamesDirectory();
417 if (gamesDir.empty() || !fs::exists(gamesDir))
418 {
419 Logger::info("[GameScanner] Lutris games directory not found");
420 return games;
421 }
422
423 Logger::info("[GameScanner] Scanning Lutris games at {}", gamesDir);
424
425 try
426 {
427 for (const auto& entry : fs::directory_iterator(gamesDir))
428 {
429 if (!entry.is_regular_file())
430 continue;
431
432 std::string filename = entry.path().filename().string();
433 if (filename.size() < 4 || filename.substr(filename.size() - 4) != ".yml")
434 continue;
435
436 auto parsed = parseLutrisConfig(entry.path().string());
437 for (auto& game : parsed)
438 {
439 games.push_back(std::move(game));
440 }
441 }
442 }
443 catch (const std::exception& e)
444 {
445 Logger::warn("[GameScanner] Error scanning Lutris: {}", e.what());
446 }
447
448 Logger::info("[GameScanner] Found {} games in Lutris", games.size());
449 return games;
450}
451
452std::vector<ScannedGame> GameScannerService::parseLutrisConfig(const std::string& configPath)
453{
454 std::vector<ScannedGame> games;
455
457 if (!config.isValid())
458 {
459 return games;
460 }
461
462 ScannedGame game;
463 game.name = config.name;
465 game.sourceId = config.slug;
466 game.configPath = configPath;
467
468 // Executable and paths
470 game.installDir = config.prefix;
471 game.winePrefix = config.prefix;
472 game.workingDir = config.workingDir;
473 game.arguments = config.arguments;
474
475 // Runner - detect if it's Proton based on wine version
476 if (config.arch == "win32" || config.arch == "win64" || !config.prefix.empty())
477 {
478 // Check if wine version indicates Proton
479 std::string lowerWineVersion = config.wineVersion;
480 std::transform(lowerWineVersion.begin(), lowerWineVersion.end(), lowerWineVersion.begin(),
481 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
482
483 if (lowerWineVersion.find("proton") != std::string::npos ||
484 lowerWineVersion.find("umu") != std::string::npos ||
485 lowerWineVersion.find("ge-proton") != std::string::npos)
486 {
488 game.runnerVersion = config.wineVersion; // This is the Proton version
489 Logger::info("[GameScanner] Detected Proton runner for {}: {}", config.name,
490 config.wineVersion);
491 }
492 else
493 {
495 game.runnerVersion = config.wineVersion;
496 }
497 }
498 else
499 {
501 }
502
503 // Environment, DLL overrides, and exclude processes
505 game.dllOverrides = config.dllOverrides;
507
508 // Auto-detect launcher games and add comprehensive exclude lists
509 // This helps with process tracking - we want to track the actual game, not the launcher
510 std::string nameLower = config.name;
511 std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(),
512 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
513
514 if (nameLower.find("battle.net") != std::string::npos ||
515 nameLower.find("battlenet") != std::string::npos ||
516 nameLower.find("blizzard") != std::string::npos)
517 {
518 // Battle.net launcher - add all known launcher and helper processes
519 std::vector<std::string> battlenetExcludes = {
520 "Agent.exe", "Battle.net Helper.exe",
521 "Battle.net.exe", "Battle.net Launcher.exe",
522 "CrashReporter.exe", "BlizzardBrowser.exe",
523 "BlizzardError.exe", "Blizzard Update Agent.exe",
524 "WowVoiceProxy.exe"};
525 for (const auto& proc : battlenetExcludes)
526 {
527 bool found = false;
528 for (const auto& existing : game.excludeProcesses)
529 {
530 if (existing == proc)
531 {
532 found = true;
533 break;
534 }
535 }
536 if (!found)
537 game.excludeProcesses.push_back(proc);
538 }
539 Logger::info("[GameScanner] Added Battle.net launcher exclusions for: {}", config.name);
540 }
541 else if (nameLower.find("ea app") != std::string::npos ||
542 nameLower.find("origin") != std::string::npos)
543 {
544 // EA App / Origin launcher
545 std::vector<std::string> eaExcludes = {"EADesktop.exe",
546 "EABackgroundService.exe",
547 "EALocalHostSvc.exe",
548 "Origin.exe",
549 "OriginWebHelperService.exe",
550 "OriginClientService.exe",
551 "IGOProxy.exe",
552 "IGOProxy32.exe",
553 "IGOProxy64.exe"};
554 for (const auto& proc : eaExcludes)
555 {
556 bool found = false;
557 for (const auto& existing : game.excludeProcesses)
558 {
559 if (existing == proc)
560 {
561 found = true;
562 break;
563 }
564 }
565 if (!found)
566 game.excludeProcesses.push_back(proc);
567 }
568 Logger::info("[GameScanner] Added EA App launcher exclusions for: {}", config.name);
569 }
570 else if (nameLower.find("epic") != std::string::npos)
571 {
572 // Epic Games Launcher
573 std::vector<std::string> epicExcludes = {"EpicGamesLauncher.exe", "EpicWebHelper.exe",
574 "UnrealCEFSubProcess.exe",
575 "CrashReportClient.exe"};
576 for (const auto& proc : epicExcludes)
577 {
578 bool found = false;
579 for (const auto& existing : game.excludeProcesses)
580 {
581 if (existing == proc)
582 {
583 found = true;
584 break;
585 }
586 }
587 if (!found)
588 game.excludeProcesses.push_back(proc);
589 }
590 Logger::info("[GameScanner] Added Epic Games launcher exclusions for: {}", config.name);
591 }
592 else if (nameLower.find("ubisoft") != std::string::npos ||
593 nameLower.find("uplay") != std::string::npos)
594 {
595 // Ubisoft Connect / Uplay
596 std::vector<std::string> ubiExcludes = {
597 "UbisoftConnect.exe", "UbisoftGameLauncher.exe", "upc.exe", "UplayWebCore.exe",
598 "Uplay.exe", "UplayCrashReporter.exe"};
599 for (const auto& proc : ubiExcludes)
600 {
601 bool found = false;
602 for (const auto& existing : game.excludeProcesses)
603 {
604 if (existing == proc)
605 {
606 found = true;
607 break;
608 }
609 }
610 if (!found)
611 game.excludeProcesses.push_back(proc);
612 }
613 Logger::info("[GameScanner] Added Ubisoft launcher exclusions for: {}", config.name);
614 }
615 else if (nameLower.find("gog") != std::string::npos ||
616 nameLower.find("galaxy") != std::string::npos)
617 {
618 // GOG Galaxy
619 std::vector<std::string> gogExcludes = {"GalaxyClient.exe", "GalaxyClientService.exe",
620 "GalaxyCommunication.exe", "GOG Galaxy.exe",
621 "GOGGalaxy.exe"};
622 for (const auto& proc : gogExcludes)
623 {
624 bool found = false;
625 for (const auto& existing : game.excludeProcesses)
626 {
627 if (existing == proc)
628 {
629 found = true;
630 break;
631 }
632 }
633 if (!found)
634 game.excludeProcesses.push_back(proc);
635 }
636 Logger::info("[GameScanner] Added GOG Galaxy launcher exclusions for: {}", config.name);
637 }
638
639 // Metadata
640 game.lastModified = getLastModified(configPath);
641
642 // Try to estimate size from prefix
643 if (!game.winePrefix.empty() && fs::exists(game.winePrefix))
644 {
645 // Only get size if it's a reasonable path
646 fs::path prefixPath(game.winePrefix);
647 if (prefixPath.filename() != "." && prefixPath.filename() != "..")
648 {
649 game.sizeOnDisk = getDirectorySize(game.winePrefix);
650 }
651 }
652
653 // Look for Lutris artwork - use gameSlug for artwork lookups (not config slug)
654 std::string artworkSlug = config.gameSlug.empty() ? config.slug : config.gameSlug;
655
656 // Lutris stores cover art (vertical 600x900) in coverart directory
657 std::string coverPath = expandPath("~/.local/share/lutris/coverart/" + artworkSlug + ".jpg");
658 if (fs::exists(coverPath))
659 {
660 game.coverPath = coverPath;
661 Logger::debug("[GameScanner] Found Lutris cover art: {}", coverPath);
662 }
663 else
664 {
665 // Try PNG format as fallback
666 coverPath = expandPath("~/.local/share/lutris/coverart/" + artworkSlug + ".png");
667 if (fs::exists(coverPath))
668 {
669 game.coverPath = coverPath;
670 }
671 }
672
673 // Lutris stores banners (hero images) in banners directory
674 std::string bannerPath = expandPath("~/.local/share/lutris/banners/" + artworkSlug + ".jpg");
675 if (fs::exists(bannerPath))
676 {
677 game.bannerPath = bannerPath;
678 Logger::debug("[GameScanner] Found Lutris banner: {}", bannerPath);
679 }
680 else
681 {
682 bannerPath = expandPath("~/.local/share/lutris/banners/" + artworkSlug + ".png");
683 if (fs::exists(bannerPath))
684 {
685 game.bannerPath = bannerPath;
686 }
687 }
688
689 // Look for icon in XDG icon theme
690 std::string iconPath =
691 expandPath("~/.local/share/icons/hicolor/128x128/apps/lutris_" + config.slug + ".png");
692 if (fs::exists(iconPath))
693 {
694 game.iconPath = iconPath;
695 }
696 else
697 {
698 // Try icons directory in Lutris data
699 iconPath = expandPath("~/.local/share/lutris/icons/" + artworkSlug + ".png");
700 if (fs::exists(iconPath))
701 {
702 game.iconPath = iconPath;
703 }
704 }
705
706 game.generateId();
707 games.push_back(game);
708
709 return games;
710}
711
712// ==============================================================================
713// Bottles Scanner
714// ==============================================================================
715
716std::vector<ScannedGame> GameScannerService::scanBottles()
717{
718 std::vector<ScannedGame> games;
719
720 std::string bottlesDir = expandPath("~/.local/share/bottles/bottles");
721 if (!fs::exists(bottlesDir))
722 {
723 bottlesDir = expandPath("~/.var/app/com.usebottles.bottles/data/bottles/bottles");
724 }
725 if (!fs::exists(bottlesDir))
726 {
727 Logger::info("[GameScanner] Bottles directory not found");
728 return games;
729 }
730
731 Logger::info("[GameScanner] Scanning Bottles at {}", bottlesDir);
732
733 try
734 {
735 for (const auto& entry : fs::directory_iterator(bottlesDir))
736 {
737 if (!entry.is_directory())
738 continue;
739
740 std::string bottlePath = entry.path().string();
741
742 // Check if it's a valid bottle (has drive_c)
743 if (!fs::exists(bottlePath + "/drive_c"))
744 continue;
745
746 auto parsed = parseBottleConfig(bottlePath);
747 for (auto& game : parsed)
748 {
749 games.push_back(std::move(game));
750 }
751 }
752 }
753 catch (const std::exception& e)
754 {
755 Logger::warn("[GameScanner] Error scanning Bottles: {}", e.what());
756 }
757
758 Logger::info("[GameScanner] Found {} games in Bottles", games.size());
759 return games;
760}
761
762std::vector<ScannedGame> GameScannerService::parseBottleConfig(const std::string& bottlePath)
763{
764 std::vector<ScannedGame> games;
765
766 // Check for bottle.yml config. The YAML body is not parsed today
767 // (programs are pulled from .local/share/applications instead) so
768 // we only need to confirm the bottle is initialised.
769 std::string configPath = bottlePath + "/bottle.yml";
770 if (!fs::exists(configPath))
771 {
772 // Fallback: scan for executables
773 return games;
774 }
775
776 // Look for external programs configured in the bottle
777 // Bottles stores programs in a Programs section
778 std::string programsPath = bottlePath + "/.local/share/applications";
779 if (fs::exists(programsPath))
780 {
781 for (const auto& entry : fs::directory_iterator(programsPath))
782 {
783 if (!entry.is_regular_file())
784 continue;
785
786 std::string filename = entry.path().filename().string();
787 if (filename.find(".desktop") == std::string::npos)
788 continue;
789
790 auto desktopGames = parseDesktopFile(entry.path().string());
791 for (auto& game : desktopGames)
792 {
793 game.source = GameSource::Local; // Bottles as Local/Wine
794 game.winePrefix = bottlePath;
796 games.push_back(std::move(game));
797 }
798 }
799 }
800
801 // Also scan common game locations in the bottle
802 std::vector<std::string> gameDirs = {
803 bottlePath + "/drive_c/Program Files/",
804 bottlePath + "/drive_c/Program Files (x86)/",
805 bottlePath + "/drive_c/Games/",
806 };
807
808 for (const auto& gameDir : gameDirs)
809 {
810 if (!fs::exists(gameDir))
811 continue;
812
813 try
814 {
815 for (const auto& entry : fs::directory_iterator(gameDir))
816 {
817 if (!entry.is_directory())
818 continue;
819
820 std::string gamePath = entry.path().string();
821 std::string gameName = entry.path().filename().string();
822
823 // Skip common non-game directories
824 if (gameName == "Common Files" || gameName == "Internet Explorer" ||
825 gameName == "Windows NT" || gameName == "WindowsPowerShell" ||
826 gameName.find("Microsoft") != std::string::npos)
827 {
828 continue;
829 }
830
831 // Look for an executable
832 for (const auto& gameEntry : fs::directory_iterator(gamePath))
833 {
834 if (!gameEntry.is_regular_file())
835 continue;
836
837 std::string exeName = gameEntry.path().filename().string();
838 if (exeName.size() > 4 && exeName.substr(exeName.size() - 4) == ".exe")
839 {
840 // Skip common non-game executables
841 std::string lowerExe = exeName;
842 std::transform(lowerExe.begin(), lowerExe.end(), lowerExe.begin(),
843 [](unsigned char c)
844 { return static_cast<char>(::tolower(c)); });
845 if (lowerExe.find("unins") != std::string::npos ||
846 lowerExe.find("setup") != std::string::npos ||
847 lowerExe.find("install") != std::string::npos ||
848 lowerExe.find("update") != std::string::npos ||
849 lowerExe.find("crash") != std::string::npos ||
850 lowerExe.find("report") != std::string::npos)
851 {
852 continue;
853 }
854
855 ScannedGame game;
856 game.name = gameName;
858 game.executablePath = gameEntry.path().string();
859 game.installDir = gamePath;
860 game.winePrefix = bottlePath;
862 game.sizeOnDisk = getDirectorySize(gamePath);
863 game.lastModified = getLastModified(gameEntry.path().string());
864 game.generateId();
865
866 games.push_back(game);
867 break; // One exe per game folder
868 }
869 }
870 }
871 }
872 catch (...)
873 {
874 // Skip directories we can't read
875 }
876 }
877
878 return games;
879}
880
881// ==============================================================================
882// Heroic Scanner (Epic + GOG)
883// ==============================================================================
884
885std::vector<ScannedGame> GameScannerService::scanHeroic()
886{
887 std::vector<ScannedGame> games;
888
889 std::string heroicDir = expandPath("~/.config/heroic");
890 if (!fs::exists(heroicDir))
891 {
892 heroicDir = expandPath("~/.var/app/com.heroicgameslauncher.hgl/config/heroic");
893 }
894 if (!fs::exists(heroicDir))
895 {
896 Logger::info("[GameScanner] Heroic directory not found");
897 return games;
898 }
899
900 Logger::info("[GameScanner] Scanning Heroic at {}", heroicDir);
901
902 // Scan GOG installed games
903 std::string gogInstalledPath = heroicDir + "/gog_store/installed.json";
904 if (fs::exists(gogInstalledPath))
905 {
906 auto gogGames = parseHeroicInstalledJson(gogInstalledPath, GameSource::GOG);
907 for (auto& game : gogGames)
908 {
909 games.push_back(std::move(game));
910 }
911 }
912
913 // Scan Epic installed games (legendaryConfig or store)
914 std::string epicInstalledPath = heroicDir + "/legendaryConfig/legendary/installed.json";
915 if (fs::exists(epicInstalledPath))
916 {
917 auto epicGames = parseHeroicInstalledJson(epicInstalledPath, GameSource::Epic);
918 for (auto& game : epicGames)
919 {
920 games.push_back(std::move(game));
921 }
922 }
923
924 // Alternative Epic path
925 epicInstalledPath = heroicDir + "/store/installed.json";
926 if (fs::exists(epicInstalledPath))
927 {
928 auto epicGames = parseHeroicInstalledJson(epicInstalledPath, GameSource::Epic);
929 for (auto& game : epicGames)
930 {
931 games.push_back(std::move(game));
932 }
933 }
934
935 Logger::info("[GameScanner] Found {} games in Heroic", games.size());
936 return games;
937}
938
939std::vector<ScannedGame> GameScannerService::parseHeroicInstalledJson(const std::string& jsonPath,
940 GameSource source)
941{
942 std::vector<ScannedGame> games;
943
944 std::ifstream file(jsonPath);
945 if (!file.is_open())
946 return games;
947
948 try
949 {
950 nlohmann::json j;
951 file >> j;
952
953 // Heroic stores installed games as {"app_name": {details}, ...} or as an array
954 if (j.is_object())
955 {
956 for (auto& [key, value] : j.items())
957 {
958 if (!value.is_object())
959 continue;
960
961 std::string installPath = value.value("install_path", "");
962 std::string title = value.value("title", key);
963 std::string appName = value.value("app_name", key);
964 std::string executable = value.value("executable", "");
965
966 if (installPath.empty())
967 continue;
968
969 ScannedGame game;
970 game.name = title.empty() ? appName : title;
971 game.source = source;
972 game.installDir = installPath;
973 game.runner = GameRunner::Native; // Heroic handles Wine internally
974
975 // Defense-in-depth: ensure the executable from Heroic's
976 // installed.json resolves inside installPath. The user
977 // owns this file so this isn't a security boundary, but
978 // a malformed/edited entry that escaped the install root
979 // would silently launch the wrong binary. Mirrors
980 // gog_integration's launchGame containment check.
981 if (!executable.empty())
982 {
983 const fs::path resolved = resolveContainedExecutable(installPath, executable);
984 if (!resolved.empty() && fs::exists(resolved))
985 {
986 game.executablePath = resolved.string();
987 }
988 else if (resolved.empty())
989 {
990 Logger::warn("[Scanner] Rejected Heroic executable that "
991 "escapes installPath: {}",
992 executable);
993 game.executablePath = installPath;
994 }
995 else
996 {
997 // Resolved cleanly but file doesn't exist yet —
998 // common pre-install state. Fall back to install dir.
999 game.executablePath = installPath;
1000 }
1001 }
1002 else
1003 {
1004 game.executablePath = installPath;
1005 }
1006
1007 // Check for Windows exe to set runner
1008 std::string ext = fs::path(game.executablePath).extension().string();
1009 std::transform(ext.begin(), ext.end(), ext.begin(),
1010 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
1011 if (ext == ".exe")
1012 game.runner = GameRunner::Wine;
1013
1014 game.sizeOnDisk = getDirectorySize(installPath);
1015 game.lastModified = getLastModified(installPath);
1016 game.generateId();
1017 games.push_back(game);
1018 }
1019 }
1020 else if (j.is_array())
1021 {
1022 for (const auto& value : j)
1023 {
1024 if (!value.is_object())
1025 continue;
1026
1027 std::string installPath = value.value("install_path", "");
1028 std::string title = value.value("title", "");
1029 std::string appName = value.value("app_name", "");
1030
1031 if (installPath.empty())
1032 continue;
1033
1034 ScannedGame game;
1035 game.name = title.empty() ? appName : title;
1036 game.source = source;
1037 game.installDir = installPath;
1038 game.executablePath = installPath;
1040
1041 std::string executable = value.value("executable", "");
1042 if (!executable.empty())
1043 {
1044 bool hasTraversal = false;
1045 for (const auto& component : fs::path(executable))
1046 {
1047 if (component == "..")
1048 {
1049 hasTraversal = true;
1050 break;
1051 }
1052 }
1053 if (!hasTraversal)
1054 {
1055 std::string fullExe = installPath + "/" + executable;
1056 if (fs::exists(fullExe))
1057 game.executablePath = fullExe;
1058 }
1059 else
1060 {
1061 Logger::warn("[Scanner] Rejected executable with path traversal: {}",
1062 executable);
1063 }
1064 }
1065
1066 std::string ext = fs::path(game.executablePath).extension().string();
1067 std::transform(ext.begin(), ext.end(), ext.begin(),
1068 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
1069 if (ext == ".exe")
1070 game.runner = GameRunner::Wine;
1071
1072 game.sizeOnDisk = getDirectorySize(installPath);
1073 game.lastModified = getLastModified(installPath);
1074 game.generateId();
1075 games.push_back(game);
1076 }
1077 }
1078 }
1079 catch (const std::exception& e)
1080 {
1081 Logger::error("[GameScanner] Failed to parse Heroic JSON {}: {}", jsonPath, e.what());
1082 }
1083
1084 return games;
1085}
1086
1087// ==============================================================================
1088// Legendary Scanner
1089// ==============================================================================
1090
1091std::vector<ScannedGame> GameScannerService::scanLegendary()
1092{
1093 std::vector<ScannedGame> games;
1094
1095 std::string legendaryDir = expandPath("~/.config/legendary");
1096 std::string installedPath = legendaryDir + "/installed.json";
1097
1098 if (!fs::exists(installedPath))
1099 {
1100 Logger::info("[GameScanner] Legendary installed.json not found");
1101 return games;
1102 }
1103
1104 Logger::info("[GameScanner] Scanning Legendary at {}", legendaryDir);
1105
1106 auto parsedGames = parseLegendaryInstalledJson(installedPath);
1107 for (auto& game : parsedGames)
1108 {
1109 games.push_back(std::move(game));
1110 }
1111
1112 Logger::info("[GameScanner] Found {} games in Legendary", games.size());
1113 return games;
1114}
1115
1116std::vector<ScannedGame>
1117GameScannerService::parseLegendaryInstalledJson(const std::string& jsonPath)
1118{
1119 std::vector<ScannedGame> games;
1120
1121 std::ifstream file(jsonPath);
1122 if (!file.is_open())
1123 return games;
1124
1125 try
1126 {
1127 nlohmann::json j;
1128 file >> j;
1129
1130 for (auto& [appName, value] : j.items())
1131 {
1132 if (!value.is_object())
1133 continue;
1134
1135 std::string installPath = value.value("install_path", "");
1136 if (installPath.empty())
1137 continue;
1138
1139 std::string title = value.value("title", appName);
1140 std::string executable = value.value("executable", "");
1141
1142 ScannedGame game;
1143 game.name = title;
1144 game.source = GameSource::Epic;
1145 game.installDir = installPath;
1146 game.runner = GameRunner::Native; // Legendary handles Wine
1147
1148 if (!executable.empty())
1149 {
1150 // Defense-in-depth: ensure the executable from Legendary's
1151 // installed.json resolves inside installPath (see Heroic
1152 // branch above for rationale — same containment pattern).
1153 const fs::path resolved = resolveContainedExecutable(installPath, executable);
1154 if (!resolved.empty() && fs::exists(resolved))
1155 {
1156 game.executablePath = resolved.string();
1157 }
1158 else if (resolved.empty())
1159 {
1160 Logger::warn("[Scanner] Rejected Legendary executable that "
1161 "escapes installPath: {}",
1162 executable);
1163 game.executablePath = installPath;
1164 }
1165 else
1166 {
1167 game.executablePath = installPath;
1168 }
1169 }
1170 else
1171 {
1172 game.executablePath = installPath;
1173 }
1174
1175 std::string ext = fs::path(game.executablePath).extension().string();
1176 std::transform(ext.begin(), ext.end(), ext.begin(),
1177 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
1178 if (ext == ".exe")
1179 game.runner = GameRunner::Wine;
1180
1181 game.sizeOnDisk = getDirectorySize(installPath);
1182 game.lastModified = getLastModified(installPath);
1183 game.generateId();
1184 games.push_back(game);
1185 }
1186 }
1187 catch (const std::exception& e)
1188 {
1189 Logger::error("[GameScanner] Failed to parse Legendary JSON {}: {}", jsonPath, e.what());
1190 }
1191
1192 return games;
1193}
1194
1195// ==============================================================================
1196// Native Games Scanner
1197// ==============================================================================
1198
1199std::vector<ScannedGame> GameScannerService::scanNativeGames()
1200{
1201 std::vector<ScannedGame> games;
1202
1203 Logger::info("[GameScanner] Scanning for native Linux games");
1204
1205 // Scan common game directories
1206 std::vector<std::string> gameDirs = {
1207 expandPath("~/Games"),
1208 expandPath("~/games"),
1209 expandPath("~/GOG Games"),
1210 expandPath("~/.local/share/games"),
1211 "/opt/games",
1212 "/usr/share/games",
1213 };
1214
1215 // Append custom scan directories configured by the user
1216 {
1217 std::lock_guard<std::mutex> lock(customScanDirsMutex_);
1218 for (const auto& customDir : customScanDirs_)
1219 {
1220 if (!customDir.empty())
1221 {
1222 gameDirs.push_back(customDir);
1223 }
1224 }
1225 }
1226
1227 for (const auto& gameDir : gameDirs)
1228 {
1229 if (!fs::exists(gameDir))
1230 continue;
1231
1232 try
1233 {
1234 for (const auto& entry : fs::directory_iterator(gameDir))
1235 {
1236 if (!entry.is_directory())
1237 continue;
1238
1239 std::string gamePath = entry.path().string();
1240 std::string gameName = entry.path().filename().string();
1241
1242 // Skip Steam-related directories
1243 std::string lowerName = gameName;
1244 std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(),
1245 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
1246 if (lowerName == "steamapps" || lowerName == "steam" ||
1247 lowerName.find("steamapps") != std::string::npos)
1248 {
1249 Logger::debug("[GameScanner] Skipping Steam directory: {}", gameName);
1250 continue;
1251 }
1252
1253 // Skip Wine/Proton prefixes (contain pfx.lock, drive_c, or dosdevices)
1254 if (fs::exists(gamePath + "/pfx.lock") || fs::exists(gamePath + "/drive_c") ||
1255 fs::exists(gamePath + "/dosdevices"))
1256 {
1257 Logger::debug("[GameScanner] Skipping Wine prefix: {}", gameName);
1258 continue;
1259 }
1260
1261 // Look for executable
1262 for (const auto& gameEntry : fs::directory_iterator(gamePath))
1263 {
1264 if (!gameEntry.is_regular_file())
1265 continue;
1266
1267 try
1268 {
1269 auto perms = fs::status(gameEntry.path()).permissions();
1270 if ((perms & fs::perms::owner_exec) != fs::perms::none)
1271 {
1272 std::string filename = gameEntry.path().filename().string();
1273 std::string ext = gameEntry.path().extension().string();
1274
1275 // Skip obvious non-games
1276 std::string lower = filename;
1277 std::transform(lower.begin(), lower.end(), lower.begin(),
1278 [](unsigned char c)
1279 { return static_cast<char>(::tolower(c)); });
1280 if (lower.find("unins") != std::string::npos ||
1281 lower.find("crash") != std::string::npos ||
1282 lower.find("report") != std::string::npos || lower == "start.sh" ||
1283 lower == "run.sh")
1284 {
1285 continue;
1286 }
1287
1288 // Allow .sh files as potential game launchers (many native Linux games
1289 // use .sh) but skip known non-game scripts
1290 if (ext == ".sh" && (lower.find("install") != std::string::npos ||
1291 lower.find("setup") != std::string::npos ||
1292 lower.find("config") != std::string::npos))
1293 continue;
1294
1295 // Skip Wine/Proton-related files
1296 if (lower == "pfx.lock" || lower.find(".lock") != std::string::npos ||
1297 ext == ".acf" || ext == ".vdf" ||
1298 lower.find("wine") != std::string::npos ||
1299 lower.find("proton") != std::string::npos)
1300 {
1301 continue;
1302 }
1303
1304 ScannedGame game;
1305 game.name = gameName;
1307 game.executablePath = gameEntry.path().string();
1308 game.installDir = gamePath;
1310 game.sizeOnDisk = getDirectorySize(gamePath);
1311 game.lastModified = getLastModified(gameEntry.path().string());
1312 game.generateId();
1313
1314 games.push_back(game);
1315 break; // One exe per directory
1316 }
1317 }
1318 catch (...)
1319 {
1320 }
1321 }
1322 }
1323 }
1324 catch (...)
1325 {
1326 }
1327 }
1328
1329 // Also scan .desktop files for games
1330 std::string applicationsDir = expandPath("~/.local/share/applications");
1331 if (fs::exists(applicationsDir))
1332 {
1333 for (const auto& entry : fs::directory_iterator(applicationsDir))
1334 {
1335 if (!entry.is_regular_file())
1336 continue;
1337
1338 std::string filename = entry.path().filename().string();
1339 if (filename.find(".desktop") == std::string::npos)
1340 continue;
1341
1342 // Skip Steam app shortcuts — these are managed by the Steam scanner
1343 // Check both the standard steam_app_ prefix AND the file contents
1344 if (filename.find("steam_app_") == 0)
1345 {
1346 Logger::debug("[GameScanner] Skipping Steam desktop file: {}", filename);
1347 continue;
1348 }
1349
1350 // Quick-check: skip desktop files that launch via Steam
1351 // (Steam creates shortcuts like "Exec=steam steam://rungameid/XXXXX")
1352 {
1353 std::ifstream quickCheck(entry.path().string());
1354 std::string checkLine;
1355 bool isSteamShortcut = false;
1356 while (std::getline(quickCheck, checkLine))
1357 {
1358 if (checkLine.find("Exec=") == 0 &&
1359 (checkLine.find("steam://") != std::string::npos ||
1360 checkLine.find("Exec=steam ") == 0))
1361 {
1362 isSteamShortcut = true;
1363 break;
1364 }
1365 if (checkLine.find("Icon=steam_icon_") == 0)
1366 {
1367 isSteamShortcut = true;
1368 break;
1369 }
1370 }
1371 if (isSteamShortcut)
1372 {
1373 Logger::debug("[GameScanner] Skipping Steam shortcut: {}", filename);
1374 continue;
1375 }
1376 }
1377
1378 auto desktopGames = parseDesktopFile(entry.path().string());
1379 for (auto& game : desktopGames)
1380 {
1381 // Check if we already have this game
1382 bool duplicate = false;
1383 for (const auto& existing : games)
1384 {
1385 if (existing.executablePath == game.executablePath)
1386 {
1387 duplicate = true;
1388 break;
1389 }
1390 }
1391 if (!duplicate)
1392 {
1393 games.push_back(std::move(game));
1394 }
1395 }
1396 }
1397 }
1398
1399 Logger::info("[GameScanner] Found {} native games", games.size());
1400 return games;
1401}
1402
1403std::vector<ScannedGame> GameScannerService::parseDesktopFile(const std::string& desktopPath)
1404{
1405 std::vector<ScannedGame> games;
1406
1407 std::ifstream file(desktopPath);
1408 if (!file.is_open())
1409 return games;
1410
1411 std::string name, exec, icon, categories;
1412 std::string line;
1413 bool inDesktopEntry = false;
1414
1415 while (std::getline(file, line))
1416 {
1417 // Trim whitespace
1418 size_t start = line.find_first_not_of(" \t");
1419 if (start == std::string::npos)
1420 continue;
1421 line = line.substr(start);
1422
1423 if (line[0] == '[')
1424 {
1425 inDesktopEntry = (line == "[Desktop Entry]");
1426 continue;
1427 }
1428
1429 if (!inDesktopEntry)
1430 continue;
1431
1432 size_t eq = line.find('=');
1433 if (eq == std::string::npos)
1434 continue;
1435
1436 std::string key = line.substr(0, eq);
1437 std::string value = line.substr(eq + 1);
1438
1439 if (key == "Name")
1440 name = value;
1441 else if (key == "Exec")
1442 exec = value;
1443 else if (key == "Icon")
1444 icon = value;
1445 else if (key == "Categories")
1446 categories = value;
1447 }
1448
1449 // Check if it's a game
1450 if (!exec.empty() && !name.empty())
1451 {
1452 bool isGame = categories.find("Game") != std::string::npos;
1453
1454 // Heuristics for games even without Game category
1455 if (!isGame)
1456 {
1457 std::string lowerName = name;
1458 std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(),
1459 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
1460
1461 // Skip obvious non-games
1462 if (lowerName.find("settings") != std::string::npos ||
1463 lowerName.find("configure") != std::string::npos ||
1464 lowerName.find("editor") != std::string::npos ||
1465 lowerName.find("utility") != std::string::npos)
1466 {
1467 return games;
1468 }
1469 // Treat as a game even without Categories=Game — many native Linux
1470 // games omit the category. The non-game filter above already excluded
1471 // the obvious false positives.
1472 isGame = true;
1473 }
1474
1475 if (isGame)
1476 {
1477 // Skip the Game Launcher itself — don't add ourselves to the library
1478 {
1479 std::string lowerExec = exec;
1480 std::transform(lowerExec.begin(), lowerExec.end(), lowerExec.begin(),
1481 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
1482 if (lowerExec.find("gamelauncher") != std::string::npos)
1483 return games;
1484 }
1485
1486 // Extract the actual executable path from Exec line
1487 // Format can be: /path/to/exe, or exe with args, or env vars
1488 std::string exePath = exec;
1489
1490 // Remove any field codes like %f, %u, etc.
1491 std::regex fieldCode("%[fFuUdDnNickvm]");
1492 exePath = std::regex_replace(exePath, fieldCode, "");
1493
1494 // Trim whitespace
1495 size_t first = exePath.find_first_not_of(" \t");
1496 size_t last = exePath.find_last_not_of(" \t");
1497 if (first != std::string::npos)
1498 exePath = exePath.substr(first, last - first + 1);
1499
1500 // If it starts with env or other commands, extract the actual path
1501 if (exePath.find("env ") == 0)
1502 {
1503 // Skip env and its variables
1504 std::regex envRegex("env\\s+[^/]+(/[^ ]+)");
1505 std::smatch match;
1506 if (std::regex_search(exePath, match, envRegex))
1507 {
1508 exePath = match[1].str();
1509 }
1510 }
1511
1512 // Get first space-separated token if it's a path
1513 size_t space = exePath.find(' ');
1514 if (space != std::string::npos)
1515 {
1516 std::string firstToken = exePath.substr(0, space);
1517 if (firstToken[0] == '/' || firstToken[0] == '~')
1518 {
1519 exePath = firstToken;
1520 }
1521 }
1522
1523 exePath = expandPath(exePath);
1524
1525 if (!exePath.empty() && (fs::exists(exePath) || exePath[0] != '/'))
1526 {
1527 ScannedGame game;
1528 game.name = name;
1530 game.executablePath = exePath;
1532 game.configPath = desktopPath;
1533
1534 if (!icon.empty())
1535 {
1536 game.iconPath = expandPath(icon);
1537 }
1538
1539 // Try to get install dir from executable path
1540 if (fs::exists(exePath))
1541 {
1542 game.installDir = fs::path(exePath).parent_path().string();
1543 game.lastModified = getLastModified(exePath);
1544 }
1545
1546 game.generateId();
1547 games.push_back(game);
1548 }
1549 }
1550 }
1551
1552 return games;
1553}
1554
1555// ==============================================================================
1556// Wine Prefixes Scanner
1557// ==============================================================================
1558
1560{
1561 std::vector<ScannedGame> games;
1562
1563 Logger::info("[GameScanner] Scanning Wine prefixes");
1564
1565 // Common Wine prefix locations
1566 std::vector<std::string> prefixDirs = {
1567 expandPath("~/.wine"),
1568 expandPath("~/.wineprefixes"),
1569 };
1570
1571 for (const auto& prefixPath : prefixDirs)
1572 {
1573 if (!fs::exists(prefixPath))
1574 continue;
1575
1576 // Check if it's a single prefix or a directory of prefixes
1577 if (fs::exists(prefixPath + "/drive_c"))
1578 {
1579 // Single prefix
1580 auto bottleGames = parseBottleConfig(prefixPath);
1581 for (auto& game : bottleGames)
1582 {
1584 games.push_back(std::move(game));
1585 }
1586 }
1587 else
1588 {
1589 // Directory of prefixes
1590 try
1591 {
1592 for (const auto& entry : fs::directory_iterator(prefixPath))
1593 {
1594 if (!entry.is_directory())
1595 continue;
1596
1597 if (fs::exists(entry.path().string() + "/drive_c"))
1598 {
1599 auto prefixGames = parseBottleConfig(entry.path().string());
1600 for (auto& game : prefixGames)
1601 {
1603 games.push_back(std::move(game));
1604 }
1605 }
1606 }
1607 }
1608 catch (...)
1609 {
1610 }
1611 }
1612 }
1613
1614 Logger::info("[GameScanner] Found {} games in Wine prefixes", games.size());
1615 return games;
1616}
1617
1618// ==============================================================================
1619// Full Scan
1620// ==============================================================================
1621
1622std::vector<ScannedGame> GameScannerService::scanAll(ProgressCallback progressCallback)
1623{
1624 std::vector<ScannedGame> allGames;
1625 ScanProgress progress;
1626 progress.totalSources = 6;
1627
1628 auto reportProgress = [&](const std::string& source)
1629 {
1630 progress.currentSource = source;
1631 progress.sourcesCompleted++;
1632 // Cap at 95% until deduplication completes so the UI doesn't see 100%
1633 // prematurely (100% is fired explicitly after removeDuplicates).
1634 progress.overallPercent = (progress.sourcesCompleted * 95) / progress.totalSources;
1635 progress.gamesFound = static_cast<int>(allGames.size());
1636 if (progressCallback)
1637 {
1638 progressCallback(progress);
1639 }
1640 };
1641
1642 // Helper to safely scan a source with error handling
1643 auto safeScan = [&](const std::string& source,
1644 const std::function<std::vector<ScannedGame>()>& scanFunc,
1645 const std::function<bool()>& isInstalled = nullptr)
1646 {
1647 progress.currentSource = source;
1648 progress.currentOperation = "Scanning " + source + "...";
1649 if (progressCallback)
1650 progressCallback(progress);
1651
1652 try
1653 {
1654 if (isInstalled && !isInstalled())
1655 {
1656 // Not installed, skip silently
1657 reportProgress(source);
1658 return;
1659 }
1660
1661 auto games = scanFunc();
1662 for (auto& game : games)
1663 {
1664 allGames.push_back(std::move(game));
1665 }
1666
1667 if (games.empty())
1668 {
1669 Logger::debug("[GameScanner] No games found in {}", source);
1670 }
1671 }
1672 catch (const fs::filesystem_error& e)
1673 {
1674 std::string errorMsg = "Filesystem error: " + std::string(e.what());
1675 Logger::warn("[GameScanner] {} scan failed: {}", source, errorMsg);
1676 progress.addError(source, errorMsg);
1677 }
1678 catch (const std::exception& e)
1679 {
1680 std::string errorMsg = e.what();
1681 Logger::warn("[GameScanner] {} scan failed: {}", source, errorMsg);
1682 progress.addError(source, errorMsg);
1683 }
1684 catch (...)
1685 {
1686 Logger::warn("[GameScanner] {} scan failed: Unknown error", source);
1687 progress.addError(source, "Unknown error during scan");
1688 }
1689
1690 reportProgress(source);
1691 };
1692
1693 // Scan all sources with proper error handling
1694 safeScan("Lutris", scanLutris, isLutrisInstalled);
1695 safeScan("Bottles", scanBottles, isBottlesInstalled);
1696 safeScan("Heroic", scanHeroic, isHeroicInstalled);
1697 safeScan("Legendary", scanLegendary, isLegendaryInstalled);
1698 safeScan("Native", scanNativeGames);
1699 safeScan("Wine", scanWinePrefixes);
1700
1701 // Remove duplicates
1702 allGames = removeDuplicates(std::move(allGames));
1703
1704 // Fire 100% completion now that deduplication is done
1705 if (progressCallback)
1706 {
1707 progress.overallPercent = 100;
1708 progress.gamesFound = static_cast<int>(allGames.size());
1709 progressCallback(progress);
1710 }
1711
1712 // Log final status
1713 if (progress.hasErrors())
1714 {
1715 Logger::warn("[GameScanner] Completed with {} errors", progress.errors.size());
1716 for (const auto& error : progress.errors)
1717 {
1718 Logger::warn("[GameScanner] {}", error);
1719 }
1720 }
1721
1722 Logger::info("[GameScanner] Total games found: {}", allGames.size());
1723 return allGames;
1724}
1725
1727 const ProgressCallback& onProgress)
1728{
1729 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
1730 [onComplete, onProgress]()
1731 {
1732 auto games =
1733 scanAll(onProgress);
1734 if (onComplete)
1735 onComplete(games);
1736 }));
1737 storeFuture(std::move(future));
1738}
1739
1740// ==============================================================================
1741// Deduplication and Library Matching
1742// ==============================================================================
1743
1744std::vector<ScannedGame> GameScannerService::removeDuplicates(std::vector<ScannedGame> games)
1745{
1746 std::vector<ScannedGame> unique;
1747 std::map<std::string, size_t> seenPaths;
1748 std::map<int, size_t> seenSteamAppIds;
1749
1750 auto tryMerge = [&](size_t existingIdx, ScannedGame& game)
1751 {
1752 ScannedGame& existing = unique[existingIdx];
1753 // Prefer games with more metadata: Steam > Lutris > GOG/Epic > Local
1754 if (game.source == GameSource::Steam && existing.source != GameSource::Steam)
1755 {
1756 existing = std::move(game);
1757 }
1758 else if (game.source == GameSource::Lutris && existing.source == GameSource::Local)
1759 {
1760 existing = std::move(game);
1761 }
1762 else if ((game.source == GameSource::GOG || game.source == GameSource::Epic) &&
1763 existing.source == GameSource::Local)
1764 {
1765 existing = std::move(game);
1766 }
1767 };
1768
1769 for (auto& game : games)
1770 {
1771 // Check by Steam App ID first (catches cross-source duplicates)
1772 if (game.steamAppId > 0)
1773 {
1774 auto steamIt = seenSteamAppIds.find(game.steamAppId);
1775 if (steamIt != seenSteamAppIds.end())
1776 {
1777 tryMerge(steamIt->second, game);
1778 continue;
1779 }
1780 }
1781
1782 // Then check by executable path
1783 std::string key = game.executablePath;
1784 if (!key.empty())
1785 {
1786 try
1787 {
1788 key = fs::canonical(key).string();
1789 }
1790 catch (...)
1791 {
1792 }
1793 }
1794
1795 auto it = seenPaths.find(key);
1796 if (it == seenPaths.end())
1797 {
1798 size_t idx = unique.size();
1799 if (!key.empty())
1800 seenPaths[key] = idx;
1801 if (game.steamAppId > 0)
1802 seenSteamAppIds[game.steamAppId] = idx;
1803 unique.push_back(std::move(game));
1804 }
1805 else
1806 {
1807 tryMerge(it->second, game);
1808 }
1809 }
1810
1811 return unique;
1812}
1813
1814void GameScannerService::markAlreadyImported(std::vector<ScannedGame>& games,
1815 const std::vector<Game>& library)
1816{
1817 // Build lookup maps from library for multi-strategy deduplication
1818 std::map<std::string, std::string> libraryPaths; // canonical exe path -> game id
1819 std::map<int, std::string> librarySteamAppIds; // steam app id -> game id
1820 std::map<std::string, std::string> libraryInstallDirs; // canonical install dir -> game id
1821
1822 for (const auto& game : library)
1823 {
1824 // Strategy 1: Executable path matching
1825 if (!game.runnerConfig.executablePath.empty())
1826 {
1827 std::string path = game.runnerConfig.executablePath;
1828 try
1829 {
1830 path = fs::canonical(path).string();
1831 }
1832 catch (...)
1833 {
1834 }
1835 libraryPaths[path] = game.id;
1836 }
1837
1838 // Strategy 2: Steam App ID matching (catches Steam vs Local duplicates)
1839 if (game.metadata.steamAppId > 0)
1840 {
1841 librarySteamAppIds[game.metadata.steamAppId] = game.id;
1842 }
1843
1844 // Strategy 3: Install directory matching (catches same game from different sources)
1845 if (!game.installPath.empty())
1846 {
1847 std::string dir = game.installPath;
1848 try
1849 {
1850 dir = fs::canonical(dir).string();
1851 }
1852 catch (...)
1853 {
1854 }
1855 libraryInstallDirs[dir] = game.id;
1856 }
1857 }
1858
1859 // Check each scanned game against all strategies
1860 for (auto& game : games)
1861 {
1862 if (game.alreadyImported)
1863 continue;
1864
1865 // Strategy 1: Check by executable path
1866 std::string path = game.executablePath;
1867 try
1868 {
1869 path = fs::canonical(path).string();
1870 }
1871 catch (...)
1872 {
1873 }
1874
1875 auto it = libraryPaths.find(path);
1876 if (it != libraryPaths.end())
1877 {
1878 game.alreadyImported = true;
1879 game.existingGameId = it->second;
1880 continue;
1881 }
1882
1883 // Strategy 2: Check by Steam App ID (primary fix for Steam+Local duplicates)
1884 if (game.steamAppId > 0)
1885 {
1886 auto steamIt = librarySteamAppIds.find(game.steamAppId);
1887 if (steamIt != librarySteamAppIds.end())
1888 {
1889 game.alreadyImported = true;
1890 game.existingGameId = steamIt->second;
1891 Logger::debug("Marked '{}' as already imported (Steam App ID {} matches {})",
1892 game.name, game.steamAppId, steamIt->second);
1893 continue;
1894 }
1895 }
1896
1897 // Strategy 3: Check by install directory
1898 if (!game.installDir.empty())
1899 {
1900 std::string dir = game.installDir;
1901 try
1902 {
1903 dir = fs::canonical(dir).string();
1904 }
1905 catch (...)
1906 {
1907 }
1908
1909 auto dirIt = libraryInstallDirs.find(dir);
1910 if (dirIt != libraryInstallDirs.end())
1911 {
1912 game.alreadyImported = true;
1913 game.existingGameId = dirIt->second;
1914 Logger::debug("Marked '{}' as already imported (install dir matches {})", game.name,
1915 dirIt->second);
1916 continue;
1917 }
1918 }
1919 }
1920}
static bool isHeroicInstalled()
Check if Heroic Launcher is installed.
static std::vector< ScannedGame > scanLegendary()
Scan Legendary (Epic Games CLI) for installed games.
std::function< void(const std::vector< ScannedGame > &)> CompletionCallback
static bool isLegendaryInstalled()
Check if Legendary is installed.
static std::string getSourceIcon(GameSource source)
Get icon name for a game source.
static std::vector< ScannedGame > scanWinePrefixes()
Scan generic Wine prefixes for games.
static std::string getSourceDisplayName(GameSource source)
Get display name for a game source.
static std::vector< ScannedGame > scanBottles()
Scan Bottles for installed games.
static bool isLutrisInstalled()
Check if Lutris is installed.
static bool isBottlesInstalled()
Check if Bottles is installed.
static std::vector< ScannedGame > removeDuplicates(std::vector< ScannedGame > games)
Remove duplicate games from the list.
static void setCustomScanDirectories(const std::vector< std::string > &dirs)
Set custom scan directories for native game scanning.
static std::vector< ScannedGame > scanNativeGames()
Scan for native Linux games.
static std::vector< ScannedGame > scanAll(ProgressCallback progressCallback=nullptr)
Scan all available sources for games.
static void scanAllAsync(const CompletionCallback &onComplete, const ProgressCallback &onProgress=nullptr)
Scan all sources asynchronously.
static std::vector< ScannedGame > scanLutris()
Scan Lutris for installed games.
static std::vector< ScannedGame > scanHeroic()
Scan Heroic Launcher for Epic and GOG games.
static void markAlreadyImported(std::vector< ScannedGame > &games, const std::vector< Game > &library)
Mark games that are already in the library.
std::function< void(const ScanProgress &)> ProgressCallback
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
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
static std::string getGamesDirectory()
Get the Lutris games directory.
static LutrisGameConfig parseConfigFile(const std::string &configPath)
Parse a Lutris game config file.
GameSource
Where the game was acquired from (store/service/local).
Definition game.h:39
@ Steam
Steam store/platform.
Definition game.h:41
@ Local
Manually added game (not from a store).
Definition game.h:40
@ Itch
itch.io indie games
Definition game.h:44
@ Lutris
Lutris community scripts.
Definition game.h:45
@ GOG
GOG.com (DRM-free games).
Definition game.h:42
@ Flatpak
Flatpak package.
Definition game.h:46
@ Epic
Epic Games Store.
Definition game.h:43
@ 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
@ Wine
Wine compatibility layer.
Definition game.h:83
nlohmann::json json
fs::path resolveContainedExecutable(const std::string &installPath, const std::string &executable)
void storeFuture(std::shared_ptr< std::future< void > > f)
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
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
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
GameImagePaths imagePaths
Paths to all available image assets.
Definition game.h:562
std::string executablePath
Full path to game executable.
Definition game.h:141
std::string wineDLL
DLL overrides (e.g., "d3d11=native,builtin").
Definition game.h:169
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::vector< std::string > excludeProcesses
Processes to exclude when tracking launcher child processes These are helper processes that should no...
Definition game.h:175
std::string winePrefix
WINEPREFIX path (Wine install location).
Definition game.h:167
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
Parsed configuration for a Lutris-managed game.
std::string workingDir
Working directory (optional).
std::string gameSlug
Game slug from lutris.net.
std::string name
Game display name.
std::string getFullExecutablePath() const
Get the full path to the executable.
std::map< std::string, std::string > dllOverrides
std::string prefix
Wine prefix path.
std::map< std::string, std::string > environmentVariables
std::vector< std::string > excludeProcesses
std::string wineVersion
Wine version name (e.g., "Proton - Experimental").
std::string slug
Game slug (unique identifier).
std::string arguments
Command line arguments (optional).
bool isValid() const
Check if config is valid and usable.
std::string arch
Wine architecture: "win32" or "win64".
void addError(const std::string &source, const std::string &message)
std::vector< std::string > errors
bool hasErrors() const
std::string currentOperation
std::string currentSource
std::string sourceId
std::string runnerVersion
std::string configPath
std::map< std::string, std::string > environmentVars
std::string coverPath
std::string iconPath
std::vector< std::string > excludeProcesses
std::string winePrefix
std::string workingDir
std::string existingGameId
std::string bannerPath
std::string arguments
std::string executablePath
std::string installDir
std::map< std::string, std::string > dllOverrides