game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_suggestion_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_suggestion_service.cpp
4// ==============================================================================
5// Implementation of smart game settings recommendation service
6// ==============================================================================
7
9#include "models/game.h"
12#include "util/logger.h"
13#include "util/lru_cache.h"
14
15#include "util/shell_utils.h"
16
17#include <algorithm>
18#include <array>
19#include <cctype>
20#include <cstdio>
21#include <cstring>
22#include <fstream>
23#include <future>
24#include <map>
25#include <regex>
26#include <sstream>
27#include <sys/wait.h>
28#include <unordered_map>
29
30// ==============================================================================
31// Suggestion Cache Configuration
32// ==============================================================================
33
34// Cache complete GameSuggestions results to avoid re-fetching from multiple APIs
35static constexpr size_t SUGGESTIONS_CACHE_MAX_SIZE = 200; // Max cached suggestions
36static constexpr int SUGGESTIONS_CACHE_TTL_SECONDS = 1800; // 30 minutes TTL
37
38// Global suggestions cache. LRUCache's constructor only stores two ints
39// and reserves no heap; clang-tidy flags it as "may throw" because it
40// can't see through the LRUCache header. Suppress — the warning is a
41// false positive for this initialization.
42// NOLINTNEXTLINE(bugprone-throwing-static-initialization)
45
46// ==============================================================================
47// ProtonDB tier → SuggestionPriority / auto-apply mapping
48// ==============================================================================
49
50// ProtonDB tweaks vary wildly in quality. Before this existed, every tweak
51// regardless of tier was emitted as Recommended + canAutoApply=true, which
52// meant a borked-tier suggestion from 3 reports was applied with the same
53// confidence as a platinum tweak from 500 reports. The helpers below scale
54// the priority and auto-apply bit by the tier reliability.
55namespace
56{
58{
59 if (tier == "platinum" || tier == "native")
61 if (tier == "gold")
63 if (tier == "silver")
65 if (tier == "bronze")
67 if (tier == "borked")
69 return SuggestionPriority::Optional; // unknown / pending
70}
71
72bool protonDbTierAutoApply(const std::string& tier)
73{
74 return tier == "platinum" || tier == "native" || tier == "gold";
75}
76} // namespace
77
78// ==============================================================================
79// GameSuggestions Implementation
80// ==============================================================================
81
83{
84 return std::any_of(suggestions.begin(), suggestions.end(), [](const GameSuggestion& s)
85 { return s.priority == SuggestionPriority::Critical; });
86}
87
89{
90 return std::any_of(
91 suggestions.begin(), suggestions.end(), [](const GameSuggestion& s)
92 { return s.category == SuggestionCategory::Runner && !s.recommendedRunner.empty(); });
93}
94
95std::vector<GameSuggestion> GameSuggestions::getByCategory(SuggestionCategory category) const
96{
97 std::vector<GameSuggestion> result;
98 for (const auto& s : suggestions)
99 {
100 if (s.category == category)
101 {
102 result.push_back(s);
103 }
104 }
105 return result;
106}
107
108std::vector<GameSuggestion> GameSuggestions::getByPriority(SuggestionPriority priority) const
109{
110 std::vector<GameSuggestion> result;
111 for (const auto& s : suggestions)
112 {
113 if (s.priority == priority)
114 {
115 result.push_back(s);
116 }
117 }
118 return result;
119}
120
122{
123 for (const auto& s : suggestions)
124 {
125 if (s.category == SuggestionCategory::Runner && !s.recommendedRunner.empty())
126 {
127 return s.recommendedRunner;
128 }
129 }
130 return "";
131}
132
133std::vector<std::pair<std::string, std::string>> GameSuggestions::getEnvironmentVariables() const
134{
135 std::vector<std::pair<std::string, std::string>> result;
136 for (const auto& s : suggestions)
137 {
138 if (!s.envKey.empty() && !s.envValue.empty())
139 {
140 result.emplace_back(s.envKey, s.envValue);
141 }
142 }
143 return result;
144}
145
147{
148 std::string combined;
149 for (const auto& s : suggestions)
150 {
151 if (!s.dllOverrides.empty())
152 {
153 if (!combined.empty())
154 {
155 combined += ";";
156 }
157 combined += s.dllOverrides;
158 }
159 }
160 return combined;
161}
162
164{
165 // Blocking issues = Low confidence regardless of other factors
167 {
169 }
170
171 // Native Linux = Very High (best case)
172 if (hasNativeLinux)
173 {
175 }
176
177 // Calculate based on available data sources
178 bool hasDeckVerified = (steamDeckStatus == "Verified");
179 bool hasDeckPlayable = (steamDeckStatus == "Playable");
180 bool hasPlatinum = (protondbTier == "platinum");
181 bool hasGold = (protondbTier == "gold");
182 bool hasSilver = (protondbTier == "silver");
183 bool hasHighReportCount = (protondbReportCount >= 50);
184 bool hasGoodReportCount = (protondbReportCount >= 10);
185 bool hasStrongConfidence = (protondbConfidence == "strong" || protondbConfidence == "good");
186
187 // Very High: Multiple strong signals corroborating each other
188 // Platinum + strong + many reports = tested across diverse hardware
189 if ((hasDeckVerified && hasPlatinum) ||
190 (hasPlatinum && hasStrongConfidence && hasHighReportCount))
191 {
193 }
194
195 // High: Single strong signal or two moderate signals
196 if (hasDeckVerified || (hasPlatinum && hasStrongConfidence && hasGoodReportCount))
197 {
199 }
200
201 // High: Deck Playable + Gold/Platinum
202 if (hasDeckPlayable && (hasGold || hasPlatinum))
203 {
205 }
206
207 // Medium: Gold with good reports, or well-tested on Lutris
208 if ((hasGold && hasGoodReportCount) || (hasLutrisInstaller && lutrisDownloadCount >= 100))
209 {
211 }
212
213 // Medium: Silver or Gold with few reports
214 if (hasSilver || hasGold)
215 {
217 }
218
219 // Medium: Has Lutris community configuration
221 {
223 }
224
225 // Low: Bronze or Borked tier
226 if (protondbTier == "bronze" || protondbTier == "borked")
227 {
229 }
230
231 // Unknown: No data available from any source
232 if (protondbTier.empty() && steamDeckStatus.empty() && !hasLutrisInstaller)
233 {
235 }
236
238}
239
241{
242 float score = 0.0f;
243
244 // Blocking issues severely reduce confidence
246 {
247 return 0.1f;
248 }
249
250 // Native Linux = perfect confidence
251 if (hasNativeLinux)
252 {
253 return 1.0f;
254 }
255
256 // Steam Deck verification (official Valve testing - single device)
257 // Weighted slightly below ProtonDB Platinum+strong+high-reports since
258 // ProtonDB represents broader hardware testing across many configurations
259 if (steamDeckStatus == "Verified")
260 score += 0.30f;
261 else if (steamDeckStatus == "Playable")
262 score += 0.20f;
263 else if (steamDeckStatus == "Unsupported")
264 score -= 0.2f;
265
266 // ProtonDB tier (community-tested across diverse hardware)
267 // Platinum with strong confidence + many reports is the gold standard
268 if (protondbTier == "platinum")
269 score += 0.35f;
270 else if (protondbTier == "gold")
271 score += 0.22f;
272 else if (protondbTier == "silver")
273 score += 0.12f;
274 else if (protondbTier == "bronze")
275 score += 0.05f;
276 else if (protondbTier == "borked")
277 score -= 0.15f;
278
279 // ProtonDB confidence (quality of reports)
280 if (protondbConfidence == "strong")
281 score += 0.10f;
282 else if (protondbConfidence == "good")
283 score += 0.05f;
284
285 // Report count — high counts represent real-world reliability
286 // 100+ reports with platinum is as reliable as it gets
287 if (protondbReportCount >= 100)
288 score += 0.15f;
289 else if (protondbReportCount >= 50)
290 score += 0.12f;
291 else if (protondbReportCount >= 20)
292 score += 0.08f;
293 else if (protondbReportCount >= 10)
294 score += 0.05f;
295 else if (protondbReportCount >= 5)
296 score += 0.03f;
297
298 // Lutris installer (community tested configurations)
300 {
301 score += 0.08f;
302 if (lutrisDownloadCount >= 5000)
303 score += 0.07f;
304 else if (lutrisDownloadCount >= 1000)
305 score += 0.05f;
306 else if (lutrisDownloadCount >= 100)
307 score += 0.02f;
308 }
309
310 // Apply any additional boosts
311 score += confidenceBoost;
312
313 // Clamp to 0.0-1.0
314 return std::max(0.0f, std::min(1.0f, score));
315}
316
318{
319 std::string summary;
320
322 {
323 summary = "⚠️ Known issues may prevent this game from running (anti-cheat, DRM, etc.)";
324 return summary;
325 }
326
327 if (hasNativeLinux)
328 {
329 summary = "✓ Native Linux version available - best compatibility";
330 return summary;
331 }
332
334 switch (level)
335 {
337 summary = "✓ Excellent compatibility - ";
338 if (steamDeckStatus == "Verified" && protondbTier == "platinum")
339 summary += "Steam Deck Verified + ProtonDB Platinum";
340 else if (steamDeckStatus == "Verified")
341 summary += "Steam Deck Verified by Valve";
342 else
343 summary += "ProtonDB Platinum with strong community confidence";
344 break;
345
347 summary = "✓ Good compatibility - ";
348 if (steamDeckStatus == "Verified")
349 summary += "Steam Deck Verified";
350 else if (steamDeckStatus == "Playable")
351 summary += "Steam Deck Playable + " + protondbTier + " on ProtonDB";
352 else
353 summary += "ProtonDB " + protondbTier + " with " + std::to_string(protondbReportCount) +
354 " reports";
355 break;
356
358 summary = "○ Likely works - ";
360 summary += "Lutris tested (" + std::to_string(lutrisDownloadCount) + " downloads)";
361 else if (!protondbTier.empty())
362 summary += "ProtonDB " + protondbTier;
363 else
364 summary += "limited data available";
365 break;
366
368 summary = "⚠ Limited data - ";
369 if (protondbTier == "bronze")
370 summary += "ProtonDB Bronze rating, may have issues";
371 else if (protondbTier == "borked")
372 summary += "ProtonDB Borked rating, likely won't work";
373 else
374 summary += "proceed with caution, results may vary";
375 break;
376
378 summary = "? No compatibility data found - game may or may not work with Proton";
379 break;
380 }
381
382 return summary;
383}
384
385// ==============================================================================
386// GameSuggestionService Implementation
387// ==============================================================================
388
390{
391 int steamAppId = game.metadata.steamAppId;
392 return getSuggestions(steamAppId, game.name);
393}
394
395GameSuggestions GameSuggestionService::getSuggestions(int steamAppId, const std::string& gameName)
396{
397 // Check suggestion-level cache first (avoids all API calls if cached)
398 if (steamAppId > 0)
399 {
400 auto cached = suggestionsCache_.get(steamAppId);
401 if (cached)
402 {
403 Logger::debug("Suggestions cache hit for {} (AppID: {})", gameName, steamAppId);
404 return *cached;
405 }
406 }
407
408 Logger::info("=== Generating recommendations for: {} (AppID: {}) ===", gameName, steamAppId);
409
410 GameSuggestions suggestions;
411 suggestions.steamAppId = steamAppId;
412 suggestions.gameName = gameName;
413
414 // Get system info
415 const auto& caps = effectiveCapabilities();
416 suggestions.detectedGPU = effectiveGPUVendorName();
417 suggestions.isCachyOS = caps.isCachyOS();
418
419 // Log system capabilities that affect recommendations
420 Logger::info("System context: GPU={} (gen={}), CachyOS={}, Runners={}", suggestions.detectedGPU,
421 static_cast<int>(caps.gpu.generation), suggestions.isCachyOS ? "yes" : "no",
422 caps.runners.size());
423
424 Logger::info("GPU features: RDNA2+={}, RTX={}, FSR3={}, DLSS={}, XeSS={}",
425 caps.hasRDNA2OrNewer() ? "yes" : "no", caps.hasRTXCapable() ? "yes" : "no",
426 caps.gpu.supportsFSR3 ? "yes" : "no", caps.gpu.supportsDLSS ? "yes" : "no",
427 caps.gpu.supportsXeSS ? "yes" : "no");
428
429 // Add suggestions from various sources
430 if (steamAppId > 0)
431 {
432 Logger::debug("Fetching ProtonDB suggestions...");
433 addProtonDBSuggestions(suggestions, steamAppId);
434 }
435
436 Logger::debug("Adding system-based suggestions...");
437 addSystemSuggestions(suggestions);
438
439 if (suggestions.isCachyOS)
440 {
441 Logger::debug("Adding CachyOS-specific suggestions...");
442 addCachyOSSuggestions(suggestions);
443 }
444
445 Logger::debug("Adding built-in game fixes...");
446 addBuiltinFixes(suggestions, steamAppId, gameName);
447
448 // Deduplicate suggestions - prefer higher priority sources
449 // If ProtonDB and Lutris both suggest the same env var, keep ProtonDB (more reports)
450 {
451 std::unordered_map<std::string, size_t> envVarSeen; // envKey -> index of first occurrence
452 std::vector<GameSuggestion> deduplicated;
453 deduplicated.reserve(suggestions.suggestions.size());
454
455 for (auto& s : suggestions.suggestions)
456 {
457 if (!s.envKey.empty())
458 {
459 auto it = envVarSeen.find(s.envKey);
460 if (it != envVarSeen.end())
461 {
462 // Already have this env var - check if this one has more report support
463 auto& existing = deduplicated[it->second];
464 if (s.reportCount > existing.reportCount ||
465 (s.source == "ProtonDB" && existing.source != "ProtonDB"))
466 {
467 // Replace with better source, but note the additional source
468 existing.reason += " (also confirmed by " + s.source + ")";
469 existing.reportCount = std::max(existing.reportCount, s.reportCount);
470 }
471 else
472 {
473 // Keep existing, but note the confirmation
474 existing.reason += " (also confirmed by " + s.source + ")";
475 }
476 continue; // Skip adding duplicate
477 }
478 envVarSeen[s.envKey] = deduplicated.size();
479 }
480 deduplicated.push_back(std::move(s));
481 }
482
483 if (suggestions.suggestions.size() != deduplicated.size())
484 {
485 Logger::debug("Deduplicated {} suggestions (removed {} duplicates)",
486 deduplicated.size(),
487 suggestions.suggestions.size() - deduplicated.size());
488 }
489 suggestions.suggestions = std::move(deduplicated);
490 }
491
492 // Sort by priority
493 std::sort(suggestions.suggestions.begin(), suggestions.suggestions.end(),
494 [](const GameSuggestion& a, const GameSuggestion& b)
495 { return static_cast<int>(a.priority) < static_cast<int>(b.priority); });
496
497 // Log summary of suggestions
498 int critical = 0, recommended = 0, optional = 0, informational = 0;
499 for (const auto& s : suggestions.suggestions)
500 {
501 switch (s.priority)
502 {
504 ++critical;
505 break;
507 ++recommended;
508 break;
510 ++optional;
511 break;
513 ++informational;
514 break;
515 }
516 }
517 Logger::info("Generated {} total suggestions: {} critical, {} recommended, {} optional, {} "
518 "informational",
519 suggestions.suggestions.size(), critical, recommended, optional, informational);
520
521 // Log confidence assessment
522 Logger::info("Confidence: {:.0f}% - {}", suggestions.getConfidenceScore() * 100.0f,
523 suggestions.getConfidenceSummary());
524
525 // Log data sources used
526 Logger::debug("Data sources: ProtonDB={} (tier={}, reports={}), Deck={}, Lutris={} "
527 "(downloads={}), Native={}",
528 !suggestions.protondbTier.empty() ? "yes" : "no",
529 suggestions.protondbTier.empty() ? "n/a" : suggestions.protondbTier,
530 suggestions.protondbReportCount,
531 suggestions.steamDeckStatus.empty() ? "n/a" : suggestions.steamDeckStatus,
532 suggestions.hasLutrisInstaller ? "yes" : "no", suggestions.lutrisDownloadCount,
533 suggestions.hasNativeLinux ? "yes" : "no");
534
535 // Log each recommendation at debug level
536 for (const auto& s : suggestions.suggestions)
537 {
538 std::string details;
539 if (!s.envKey.empty())
540 details += s.envKey + "=" + s.envValue;
541 if (!s.recommendedRunner.empty())
542 details += "runner=" + s.recommendedRunner;
543 Logger::debug(" [{}] {}: {} {}", priorityToString(s.priority), s.title, s.description,
544 details.empty() ? "" : "(" + details + ")");
545 }
546
547 // Cache the result for future requests (only if we have a valid Steam App ID)
548 if (steamAppId > 0)
549 {
550 suggestionsCache_.put(steamAppId, suggestions);
551
552 // Log cache stats periodically
553 auto stats = suggestionsCache_.getStats();
554 if (stats.currentSize % 20 == 0)
555 {
556 Logger::debug("Suggestions cache: {} entries, {:.1f}% hit rate", stats.currentSize,
557 stats.hitRate() * 100.0f);
558 }
559 }
560
561 return suggestions;
562}
563
565{
566 getSuggestionsAsync(game.metadata.steamAppId, game.name, std::move(callback));
567}
568
569void GameSuggestionService::getSuggestionsAsync(int steamAppId, const std::string& gameName,
570 SuggestionsCallback callback)
571{
572 // Store in a static collection to prevent premature destruction
573 static std::mutex futuresMutex;
574 static std::vector<std::shared_ptr<std::future<void>>> activeFutures;
575
576 // Check capacity BEFORE launching the async task. The previous pattern
577 // created the future first, then returned early without adding it to
578 // activeFutures — the future's destructor then blocked the calling thread
579 // waiting for network I/O to complete (std::async future dtors join the
580 // thread). By checking capacity first we avoid that silent stall.
581 {
582 std::lock_guard<std::mutex> lock(futuresMutex);
583
584 // Clean up completed futures (those that are ready)
585 activeFutures.erase(std::remove_if(activeFutures.begin(), activeFutures.end(),
586 [](const std::shared_ptr<std::future<void>>& f)
587 {
588 return f->wait_for(std::chrono::milliseconds(0)) ==
589 std::future_status::ready;
590 }),
591 activeFutures.end());
592
593 // Limit concurrent suggestion requests to prevent unbounded growth
594 // if futures block on network I/O and never become ready.
595 constexpr size_t kMaxActiveFutures = 32;
596 if (activeFutures.size() >= kMaxActiveFutures)
597 {
598 Logger::warn("[Suggestions] Too many pending async requests, dropping new request");
599 // Fire the callback with an empty result so the UI does not hang
600 // waiting for a result that will never arrive.
601 if (callback)
602 callback(GameSuggestions{});
603 return;
604 }
605 }
606
607 // Launch the async task after releasing the lock so getSuggestions()
608 // (which performs blocking network I/O) does not hold futuresMutex.
609 auto future = std::make_shared<std::future<void>>(
610 std::async(std::launch::async,
611 [steamAppId, gameName, callback = std::move(callback)]()
612 {
613 auto suggestions = getSuggestions(steamAppId, gameName);
614 callback(suggestions);
615 }));
616
617 {
618 std::lock_guard<std::mutex> lock(futuresMutex);
619 activeFutures.push_back(future);
620 }
621}
622
623void GameSuggestionService::addProtonDBSuggestions(GameSuggestions& suggestions, int steamAppId)
624{
625 // Fetch data from multiple sources IN PARALLEL for better performance
626 // Each API call is independent, so we can run them concurrently
627 Logger::debug("Fetching data from 4 APIs in parallel for AppID {}", steamAppId);
628
629 auto protonFuture = std::async(std::launch::async, [steamAppId]()
630 { return ProtonDBService::getGameInfo(steamAppId); });
631
632 auto deckFuture = std::async(std::launch::async, [steamAppId]()
633 { return ProtonDBService::getSteamDeckInfo(steamAppId); });
634
635 auto steamFuture = std::async(std::launch::async, [steamAppId]()
636 { return ProtonDBService::getSteamAppInfo(steamAppId); });
637
638 auto lutrisFuture = std::async(std::launch::async, [steamAppId]()
639 { return ProtonDBService::getLutrisInfo(steamAppId); });
640
641 // Wait for all futures and get results
642 auto protonInfo = protonFuture.get();
643 auto deckInfo = deckFuture.get();
644 auto steamInfo = steamFuture.get();
645 auto lutrisInfo = lutrisFuture.get();
646
647 Logger::debug("All API fetches completed for AppID {}", steamAppId);
648
649 // === CHECK FOR NATIVE LINUX SUPPORT FIRST ===
650 if (steamInfo.found && steamInfo.supportsLinux)
651 {
652 suggestions.hasNativeLinux = true;
653
654 GameSuggestion nativeSuggestion;
655 nativeSuggestion.priority =
656 SuggestionPriority::Critical; // High priority - affects everything
657 nativeSuggestion.category = SuggestionCategory::Runner;
658 nativeSuggestion.title = "Native Linux Available";
659 nativeSuggestion.description =
660 "This game has a native Linux version. Consider using it instead of Proton.";
661 nativeSuggestion.reason =
662 "Native builds typically have better performance and fewer issues";
663 nativeSuggestion.recommendedRunner = "native";
664 nativeSuggestion.source = "Steam Store";
665 nativeSuggestion.canAutoApply = true;
666 suggestions.suggestions.push_back(std::move(nativeSuggestion));
667
668 Logger::info("Game {} has native Linux support", suggestions.gameName);
669 // Still continue to add other suggestions in case user prefers Windows version
670 }
671
672 // === STEAM DECK COMPATIBILITY INFO ===
673 if (deckInfo.found)
674 {
675 suggestions.steamDeckStatus = deckInfo.compatibilityString;
676
677 GameSuggestion deckSuggestion;
679 deckSuggestion.source = "Steam Deck (Valve Testing)";
680 deckSuggestion.reportCount = 1; // Official Valve testing
681
682 switch (deckInfo.compatibility)
683 {
686 deckSuggestion.title = "Steam Deck Verified";
687 deckSuggestion.description =
688 "Valve has verified this game works great on Steam Deck with Proton";
689 deckSuggestion.reason = "Official Valve testing confirms excellent compatibility";
690 suggestions.confidenceBoost += 0.2f; // High confidence boost
691 break;
692
695 deckSuggestion.title = "Steam Deck Playable";
696 deckSuggestion.description =
697 "This game is playable on Steam Deck but may require configuration";
698 deckSuggestion.reason = "Valve testing confirms the game works with Proton";
699 suggestions.confidenceBoost += 0.1f;
700 break;
701
703 deckSuggestion.priority = SuggestionPriority::Critical;
704 deckSuggestion.title = "Steam Deck Unsupported";
705 deckSuggestion.description =
706 "Valve reports this game does not currently work on Steam Deck";
707 deckSuggestion.reason = "May have anti-cheat, DRM, or other blocking issues";
708 suggestions.hasBlockingIssue = true;
709 break;
710
711 default:
712 // Unknown - no suggestion needed
713 break;
714 }
715
716 if (deckInfo.compatibility != SteamDeckCompatibility::Unknown)
717 {
718 suggestions.suggestions.push_back(std::move(deckSuggestion));
719 }
720 }
721
722 // === MULTIPLAYER/ANTI-CHEAT WARNING ===
723 if (steamInfo.found && steamInfo.hasMultiplayer && !steamInfo.supportsLinux)
724 {
725 // Multiplayer Windows-only game - potential anti-cheat issues
726 GameSuggestion acWarning;
729 acWarning.title = "Multiplayer Game Warning";
730 acWarning.description =
731 "This is a multiplayer game. Some anti-cheat systems may not work with Proton.";
732 acWarning.reason = "Check ProtonDB reports or areweanticheatyet.com for anti-cheat status";
733 acWarning.source = "Steam Store";
734 acWarning.canAutoApply = false;
735 suggestions.suggestions.push_back(std::move(acWarning));
736 }
737
738 // === DRM WARNING ===
739 if (steamInfo.found && !steamInfo.drmNotice.empty())
740 {
741 GameSuggestion drmWarning;
744 drmWarning.title = "Third-Party DRM";
745 drmWarning.description = "Game uses: " + steamInfo.drmNotice;
746 drmWarning.reason = "Some DRM may affect compatibility or require additional setup";
747 drmWarning.source = "Steam Store";
748 suggestions.suggestions.push_back(std::move(drmWarning));
749 }
750
751 // === LUTRIS INSTALLER CONFIGS ===
752 if (lutrisInfo.found && !lutrisInfo.installers.empty())
753 {
754 suggestions.hasLutrisInstaller = true;
755 const auto& bestInstaller = lutrisInfo.installers[0]; // Already sorted by popularity
756 suggestions.lutrisDownloadCount = bestInstaller.downloadCount;
757
758 // === ANTI-CHEAT RUNTIME SUGGESTIONS ===
759 // Lutris community installers flag whether BattlEye / EAC need to be
760 // enabled. Surface them as Critical so the game launches at all, and
761 // record the need so the runner picker can prefer proton-cachyos-slr.
762 if (bestInstaller.eac)
763 {
764 suggestions.needsEACRuntime = true;
765 GameSuggestion eacRt;
768 eacRt.title = "Easy Anti-Cheat Runtime";
769 eacRt.description =
770 "Enable the Proton EAC runtime so the anti-cheat initialises correctly.";
771 eacRt.reason = "Lutris installer reports this game requires Easy Anti-Cheat";
772 eacRt.envKey = "PROTON_EAC_RUNTIME";
773 eacRt.envValue = "1";
774 eacRt.source = "Lutris";
775 eacRt.canAutoApply = true;
776 suggestions.suggestions.push_back(std::move(eacRt));
777 }
778 if (bestInstaller.battleye)
779 {
780 suggestions.needsBattleyeRuntime = true;
781 GameSuggestion beRt;
784 beRt.title = "BattlEye Runtime";
785 beRt.description =
786 "Enable the Proton BattlEye runtime so the anti-cheat initialises correctly.";
787 beRt.reason = "Lutris installer reports this game requires BattlEye";
788 beRt.envKey = "PROTON_BATTLEYE_RUNTIME";
789 beRt.envValue = "1";
790 beRt.source = "Lutris";
791 beRt.canAutoApply = true;
792 suggestions.suggestions.push_back(std::move(beRt));
793 }
794
795 // Apply environment variables from Lutris
796 for (const auto& [key, value] : bestInstaller.environmentVariables)
797 {
798 GameSuggestion envSuggestion;
801 envSuggestion.title = key;
802 envSuggestion.description = "Set " + key + "=" + value;
803 envSuggestion.reason = "From Lutris community-tested installer";
804 envSuggestion.envKey = key;
805 envSuggestion.envValue = value;
806 envSuggestion.source = "Lutris";
807 envSuggestion.canAutoApply = true;
808 suggestions.suggestions.push_back(std::move(envSuggestion));
809 }
810
811 // Apply DLL overrides from Lutris
812 if (!bestInstaller.dllOverrides.empty())
813 {
814 GameSuggestion dllSuggestion;
817 dllSuggestion.title = "DLL Overrides (Lutris)";
818 dllSuggestion.description = "Apply: " + bestInstaller.dllOverrides;
819 dllSuggestion.reason = "From Lutris tested configuration";
820 dllSuggestion.dllOverrides = bestInstaller.dllOverrides;
821 dllSuggestion.source = "Lutris";
822 dllSuggestion.canAutoApply = true;
823 suggestions.suggestions.push_back(std::move(dllSuggestion));
824 }
825
826 // Wine version recommendation from Lutris
827 if (!bestInstaller.wineVersion.empty())
828 {
829 GameSuggestion wineSuggestion;
830 wineSuggestion.priority = SuggestionPriority::Optional;
831 wineSuggestion.category = SuggestionCategory::Runner;
832 wineSuggestion.title = "Lutris Wine Version";
833 wineSuggestion.description = "Lutris uses: " + bestInstaller.wineVersion;
834 wineSuggestion.reason = "Community-tested Wine/Proton version";
835 wineSuggestion.source = "Lutris";
836 suggestions.suggestions.push_back(std::move(wineSuggestion));
837 }
838
839 Logger::info("Added {} suggestions from Lutris for {}",
840 bestInstaller.environmentVariables.size() +
841 (bestInstaller.dllOverrides.empty() ? 0 : 1),
842 suggestions.gameName);
843 }
844
845 // === PROTONDB DATA ===
846 if (!protonInfo.found)
847 {
848 return;
849 }
850
851 suggestions.protondbTier = protonInfo.tier;
852 suggestions.protondbConfidence = protonInfo.confidence;
853 suggestions.protondbScore = protonInfo.score;
854 suggestions.protondbReportCount = protonInfo.totalReports;
855
856 // Tier-aware priority and auto-apply for ProtonDB-sourced tweaks. A
857 // platinum-tier tweak with many reports is treated as Recommended + auto;
858 // a borked-tier tweak drops to Informational and never auto-applies.
859 const SuggestionPriority tierPriority = protonDbTierPriority(protonInfo.tier);
860 const bool tierAutoApply = protonDbTierAutoApply(protonInfo.tier);
861 const std::string tierReason =
862 protonInfo.tier.empty() ? std::string("community reports")
863 : "tier=" + protonInfo.tier + ", " +
864 std::to_string(protonInfo.tweaks.reportCount) + " reports";
865
866 // Add runner recommendation
867 if (!protonInfo.tweaks.recommendedProtonVersion.empty())
868 {
869 GameSuggestion runnerSuggestion;
870 runnerSuggestion.priority = tierPriority;
871 runnerSuggestion.category = SuggestionCategory::Runner;
872 runnerSuggestion.title = "Recommended Proton Version";
873 runnerSuggestion.description = "Use " + protonInfo.tweaks.recommendedProtonVersion;
874 runnerSuggestion.reason = "Based on " + tierReason;
875 runnerSuggestion.recommendedRunner = protonInfo.tweaks.recommendedProtonVersion;
876 runnerSuggestion.source = "ProtonDB";
877 runnerSuggestion.reportCount = protonInfo.tweaks.reportCount;
878 runnerSuggestion.canAutoApply = tierAutoApply;
879 suggestions.suggestions.push_back(std::move(runnerSuggestion));
880 }
881
882 // Add environment variable suggestions
883 for (const auto& [key, value] : protonInfo.tweaks.environmentVariables)
884 {
885 GameSuggestion envSuggestion;
886 envSuggestion.priority = tierPriority;
887 envSuggestion.category = SuggestionCategory::Compatibility;
888 envSuggestion.title = key;
889 envSuggestion.description = "Set " + key + "=" + value;
890 envSuggestion.reason = "Commonly used fix (" + tierReason + ")";
891 envSuggestion.envKey = key;
892 envSuggestion.envValue = value;
893 envSuggestion.source = "ProtonDB";
894 envSuggestion.reportCount = protonInfo.tweaks.reportCount;
895 envSuggestion.canAutoApply = tierAutoApply;
896 suggestions.suggestions.push_back(std::move(envSuggestion));
897 }
898
899 // Add DLL overrides
900 if (!protonInfo.tweaks.dllOverrides.empty())
901 {
902 GameSuggestion dllSuggestion;
903 dllSuggestion.priority = tierPriority;
904 dllSuggestion.category = SuggestionCategory::Compatibility;
905 dllSuggestion.title = "DLL Overrides";
906 dllSuggestion.description = "Apply DLL overrides: " + protonInfo.tweaks.dllOverrides;
907 dllSuggestion.reason = "Community-reported fix (" + tierReason + ")";
908 dllSuggestion.dllOverrides = protonInfo.tweaks.dllOverrides;
909 dllSuggestion.source = "ProtonDB";
910 dllSuggestion.canAutoApply = tierAutoApply;
911 suggestions.suggestions.push_back(std::move(dllSuggestion));
912 }
913
914 // Add launch arguments. These are inherently per-title and can change
915 // behaviour drastically, so cap them at Optional even for platinum tier.
916 if (!protonInfo.tweaks.launchArguments.empty())
917 {
918 GameSuggestion argsSuggestion;
919 // Enum order: Critical(0) < Recommended(1) < Optional(2) < Informational(3).
920 // Higher enum value = lower priority. "Cap at Optional" = max().
921 argsSuggestion.priority = std::max(tierPriority, SuggestionPriority::Optional);
922 argsSuggestion.category = SuggestionCategory::Compatibility;
923 argsSuggestion.title = "Launch Arguments";
924 argsSuggestion.description = "Add launch arguments: " + protonInfo.tweaks.launchArguments;
925 argsSuggestion.reason = "May improve game behavior (" + tierReason + ")";
926 argsSuggestion.launchArgs = protonInfo.tweaks.launchArguments;
927 argsSuggestion.source = "ProtonDB";
928 argsSuggestion.canAutoApply = tierAutoApply;
929 suggestions.suggestions.push_back(std::move(argsSuggestion));
930 }
931
932 // Add notes as informational suggestions
933 for (const auto& note : protonInfo.tweaks.notes)
934 {
935 if (note.length() > 10) // Skip very short notes
936 {
937 GameSuggestion noteSuggestion;
938 noteSuggestion.priority = SuggestionPriority::Informational;
939 noteSuggestion.category = SuggestionCategory::General;
940 noteSuggestion.title = "Community Note";
941 noteSuggestion.description = note;
942 noteSuggestion.source = "ProtonDB";
943 suggestions.suggestions.push_back(std::move(noteSuggestion));
944 }
945 }
946
947 Logger::info("Added {} ProtonDB suggestions for app {}", suggestions.suggestions.size(),
948 steamAppId);
949}
950
951void GameSuggestionService::addRunnerSuggestions(GameSuggestions& suggestions)
952{
953 const auto& caps = effectiveCapabilities();
954 const auto& runners = caps.runners;
955
956 if (runners.empty())
957 {
958 GameSuggestion noRunners;
961 noRunners.title = "No Proton Versions Found";
962 noRunners.description =
963 "No Proton/Wine versions detected. Install Proton via Steam or a custom Proton build.";
964 noRunners.reason = "Proton is required to run Windows games";
965 noRunners.source = "System Detection";
966 noRunners.canAutoApply = false;
967 suggestions.suggestions.push_back(std::move(noRunners));
968 return;
969 }
970
971 // Check if the suggestions already have a runner recommendation (from ProtonDB)
972 if (suggestions.hasRunnerSuggestion())
973 {
974 return; // Don't override ProtonDB recommendation
975 }
976
977 // Find the best runner based on system configuration
978 const RunnerInfo* bestRunner = nullptr;
979 const RunnerInfo* geProton = nullptr;
980 const RunnerInfo* cachyProton = nullptr; // Any proton-cachyos variant
981 const RunnerInfo* cachyProtonSLR = nullptr; // SLR wrapper variant (required for anti-cheat)
982 const RunnerInfo* protonExp = nullptr;
983 const RunnerInfo* latestOfficial = nullptr;
984
985 for (const auto& runner : runners)
986 {
987 // Track specific runner types
988 if (runner.type == "proton-ge" && (!geProton || runner.version > geProton->version))
989 {
990 geProton = &runner;
991 }
992 else if (runner.type == "proton-cachyos")
993 {
994 const bool isSLR = runner.name.find("slr") != std::string::npos ||
995 runner.name.find("SLR") != std::string::npos;
996 if (isSLR && (!cachyProtonSLR || runner.version > cachyProtonSLR->version))
997 {
998 cachyProtonSLR = &runner;
999 }
1000 if (!cachyProton || runner.version > cachyProton->version)
1001 {
1002 cachyProton = &runner;
1003 }
1004 }
1005 else if (runner.name.find("Experimental") != std::string::npos)
1006 {
1007 protonExp = &runner;
1008 }
1009 else if (runner.type == "proton" &&
1010 (!latestOfficial || runner.version > latestOfficial->version))
1011 {
1012 latestOfficial = &runner;
1013 }
1014 }
1015
1016 // Determine best runner based on system
1017 std::string reason;
1018
1019 const bool needsAntiCheat = suggestions.needsEACRuntime || suggestions.needsBattleyeRuntime;
1020
1021 // Anti-cheat titles: prefer the SLR-wrapped proton-cachyos on CachyOS —
1022 // the Steam Linux Runtime container it ships is what the AC modules
1023 // ABI-check against. Fall back to GE-Proton which bundles the runtimes.
1024 if (needsAntiCheat && caps.isCachyOS() && cachyProtonSLR)
1025 {
1026 bestRunner = cachyProtonSLR;
1027 reason = "proton-cachyos-slr ships the SLR container and anti-cheat runtimes "
1028 "this game requires";
1029 }
1030 // CachyOS users prefer proton-cachyos regardless of GPU vendor — it
1031 // tracks proton-cachyos daily and carries NVIDIA (NVML, DLSS upgrade),
1032 // AMD (FSR4 path), and scheduler-aware fixes that stock GE-Proton lacks.
1033 else if (caps.isCachyOS() && cachyProton)
1034 {
1035 bestRunner = cachyProton;
1036 reason = "proton-cachyos is the CachyOS-optimised build and tracks upstream daily";
1037 }
1038 else if (caps.hasNVIDIAGPU() && geProton)
1039 {
1040 // GE-Proton often has better NVIDIA support and includes additional patches
1041 bestRunner = geProton;
1042 reason = "GE-Proton includes extra patches and often better NVIDIA support";
1043 }
1044 else if (caps.hasAMDGPU())
1045 {
1046 // For AMD off CachyOS, GE-Proton is the default choice
1047 if (geProton)
1048 {
1049 bestRunner = geProton;
1050 reason = "GE-Proton has excellent AMD support and additional game fixes";
1051 }
1052 else if (protonExp)
1053 {
1054 bestRunner = protonExp;
1055 reason = "Proton Experimental has the latest features for AMD GPUs";
1056 }
1057 }
1058 else if (caps.hasIntelGPU())
1059 {
1060 // Intel Arc benefits from latest Proton versions
1061 if (protonExp)
1062 {
1063 bestRunner = protonExp;
1064 reason = "Proton Experimental has the best Intel Arc GPU support";
1065 }
1066 else if (geProton)
1067 {
1068 bestRunner = geProton;
1069 reason = "GE-Proton includes fixes that may help Intel GPU compatibility";
1070 }
1071 }
1072
1073 // Fallback: prefer GE-Proton > Experimental > latest official
1074 if (!bestRunner)
1075 {
1076 if (geProton)
1077 {
1078 bestRunner = geProton;
1079 reason = "GE-Proton includes community patches and additional codec support";
1080 }
1081 else if (protonExp)
1082 {
1083 bestRunner = protonExp;
1084 reason = "Proton Experimental has the latest features and fixes";
1085 }
1086 else if (latestOfficial)
1087 {
1088 bestRunner = latestOfficial;
1089 reason = "Latest stable Proton version";
1090 }
1091 }
1092
1093 if (bestRunner)
1094 {
1095 GameSuggestion runnerSuggestion;
1096 runnerSuggestion.priority = SuggestionPriority::Recommended;
1097 runnerSuggestion.category = SuggestionCategory::Runner;
1098 runnerSuggestion.title = "Recommended Runner";
1099 runnerSuggestion.description = "Use " + bestRunner->name + " for best compatibility";
1100 runnerSuggestion.reason = reason;
1101 runnerSuggestion.recommendedRunner = bestRunner->name;
1102 runnerSuggestion.source = "System Detection";
1103 runnerSuggestion.canAutoApply = true;
1104 suggestions.suggestions.push_back(std::move(runnerSuggestion));
1105 }
1106
1107 // Also list available runners as informational
1108 if (runners.size() > 1)
1109 {
1110 std::string runnerList;
1111 int count = 0;
1112 for (const auto& runner : runners)
1113 {
1114 if (count > 0)
1115 runnerList += ", ";
1116 runnerList += runner.name;
1117 if (++count >= 5) // Limit to 5 runners in the list
1118 {
1119 runnerList += " (+" + std::to_string(runners.size() - 5) + " more)";
1120 break;
1121 }
1122 }
1123
1124 GameSuggestion availableRunners;
1126 availableRunners.category = SuggestionCategory::Runner;
1127 availableRunners.title = "Available Runners";
1128 availableRunners.description = runnerList;
1129 availableRunners.reason =
1130 std::to_string(runners.size()) + " Proton/Wine versions installed";
1131 availableRunners.source = "System Detection";
1132 availableRunners.canAutoApply = false;
1133 suggestions.suggestions.push_back(std::move(availableRunners));
1134 }
1135
1136 // Check for GE-Proton updates (only if user has GE-Proton installed)
1137 if (geProton)
1138 {
1139 std::string latestVersion = getLatestGEProtonVersion();
1140 if (!latestVersion.empty() && latestVersion != geProton->name &&
1141 latestVersion > geProton->name) // Simple string comparison works for GE-Proton naming
1142 {
1143 GameSuggestion updateSuggestion;
1144 updateSuggestion.priority = SuggestionPriority::Optional;
1145 updateSuggestion.category = SuggestionCategory::Runner;
1146 updateSuggestion.title = "GE-Proton Update Available";
1147 updateSuggestion.description =
1148 "Latest version: " + latestVersion + " (you have: " + geProton->name + ")";
1149 updateSuggestion.reason =
1150 "Newer versions may include bug fixes and game compatibility improvements";
1151 updateSuggestion.source = "GitHub";
1152 updateSuggestion.canAutoApply = false;
1153 suggestions.suggestions.push_back(std::move(updateSuggestion));
1154 }
1155 }
1156}
1157
1158void GameSuggestionService::addSystemSuggestions(GameSuggestions& suggestions)
1159{
1160 // Add all system-based suggestions from different categories
1161 addRunnerSuggestions(suggestions); // Add runner suggestions first
1162 addGPUSuggestions(suggestions);
1163 addSyncSuggestions(suggestions);
1164 addShaderCacheSuggestions(suggestions);
1165 addKernelParamSuggestions(suggestions);
1166 addDisplaySuggestions(suggestions);
1167 addMemorySuggestions(suggestions);
1168 addPowerSuggestions(suggestions);
1169 addControllerSuggestions(suggestions);
1170 addAudioSuggestions(suggestions);
1171
1172 const auto& caps = effectiveCapabilities();
1173
1174 // GameMode suggestion — skipped when ananicy-cpp is already managing
1175 // scheduling, since enabling GameMode on top would cause sched conflicts.
1176 if (caps.canUseGameMode() && caps.tools.shouldUseGameMode())
1177 {
1178 GameSuggestion gameMode;
1181 gameMode.title = "GameMode";
1182 gameMode.description = "Enable GameMode for CPU optimizations";
1183 gameMode.reason = "GameMode is installed on this system";
1184 gameMode.source = "System Detection";
1185 gameMode.canAutoApply = false; // Requires enabling in game config
1186 suggestions.suggestions.push_back(std::move(gameMode));
1187 }
1188
1189 // MangoHud suggestion
1190 if (caps.tools.mangoHud)
1191 {
1192 GameSuggestion mangoHud;
1195 mangoHud.title = "MangoHud Available";
1196 mangoHud.description = "MangoHud is available for FPS/performance monitoring";
1197 mangoHud.reason = "MangoHud is installed on this system";
1198 mangoHud.source = "System Detection";
1199 mangoHud.canAutoApply = false;
1200 suggestions.suggestions.push_back(std::move(mangoHud));
1201 }
1202
1203 // Gamescope suggestion
1204 if (caps.tools.gamescope)
1205 {
1206 GameSuggestion gamescope;
1209 gamescope.title = "Gamescope Available";
1210 gamescope.description =
1211 "Gamescope compositor available for HDR, FSR, and resolution scaling";
1212 gamescope.reason = "Gamescope is installed on this system";
1213 gamescope.source = "System Detection";
1214 gamescope.canAutoApply = false;
1215 suggestions.suggestions.push_back(std::move(gamescope));
1216 }
1217
1218 // CPU Governor suggestion
1219 if (!caps.cpu.hasOptimalGovernor())
1220 {
1221 GameSuggestion govSuggestion;
1224 govSuggestion.title = "CPU Governor Optimization";
1225 govSuggestion.description =
1226 "Current governor '" + caps.cpu.governor +
1227 "' may not be optimal for gaming. Consider using 'performance' or 'schedutil'.";
1228 govSuggestion.reason = "Non-optimal CPU governor can cause frame drops";
1229 govSuggestion.source = "System Detection";
1230 govSuggestion.canAutoApply = false; // Requires system-level change
1231 suggestions.suggestions.push_back(std::move(govSuggestion));
1232 }
1233
1234 // Scheduler info for CachyOS
1235 if (caps.cpu.scheduler == CPUScheduler::BORE)
1236 {
1237 GameSuggestion schedInfo;
1240 schedInfo.title = "BORE Scheduler";
1241 schedInfo.description = "You're using the BORE scheduler which is optimized for gaming and "
1242 "desktop responsiveness";
1243 schedInfo.reason = "CachyOS BORE scheduler detected";
1244 schedInfo.source = "System Detection";
1245 schedInfo.canAutoApply = false;
1246 suggestions.suggestions.push_back(std::move(schedInfo));
1247 }
1248}
1249
1250void GameSuggestionService::addGPUSuggestions(GameSuggestions& suggestions)
1251{
1252 const auto& caps = effectiveCapabilities();
1253
1254 if (caps.hasAMDGPU())
1255 {
1256 // Check for TeraScale GPUs (no Vulkan support)
1257 if (caps.gpu.isTeraScale())
1258 {
1259 GameSuggestion noVulkan;
1262 noVulkan.title = "No Vulkan Support";
1263 noVulkan.description =
1264 "TeraScale GPU detected (HD 2000-6000 series) - Vulkan is not supported";
1265 noVulkan.reason =
1266 "Proton and DXVK require Vulkan. Consider Wine + wined3d for OpenGL games";
1267 noVulkan.source = "System Detection";
1268 noVulkan.canAutoApply = false;
1269 suggestions.suggestions.push_back(std::move(noVulkan));
1270
1271 // Suggest wined3d for TeraScale
1272 GameSuggestion useWined3d;
1275 useWined3d.title = "Use WineD3D (OpenGL)";
1276 useWined3d.description = "Use WineD3D OpenGL backend instead of DXVK";
1277 useWined3d.reason = "WineD3D works on GPUs without Vulkan support";
1278 useWined3d.envKey = "PROTON_USE_WINED3D";
1279 useWined3d.envValue = "1";
1280 useWined3d.source = "System Detection";
1281 useWined3d.canAutoApply = false; // Major compatibility change
1282 suggestions.suggestions.push_back(std::move(useWined3d));
1283
1284 return; // Skip modern GPU suggestions for TeraScale
1285 }
1286
1287 // Check for pre-Polaris GCN GPUs (limited Vulkan)
1288 if (!caps.gpu.isPolarisOrNewer() && caps.gpu.isGCNArchitecture())
1289 {
1290 GameSuggestion gcnWarning;
1293 gcnWarning.title = "Pre-Polaris GCN GPU";
1294 gcnWarning.description = "GCN 1-4 GPU detected - some newer games may have issues";
1295 gcnWarning.reason = "Older GCN GPUs have limited Vulkan feature support";
1296 gcnWarning.source = "System Detection";
1297 gcnWarning.canAutoApply = false;
1298 suggestions.suggestions.push_back(std::move(gcnWarning));
1299
1300 // Recommend ACO compiler for older GCN
1301 GameSuggestion acoCompiler;
1304 acoCompiler.title = "ACO Shader Compiler";
1305 acoCompiler.description = "Use ACO compiler for better shader compilation on GCN";
1306 acoCompiler.reason = "ACO is faster and has better GCN support than LLVM";
1307 acoCompiler.envKey = "AMD_VULKAN_ICD";
1308 acoCompiler.envValue = "RADV";
1309 acoCompiler.source = "Mesa";
1310 acoCompiler.canAutoApply = true;
1311 suggestions.suggestions.push_back(std::move(acoCompiler));
1312 }
1313
1314 // AMD Anti-Lag (Mesa layer) - only for Polaris+
1315 if (caps.gpu.isPolarisOrNewer())
1316 {
1317 GameSuggestion antiLag;
1320 antiLag.title = "AMD Anti-Lag";
1321 antiLag.description = "Enable AMD Anti-Lag via Mesa layer for reduced input latency";
1322 antiLag.reason = "Detected AMD GPU";
1323 antiLag.envKey = "ENABLE_LAYER_MESA_ANTI_LAG";
1324 antiLag.envValue = "1";
1325 antiLag.source = "CachyOS Wiki";
1326 antiLag.canAutoApply = true;
1327 suggestions.suggestions.push_back(std::move(antiLag));
1328
1329 // Note: RADV_PERFTEST=gpl removed - GPL is default in Mesa 24.0+
1330 }
1331
1332 // FSR suggestion (works on all GCN+ GPUs via Wine)
1333 if (caps.gpu.isGCNArchitecture())
1334 {
1335 GameSuggestion fsr;
1338 fsr.title = "Wine FSR Upscaling";
1339 fsr.description = "Enable FidelityFX Super Resolution for better performance";
1340 fsr.reason = "Detected AMD GPU with Vulkan/FSR support";
1341 fsr.envKey = "WINE_FULLSCREEN_FSR";
1342 fsr.envValue = "1";
1343 fsr.source = "CachyOS Wiki";
1344 fsr.canAutoApply = false; // User preference
1345 suggestions.suggestions.push_back(std::move(fsr));
1346 }
1347
1348 // FSR4 ML Frame Gen (proton-cachyos 10.0+ and GE-Proton 10.x+).
1349 // Native on RDNA4; RDNA3 can opt into a compatible DLL via RDNA3_UPGRADE.
1350 // Gated on CachyOS detection because PROTON_FSR4_* is not in stock Valve Proton.
1351 if (caps.gpu.supportsFSR4 && caps.isCachyOS())
1352 {
1353 GameSuggestion fsr4;
1356 fsr4.title = "FSR 4 Auto-Upgrade";
1357 fsr4.description = "Upgrade in-game FSR to FSR 4 ML upscaling (native on RDNA4)";
1358 fsr4.reason = "RDNA4 GPU with proton-cachyos available";
1359 fsr4.envKey = "PROTON_FSR4_UPGRADE";
1360 fsr4.envValue = "1";
1361 fsr4.source = "proton-cachyos";
1362 fsr4.canAutoApply = true;
1363 suggestions.suggestions.push_back(std::move(fsr4));
1364 }
1365 else if (caps.gpu.supportsFSR4RDNA3 && !caps.gpu.supportsFSR4 && caps.isCachyOS())
1366 {
1367 GameSuggestion fsr4r3;
1370 fsr4r3.title = "FSR 4 on RDNA 3 (opt-in)";
1371 fsr4r3.description =
1372 "Use the RDNA3-optimised FSR 4 DLL in proton-cachyos. "
1373 "ML Frame-Gen auto-enables once amdxcffx64.dll >= 4.0.3 is cached.";
1374 fsr4r3.reason = "RDNA3 GPU with proton-cachyos available";
1375 fsr4r3.envKey = "PROTON_FSR4_RDNA3_UPGRADE";
1376 fsr4r3.envValue = "1";
1377 fsr4r3.source = "proton-cachyos";
1378 fsr4r3.canAutoApply = false; // per-title choice; can regress visuals
1379 suggestions.suggestions.push_back(std::move(fsr4r3));
1380 }
1381 }
1382 else if (caps.hasNVIDIAGPU())
1383 {
1384 // NVAPI support for all NVIDIA GPUs
1385 GameSuggestion nvapi;
1388 nvapi.title = "NVIDIA NVAPI";
1389 nvapi.description = "Enable NVAPI for DLSS/Reflex support";
1390 nvapi.reason = "Detected NVIDIA GPU";
1391 nvapi.envKey = "PROTON_FORCE_NVAPI";
1392 nvapi.envValue = "1";
1393 nvapi.source = "CachyOS Wiki";
1394 nvapi.canAutoApply = true;
1395 suggestions.suggestions.push_back(std::move(nvapi));
1396
1397 // RTX-specific: DLSS auto-upgrade
1398 if (caps.hasRTXCapable())
1399 {
1400 GameSuggestion dlss;
1403 dlss.title = "DLSS Auto-Upgrade";
1404 dlss.description = "Automatically upgrade DLSS to the latest version in games";
1405 dlss.reason = "RTX GPU detected - supports DLSS";
1406 dlss.envKey = "PROTON_DLSS_UPGRADE";
1407 dlss.envValue = "1";
1408 dlss.source = "CachyOS Wiki";
1409 dlss.canAutoApply = true;
1410 suggestions.suggestions.push_back(std::move(dlss));
1411 }
1412
1413 // Ada Lovelace specific: DLSS 3 Frame Gen
1414 if (caps.gpu.generation == GPUGeneration::NVIDIA_Ada)
1415 {
1416 GameSuggestion dlss3;
1419 dlss3.title = "DLSS 3 Frame Generation";
1420 dlss3.description = "RTX 40 series GPU detected - DLSS 3 Frame Gen supported";
1421 dlss3.reason = "Ada Lovelace GPU supports DLSS 3 Frame Generation";
1422 dlss3.source = "System Detection";
1423 dlss3.canAutoApply = false;
1424 suggestions.suggestions.push_back(dlss3);
1425 }
1426
1427 // NVIDIA libs for PhysX/CUDA games
1428 GameSuggestion nvLibs;
1431 nvLibs.title = "NVIDIA PhysX/CUDA";
1432 nvLibs.description = "Enable PhysX and CUDA support for compatible games";
1433 nvLibs.reason = "Enables GPU-accelerated physics and compute";
1434 nvLibs.envKey = "PROTON_NVIDIA_LIBS";
1435 nvLibs.envValue = "1";
1436 nvLibs.source = "CachyOS Wiki";
1437 nvLibs.canAutoApply = false; // Only needed for specific games
1438 suggestions.suggestions.push_back(std::move(nvLibs));
1439 }
1440 else if (caps.hasIntelGPU())
1441 {
1442 // Intel Arc specific: XeSS auto-upgrade
1443 if (caps.hasArcGPU())
1444 {
1445 GameSuggestion xess;
1448 xess.title = "XeSS Auto-Upgrade";
1449 xess.description = "Automatically upgrade Intel XeSS to the latest version";
1450 xess.reason = "Intel Arc GPU detected - supports XeSS";
1451 xess.envKey = "PROTON_XESS_UPGRADE";
1452 xess.envValue = "1";
1453 xess.source = "CachyOS Wiki";
1454 xess.canAutoApply = true;
1455 suggestions.suggestions.push_back(std::move(xess));
1456 }
1457 }
1458
1459 // FSR via Wine works on all GPUs
1460 if (!caps.hasAMDGPU())
1461 {
1462 GameSuggestion fsr;
1465 fsr.title = "Wine FSR Upscaling";
1466 fsr.description = "Enable AMD FSR upscaling (works on all GPUs)";
1467 fsr.reason = "FSR is vendor-agnostic and works on all Vulkan GPUs";
1468 fsr.envKey = "WINE_FULLSCREEN_FSR";
1469 fsr.envValue = "1";
1470 fsr.source = "System Detection";
1471 fsr.canAutoApply = false;
1472 suggestions.suggestions.push_back(std::move(fsr));
1473 }
1474}
1475
1476void GameSuggestionService::addSyncSuggestions(GameSuggestions& suggestions)
1477{
1478 const auto& caps = effectiveCapabilities();
1479
1480 // NTSync suggestion (best performance if available)
1481 if (caps.canUseNTSync())
1482 {
1483 GameSuggestion ntsync;
1486 ntsync.title = "NTSync Enabled";
1487 ntsync.description = "NTSync is available for best synchronization performance";
1488 ntsync.reason = "Kernel " + caps.kernel.version + " has NTSync support";
1489 ntsync.envKey = "PROTON_USE_NTSYNC";
1490 ntsync.envValue = "1";
1491 ntsync.source = "CachyOS Wiki";
1492 ntsync.canAutoApply = true;
1493 suggestions.suggestions.push_back(std::move(ntsync));
1494 }
1495 else if (caps.kernel.supportsNTSync && !caps.kernel.ntsyncModuleLoaded)
1496 {
1497 // Kernel supports it but module not loaded
1498 GameSuggestion ntsyncHint;
1501 ntsyncHint.title = "NTSync Available (needs modprobe)";
1502 ntsyncHint.description =
1503 "NTSync module available but not loaded. Run: sudo modprobe ntsync";
1504 ntsyncHint.reason = "NTSync provides better performance than fsync/esync";
1505 ntsyncHint.source = "System Detection";
1506 ntsyncHint.canAutoApply = false;
1507 suggestions.suggestions.push_back(std::move(ntsyncHint));
1508 }
1509
1510 // Fsync suggestion (second best)
1511 if (caps.canUseFsync() && !caps.canUseNTSync())
1512 {
1513 GameSuggestion fsync;
1516 fsync.title = "Fsync Enabled";
1517 fsync.description = "Fsync is available for improved synchronization";
1518 fsync.reason = "Kernel " + caps.kernel.version + " supports fsync";
1519 fsync.source = "System Detection";
1520 fsync.canAutoApply = true; // Auto-enabled by Proton
1521 suggestions.suggestions.push_back(std::move(fsync));
1522 }
1523 else if (caps.canUseNTSync())
1524 {
1525 // Informational: fsync available but NTSync is better
1526 GameSuggestion fsyncInfo;
1529 fsyncInfo.title = "Fsync Available";
1530 fsyncInfo.description = "Fsync is available as fallback (NTSync is preferred)";
1531 fsyncInfo.reason = "Kernel supports both NTSync and fsync";
1532 fsyncInfo.source = "System Detection";
1533 fsyncInfo.canAutoApply = false;
1534 suggestions.suggestions.push_back(std::move(fsyncInfo));
1535 }
1536}
1537
1538void GameSuggestionService::addShaderCacheSuggestions(GameSuggestions& suggestions)
1539{
1540 const auto& caps = effectiveCapabilities();
1541
1542 // Per-game shader cache
1543 GameSuggestion localCache;
1546 localCache.title = "Local Shader Cache";
1547 localCache.description = "Enable per-game shader cache for faster subsequent loads";
1548 localCache.reason = "Reduces shader compilation stutter on repeated plays";
1549 localCache.envKey = "__GL_SHADER_DISK_CACHE";
1550 localCache.envValue = "1";
1551 localCache.source = "CachyOS Wiki";
1552 localCache.canAutoApply = true;
1553 suggestions.suggestions.push_back(std::move(localCache));
1554
1555 // GPU-specific shader cache size recommendations
1556 uint64_t cacheSize = caps.getRecommendedShaderCacheSize();
1557 std::string cacheSizeStr = std::to_string(cacheSize);
1558
1559 if (caps.hasNVIDIAGPU())
1560 {
1561 GameSuggestion nvCache;
1564 nvCache.title = "NVIDIA Shader Cache Size";
1565 nvCache.description = "Set NVIDIA shader disk cache to " +
1566 std::to_string(cacheSize / (1024 * 1024 * 1024)) + "GB";
1567 nvCache.reason = "Larger cache reduces shader recompilation";
1568 nvCache.envKey = "__GL_SHADER_DISK_CACHE_SIZE";
1569 nvCache.envValue = cacheSizeStr;
1570 nvCache.source = "CachyOS Wiki";
1571 nvCache.canAutoApply = true;
1572 suggestions.suggestions.push_back(std::move(nvCache));
1573 }
1574 else if (caps.hasAMDGPU() || caps.hasIntelGPU())
1575 {
1576 // Mesa shader cache for AMD/Intel
1577 std::string mesaCacheSize = std::to_string(cacheSize / (1024 * 1024 * 1024)) + "G";
1578 GameSuggestion mesaCache;
1581 mesaCache.title = "Mesa Shader Cache Size";
1582 mesaCache.description = "Set Mesa shader cache to " + mesaCacheSize;
1583 mesaCache.reason = "Larger cache reduces shader recompilation";
1584 mesaCache.envKey = "MESA_SHADER_CACHE_MAX_SIZE";
1585 mesaCache.envValue = mesaCacheSize;
1586 mesaCache.source = "CachyOS Wiki";
1587 mesaCache.canAutoApply = true;
1588 suggestions.suggestions.push_back(std::move(mesaCache));
1589 }
1590}
1591
1592void GameSuggestionService::addKernelParamSuggestions(GameSuggestions& suggestions)
1593{
1594 const auto& caps = effectiveCapabilities();
1595
1596 // Check vm.max_map_count
1597 if (!caps.kernel.maxMapCountOk)
1598 {
1599 GameSuggestion maxMap;
1602 maxMap.title = "Increase vm.max_map_count";
1603 maxMap.description = "Current value (" + std::to_string(caps.kernel.maxMapCount) +
1604 ") is too low. Some games may crash.";
1605 maxMap.reason = "Many games need higher memory map limits. Add to "
1606 "/etc/sysctl.d/gaming.conf: vm.max_map_count=2147483642";
1607 maxMap.source = "Arch Wiki Gaming";
1608 maxMap.canAutoApply = false; // Requires system config
1609 suggestions.suggestions.push_back(std::move(maxMap));
1610 }
1611
1612 // Check swappiness
1613 if (!caps.kernel.swappinessOk && caps.kernel.swappiness >= 0)
1614 {
1615 GameSuggestion swappiness;
1618 swappiness.title = "Reduce vm.swappiness";
1619 swappiness.description = "Current value (" + std::to_string(caps.kernel.swappiness) +
1620 ") may cause stutters. Recommended: 10 or lower.";
1621 swappiness.reason = "Lower swappiness reduces disk I/O during gaming";
1622 swappiness.source = "Arch Wiki Gaming";
1623 swappiness.canAutoApply = false; // Requires system config
1624 suggestions.suggestions.push_back(std::move(swappiness));
1625 }
1626
1627 // CPU topology suggestions for high-core-count AMD systems (Ryzen 9, Threadripper).
1628 // These CPUs have multiple CCDs (Core Complex Dies) with cross-CCD latency.
1629 // Derive the pinning string from the detected core count — 7950X ships with
1630 // 16 physical cores / 2 CCDs → 8 per CCD; 7900X: 12/2 → 6 per CCD;
1631 // Threadripper: 24+ cores → cap at 8 per group as a sensible first-CCD mask.
1632 if (caps.cpu.coreCount >= 12 && caps.cpu.vendor == "AMD")
1633 {
1634 const int physical = caps.cpu.coreCount;
1635 // SMT/hyper-threading means logical cores are 2× physical; we pin by
1636 // physical core index. Assume even-indexed logical cores are the
1637 // physical ones (Linux ordering on Ryzen). First CCD = first half.
1638 const int firstCcdCores = std::max(4, std::min(8, physical / 2));
1639 std::string cpuList;
1640 for (int i = 0; i < firstCcdCores; ++i)
1641 {
1642 if (!cpuList.empty())
1643 cpuList += ",";
1644 cpuList += std::to_string(i * 2); // physical cores at even indices
1645 }
1646 const std::string topologyValue = std::to_string(firstCcdCores) + ":" + cpuList;
1647
1648 GameSuggestion topology;
1651 topology.title = "CPU Topology Optimization";
1652 topology.description = "High-core AMD CPU detected. Some games may benefit from "
1653 "limiting cores to a single CCD to avoid cross-chiplet latency.";
1654 topology.reason = caps.cpu.model + " has " + std::to_string(physical) +
1655 " cores across multiple CCDs. Games that don't use many threads may "
1656 "perform better pinned to one CCD.";
1657 topology.envKey = "PROTON_CPU_TOPOLOGY";
1658 topology.envValue = topologyValue;
1659 topology.source = "CachyOS/AMD Gaming";
1660 topology.canAutoApply = false; // Game-specific, may hurt multi-threaded games
1661 suggestions.suggestions.push_back(std::move(topology));
1662 }
1663
1664 // Intel hybrid CPU (P-cores + E-cores) suggestion
1665 if (caps.cpu.isHybrid && caps.cpu.performanceCores > 0)
1666 {
1667 GameSuggestion hybridNote;
1670 hybridNote.title = "Intel Hybrid CPU";
1671 hybridNote.description = "Hybrid CPU detected with " +
1672 std::to_string(caps.cpu.performanceCores) + " P-cores and " +
1673 std::to_string(caps.cpu.efficiencyCores) +
1674 " E-cores. "
1675 "Some games may benefit from disabling E-cores.";
1676 hybridNote.reason = "Games not optimized for hybrid architectures may stutter when "
1677 "threads are scheduled on E-cores. CachyOS sched-ext helps with this.";
1678 hybridNote.source = "Intel Gaming";
1679 hybridNote.canAutoApply = false;
1680 suggestions.suggestions.push_back(std::move(hybridNote));
1681 }
1682
1683 // CPU governor suggestion
1684 if (!caps.cpu.isPerformanceGovernor() && !caps.cpu.hasOptimalGovernor())
1685 {
1686 GameSuggestion governor;
1689 governor.title = "CPU Governor: " + caps.cpu.governor;
1690 governor.description = "Your CPU is using '" + caps.cpu.governor +
1691 "' governor. Consider 'performance' or 'schedutil' for gaming.";
1692 governor.reason = "GameMode automatically sets performance governor while gaming";
1693 governor.source = "CachyOS Wiki";
1694 governor.canAutoApply = false; // System-level setting
1695 suggestions.suggestions.push_back(std::move(governor));
1696 }
1697}
1698
1699void GameSuggestionService::addDisplaySuggestions(GameSuggestions& suggestions)
1700{
1701 const auto& caps = effectiveCapabilities();
1702
1703 // Wayland-specific suggestions
1704 if (caps.isWayland())
1705 {
1706 GameSuggestion wayland;
1709 wayland.title = "Native Wayland Support";
1710 wayland.description = "Enable experimental native Wayland mode in Proton";
1711 wayland.reason = "Running on Wayland - native mode may improve latency";
1712 wayland.envKey = "PROTON_ENABLE_WAYLAND";
1713 wayland.envValue = "1";
1714 wayland.source = "CachyOS Wiki";
1715 wayland.canAutoApply = false; // Experimental
1716 suggestions.suggestions.push_back(std::move(wayland));
1717 }
1718
1719 // HDR suggestion based on monitor capability
1720 if (caps.hasHDRMonitor())
1721 {
1722 GameSuggestion hdr;
1725 hdr.title = "HDR Support";
1726 hdr.description = "Enable HDR output for supported games";
1727 hdr.reason = "HDR-capable monitor detected";
1728 hdr.envKey = "PROTON_ENABLE_HDR";
1729 hdr.envValue = "1";
1730 hdr.source = "System Detection";
1731 hdr.canAutoApply = false; // Game must support HDR
1732 suggestions.suggestions.push_back(std::move(hdr));
1733
1734 // DXVK HDR for games that need it
1735 GameSuggestion dxvkHdr;
1738 dxvkHdr.title = "DXVK HDR";
1739 dxvkHdr.description = "Enable DXVK HDR for DirectX games";
1740 dxvkHdr.reason = "May improve HDR output in some games";
1741 dxvkHdr.envKey = "DXVK_HDR";
1742 dxvkHdr.envValue = "1";
1743 dxvkHdr.source = "System Detection";
1744 dxvkHdr.canAutoApply = false;
1745 suggestions.suggestions.push_back(std::move(dxvkHdr));
1746 }
1747
1748 // VRR/FreeSync/G-Sync suggestion
1749 if (caps.hasVRRMonitor())
1750 {
1751 GameSuggestion vrr;
1754 vrr.title = "Variable Refresh Rate";
1755 vrr.description =
1756 "Your monitor supports VRR (FreeSync/G-Sync). Ensure it's enabled in your compositor.";
1757 vrr.reason = "VRR reduces screen tearing and stuttering";
1758 vrr.source = "System Detection";
1759 vrr.canAutoApply = false;
1760 suggestions.suggestions.push_back(std::move(vrr));
1761 }
1762
1763 // High refresh rate monitor - suggest uncapped FPS
1764 if (caps.hasHighRefreshMonitor())
1765 {
1766 const auto* primary = caps.getPrimaryMonitor();
1767 if (primary)
1768 {
1769 GameSuggestion highRefresh;
1772 highRefresh.title = "High Refresh Monitor";
1773 highRefresh.description = "Your monitor supports " +
1774 std::to_string(static_cast<int>(primary->refreshRate)) +
1775 "Hz. Disable V-Sync in-game for best responsiveness.";
1776 highRefresh.reason = "High refresh rate monitor detected";
1777 highRefresh.source = "System Detection";
1778 highRefresh.canAutoApply = false;
1779 suggestions.suggestions.push_back(std::move(highRefresh));
1780 }
1781 }
1782
1783 // 4K monitor - suggest FSR/DLSS
1784 const auto* primary = caps.getPrimaryMonitor();
1785 if (primary && primary->is4K())
1786 {
1787 GameSuggestion upscale;
1790 upscale.title = "4K Display - Consider Upscaling";
1791 upscale.description = "Running at 4K. Consider FSR/DLSS/XeSS for better performance.";
1792 upscale.reason = "4K native rendering is demanding";
1793 upscale.source = "System Detection";
1794 upscale.canAutoApply = false;
1795 suggestions.suggestions.push_back(std::move(upscale));
1796 }
1797
1798 // Window decoration suggestion
1799 GameSuggestion noDecor;
1802 noDecor.title = "Disable Window Decorations";
1803 noDecor.description = "Remove window decorations for borderless fullscreen";
1804 noDecor.reason = "May improve fullscreen behavior in some games";
1805 noDecor.envKey = "PROTON_NO_WM_DECORATION";
1806 noDecor.envValue = "1";
1807 noDecor.source = "CachyOS Wiki";
1808 noDecor.canAutoApply = false;
1809 suggestions.suggestions.push_back(std::move(noDecor));
1810}
1811
1812void GameSuggestionService::addMemorySuggestions(GameSuggestions& suggestions)
1813{
1814 const auto& caps = effectiveCapabilities();
1815 const auto& mem = caps.memory;
1816
1817 // Low RAM warning
1818 if (mem.totalMB < 8000)
1819 {
1820 GameSuggestion lowRam;
1823 lowRam.title = "Low System Memory";
1824 lowRam.description = "Your system has less than 8GB RAM (" +
1825 std::to_string(mem.totalMB / 1024) +
1826 "GB). Many modern games require 16GB+.";
1827 lowRam.reason = "Insufficient RAM can cause severe performance issues and crashes";
1828 lowRam.source = "System Detection";
1829 lowRam.canAutoApply = false;
1830 suggestions.suggestions.push_back(std::move(lowRam));
1831 }
1832 else if (mem.totalMB < 16000)
1833 {
1834 GameSuggestion medRam;
1837 medRam.title = "Memory Notice";
1838 medRam.description = "Your system has " + std::to_string(mem.totalMB / 1024) +
1839 "GB RAM. Some AAA games may benefit from 16GB+.";
1840 medRam.reason = "Newer AAA titles often recommend 16GB RAM";
1841 medRam.source = "System Detection";
1842 medRam.canAutoApply = false;
1843 suggestions.suggestions.push_back(std::move(medRam));
1844 }
1845
1846 // Low available memory warning (runtime)
1847 if (mem.availableMB < 4000 && mem.totalMB >= 8000)
1848 {
1849 GameSuggestion lowAvail;
1852 lowAvail.title = "Low Available Memory";
1853 lowAvail.description = "Only " + std::to_string(mem.availableMB / 1024) +
1854 "GB RAM currently available. Consider closing other applications.";
1855 lowAvail.reason = "Other applications are using significant memory";
1856 lowAvail.source = "System Detection";
1857 lowAvail.canAutoApply = false;
1858 suggestions.suggestions.push_back(std::move(lowAvail));
1859 }
1860
1861 // No swap warning
1862 if (mem.swapTotalMB == 0)
1863 {
1864 GameSuggestion noSwap;
1867 noSwap.title = "No Swap Space";
1868 noSwap.description =
1869 "No swap space configured. This may cause crashes if RAM is exhausted.";
1870 noSwap.reason = "Swap provides a safety net when RAM is full";
1871 noSwap.source = "System Detection";
1872 noSwap.canAutoApply = false;
1873 suggestions.suggestions.push_back(std::move(noSwap));
1874 }
1875}
1876
1877void GameSuggestionService::addPowerSuggestions(GameSuggestions& suggestions)
1878{
1879 const auto& caps = effectiveCapabilities();
1880 const auto& power = caps.power;
1881
1882 // Battery warning
1883 if (power.isLaptop && power.onBattery)
1884 {
1885 GameSuggestion batteryWarn;
1888 batteryWarn.title = "Running on Battery";
1889 batteryWarn.description = "You're running on battery power. Performance may be limited.";
1890 if (power.batteryPercent >= 0)
1891 {
1892 batteryWarn.description += " Battery: " + std::to_string(power.batteryPercent) + "%";
1893 }
1894 batteryWarn.reason = "Battery power limits CPU/GPU performance to conserve power";
1895 batteryWarn.source = "System Detection";
1896 batteryWarn.canAutoApply = false;
1897 suggestions.suggestions.push_back(std::move(batteryWarn));
1898 }
1899
1900 // Non-performance power profile on laptop
1901 if (power.isLaptop && power.profile != PowerProfile::Unknown &&
1902 power.profile != PowerProfile::Performance)
1903 {
1904 GameSuggestion powerProfile;
1907 powerProfile.title = "Power Profile";
1908 powerProfile.description =
1909 "Consider switching to 'performance' power profile for better gaming performance.";
1910 powerProfile.reason = "Current profile: " + power.activeProfile;
1911 powerProfile.source = "System Detection";
1912 powerProfile.canAutoApply = false; // Requires system-level change
1913 suggestions.suggestions.push_back(std::move(powerProfile));
1914 }
1915
1916 // Low battery warning
1917 if (power.isLaptop && power.onBattery && power.batteryPercent >= 0 && power.batteryPercent < 20)
1918 {
1919 GameSuggestion lowBattery;
1922 lowBattery.title = "Low Battery Warning";
1923 lowBattery.description = "Battery is at " + std::to_string(power.batteryPercent) +
1924 "%. Plug in to avoid losing progress!";
1925 lowBattery.reason = "Game may be interrupted if battery dies";
1926 lowBattery.source = "System Detection";
1927 lowBattery.canAutoApply = false;
1928 suggestions.suggestions.push_back(std::move(lowBattery));
1929 }
1930}
1931
1932void GameSuggestionService::addControllerSuggestions(GameSuggestions& suggestions)
1933{
1934 const auto& caps = effectiveCapabilities();
1935
1936 // No controller detected
1937 if (caps.controllers.empty())
1938 {
1939 // This is informational only, many games are fine with keyboard/mouse
1940 return;
1941 }
1942
1943 // PlayStation controller suggestion
1944 if (caps.hasPlayStationController())
1945 {
1946 GameSuggestion psSuggestion;
1948 psSuggestion.category = SuggestionCategory::Input;
1949 psSuggestion.title = "PlayStation Controller Detected";
1950 psSuggestion.description =
1951 "Enable SDL for better PlayStation controller support in some games";
1952 psSuggestion.reason = "PlayStation controllers may need SDL for proper button mapping";
1953 psSuggestion.envKey = "PROTON_PREFER_SDL";
1954 psSuggestion.envValue = "1";
1955 psSuggestion.source = "System Detection";
1956 psSuggestion.canAutoApply = false;
1957 suggestions.suggestions.push_back(std::move(psSuggestion));
1958 }
1959
1960 // Multiple controllers
1961 if (caps.controllers.size() > 1)
1962 {
1963 GameSuggestion multiController;
1965 multiController.category = SuggestionCategory::Input;
1966 multiController.title = "Multiple Controllers";
1967 multiController.description =
1968 std::to_string(caps.controllers.size()) +
1969 " controllers detected. Some games may have issues with multiple inputs.";
1970 multiController.reason = "Detected: " + caps.controllers[0].name + " and others";
1971 multiController.source = "System Detection";
1972 multiController.canAutoApply = false;
1973 suggestions.suggestions.push_back(std::move(multiController));
1974 }
1975
1976 // Xalia / controller-as-kbd-mouse shim. Default-on in Proton 10.0-2+;
1977 // breaks flight sims and rhythm games that expect raw controller input.
1978 // Not auto-applied — only surface as an informational hint.
1979 {
1980 GameSuggestion xaliaHint;
1983 xaliaHint.title = "Xalia controller-to-kbd/mouse (default on)";
1984 xaliaHint.description = "Proton 10.0-2+ auto-maps controllers to "
1985 "keyboard/mouse for games without controller "
1986 "support. Set PROTON_USE_XALIA=0 for flight "
1987 "sims or rhythm games that expect raw input.";
1988 xaliaHint.reason = "Proton default behaviour; reversible per-game";
1989 xaliaHint.envKey = "PROTON_USE_XALIA";
1990 xaliaHint.envValue = "0"; // value to set if the user wants to disable
1991 xaliaHint.source = "Proton 10.0-2 release notes";
1992 xaliaHint.canAutoApply = false;
1993 suggestions.suggestions.push_back(std::move(xaliaHint));
1994 }
1995}
1996
1997void GameSuggestionService::addAudioSuggestions(GameSuggestions& suggestions)
1998{
1999 // Audio back-end hints. Most users on CachyOS / modern Arch run PipeWire
2000 // (with pipewire-pulse for compat). When a pure PulseAudio server is
2001 // running instead, some games benefit from a larger latency setting.
2002 // We detect by checking for the active systemd user unit.
2003 const bool pipewireActive =
2004 std::system("systemctl --user is-active --quiet pipewire.service 2>/dev/null") == 0;
2005 const bool pulseActive =
2006 std::system("systemctl --user is-active --quiet pulseaudio.service 2>/dev/null") == 0;
2007
2008 if (pipewireActive)
2009 {
2010 GameSuggestion pipewireHint;
2012 pipewireHint.category = SuggestionCategory::Audio;
2013 pipewireHint.title = "PipeWire audio stack detected";
2014 pipewireHint.description = "Native PipeWire support via pipewire-pulse. "
2015 "No additional env vars needed for most games.";
2016 pipewireHint.reason = "pipewire.service is active";
2017 pipewireHint.source = "System Detection";
2018 pipewireHint.canAutoApply = false;
2019 suggestions.suggestions.push_back(std::move(pipewireHint));
2020 }
2021 else if (pulseActive)
2022 {
2023 // Pure PulseAudio: some titles benefit from a larger latency buffer
2024 // to avoid crackling under load. 60ms is the commonly-reported value.
2025 GameSuggestion pulseLatency;
2027 pulseLatency.category = SuggestionCategory::Audio;
2028 pulseLatency.title = "PulseAudio latency buffer";
2029 pulseLatency.description = "Increase PulseAudio latency to reduce audio "
2030 "crackling or stutter in demanding games.";
2031 pulseLatency.reason = "PulseAudio-only server detected";
2032 pulseLatency.envKey = "PULSE_LATENCY_MSEC";
2033 pulseLatency.envValue = "60";
2034 pulseLatency.source = "Arch Wiki - Gaming audio";
2035 pulseLatency.canAutoApply = false;
2036 suggestions.suggestions.push_back(std::move(pulseLatency));
2037 }
2038}
2039
2040void GameSuggestionService::addCachyOSSuggestions(GameSuggestions& suggestions)
2041{
2042 const auto& caps = effectiveCapabilities();
2043
2044 // game-performance wrapper
2045 if (caps.tools.gamePerformance)
2046 {
2047 GameSuggestion gamePerf;
2050 gamePerf.title = "CachyOS game-performance";
2051 gamePerf.description = "Use game-performance wrapper for optimal CPU scheduling";
2052 gamePerf.reason = "Running on CachyOS with game-performance available";
2053 gamePerf.source = "CachyOS";
2054 gamePerf.canAutoApply = false; // Requires enabling in game config
2055 suggestions.suggestions.push_back(std::move(gamePerf));
2056 }
2057
2058 // CachyOS kernel optimizations
2059 GameSuggestion kernelOpt;
2062 kernelOpt.title = "CachyOS Kernel";
2063 kernelOpt.description = "You're running the CachyOS kernel with gaming optimizations";
2064 kernelOpt.reason = "CachyOS kernel detected: " + caps.kernel.version;
2065 kernelOpt.source = "CachyOS";
2066 suggestions.suggestions.push_back(std::move(kernelOpt));
2067
2068 // Suggest CachyOS Proton if available
2069 for (const auto& runner : caps.runners)
2070 {
2071 if (runner.type == "proton-cachyos")
2072 {
2073 GameSuggestion cachyProton;
2076 cachyProton.title = "CachyOS Proton";
2077 cachyProton.description = "Use " + runner.name + " for best CachyOS integration";
2078 cachyProton.reason = "CachyOS Proton is optimized for this distro";
2079 cachyProton.recommendedRunner = runner.name;
2080 cachyProton.source = "CachyOS";
2081 cachyProton.canAutoApply = true;
2082 suggestions.suggestions.push_back(std::move(cachyProton));
2083 break;
2084 }
2085 }
2086}
2087
2088void GameSuggestionService::addBuiltinFixes(GameSuggestions& suggestions, int steamAppId,
2089 const std::string& gameName)
2090{
2091 // First try to load from JSON if not already attempted
2092 static bool loadAttempted = false;
2093 if (!loadAttempted)
2094 {
2095 loadAttempted = true; // set before load so recursive calls don't retry
2096 // Try multiple paths for the JSON file
2097 const char* homeEnv = std::getenv("HOME");
2098 const std::string homeStr = homeEnv ? homeEnv : "";
2099 std::vector<std::string> searchPaths = {
2100 "./data/game_fixes.json", // Development path
2101 "../data/game_fixes.json", // Alt development path
2102 "/usr/share/gamelauncher/game_fixes.json", // System install
2103 homeStr + "/.local/share/gamelauncher/game_fixes.json", // User install
2104 homeStr + "/.config/gamelauncher/game_fixes.json" // User config
2105 };
2106
2107 for (const auto& path : searchPaths)
2108 {
2109 if (loadFixesFromJSON(path))
2110 {
2111 Logger::info("Loaded game fixes from: {}", path);
2112 break;
2113 }
2114 }
2115 }
2116
2117 // Look up fixes by Steam App ID using hashmap for O(1) lookup
2118 if (hasLoadedExternalFixes_)
2119 {
2120 auto it = fixesByAppId_.find(steamAppId);
2121 if (it != fixesByAppId_.end())
2122 {
2123 Logger::debug("Applying JSON fixes for {} (AppID: {})", it->second->name, steamAppId);
2124 for (const auto& suggestion : it->second->suggestions)
2125 {
2126 suggestions.suggestions.push_back(suggestion);
2127 }
2128 return;
2129 }
2130 }
2131
2132 // No external fixes found — this is expected for games without known issues.
2133 // To add fixes for a game, edit data/game_fixes.json (no recompilation needed).
2134 (void)gameName;
2135}
2136
2138 SuggestionPriority applyLevel)
2139{
2140 Logger::info("Applying suggestions for: {} (level: {})", suggestions.gameName,
2141 priorityToString(applyLevel));
2142
2143 // Check for conflicts first
2144 auto conflicts = checkConflicts(suggestions);
2145 for (const auto& conflict : conflicts)
2146 {
2147 Logger::warn("Conflict detected: {}", conflict);
2148 }
2149
2150 int appliedCount = 0;
2151 int skippedCount = 0;
2152
2153 for (const auto& suggestion : suggestions.suggestions)
2154 {
2155 if (!suggestion.canAutoApply)
2156 {
2157 continue;
2158 }
2159
2160 if (static_cast<int>(suggestion.priority) > static_cast<int>(applyLevel))
2161 {
2162 continue;
2163 }
2164
2165 // Validate before applying
2166 std::string validationReason;
2167 if (!validateSuggestion(suggestion, validationReason))
2168 {
2169 Logger::warn("Skipping suggestion '{}': {}", suggestion.title, validationReason);
2170 skippedCount++;
2171 continue;
2172 }
2173
2174 // Apply environment variables
2175 if (!suggestion.envKey.empty() && !suggestion.envValue.empty())
2176 {
2177 game.runnerConfig.environmentVariables[suggestion.envKey] = suggestion.envValue;
2178 Logger::debug("Applied env var: {}={}", suggestion.envKey, suggestion.envValue);
2179 appliedCount++;
2180 }
2181
2182 // Apply runner recommendation (only if not already set).
2183 // Proton games must use protonVersion (the primary field read by
2184 // findProtonExecutable); Wine/other games use runnerVersion.
2185 if (!suggestion.recommendedRunner.empty())
2186 {
2187 if (game.runner == GameRunner::Proton && game.runnerConfig.protonVersion.empty())
2188 {
2189 game.runnerConfig.protonVersion = suggestion.recommendedRunner;
2190 Logger::debug("Applied Proton version: {}", suggestion.recommendedRunner);
2191 appliedCount++;
2192 }
2193 else if (game.runner != GameRunner::Proton && game.runnerConfig.runnerVersion.empty())
2194 {
2195 game.runnerConfig.runnerVersion = suggestion.recommendedRunner;
2196 Logger::debug("Applied runner: {}", suggestion.recommendedRunner);
2197 appliedCount++;
2198 }
2199 }
2200
2201 // Apply DLL overrides
2202 if (!suggestion.dllOverrides.empty())
2203 {
2204 if (game.runnerConfig.wineDLL.empty())
2205 {
2206 game.runnerConfig.wineDLL = suggestion.dllOverrides;
2207 }
2208 else
2209 {
2210 game.runnerConfig.wineDLL += ";" + suggestion.dllOverrides;
2211 }
2212 Logger::debug("Applied DLL overrides: {}", suggestion.dllOverrides);
2213 appliedCount++;
2214 }
2215
2216 // Apply launch arguments
2217 if (!suggestion.launchArgs.empty())
2218 {
2219 if (game.runnerConfig.arguments.empty())
2220 {
2221 game.runnerConfig.arguments = suggestion.launchArgs;
2222 }
2223 else
2224 {
2225 game.runnerConfig.arguments += " " + suggestion.launchArgs;
2226 }
2227 Logger::debug("Applied launch args: {}", suggestion.launchArgs);
2228 appliedCount++;
2229 }
2230 }
2231
2232 Logger::info("Applied {} suggestions, skipped {} (validation failed)", appliedCount,
2233 skippedCount);
2234 return appliedCount;
2235}
2236
2237// ==============================================================================
2238// Validation Methods
2239// ==============================================================================
2240
2242 std::string& reason)
2243{
2244 // Validate runner availability
2245 if (!suggestion.recommendedRunner.empty())
2246 {
2247 if (!isRunnerAvailable(suggestion.recommendedRunner))
2248 {
2249 reason =
2250 "Runner '" + suggestion.recommendedRunner + "' is not installed on this system";
2251 return false;
2252 }
2253 }
2254
2255 // Validate environment variable keys (must be valid shell variable names)
2256 if (!suggestion.envKey.empty())
2257 {
2258 // Check for valid environment variable name
2259 const std::string& key = suggestion.envKey;
2260 if (key.empty() || (!std::isalpha(static_cast<unsigned char>(key[0])) && key[0] != '_'))
2261 {
2262 reason = "Invalid environment variable name: " + key;
2263 return false;
2264 }
2265
2266 for (char c : key)
2267 {
2268 if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_')
2269 {
2270 reason = "Invalid character in environment variable name: " + key;
2271 return false;
2272 }
2273 }
2274
2275 // Check for potentially dangerous values (shell injection)
2276 const std::string& value = suggestion.envValue;
2277 if (value.find('`') != std::string::npos || value.find("$(") != std::string::npos ||
2278 value.find("${") != std::string::npos)
2279 {
2280 reason = "Environment variable value contains potentially unsafe characters";
2281 return false;
2282 }
2283 }
2284
2285 // Validate GPU-specific suggestions match system GPU
2286 const auto& caps = effectiveCapabilities();
2287
2288 // Don't apply NVIDIA settings on non-NVIDIA systems
2289 if (suggestion.envKey.find("DLSS") != std::string::npos ||
2290 suggestion.envKey.find("NVIDIA") != std::string::npos ||
2291 suggestion.envKey.find("NV_") != std::string::npos)
2292 {
2293 if (caps.gpu.vendor != GPUVendor::NVIDIA)
2294 {
2295 reason = "NVIDIA-specific setting on non-NVIDIA system (detected: " +
2296 effectiveGPUVendorName() + ")";
2297 return false;
2298 }
2299 }
2300
2301 // Don't apply AMD FSR4 settings on non-AMD systems
2302 if (suggestion.envKey.find("FSR4") != std::string::npos)
2303 {
2304 if (caps.gpu.vendor != GPUVendor::AMD)
2305 {
2306 reason = "AMD FSR4-specific setting on non-AMD system (detected: " +
2307 effectiveGPUVendorName() + ")";
2308 return false;
2309 }
2310 // PROTON_FSR4_RDNA3_UPGRADE requires RDNA3; PROTON_FSR4_UPGRADE benefits
2311 // from native RDNA4 but works on RDNA3 too (auto-path through RDNA3 DLL).
2312 const bool isRdna3UpgradeKey = (suggestion.envKey == "PROTON_FSR4_RDNA3_UPGRADE");
2313 if (isRdna3UpgradeKey && !caps.gpu.supportsFSR4RDNA3)
2314 {
2315 reason = "PROTON_FSR4_RDNA3_UPGRADE requires RDNA3 or newer GPU";
2316 return false;
2317 }
2318 if (!isRdna3UpgradeKey && !caps.gpu.supportsFSR4 && !caps.gpu.supportsFSR4RDNA3)
2319 {
2320 reason = "FSR4 requires RDNA3 or newer GPU";
2321 return false;
2322 }
2323 }
2324
2325 // Don't apply Intel XeSS settings on non-Intel systems
2326 if (suggestion.envKey.find("XESS") != std::string::npos)
2327 {
2328 if (caps.gpu.vendor != GPUVendor::Intel)
2329 {
2330 reason = "Intel XeSS-specific setting on non-Intel system (detected: " +
2331 effectiveGPUVendorName() + ")";
2332 return false;
2333 }
2334 }
2335
2336 return true;
2337}
2338
2339bool GameSuggestionService::isRunnerAvailable(const std::string& runnerName)
2340{
2341 const auto& runners = effectiveCapabilities().runners;
2342
2343 // Convert runner name to lowercase for comparison
2344 std::string runnerLower = runnerName;
2345 std::transform(runnerLower.begin(), runnerLower.end(), runnerLower.begin(),
2346 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
2347
2348 for (const auto& runner : runners)
2349 {
2350 std::string installedLower = runner.name;
2351 std::transform(installedLower.begin(), installedLower.end(), installedLower.begin(),
2352 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
2353
2354 // Exact match
2355 if (installedLower == runnerLower)
2356 {
2357 Logger::debug("Runner '{}' found (exact match)", runnerName);
2358 return true;
2359 }
2360
2361 // Partial match - installed runner contains the recommended name
2362 if (installedLower.find(runnerLower) != std::string::npos)
2363 {
2364 Logger::debug("Runner '{}' found (partial match: {})", runnerName, runner.name);
2365 return true;
2366 }
2367
2368 // Check if recommended runner is a prefix/base of installed
2369 // e.g., "GE-Proton" matches "GE-Proton9-20"
2370 if (runnerLower.find("ge-proton") != std::string::npos &&
2371 installedLower.find("ge-proton") != std::string::npos)
2372 {
2373 Logger::debug("Runner '{}' found (GE-Proton family match: {})", runnerName,
2374 runner.name);
2375 return true;
2376 }
2377
2378 // Handle "Proton" vs "proton-" naming variations
2379 if (runnerLower.find("proton") != std::string::npos &&
2380 installedLower.find("proton") != std::string::npos)
2381 {
2382 // Extract version numbers for comparison
2383 std::regex versionRegex(R"(proton[- ]?(\d+)\.?(\d*))", std::regex::icase);
2384 std::smatch runnerMatch, installedMatch;
2385
2386 if (std::regex_search(runnerName, runnerMatch, versionRegex) &&
2387 std::regex_search(runner.name, installedMatch, versionRegex))
2388 {
2389 // Compare major versions. Guard std::stoi: the regex captures
2390 // digits, but a version number larger than INT_MAX throws
2391 // std::out_of_range, which was previously uncaught here.
2392 try
2393 {
2394 int runnerMajor = std::stoi(runnerMatch[1].str());
2395 int installedMajor = std::stoi(installedMatch[1].str());
2396
2397 if (installedMajor >= runnerMajor)
2398 {
2399 Logger::debug("Runner '{}' satisfied by newer version: {}", runnerName,
2400 runner.name);
2401 return true;
2402 }
2403 }
2404 catch (const std::exception&)
2405 {
2406 // Unparseable/overflowing version number — not a match.
2407 }
2408 }
2409 }
2410 }
2411
2412 // If no runners are detected, allow any runner (detection might have failed)
2413 if (runners.empty())
2414 {
2416 "No runners detected on system, allowing runner '{}' (detection may have failed)",
2417 runnerName);
2418 return true;
2419 }
2420
2421 Logger::debug("Runner '{}' not found among {} detected runners", runnerName, runners.size());
2422 return false;
2423}
2424
2425std::vector<std::string> GameSuggestionService::checkConflicts(const GameSuggestions& suggestions)
2426{
2427 std::vector<std::string> conflicts;
2428
2429 // Build a map of environment variables being set
2430 std::map<std::string, std::string> envVars;
2431 for (const auto& s : suggestions.suggestions)
2432 {
2433 if (!s.envKey.empty() && s.canAutoApply)
2434 {
2435 envVars[s.envKey] = s.envValue;
2436 }
2437 }
2438
2439 // Check for known conflicts
2440 // WINED3D conflicts with DXVK
2441 if (envVars.count("PROTON_USE_WINED3D") && envVars.count("DXVK_ASYNC"))
2442 {
2443 conflicts.push_back("PROTON_USE_WINED3D conflicts with DXVK_ASYNC (WINED3D disables DXVK)");
2444 }
2445
2446 // FSR and DLSS upgrades should not both be enabled
2447 if (envVars.count("PROTON_FSR4_UPGRADE") && envVars.count("PROTON_DLSS_UPGRADE"))
2448 {
2449 conflicts.push_back("Both FSR4 and DLSS upgrades enabled - only one should be active");
2450 }
2451
2452 // Native FSR with DLSS upgrade is redundant
2453 if (envVars.count("WINE_FULLSCREEN_FSR") && envVars.count("PROTON_DLSS_UPGRADE"))
2454 {
2455 conflicts.push_back("WINE_FULLSCREEN_FSR with DLSS upgrade is redundant - DLSS upgrade "
2456 "should be sufficient");
2457 }
2458
2459 // Esync and Fsync together - Fsync supersedes Esync
2460 if (envVars.count("PROTON_NO_ESYNC") && envVars.count("PROTON_NO_FSYNC"))
2461 {
2462 if (envVars["PROTON_NO_ESYNC"] == "0" && envVars["PROTON_NO_FSYNC"] == "0")
2463 {
2464 conflicts.push_back(
2465 "Both Esync and Fsync enabled - Fsync is preferred and supersedes Esync");
2466 }
2467 }
2468
2469 // HDR with certain compatibility modes
2470 if (envVars.count("DXVK_HDR") && envVars.count("PROTON_USE_WINED3D"))
2471 {
2472 conflicts.push_back("DXVK_HDR incompatible with WINED3D (HDR requires DXVK)");
2473 }
2474
2475 // Check GPU-specific conflicts
2476 const auto& caps = effectiveCapabilities();
2477
2478 if (caps.gpu.vendor == GPUVendor::AMD)
2479 {
2480 if (envVars.count("PROTON_DLSS_UPGRADE"))
2481 {
2482 conflicts.push_back("DLSS upgrade set but AMD GPU detected - should use FSR instead");
2483 }
2484 if (envVars.count("PROTON_ENABLE_XESS"))
2485 {
2486 conflicts.push_back("XeSS set but AMD GPU detected - should use FSR instead");
2487 }
2488 }
2489 else if (caps.gpu.vendor == GPUVendor::NVIDIA)
2490 {
2491 if (envVars.count("PROTON_FSR4_UPGRADE"))
2492 {
2493 conflicts.push_back(
2494 "FSR4 upgrade set but NVIDIA GPU detected - should use DLSS instead");
2495 }
2496 }
2497 else if (caps.gpu.vendor == GPUVendor::Intel)
2498 {
2499 if (envVars.count("PROTON_DLSS_UPGRADE"))
2500 {
2501 conflicts.push_back(
2502 "DLSS upgrade set but Intel GPU detected - should use XeSS instead");
2503 }
2504 if (envVars.count("PROTON_FSR4_UPGRADE"))
2505 {
2506 conflicts.push_back(
2507 "FSR4 upgrade set but Intel GPU detected - should use XeSS instead");
2508 }
2509 }
2510
2511 return conflicts;
2512}
2513
2515{
2516 switch (priority)
2517 {
2519 return "Critical";
2521 return "Recommended";
2523 return "Optional";
2525 return "Info";
2526 default:
2527 return "Unknown";
2528 }
2529}
2530
2532{
2533 switch (category)
2534 {
2536 return "Runner";
2538 return "Environment";
2540 return "Performance";
2542 return "Compatibility";
2544 return "Graphics";
2546 return "Audio";
2548 return "Input";
2550 return "General";
2551 default:
2552 return "Unknown";
2553 }
2554}
2555
2556void GameSuggestionService::initBuiltinFixes()
2557{
2558 // This could load from a JSON/TOML file in the future
2559 // For now, fixes are hardcoded in addBuiltinFixes()
2560}
2561
2562// ==============================================================================
2563// GE-Proton Version Checking
2564// ==============================================================================
2565
2566// Static member definitions. The time_point default ctor is noexcept,
2567// but the clang-tidy heuristic doesn't model that and flags it; suppress.
2568std::string GameSuggestionService::cachedGEProtonVersion_;
2569// NOLINTNEXTLINE(bugprone-throwing-static-initialization)
2570std::chrono::steady_clock::time_point GameSuggestionService::geProtonCacheTime_;
2571bool GameSuggestionService::hasLoadedExternalFixes_ = false;
2572std::vector<GameSuggestionService::GameFixEntry> GameSuggestionService::loadedFixes_;
2573std::unordered_map<int, const GameSuggestionService::GameFixEntry*>
2574 GameSuggestionService::fixesByAppId_;
2575const SystemCapabilities* GameSuggestionService::capabilitiesOverride_ = nullptr;
2576
2577// ==============================================================================
2578// Test-only capabilities override
2579// ==============================================================================
2580
2582{
2583 capabilitiesOverride_ = caps;
2584}
2585
2586const SystemCapabilities& GameSuggestionService::effectiveCapabilities()
2587{
2588 if (capabilitiesOverride_)
2589 return *capabilitiesOverride_;
2591}
2592
2593std::string GameSuggestionService::effectiveGPUVendorName()
2594{
2595 if (capabilitiesOverride_)
2596 {
2597 switch (capabilitiesOverride_->gpu.vendor)
2598 {
2599 case GPUVendor::AMD:
2600 return "AMD";
2601 case GPUVendor::NVIDIA:
2602 return "NVIDIA";
2603 case GPUVendor::Intel:
2604 return "Intel";
2605 case GPUVendor::Unknown:
2606 default:
2607 return "Unknown";
2608 }
2609 }
2611}
2612
2613// ==============================================================================
2614// Local-only suggestions (no network)
2615// ==============================================================================
2616// Implements the header-declared getLocalSuggestions(). Previously this
2617// was a dangling declaration — anyone calling it would have hit a link
2618// error. Now it composes the same system + CachyOS + built-in-fixes
2619// pipeline that getSuggestions runs, minus the ProtonDB network fetch and
2620// minus the persistent suggestions cache.
2621
2623{
2624 GameSuggestions suggestions;
2625 suggestions.gameName = game.name;
2626 suggestions.steamAppId = game.metadata.steamAppId;
2627
2628 const auto& caps = effectiveCapabilities();
2629 suggestions.detectedGPU = effectiveGPUVendorName();
2630 suggestions.isCachyOS = caps.isCachyOS();
2631
2632 addSystemSuggestions(suggestions);
2633 if (suggestions.isCachyOS)
2634 addCachyOSSuggestions(suggestions);
2635 if (game.metadata.steamAppId > 0)
2636 addBuiltinFixes(suggestions, game.metadata.steamAppId, game.name);
2637
2638 return suggestions;
2639}
2640
2641// ==============================================================================
2642// JSON Game Fixes Loading
2643// ==============================================================================
2644
2645bool GameSuggestionService::loadFixesFromJSON(const std::string& jsonPath)
2646{
2647 // Read the JSON file
2648 std::ifstream file(jsonPath);
2649 if (!file.is_open())
2650 {
2651 Logger::debug("Could not open game fixes JSON: {}", jsonPath);
2652 return false;
2653 }
2654
2655 std::stringstream buffer;
2656 buffer << file.rdbuf();
2657 std::string jsonContent = buffer.str();
2658 file.close();
2659
2660 if (jsonContent.empty())
2661 {
2662 Logger::warn("Empty game fixes JSON file: {}", jsonPath);
2663 return false;
2664 }
2665
2666 // Simple JSON parsing (we're using basic string parsing like ProtonDBService)
2667 // Find "fixes" array
2668 size_t fixesStart = jsonContent.find("\"fixes\"");
2669 if (fixesStart == std::string::npos)
2670 {
2671 Logger::warn("No 'fixes' array found in JSON");
2672 return false;
2673 }
2674
2675 // Parse each fix entry - look for steamAppId entries
2676 loadedFixes_.clear();
2677
2678 // Find all steamAppId entries
2679 std::regex appIdRegex("\"steamAppId\"\\s*:\\s*(\\d+)");
2680 std::regex nameRegex("\"name\"\\s*:\\s*\"([^\"]+)\"");
2681 std::regex priorityRegex("\"priority\"\\s*:\\s*\"([^\"]+)\"");
2682 std::regex categoryRegex("\"category\"\\s*:\\s*\"([^\"]+)\"");
2683 std::regex titleRegex("\"title\"\\s*:\\s*\"([^\"]+)\"");
2684 std::regex descRegex("\"description\"\\s*:\\s*\"([^\"]+)\"");
2685 std::regex envKeyRegex("\"envKey\"\\s*:\\s*\"([^\"]+)\"");
2686 std::regex envValueRegex("\"envValue\"\\s*:\\s*\"([^\"]+)\"");
2687 std::regex launchArgsRegex("\"launchArgs\"\\s*:\\s*\"([^\"]+)\"");
2688 std::regex reasonRegex("\"reason\"\\s*:\\s*\"([^\"]+)\"");
2689 std::regex sourceRegex("\"source\"\\s*:\\s*\"([^\"]+)\"");
2690 std::regex autoApplyRegex("\"canAutoApply\"\\s*:\\s*(true|false)");
2691
2692 // Split by steamAppId to get each game block
2693 size_t pos = 0;
2694 while ((pos = jsonContent.find("\"steamAppId\"", pos)) != std::string::npos)
2695 {
2696 // Find the next steamAppId or end of fixes array
2697 size_t nextPos = jsonContent.find("\"steamAppId\"", pos + 12);
2698 size_t endPos = (nextPos != std::string::npos) ? nextPos : jsonContent.length();
2699 std::string gameBlock = jsonContent.substr(pos, endPos - pos);
2700
2701 GameFixEntry entry;
2702 std::smatch match;
2703
2704 // Extract steamAppId
2705 if (std::regex_search(gameBlock, match, appIdRegex))
2706 {
2707 entry.steamAppId = std::stoi(match[1].str());
2708 }
2709 else
2710 {
2711 pos = endPos;
2712 continue;
2713 }
2714
2715 // Extract name
2716 if (std::regex_search(gameBlock, match, nameRegex))
2717 {
2718 entry.name = match[1].str();
2719 }
2720
2721 // Find suggestions array for this game
2722 size_t suggestionsStart = gameBlock.find("\"suggestions\"");
2723 if (suggestionsStart != std::string::npos)
2724 {
2725 // Parse each suggestion in the array
2726 std::string suggestionsBlock = gameBlock.substr(suggestionsStart);
2727
2728 // Simple approach: find each { } block within suggestions
2729 size_t suggStart = 0;
2730 while ((suggStart = suggestionsBlock.find('{', suggStart)) != std::string::npos)
2731 {
2732 size_t suggEnd = suggestionsBlock.find('}', suggStart);
2733 if (suggEnd == std::string::npos)
2734 break;
2735
2736 std::string suggBlock = suggestionsBlock.substr(suggStart, suggEnd - suggStart + 1);
2737
2738 GameSuggestion suggestion;
2739
2740 // Extract priority
2741 if (std::regex_search(suggBlock, match, priorityRegex))
2742 {
2743 std::string p = match[1].str();
2744 if (p == "critical")
2746 else if (p == "recommended")
2748 else if (p == "optional")
2750 else
2752 }
2753
2754 // Extract category
2755 if (std::regex_search(suggBlock, match, categoryRegex))
2756 {
2757 std::string c = match[1].str();
2758 if (c == "compatibility")
2760 else if (c == "performance")
2762 else if (c == "graphics")
2764 else if (c == "input")
2766 else
2768 }
2769
2770 // Extract other fields
2771 if (std::regex_search(suggBlock, match, titleRegex))
2772 suggestion.title = match[1].str();
2773 if (std::regex_search(suggBlock, match, descRegex))
2774 suggestion.description = match[1].str();
2775 if (std::regex_search(suggBlock, match, envKeyRegex))
2776 suggestion.envKey = match[1].str();
2777 if (std::regex_search(suggBlock, match, envValueRegex))
2778 suggestion.envValue = match[1].str();
2779 if (std::regex_search(suggBlock, match, launchArgsRegex))
2780 suggestion.launchArgs = match[1].str();
2781 if (std::regex_search(suggBlock, match, reasonRegex))
2782 suggestion.reason = match[1].str();
2783 if (std::regex_search(suggBlock, match, sourceRegex))
2784 suggestion.source = match[1].str();
2785 if (std::regex_search(suggBlock, match, autoApplyRegex))
2786 suggestion.canAutoApply = (match[1].str() == "true");
2787
2788 if (!suggestion.title.empty())
2789 {
2790 entry.suggestions.push_back(suggestion);
2791 }
2792
2793 suggStart = suggEnd + 1;
2794 }
2795 }
2796
2797 if (!entry.suggestions.empty())
2798 {
2799 loadedFixes_.push_back(entry);
2800 Logger::debug("Loaded {} fixes for {} (AppID: {})", entry.suggestions.size(),
2801 entry.name, entry.steamAppId);
2802 }
2803
2804 pos = endPos;
2805 }
2806
2807 // Build O(1) lookup index by Steam App ID
2808 fixesByAppId_.clear();
2809 for (const auto& entry : loadedFixes_)
2810 {
2811 fixesByAppId_[entry.steamAppId] = &entry;
2812 }
2813
2814 hasLoadedExternalFixes_ = !loadedFixes_.empty();
2815 Logger::info("Loaded {} game fix entries from JSON ({} indexed)", loadedFixes_.size(),
2816 fixesByAppId_.size());
2817 return hasLoadedExternalFixes_;
2818}
2819
2820std::string GameSuggestionService::getLatestGEProtonVersion()
2821{
2822 // Cache for 1 hour to avoid hammering GitHub API
2823 auto now = std::chrono::steady_clock::now();
2824 auto cacheAge = std::chrono::duration_cast<std::chrono::minutes>(now - geProtonCacheTime_);
2825
2826 if (!cachedGEProtonVersion_.empty() && cacheAge.count() < 60)
2827 {
2828 return cachedGEProtonVersion_;
2829 }
2830
2831 // Fetch latest release from GitHub API
2832 static const std::string url =
2833 "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases/latest";
2834 std::string command = "curl -s -L --proto =https --connect-timeout 5 --max-time 10 " +
2835 ShellUtils::escapeArg(url) + " 2>/dev/null";
2836
2837 std::array<char, 4096> buffer;
2838 std::string result;
2839
2840 FILE* pipe = popen(command.c_str(), "r");
2841 if (!pipe)
2842 {
2843 Logger::warn("GE-Proton: Failed to execute curl command");
2844 return "";
2845 }
2846
2847 constexpr size_t kMaxGitHubResponse = 1u * 1024 * 1024; // 1 MB cap
2848 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
2849 {
2850 result += buffer.data();
2851 if (result.size() > kMaxGitHubResponse)
2852 break;
2853 }
2854
2855 int pcloseStatus = pclose(pipe);
2856 if (pcloseStatus == -1)
2857 {
2858 Logger::warn("GE-Proton: pclose failed: {}", strerror(errno));
2859 return "";
2860 }
2861 if (WIFEXITED(pcloseStatus) && WEXITSTATUS(pcloseStatus) != 0)
2862 {
2863 Logger::warn("GE-Proton: curl exited with code {}", WEXITSTATUS(pcloseStatus));
2864 return "";
2865 }
2866
2867 if (result.empty())
2868 {
2869 Logger::warn("GE-Proton: Empty response from GitHub API");
2870 return "";
2871 }
2872
2873 // Simple JSON parsing for "tag_name": "GE-ProtonX-Y"
2874 std::regex tagRegex("\"tag_name\"\\s*:\\s*\"([^\"]+)\"");
2875 std::smatch match;
2876 if (std::regex_search(result, match, tagRegex))
2877 {
2878 cachedGEProtonVersion_ = match[1].str();
2879 geProtonCacheTime_ = now;
2880 Logger::info("GE-Proton: Latest version is {}", cachedGEProtonVersion_);
2881 return cachedGEProtonVersion_;
2882 }
2883
2884 Logger::warn("GE-Proton: Could not parse tag_name from GitHub response");
2885 return "";
2886}
static GameSuggestions getLocalSuggestions(const Game &game)
Get local-only suggestions (no network requests).
static bool validateSuggestion(const GameSuggestion &suggestion, std::string &reason)
Validate a suggestion before applying.
static std::string categoryToString(SuggestionCategory category)
Get category as human-readable string.
static void setCapabilitiesOverrideForTesting(const SystemCapabilities *caps)
Override the SystemCapabilities consulted by suggestion generation.
static int applySuggestions(Game &game, const GameSuggestions &suggestions, SuggestionPriority applyLevel=SuggestionPriority::Recommended)
Apply suggestions to a game's runner config.
static bool isRunnerAvailable(const std::string &runnerName)
Check if a runner exists on the system.
static std::string priorityToString(SuggestionPriority priority)
Get priority as human-readable string.
static void getSuggestionsAsync(const Game &game, SuggestionsCallback callback)
Get suggestions asynchronously.
static GameSuggestions getSuggestions(const Game &game)
Get suggestions for a game.
std::function< void(const GameSuggestions &)> SuggestionsCallback
static std::vector< std::string > checkConflicts(const GameSuggestions &suggestions)
Check for conflicting environment variables.
Complete representation of a game in the library.
Definition game.h:767
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::string name
Display name shown in UI.
Definition game.h:774
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
Thread-safe LRU cache with optional TTL support.
Definition lru_cache.h:44
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 warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static SteamAppInfo getSteamAppInfo(int steamAppId)
Get Steam store information (native Linux, genres, DRM, etc.).
static LutrisGameInfo getLutrisInfo(int steamAppId)
Get Lutris game info and installers.
static ProtonDBGameInfo getGameInfo(int steamAppId)
Get game info by Steam App ID.
static SteamDeckInfo getSteamDeckInfo(int steamAppId)
Get Steam Deck compatibility status from Valve's testing.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
static SystemInfoService & instance()
Get singleton instance.
const SystemCapabilities & getCapabilities()
Get complete system capabilities.
std::string getGPUVendorName()
Get GPU vendor name as string.
@ Proton
Proton (Steam's Wine fork).
Definition game.h:84
static LRUCache< int, GameSuggestions > suggestionsCache_(SUGGESTIONS_CACHE_MAX_SIZE, SUGGESTIONS_CACHE_TTL_SECONDS)
static constexpr int SUGGESTIONS_CACHE_TTL_SECONDS
static constexpr size_t SUGGESTIONS_CACHE_MAX_SIZE
ConfidenceLevel
How confident we are that our recommendations will work.
SuggestionCategory
Category of the suggestion.
SuggestionPriority
Priority level for suggestions.
SuggestionPriority protonDbTierPriority(const std::string &tier)
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
std::string wineDLL
DLL overrides (e.g., "d3d11=native,builtin").
Definition game.h:169
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 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
A single setting recommendation.
SuggestionCategory category
SuggestionPriority priority
Collection of suggestions for a game.
std::vector< GameSuggestion > getByPriority(SuggestionPriority priority) const
std::string getCombinedDLLOverrides() const
std::string getRecommendedRunner() const
ConfidenceLevel getConfidenceLevel() const
std::vector< std::pair< std::string, std::string > > getEnvironmentVariables() const
std::vector< GameSuggestion > getByCategory(SuggestionCategory category) const
std::string getConfidenceSummary() const
std::vector< GameSuggestion > suggestions
std::string version
Complete system capabilities summary.