game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
protondb_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// protondb_service.cpp
4// ==============================================================================
5// ProtonDB API integration implementation
6// ==============================================================================
7
8#include "protondb_service.h"
9#include "logger.h"
10#include "lru_cache.h"
11#include "shell_utils.h"
12
13#include <algorithm>
14#include <cctype>
15#include <chrono>
16#include <cstring>
17#include <future>
18#include <iomanip>
19#include <memory>
20#include <regex>
21#include <sstream>
22
23// Use curl command-line for HTTP requests (avoids linking libcurl)
24#include <array>
25#include <cstdio>
26
27// ==============================================================================
28// Cache Configuration
29// ==============================================================================
30
31// Cache limits prevent unbounded memory growth
32static constexpr size_t PROTONDB_CACHE_MAX_SIZE = 500; // Max cached game info entries
33static constexpr int PROTONDB_CACHE_TTL_SECONDS = 1800; // 30 minutes TTL
34static constexpr size_t STEAM_DECK_CACHE_MAX_SIZE = 500;
35static constexpr int STEAM_DECK_CACHE_TTL_SECONDS = 3600; // 1 hour (less frequent updates)
36static constexpr size_t STEAM_APP_CACHE_MAX_SIZE = 1000;
37static constexpr int STEAM_APP_CACHE_TTL_SECONDS = 86400; // 24 hours (rarely changes)
38static constexpr size_t LUTRIS_CACHE_MAX_SIZE = 200;
39static constexpr int LUTRIS_CACHE_TTL_SECONDS = 3600; // 1 hour
40
41// ==============================================================================
42// Static Members - Using LRU Caches
43// ==============================================================================
44
45// Legacy cache for backwards compatibility (will be migrated)
46std::unordered_map<int, ProtonDBGameInfo> ProtonDBService::cache_;
47std::mutex ProtonDBService::cacheMutex_;
48
49// New LRU caches with TTL. Wrapped as Meyer's-singleton accessors because
50// LRUCache's allocating constructor is not noexcept; a file-scope static
51// instance would be bugprone-throwing-static-initialization /
52// CERT ERR58-CPP. Function-local statics initialise on first call,
53// thread-safe per [stmt.dcl]/4.
54namespace
55{
78
79// Return true if `response` contains a JSON member `"key": value` where the
80// integer value is exactly `value` — i.e. the digit that follows must not be
81// another digit. Plain substring matching (`response.find("\"id\":1")`) is
82// wrong: it also matches "id":10, "id":100, "id":19, so single-player games
83// were flagged as multiplayer / cloud-save capable. Tolerates the optional
84// space after the colon that some encoders emit.
85bool containsIntField(const std::string& response, const char* key, int value)
86{
87 const std::string num = std::to_string(value);
88 for (const char* sep : {"\":", "\": "})
89 {
90 const std::string base = std::string("\"") + key + sep + num;
91 size_t pos = response.find(base);
92 while (pos != std::string::npos)
93 {
94 const size_t after = pos + base.size();
95 if (after >= response.size() ||
96 !std::isdigit(static_cast<unsigned char>(response[after])))
97 return true;
98 pos = response.find(base, after);
99 }
100 }
101 return false;
102}
103} // namespace
104
105// ==============================================================================
106// HTTP Helpers
107// ==============================================================================
108
109std::string ProtonDBService::httpGet(const std::string& url)
110{
111 // Use curl command to fetch URL
112 std::string command =
113 "curl -s -L --proto =https --connect-timeout 10 --max-time 30 --max-redirs 10 " +
114 ShellUtils::escapeArg(url) + " 2>/dev/null";
115
116 std::array<char, 4096> buffer;
117 std::string result;
118
119 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(), "r"), pclose);
120 if (!pipe)
121 {
122 Logger::error("ProtonDB: Failed to execute curl command");
123 return "";
124 }
125
126 constexpr size_t kMaxResponse = 16u * 1024 * 1024; // 16 MB
127 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr)
128 {
129 result += buffer.data();
130 if (result.size() > kMaxResponse)
131 {
132 Logger::warn("[ProtonDB] HTTP response too large, truncating");
133 break;
134 }
135 }
136
137 return result;
138}
139
140std::string ProtonDBService::urlEncode(const std::string& str)
141{
142 std::ostringstream encoded;
143 encoded.fill('0');
144 encoded << std::hex;
145
146 for (char c : str)
147 {
148 if (std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_' || c == '.' ||
149 c == '~')
150 {
151 encoded << c;
152 }
153 else
154 {
155 encoded << std::uppercase;
156 encoded << '%' << std::setw(2) << static_cast<int>(static_cast<unsigned char>(c));
157 encoded << std::nouppercase;
158 }
159 }
160
161 return encoded.str();
162}
163
164// ==============================================================================
165// Simple JSON Parsing Helpers
166// ==============================================================================
167
168namespace
169{
170
171// Extract string value from JSON for a given key
172std::string jsonGetString(const std::string& json, const std::string& key)
173{
174 std::string searchKey = "\"" + key + "\"";
175 size_t pos = json.find(searchKey);
176 if (pos == std::string::npos)
177 return "";
178
179 pos = json.find(':', pos);
180 if (pos == std::string::npos)
181 return "";
182
183 // Skip whitespace and find opening quote
184 pos++;
185 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
186 pos++;
187
188 if (pos >= json.size() || json[pos] != '"')
189 return "";
190
191 pos++; // Skip opening quote
192 size_t end = pos;
193
194 // Find closing quote (handle escaped quotes)
195 while (end < json.size())
196 {
197 if (json[end] == '"' && (end == 0 || json[end - 1] != '\\'))
198 break;
199 end++;
200 }
201
202 return json.substr(pos, end - pos);
203}
204
205// Extract number value from JSON for a given key
206double jsonGetNumber(const std::string& json, const std::string& key)
207{
208 std::string searchKey = "\"" + key + "\"";
209 size_t pos = json.find(searchKey);
210 if (pos == std::string::npos)
211 return 0.0;
212
213 pos = json.find(':', pos);
214 if (pos == std::string::npos)
215 return 0.0;
216
217 pos++;
218 while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos])))
219 pos++;
220
221 try
222 {
223 return std::stod(json.substr(pos));
224 }
225 catch (...)
226 {
227 return 0.0;
228 }
229}
230
231// Extract integer value from JSON
232int jsonGetInt(const std::string& json, const std::string& key)
233{
234 return static_cast<int>(jsonGetNumber(json, key));
235}
236
237// Split JSON array into elements
238std::vector<std::string> jsonSplitArray(const std::string& json)
239{
240 std::vector<std::string> elements;
241
242 size_t start = json.find('[');
243 if (start == std::string::npos)
244 return elements;
245
246 start++;
247 int braceCount = 0;
248 bool inString = false;
249 bool escaped = false;
250 size_t elementStart = start;
251
252 for (size_t i = start; i < json.size(); i++)
253 {
254 char c = json[i];
255
256 // Track JSON string state so structural characters ({ } , ]) inside a
257 // quoted value (e.g. a title "Half-Life }") are not miscounted as
258 // braces or element delimiters.
259 if (inString)
260 {
261 if (escaped)
262 escaped = false;
263 else if (c == '\\')
264 escaped = true;
265 else if (c == '"')
266 inString = false;
267 continue;
268 }
269 if (c == '"')
270 {
271 inString = true;
272 continue;
273 }
274
275 if (c == '{')
276 braceCount++;
277 else if (c == '}')
278 braceCount--;
279 else if ((c == ',' || c == ']') && braceCount == 0)
280 {
281 std::string element = json.substr(elementStart, i - elementStart);
282 // Trim whitespace
283 size_t first = element.find_first_not_of(" \t\n\r");
284 size_t last = element.find_last_not_of(" \t\n\r");
285 if (first != std::string::npos && last != std::string::npos)
286 {
287 element = element.substr(first, last - first + 1);
288 if (!element.empty() && element[0] == '{')
289 {
290 elements.push_back(element);
291 }
292 }
293 elementStart = i + 1;
294 }
295
296 if (c == ']' && braceCount == 0)
297 break;
298 }
299
300 return elements;
301}
302
303} // anonymous namespace
304
305// ==============================================================================
306// JSON Parsing Implementation
307// ==============================================================================
308
309ProtonDBGameInfo ProtonDBService::parseSummaryJson(const std::string& json, int steamAppId)
310{
311 ProtonDBGameInfo info;
312 info.steamAppId = steamAppId;
313
314 if (json.empty() || json[0] != '{')
315 {
316 info.errorMessage = "Invalid JSON response";
317 return info;
318 }
319
320 info.tier = jsonGetString(json, "tier");
321 info.trendingTier = jsonGetString(json, "trendingTier");
322 info.score = static_cast<float>(jsonGetNumber(json, "score"));
323 info.confidence = jsonGetString(json, "confidence");
324 info.totalReports = jsonGetInt(json, "total");
325
326 if (!info.tier.empty())
327 {
328 info.found = true;
329 }
330
331 return info;
332}
333
334std::vector<ProtonDBSearchResult> ProtonDBService::parseSearchJson(const std::string& json)
335{
336 std::vector<ProtonDBSearchResult> results;
337
338 auto elements = jsonSplitArray(json);
339 for (const auto& elem : elements)
340 {
341 ProtonDBSearchResult result;
342 result.steamAppId = jsonGetInt(elem, "appId");
343 result.gameName = jsonGetString(elem, "title");
344 if (result.steamAppId > 0)
345 {
346 results.push_back(result);
347 }
348 }
349
350 return results;
351}
352
353ProtonDBTweaks ProtonDBService::parseReportsJson(const std::string& json)
354{
355 ProtonDBTweaks tweaks;
356
357 auto reports = jsonSplitArray(json);
358 tweaks.reportCount = static_cast<int>(reports.size());
359
360 // Track frequency of recommendations
361 std::map<std::string, int> envVarCounts;
362 std::map<std::string, int> dllOverrideCounts;
363 std::map<std::string, int> protonVersionCounts;
364 std::map<std::string, int> launchArgCounts;
365
366 for (const auto& report : reports)
367 {
368 std::string rating = jsonGetString(report, "rating");
369 std::string notes = jsonGetString(report, "notes");
370 std::string protonVersion = jsonGetString(report, "protonVersion");
371
372 // Track Proton version from all reports (not just high-rated ones)
373 if (!protonVersion.empty() && protonVersion != "null")
374 {
375 protonVersionCounts[protonVersion]++;
376 }
377
378 // Only extract tweaks from reports with good ratings
379 if (rating == "Platinum" || rating == "Gold")
380 {
381 // Extract tweaks from notes
382 extractTweaksFromNote(notes, tweaks);
383 }
384 }
385
386 // Find most recommended Proton version
387 int maxCount = 0;
388 for (const auto& [version, count] : protonVersionCounts)
389 {
390 if (count > maxCount)
391 {
392 maxCount = count;
393 tweaks.recommendedProtonVersion = version;
394 }
395 }
396
397 return tweaks;
398}
399
400// ==============================================================================
401// Tweak Extraction from Report Notes
402// ==============================================================================
403
404void ProtonDBService::extractTweaksFromNote(const std::string& note, ProtonDBTweaks& tweaks)
405{
406 if (note.empty())
407 return;
408
409 // Common environment variable patterns
410 // Comprehensive list based on CachyOS wiki, Proton changelog, and community reports
411 static const std::vector<std::pair<std::regex, std::string>> envVarPatterns = {
412 // PROTON_* variables - core functionality
413 {std::regex(R"(PROTON_USE_WINED3D\s*=\s*(\d))"), "PROTON_USE_WINED3D"},
414 {std::regex(R"(PROTON_NO_ESYNC\s*=\s*(\d))"), "PROTON_NO_ESYNC"},
415 {std::regex(R"(PROTON_NO_FSYNC\s*=\s*(\d))"), "PROTON_NO_FSYNC"},
416 {std::regex(R"(PROTON_NO_NTSYNC\s*=\s*(\d))"), "PROTON_NO_NTSYNC"},
417 {std::regex(R"(PROTON_FORCE_NVAPI\s*=\s*(\d))"), "PROTON_FORCE_NVAPI"},
418 {std::regex(R"(PROTON_HIDE_NVIDIA_GPU\s*=\s*(\d))"), "PROTON_HIDE_NVIDIA_GPU"},
419 {std::regex(R"(PROTON_FORCE_LARGE_ADDRESS_AWARE\s*=\s*(\d))"),
420 "PROTON_FORCE_LARGE_ADDRESS_AWARE"},
421 {std::regex(R"(PROTON_USE_WOW64\s*=\s*(\d))"), "PROTON_USE_WOW64"},
422 {std::regex(R"(PROTON_NO_WRITE_WATCH\s*=\s*(\d))"), "PROTON_NO_WRITE_WATCH"},
423 {std::regex(R"(PROTON_USE_XALIA\s*=\s*(\d))"), "PROTON_USE_XALIA"},
424 {std::regex(R"(PROTON_NVIDIA_LIBS\s*=\s*(\d))"), "PROTON_NVIDIA_LIBS"},
425 {std::regex(R"(PROTON_OLD_GL_STRING\s*=\s*(\d))"), "PROTON_OLD_GL_STRING"},
426 {std::regex(R"(PROTON_USE_SECCOMP\s*=\s*(\d))"), "PROTON_USE_SECCOMP"},
427 {std::regex(R"(PROTON_ENABLE_HDR\s*=\s*(\d))"), "PROTON_ENABLE_HDR"},
428 {std::regex(R"(PROTON_ENABLE_WAYLAND\s*=\s*(\d))"), "PROTON_ENABLE_WAYLAND"},
429 {std::regex(R"(PROTON_PREFER_SDL\s*=\s*(\d))"), "PROTON_PREFER_SDL"},
430 {std::regex(R"(PROTON_NO_STEAMINPUT\s*=\s*(\d))"), "PROTON_NO_STEAMINPUT"},
431 {std::regex(R"(PROTON_PRESERVE_GAMEPAD_ORDER\s*=\s*(\d))"),
432 "PROTON_PRESERVE_GAMEPAD_ORDER"},
433 {std::regex(R"(PROTON_CPU_TOPOLOGY\s*=\s*([^\s,;]+))"), "PROTON_CPU_TOPOLOGY"},
434
435 // PROTON upscaler upgrades
436 {std::regex(R"(PROTON_DLSS_UPGRADE\s*=\s*(\d))"), "PROTON_DLSS_UPGRADE"},
437 {std::regex(R"(PROTON_FSR4_RDNA3_UPGRADE\s*=\s*(\d))"), "PROTON_FSR4_RDNA3_UPGRADE"},
438 {std::regex(R"(PROTON_XESS_UPGRADE\s*=\s*(\d))"), "PROTON_XESS_UPGRADE"},
439
440 // DXVK variables. Note: DXVK_ASYNC is a third-party-fork flag (works
441 // on proton-cachyos / GE-Proton, no-op on stock upstream DXVK). The
442 // proton-cachyos canonical modern equivalent is PROTON_DXVK_LLASYNC.
443 {std::regex(R"(DXVK_ASYNC\s*=\s*(\d))"), "DXVK_ASYNC"},
444 {std::regex(R"(PROTON_DXVK_LLASYNC\s*=\s*(\d))"), "PROTON_DXVK_LLASYNC"},
445 {std::regex(R"(DXVK_HUD\s*=\s*([^\s,;]+))"), "DXVK_HUD"},
446 {std::regex(R"(DXVK_HDR\s*=\s*(\d))"), "DXVK_HDR"},
447 {std::regex(R"(DXVK_STATE_CACHE\s*=\s*(\d))"), "DXVK_STATE_CACHE"},
448 {std::regex(R"(DXVK_STATE_CACHE_PATH\s*=\s*([^\s,;]+))"), "DXVK_STATE_CACHE_PATH"},
449 // DXVK_FRAME_RATE was removed in DXVK 2.7 (Nov 2025, PR #5331). Use
450 // gamescope `-r` or MangoHud `fps_limit=` instead; no regex here.
451 {std::regex(R"(DXVK_CONFIG_FILE\s*=\s*([^\s,;]+))"), "DXVK_CONFIG_FILE"},
452
453 // VKD3D variables (DX12). Note: VKD3D_SHADER_CACHE_AGGRESSIVE is NOT a
454 // real upstream env var; the aggressive-cache toggle is exposed via
455 // `VKD3D_CONFIG=pipeline_library_app_cache` and is matched by the
456 // VKD3D_CONFIG regex above.
457 {std::regex(R"(VKD3D_CONFIG\s*=\s*([^\s,;]+))"), "VKD3D_CONFIG"},
458 {std::regex(R"(VKD3D_FEATURE_LEVEL\s*=\s*([^\s,;]+))"), "VKD3D_FEATURE_LEVEL"},
459 {std::regex(R"(VKD3D_DEBUG\s*=\s*([^\s,;]+))"), "VKD3D_DEBUG"},
460
461 // Mesa/RADV variables (AMD)
462 {std::regex(R"(RADV_PERFTEST\s*=\s*([^\s,;]+))"), "RADV_PERFTEST"},
463 {std::regex(R"(RADV_DEBUG\s*=\s*([^\s,;]+))"), "RADV_DEBUG"},
464 {std::regex(R"(AMD_VULKAN_ICD\s*=\s*([^\s,;]+))"), "AMD_VULKAN_ICD"},
465 {std::regex(R"(mesa_glthread\s*=\s*([^\s,;]+))"), "mesa_glthread"},
466 {std::regex(R"(MESA_SHADER_CACHE_MAX_SIZE\s*=\s*([^\s,;]+))"),
467 "MESA_SHADER_CACHE_MAX_SIZE"},
468 {std::regex(R"(ENABLE_LAYER_MESA_ANTI_LAG\s*=\s*(\d))"), "ENABLE_LAYER_MESA_ANTI_LAG"},
469
470 // SDL variables
471 {std::regex(R"(SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS\s*=\s*(\d))"),
472 "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS"},
473 {std::regex(R"(SDL_AUDIODRIVER\s*=\s*([^\s,;]+))"), "SDL_AUDIODRIVER"},
474 {std::regex(R"(SDL_GAMECONTROLLERCONFIG\s*=\s*([^\s,;]+))"), "SDL_GAMECONTROLLERCONFIG"},
475
476 // Wine variables
477 {std::regex(R"(WINE_FULLSCREEN_FSR\s*=\s*(\d))"), "WINE_FULLSCREEN_FSR"},
478 {std::regex(R"(WINE_FULLSCREEN_FSR_STRENGTH\s*=\s*(\d+))"), "WINE_FULLSCREEN_FSR_STRENGTH"},
479 {std::regex(R"(WINEFSYNC\s*=\s*(\d))"), "WINEFSYNC"},
480 {std::regex(R"(WINEESYNC\s*=\s*(\d))"), "WINEESYNC"},
481 {std::regex(R"(WINEDEBUG\s*=\s*([^\s,;]+))"), "WINEDEBUG"},
482 {std::regex(R"(WINE_LARGE_ADDRESS_AWARE\s*=\s*(\d))"), "WINE_LARGE_ADDRESS_AWARE"},
483
484 // Mangohud
485 {std::regex(R"(MANGOHUD\s*=\s*(\d))"), "MANGOHUD"},
486
487 // GameMode
488 {std::regex(R"(GAMEMODE_AUTO\s*=\s*(\d))"), "GAMEMODE_AUTO"},
489
490 // Gamescope
491 {std::regex(R"(GAMESCOPE_FSR_SHARPNESS\s*=\s*(\d+))"), "GAMESCOPE_FSR_SHARPNESS"},
492
493 // Performance/scheduling
494 {std::regex(R"(__GL_THREADED_OPTIMIZATION\s*=\s*(\d))"), "__GL_THREADED_OPTIMIZATION"},
495 {std::regex(R"(__GL_SHADER_DISK_CACHE\s*=\s*(\d))"), "__GL_SHADER_DISK_CACHE"},
496 {std::regex(R"(__GL_SHADER_DISK_CACHE_SKIP_CLEANUP\s*=\s*(\d))"),
497 "__GL_SHADER_DISK_CACHE_SKIP_CLEANUP"},
498 };
499
500 // Extract environment variables
501 for (const auto& [pattern, varName] : envVarPatterns)
502 {
503 std::smatch match;
504 if (std::regex_search(note, match, pattern) && match.size() > 1)
505 {
506 tweaks.environmentVariables[varName] = match[1].str();
507 }
508 }
509
510 // Extract DLL overrides
511 static const std::regex dllOverridePattern(R"(WINEDLLOVERRIDES\s*=\s*["\']?([^"'\s;]+)["\']?)");
512 std::smatch dllMatch;
513 if (std::regex_search(note, dllMatch, dllOverridePattern) && dllMatch.size() > 1)
514 {
515 if (tweaks.dllOverrides.empty())
516 {
517 tweaks.dllOverrides = dllMatch[1].str();
518 }
519 }
520
521 // Also check for individual DLL mentions
522 static const std::regex dllPattern(R"(([\w]+)=(native|builtin|native,builtin|builtin,native))");
523 std::string::const_iterator searchStart(note.cbegin());
524 std::smatch dllResults;
525 while (std::regex_search(searchStart, note.cend(), dllResults, dllPattern))
526 {
527 std::string dll = dllResults[1].str() + "=" + dllResults[2].str();
528 if (tweaks.dllOverrides.empty())
529 {
530 tweaks.dllOverrides = dll;
531 }
532 else if (tweaks.dllOverrides.find(dllResults[1].str()) == std::string::npos)
533 {
534 tweaks.dllOverrides += ";" + dll;
535 }
536 searchStart = dllResults.suffix().first;
537 }
538
539 // Extract launch arguments
540 static const std::vector<std::string> commonArgs = {
541 "-nojoy", "-windowed", "-fullscreen", "-novid", "-skipintro", "-dx11", "-dx12", "-vulkan"};
542
543 for (const auto& arg : commonArgs)
544 {
545 if (note.find(arg) != std::string::npos)
546 {
547 if (!tweaks.launchArguments.empty())
548 {
549 tweaks.launchArguments += " ";
550 }
551 tweaks.launchArguments += arg;
552 }
553 }
554
555 // Check for GE-Proton recommendation
556 static const std::regex geProtonPattern(R"(GE-Proton[\d-]+)");
557 std::smatch geMatch;
558 if (std::regex_search(note, geMatch, geProtonPattern))
559 {
560 if (tweaks.recommendedProtonVersion.empty())
561 {
562 tweaks.recommendedProtonVersion = geMatch[0].str();
563 }
564 }
565
566 // Store useful notes
567 if (note.length() > 10 && note.length() < 500)
568 {
569 // Only store substantive notes
570 bool hasUsefulContent =
571 note.find("=") != std::string::npos || note.find("work") != std::string::npos ||
572 note.find("fix") != std::string::npos || note.find("issue") != std::string::npos;
573
574 if (hasUsefulContent && tweaks.notes.size() < 5)
575 {
576 tweaks.notes.push_back(note);
577 }
578 }
579}
580
581// ==============================================================================
582// Public API Implementation
583// ==============================================================================
584
586{
587 if (steamAppId <= 0)
588 {
589 ProtonDBGameInfo info;
590 info.errorMessage = "Invalid Steam App ID";
591 return info;
592 }
593
594 // Check LRU cache first (handles TTL automatically)
595 auto cached = protondbCache().get(steamAppId);
596 if (cached)
597 {
598 Logger::debug("ProtonDB: Cache hit for App ID {}", steamAppId);
599 return *cached;
600 }
601
602 Logger::info("ProtonDB: Fetching info for App ID {}", steamAppId);
603
604 // Fetch summary from protondb.com (official API)
605 std::string summaryUrl =
606 "https://www.protondb.com/api/v1/reports/summaries/" + std::to_string(steamAppId) + ".json";
607 std::string summaryJson = httpGet(summaryUrl);
608
609 ProtonDBGameInfo info = parseSummaryJson(summaryJson, steamAppId);
610
611 if (info.found)
612 {
613 // Fetch detailed reports from community API for tweak extraction
614 std::string reportsUrl =
615 "https://protondb.max-p.me/games/" + std::to_string(steamAppId) + "/reports/";
616 std::string reportsJson = httpGet(reportsUrl);
617
618 if (!reportsJson.empty() && reportsJson[0] == '[')
619 {
620 info.tweaks = parseReportsJson(reportsJson);
621 }
622
623 // Cache the result in LRU cache
624 protondbCache().put(steamAppId, info);
625
626 // Log cache stats periodically
627 auto stats = protondbCache().getStats();
628 if (stats.currentSize % 50 == 0)
629 {
630 Logger::debug("ProtonDB cache: {} entries, {:.1f}% hit rate, {} evictions",
631 stats.currentSize, stats.hitRate() * 100.0f, stats.evictions);
632 }
633 }
634 else
635 {
636 Logger::warn("ProtonDB: No data found for App ID {}", steamAppId);
637 }
638
639 return info;
640}
641
642std::vector<ProtonDBSearchResult> ProtonDBService::searchByName(const std::string& gameName,
643 int maxResults)
644{
645 if (gameName.empty())
646 {
647 return {};
648 }
649
650 Logger::info("ProtonDB: Searching for '{}'", gameName);
651
652 // Use community API games list
653 std::string url = "https://protondb.max-p.me/games/";
654 std::string json = httpGet(url);
655
656 if (json.empty())
657 {
658 Logger::warn("ProtonDB: Failed to fetch games list");
659 return {};
660 }
661
662 auto allGames = parseSearchJson(json);
663
664 // Filter by name (case-insensitive partial match)
665 std::string searchLower = gameName;
666 std::transform(searchLower.begin(), searchLower.end(), searchLower.begin(),
667 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
668
669 std::vector<ProtonDBSearchResult> matches;
670 for (const auto& game : allGames)
671 {
672 std::string nameLower = game.gameName;
673 std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(),
674 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
675
676 if (nameLower.find(searchLower) != std::string::npos)
677 {
678 matches.push_back(game);
679 if (static_cast<int>(matches.size()) >= maxResults)
680 {
681 break;
682 }
683 }
684 }
685
686 return matches;
687}
688
689std::string ProtonDBService::getTier(int steamAppId)
690{
691 auto info = getGameInfo(steamAppId);
692 return info.tier;
693}
694
695// ==============================================================================
696// Async API Implementation
697// ==============================================================================
698
699// ==============================================================================
700// Async Future Management
701// ==============================================================================
702
703// Static storage for active futures to prevent premature destruction
704// This replaces detached threads with managed futures for safer async operations
705namespace
706{
708std::vector<std::shared_ptr<std::future<void>>> activeFutures_;
709
710void storeAsyncFuture(std::shared_ptr<std::future<void>> future)
711{
712 std::lock_guard<std::mutex> lock(asyncFuturesMutex_);
713
714 // Clean up completed futures
715 activeFutures_.erase(std::remove_if(activeFutures_.begin(), activeFutures_.end(),
716 [](const std::shared_ptr<std::future<void>>& f)
717 {
718 return f->wait_for(std::chrono::milliseconds(0)) ==
719 std::future_status::ready;
720 }),
721 activeFutures_.end());
722
723 // Add the new future
724 activeFutures_.push_back(std::move(future));
725}
726} // namespace
727
728void ProtonDBService::getGameInfoAsync(int steamAppId, const GameInfoCallback& callback)
729{
730 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
731 [steamAppId, callback]()
732 {
733 auto info =
734 getGameInfo(steamAppId);
735 if (callback)
736 {
737 callback(info);
738 }
739 }));
740 storeAsyncFuture(future);
741}
742
743void ProtonDBService::searchByNameAsync(const std::string& gameName, const SearchCallback& callback,
744 int maxResults)
745{
746 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
747 [gameName, callback, maxResults]()
748 {
749 auto results = searchByName(
750 gameName, maxResults);
751 if (callback)
752 {
753 callback(results);
754 }
755 }));
756 storeAsyncFuture(future);
757}
758
760{
761 ProtonDBGameInfo result;
762
763 if (gameName.empty())
764 {
765 result.errorMessage = "Empty game name";
766 return result;
767 }
768
769 Logger::info("ProtonDB: Finding game by name '{}'", gameName);
770
771 // First, search for matching games
772 auto matches = searchByName(gameName, 20);
773
774 if (matches.empty())
775 {
776 Logger::warn("ProtonDB: No games found matching '{}'", gameName);
777 result.errorMessage = "No matching games found";
778 return result;
779 }
780
781 // Find best match using fuzzy matching
782 std::string searchLower = gameName;
783 std::transform(searchLower.begin(), searchLower.end(), searchLower.begin(),
784 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
785
786 // Remove common words for better matching
787 auto removeCommonWords = [](std::string& str)
788 {
789 std::vector<std::string> wordsToRemove = {"the", "a", "an", "of", "and", "or"};
790 for (const auto& word : wordsToRemove)
791 {
792 size_t pos;
793 while ((pos = str.find(" " + word + " ")) != std::string::npos)
794 {
795 str.erase(pos, word.length() + 1);
796 }
797 }
798 };
799
800 removeCommonWords(searchLower);
801
802 int bestMatchScore = 0;
803 int bestMatchAppId = 0;
804
805 for (const auto& match : matches)
806 {
807 std::string matchLower = match.gameName;
808 std::transform(matchLower.begin(), matchLower.end(), matchLower.begin(),
809 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
810
811 int score = 0;
812
813 // Exact match is best
814 if (matchLower == searchLower)
815 {
816 score = 1000;
817 }
818 // Check if search is contained in match name
819 else if (matchLower.find(searchLower) != std::string::npos)
820 {
821 // Prefer shorter names (more specific matches)
822 score = 500 - static_cast<int>(matchLower.length() - searchLower.length());
823 }
824 // Check if match name is contained in search
825 else if (searchLower.find(matchLower) != std::string::npos)
826 {
827 score = 400 - static_cast<int>(searchLower.length() - matchLower.length());
828 }
829 // Check word-by-word matching
830 else
831 {
832 // Count matching words
833 std::istringstream searchStream(searchLower);
834 std::string searchWord;
835 int matchingWords = 0;
836
837 while (searchStream >> searchWord)
838 {
839 if (matchLower.find(searchWord) != std::string::npos)
840 {
841 matchingWords++;
842 }
843 }
844 score = matchingWords * 50;
845 }
846
847 if (score > bestMatchScore)
848 {
849 bestMatchScore = score;
850 bestMatchAppId = match.steamAppId;
851 }
852 }
853
854 if (bestMatchAppId > 0)
855 {
856 Logger::info("ProtonDB: Best match for '{}' is App ID {} (score: {})", gameName,
857 bestMatchAppId, bestMatchScore);
858 return getGameInfo(bestMatchAppId);
859 }
860
861 // Fall back to first result
862 Logger::info("ProtonDB: Using first match App ID {}", matches[0].steamAppId);
863 return getGameInfo(matches[0].steamAppId);
864}
865
866void ProtonDBService::findGameByNameAsync(const std::string& gameName,
867 const GameInfoCallback& callback)
868{
869 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
870 [gameName, callback]()
871 {
872 auto info =
873 findGameByName(gameName);
874 if (callback)
875 {
876 callback(info);
877 }
878 }));
879 storeAsyncFuture(future);
880}
881
882// ==============================================================================
883// Utility Methods
884// ==============================================================================
885
886std::string ProtonDBService::getTierDescription(const std::string& tier)
887{
888 if (tier == "native")
889 return "Native Linux version available";
890 if (tier == "platinum")
891 return "Works perfectly out of the box";
892 if (tier == "gold")
893 return "Works after minor tweaks";
894 if (tier == "silver")
895 return "Works with some issues";
896 if (tier == "bronze")
897 return "Runs with significant issues";
898 if (tier == "borked")
899 return "Does not work or crashes frequently";
900 return "Unknown compatibility";
901}
902
903void ProtonDBService::getTierColor(const std::string& tier, float& r, float& g, float& b, float& a)
904{
905 a = 1.0f;
906
907 if (tier == "native")
908 {
909 r = 0.2f;
910 g = 0.7f;
911 b = 1.0f; // Blue
912 }
913 else if (tier == "platinum")
914 {
915 r = 0.7f;
916 g = 0.85f;
917 b = 0.95f; // Platinum/Silver
918 }
919 else if (tier == "gold")
920 {
921 r = 1.0f;
922 g = 0.85f;
923 b = 0.2f; // Gold
924 }
925 else if (tier == "silver")
926 {
927 r = 0.75f;
928 g = 0.75f;
929 b = 0.75f; // Silver/Gray
930 }
931 else if (tier == "bronze")
932 {
933 r = 0.8f;
934 g = 0.5f;
935 b = 0.2f; // Bronze/Orange
936 }
937 else if (tier == "borked")
938 {
939 r = 1.0f;
940 g = 0.2f;
941 b = 0.2f; // Red
942 }
943 else
944 {
945 r = 0.5f;
946 g = 0.5f;
947 b = 0.5f; // Gray for unknown
948 }
949}
950
952{
953 // Clear legacy cache
954 {
955 std::lock_guard<std::mutex> lock(cacheMutex_);
956 cache_.clear();
957 }
958
959 // Clear all LRU caches
960 protondbCache().clear();
961 steamDeckCache().clear();
962 steamAppCache().clear();
963 lutrisCache().clear();
964
965 Logger::info("ProtonDB: All caches cleared (ProtonDB, Steam Deck, Steam Store, Lutris)");
966}
967
968// ==============================================================================
969// Steam Deck Compatibility API
970// ==============================================================================
971
973{
974 SteamDeckInfo info;
975
976 if (steamAppId <= 0)
977 {
978 return info;
979 }
980
981 // Check LRU cache first
982 auto cached = steamDeckCache().get(steamAppId);
983 if (cached)
984 {
985 Logger::debug("Steam Deck: Cache hit for app {}", steamAppId);
986 return *cached;
987 }
988
989 Logger::debug("Fetching Steam Deck compatibility for app {}", steamAppId);
990
991 // Steam Deck compatibility API endpoint (official Valve API)
992 std::string url =
993 "https://store.steampowered.com/saleaction/ajaxgetdeckappcompatibilityreport?nAppID=" +
994 std::to_string(steamAppId);
995
996 std::string response = httpGet(url);
997 if (response.empty())
998 {
999 Logger::warn("Steam Deck API: Empty response for app {}", steamAppId);
1000 return info;
1001 }
1002
1003 // Parse the response - look for compatibility category.
1004 //
1005 // Response format: {"success":1,"results":{"appid":..,"resolved_category":3,...}}
1006 //
1007 // As of SteamOS 3 GA, Valve also returns parallel `steamos_resolved_category`
1008 // and `steamos_resolved_items` keys for SteamOS-native verdicts. We
1009 // intentionally still read `resolved_category` (the Linux-desktop verdict)
1010 // because this launcher targets desktop Linux, not SteamOS handhelds.
1011 //
1012 // jsonGetString() searches for `"key"` with a leading `"` so it does NOT
1013 // match the substring inside `"steamos_resolved_category"` — confirmed by
1014 // tracing the search literal. The new keys are gracefully ignored.
1015 std::string categoryStr = jsonGetString(response, "resolved_category");
1016 int category = 0;
1017
1018 // Try to get as number if string parse failed
1019 if (categoryStr.empty())
1020 {
1021 category = jsonGetInt(response, "resolved_category");
1022 }
1023 else
1024 {
1025 try
1026 {
1027 category = std::stoi(categoryStr);
1028 }
1029 catch (...)
1030 {
1031 }
1032 }
1033
1034 // Map category to enum
1035 // 0 = Unknown, 1 = Unsupported, 2 = Playable, 3 = Verified
1036 switch (category)
1037 {
1038 case 1:
1040 info.compatibilityString = "Unsupported";
1041 break;
1042 case 2:
1044 info.compatibilityString = "Playable";
1045 break;
1046 case 3:
1048 info.compatibilityString = "Verified";
1049 break;
1050 default:
1052 info.compatibilityString = "Unknown";
1053 break;
1054 }
1055
1056 // Parse test results if available
1057 // Look for specific test flags in the response
1058 if (containsIntField(response, "display_type", 3))
1059 {
1060 info.nativeResolution = true;
1061 }
1062 if (containsIntField(response, "input", 3))
1063 {
1064 info.controllerSupport = true;
1065 }
1066
1067 // If we got a valid category, mark as found and cache
1068 if (category > 0)
1069 {
1070 info.found = true;
1071 info.protonCompatible = (category >= 2); // Playable or Verified means Proton works
1072 Logger::info("Steam Deck: App {} is {} (category {})", steamAppId, info.compatibilityString,
1073 category);
1074
1075 // Cache the result
1076 steamDeckCache().put(steamAppId, info);
1077 }
1078
1079 return info;
1080}
1081
1083 int steamAppId, const std::function<void(const SteamDeckInfo&)>& callback)
1084{
1085 auto future =
1086 std::make_shared<std::future<void>>(std::async(std::launch::async,
1087 [steamAppId, callback]()
1088 {
1089 auto info = getSteamDeckInfo(steamAppId);
1090 if (callback)
1091 {
1092 callback(info);
1093 }
1094 }));
1095 storeAsyncFuture(future);
1096}
1097
1098// ==============================================================================
1099// Steam Store API
1100// ==============================================================================
1101
1103{
1104 SteamAppInfo info;
1105 info.steamAppId = steamAppId;
1106
1107 if (steamAppId <= 0)
1108 {
1109 return info;
1110 }
1111
1112 // Check LRU cache first
1113 auto cached = steamAppCache().get(steamAppId);
1114 if (cached)
1115 {
1116 Logger::debug("Steam Store: Cache hit for app {}", steamAppId);
1117 return *cached;
1118 }
1119
1120 Logger::debug("Fetching Steam app info for {}", steamAppId);
1121
1122 // Steam Store API endpoint
1123 std::string url =
1124 "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(steamAppId);
1125
1126 std::string response = httpGet(url);
1127 if (response.empty())
1128 {
1129 Logger::warn("Steam Store API: Empty response for app {}", steamAppId);
1130 return info;
1131 }
1132
1133 // Check if the response indicates success
1134 // Format: {"123456":{"success":true,"data":{...}}}
1135 if (response.find("\"success\":true") == std::string::npos &&
1136 response.find("\"success\": true") == std::string::npos)
1137 {
1138 Logger::warn("Steam Store API: Failed response for app {}", steamAppId);
1139 return info;
1140 }
1141
1142 // Extract game name
1143 info.name = jsonGetString(response, "name");
1144
1145 // Check platform support
1146 // Look for "platforms":{"windows":true,"mac":false,"linux":true}
1147 info.supportsLinux = (response.find("\"linux\":true") != std::string::npos ||
1148 response.find("\"linux\": true") != std::string::npos);
1149 info.supportsWindows = (response.find("\"windows\":true") != std::string::npos ||
1150 response.find("\"windows\": true") != std::string::npos);
1151 info.supportsMac = (response.find("\"mac\":true") != std::string::npos ||
1152 response.find("\"mac\": true") != std::string::npos);
1153
1154 // Controller support
1155 info.controllerSupport = jsonGetString(response, "controller_support");
1156
1157 // Check for multiplayer (affects anti-cheat concerns). Delimiter-aware so
1158 // category id 1 is not matched by 10/100/19 etc.
1159 info.hasMultiplayer = containsIntField(response, "id", 1) || // Multi-player category
1160 containsIntField(response, "id", 36) || // Online Multi-Player
1161 containsIntField(response, "id", 37); // Local Multi-Player
1162
1163 // Check for cloud saves
1164 info.hasCloudSaves = containsIntField(response, "id", 23); // Steam Cloud
1165
1166 // DRM notice (important for compatibility)
1167 size_t drmPos = response.find("\"drm_notice\"");
1168 if (drmPos != std::string::npos)
1169 {
1170 info.drmNotice = jsonGetString(response, "drm_notice");
1171 }
1172
1173 // Extract genres for pattern matching
1174 // This helps identify similar games and common fixes
1175 size_t genreStart = response.find("\"genres\"");
1176 if (genreStart != std::string::npos)
1177 {
1178 size_t genreEnd = response.find("]", genreStart);
1179 if (genreEnd != std::string::npos)
1180 {
1181 std::string genreSection = response.substr(genreStart, genreEnd - genreStart + 1);
1182 // Extract genre descriptions
1183 size_t pos = 0;
1184 while ((pos = genreSection.find("\"description\":\"", pos)) != std::string::npos)
1185 {
1186 pos += 15;
1187 size_t end = genreSection.find("\"", pos);
1188 if (end != std::string::npos)
1189 {
1190 info.genres.push_back(genreSection.substr(pos, end - pos));
1191 pos = end;
1192 }
1193 }
1194 }
1195 }
1196
1197 // Extract developer/publisher
1198 info.developer = jsonGetString(response, "developers");
1199 info.publisher = jsonGetString(response, "publishers");
1200
1201 info.found = !info.name.empty();
1202
1203 if (info.found)
1204 {
1205 Logger::info("Steam Store: {} - Linux={}, Controller={}, Multiplayer={}", info.name,
1206 info.supportsLinux ? "yes" : "no",
1207 info.controllerSupport.empty() ? "none" : info.controllerSupport,
1208 info.hasMultiplayer ? "yes" : "no");
1209
1210 // Cache the result (24-hour TTL since this rarely changes)
1211 steamAppCache().put(steamAppId, info);
1212 }
1213
1214 return info;
1215}
1216
1218 const std::function<void(const SteamAppInfo&)>& callback)
1219{
1220 auto future =
1221 std::make_shared<std::future<void>>(std::async(std::launch::async,
1222 [steamAppId, callback]()
1223 {
1224 auto info = getSteamAppInfo(steamAppId);
1225 if (callback)
1226 {
1227 callback(info);
1228 }
1229 }));
1230 storeAsyncFuture(future);
1231}
1232
1233// ==============================================================================
1234// Lutris API
1235// ==============================================================================
1236
1238{
1239 LutrisGameInfo info;
1240
1241 if (steamAppId <= 0)
1242 {
1243 return info;
1244 }
1245
1246 // Check LRU cache first
1247 auto cached = lutrisCache().get(steamAppId);
1248 if (cached)
1249 {
1250 Logger::debug("Lutris: Cache hit for Steam app {}", steamAppId);
1251 return *cached;
1252 }
1253
1254 Logger::debug("Fetching Lutris info for Steam app {}", steamAppId);
1255
1256 // Lutris API - search by Steam ID
1257 std::string url = "https://lutris.net/api/games?steamid=" + std::to_string(steamAppId);
1258
1259 std::string response = httpGet(url);
1260 if (response.empty())
1261 {
1262 Logger::warn("Lutris API: Empty response for Steam app {}", steamAppId);
1263 return info;
1264 }
1265
1266 // Parse game info from results
1267 // Response format: {"count":1,"results":[{"name":"...","slug":"...","steamid":123}]}
1268 info.slug = jsonGetString(response, "slug");
1269 info.name = jsonGetString(response, "name");
1270 info.steamId = steamAppId;
1271
1272 if (info.slug.empty())
1273 {
1274 // Try to extract from results array
1275 size_t resultsPos = response.find("\"results\"");
1276 if (resultsPos != std::string::npos)
1277 {
1278 size_t slugPos = response.find("\"slug\":\"", resultsPos);
1279 if (slugPos != std::string::npos)
1280 {
1281 slugPos += 8;
1282 size_t end = response.find("\"", slugPos);
1283 if (end != std::string::npos)
1284 {
1285 info.slug = response.substr(slugPos, end - slugPos);
1286 }
1287 }
1288 size_t namePos = response.find("\"name\":\"", resultsPos);
1289 if (namePos != std::string::npos)
1290 {
1291 namePos += 8;
1292 size_t end = response.find("\"", namePos);
1293 if (end != std::string::npos)
1294 {
1295 info.name = response.substr(namePos, end - namePos);
1296 }
1297 }
1298 }
1299 }
1300
1301 if (info.slug.empty())
1302 {
1303 Logger::debug("Lutris: No game found for Steam app {}", steamAppId);
1304 return info;
1305 }
1306
1307 // Fetch installers for this game
1308 std::string installersUrl = "https://lutris.net/api/games/" + info.slug + "/installers";
1309 std::string installersResponse = httpGet(installersUrl);
1310
1311 if (!installersResponse.empty())
1312 {
1313 // Parse installers - look for wine/proton scripts
1314 // Each installer has: name, slug, runner, version, script
1315 auto installerObjects = jsonSplitArray(installersResponse);
1316
1317 for (const auto& installerJson : installerObjects)
1318 {
1319 LutrisInstaller installer;
1320 installer.slug = jsonGetString(installerJson, "slug");
1321 installer.name = jsonGetString(installerJson, "name");
1322 installer.runner = jsonGetString(installerJson, "runner");
1323 installer.version = jsonGetString(installerJson, "version");
1324
1325 // Only interested in wine/proton runners for Windows games
1326 if (installer.runner == "wine" || installer.runner == "steam" ||
1327 installer.runner.find("proton") != std::string::npos)
1328 {
1329 // Try to extract wine version from script
1330 size_t winePos = installerJson.find("\"wine\"");
1331 if (winePos != std::string::npos)
1332 {
1333 installer.wineVersion = jsonGetString(installerJson.substr(winePos), "version");
1334 }
1335
1336 // Look for environment variables in the script
1337 size_t envPos = installerJson.find("\"env\"");
1338 if (envPos != std::string::npos)
1339 {
1340 // Extract env section
1341 size_t start = installerJson.find("{", envPos);
1342 size_t end = installerJson.find("}", start);
1343 if (start != std::string::npos && end != std::string::npos)
1344 {
1345 std::string envSection = installerJson.substr(start, end - start + 1);
1346 // Parse individual env vars
1347 // Common ones: PROTON_*, DXVK_*, etc.
1348 static const std::vector<std::string> envVars = {
1349 "PROTON_USE_WINED3D",
1350 "PROTON_NO_ESYNC",
1351 "PROTON_NO_FSYNC",
1352 "PROTON_FORCE_NVAPI",
1353 "DXVK_ASYNC",
1354 "WINEDLLOVERRIDES",
1355 "PROTON_FORCE_LARGE_ADDRESS_AWARE",
1356 "mesa_glthread"};
1357 for (const auto& var : envVars)
1358 {
1359 std::string val = jsonGetString(envSection, var);
1360 if (!val.empty())
1361 {
1362 installer.environmentVariables[var] = val;
1363 }
1364 }
1365 }
1366 }
1367
1368 // Look for DLL overrides
1369 std::string dllOverrides = jsonGetString(installerJson, "WINEDLLOVERRIDES");
1370 if (!dllOverrides.empty())
1371 {
1372 installer.dllOverrides = dllOverrides;
1373 }
1374
1375 // Anti-cheat runtime flags live under the installer script's
1376 // `game:` block as booleans (true / "true" / 1). Lutris uses
1377 // these to drive runtime install prompts; we use them to emit
1378 // PROTON_*_RUNTIME suggestions.
1379 {
1380 const auto flagSet = [](const std::string& s)
1381 { return s == "true" || s == "1" || s == "True" || s == "TRUE"; };
1382 std::string eacVal = jsonGetString(installerJson, "eac");
1383 std::string beVal = jsonGetString(installerJson, "battleye");
1384 installer.eac = flagSet(eacVal);
1385 installer.battleye = flagSet(beVal);
1386 }
1387
1388 installer.found = true;
1389 info.installers.push_back(std::move(installer));
1390 }
1391 }
1392
1393 // Sort by download count (popularity) if available
1394 std::sort(info.installers.begin(), info.installers.end(),
1395 [](const LutrisInstaller& a, const LutrisInstaller& b)
1396 { return a.downloadCount > b.downloadCount; });
1397 }
1398
1399 info.found = !info.slug.empty();
1400
1401 if (info.found)
1402 {
1403 Logger::info("Lutris: Found {} with {} installers", info.name, info.installers.size());
1404
1405 // Cache the result
1406 lutrisCache().put(steamAppId, info);
1407 }
1408
1409 return info;
1410}
1411
1413{
1414 LutrisGameInfo info;
1415
1416 if (gameSlug.empty())
1417 {
1418 return info;
1419 }
1420
1421 Logger::debug("Fetching Lutris info for slug {}", gameSlug);
1422
1423 // Directly fetch by slug
1424 std::string url = "https://lutris.net/api/games/" + urlEncode(gameSlug);
1425
1426 std::string response = httpGet(url);
1427 if (response.empty() || response.find("\"detail\":\"Not found\"") != std::string::npos)
1428 {
1429 return info;
1430 }
1431
1432 info.slug = gameSlug;
1433 info.name = jsonGetString(response, "name");
1434 info.steamId = jsonGetInt(response, "steamid");
1435 info.gogId = jsonGetInt(response, "gogid");
1436 info.found = !info.name.empty();
1437
1438 // If found, also fetch installers
1439 if (info.found)
1440 {
1441 LutrisGameInfo fullInfo = getLutrisInfo(info.steamId > 0 ? info.steamId : -1);
1442 if (!fullInfo.installers.empty())
1443 {
1444 info.installers = std::move(fullInfo.installers);
1445 }
1446 }
1447
1448 return info;
1449}
1450
1452 const std::function<void(const LutrisGameInfo&)>& callback)
1453{
1454 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
1455 [steamAppId, callback]()
1456 {
1457 auto info =
1458 getLutrisInfo(steamAppId);
1459 if (callback)
1460 {
1461 callback(info);
1462 }
1463 }));
1464 storeAsyncFuture(future);
1465}
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 error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static SteamAppInfo getSteamAppInfo(int steamAppId)
Get Steam store information (native Linux, genres, DRM, etc.).
std::function< void(const ProtonDBGameInfo &)> GameInfoCallback
static std::vector< ProtonDBSearchResult > searchByName(const std::string &gameName, int maxResults=10)
Search for games by name.
static LutrisGameInfo getLutrisInfoBySlug(const std::string &gameSlug)
Get Lutris info by game slug.
static void findGameByNameAsync(const std::string &gameName, const GameInfoCallback &callback)
Find game info by name asynchronously.
static void searchByNameAsync(const std::string &gameName, const SearchCallback &callback, int maxResults=10)
Search for games by name asynchronously.
static void clearCache()
Clear cached data.
static ProtonDBGameInfo findGameByName(const std::string &gameName)
Find game info by name (searches for matching game, returns full info).
static std::string getTier(int steamAppId)
Get compatibility tier for a game (quick lookup).
static void getSteamDeckInfoAsync(int steamAppId, const std::function< void(const SteamDeckInfo &)> &callback)
Get Steam Deck compatibility asynchronously.
std::function< void(const std::vector< ProtonDBSearchResult > &)> SearchCallback
static LutrisGameInfo getLutrisInfo(int steamAppId)
Get Lutris game info and installers.
static ProtonDBGameInfo getGameInfo(int steamAppId)
Get game info by Steam App ID.
static void getTierColor(const std::string &tier, float &r, float &g, float &b, float &a)
Get tier color for UI display (RGBA).
static void getLutrisInfoAsync(int steamAppId, const std::function< void(const LutrisGameInfo &)> &callback)
Get Lutris info asynchronously.
static std::string getTierDescription(const std::string &tier)
Get human-readable tier description.
static void getSteamAppInfoAsync(int steamAppId, const std::function< void(const SteamAppInfo &)> &callback)
Get Steam app info asynchronously.
static SteamDeckInfo getSteamDeckInfo(int steamAppId)
Get Steam Deck compatibility status from Valve's testing.
static void getGameInfoAsync(int steamAppId, const GameInfoCallback &callback)
Get game info asynchronously.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
nlohmann::json json
std::string jsonGetString(const std::string &json, const std::string &key)
std::vector< std::string > jsonSplitArray(const std::string &json, const std::string &arrayKey)
int jsonGetInt(const std::string &json, const std::string &key)
double jsonGetNumber(const std::string &json, const std::string &key)
LRUCache< int, SteamDeckInfo > & steamDeckCache()
int jsonGetInt(const std::string &json, const std::string &key)
LRUCache< int, ProtonDBGameInfo > & protondbCache()
void storeAsyncFuture(std::shared_ptr< std::future< void > > future)
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
std::vector< std::string > jsonSplitArray(const std::string &json)
double jsonGetNumber(const std::string &json, const std::string &key)
std::string jsonGetString(const std::string &json, const std::string &key)
bool containsIntField(const std::string &response, const char *key, int value)
LRUCache< int, SteamAppInfo > & steamAppCache()
LRUCache< int, LutrisGameInfo > & lutrisCache()
static constexpr size_t PROTONDB_CACHE_MAX_SIZE
static constexpr size_t STEAM_DECK_CACHE_MAX_SIZE
static constexpr int PROTONDB_CACHE_TTL_SECONDS
static constexpr size_t LUTRIS_CACHE_MAX_SIZE
static constexpr int LUTRIS_CACHE_TTL_SECONDS
static constexpr int STEAM_DECK_CACHE_TTL_SECONDS
static constexpr size_t STEAM_APP_CACHE_MAX_SIZE
static constexpr int STEAM_APP_CACHE_TTL_SECONDS
Lutris database entry for a game.
std::vector< LutrisInstaller > installers
Installation script from Lutris with working configurations.
std::string wineVersion
std::string dllOverrides
std::map< std::string, std::string > environmentVariables
Complete ProtonDB information for a game.
std::string confidence
std::string trendingTier
ProtonDBTweaks tweaks
std::string errorMessage
Recommended tweaks extracted from ProtonDB reports.
std::string dllOverrides
DLL overrides (e.g., "d3d11=native,builtin").
std::map< std::string, std::string > environmentVariables
Environment variables to set (e.g., PROTON_USE_WINED3D=1).
std::string recommendedProtonVersion
Recommended Proton version (e.g., "GE-Proton8-25").
int reportCount
Number of reports these tweaks were extracted from.
std::string launchArguments
Launch arguments to add.
std::vector< std::string > notes
Notes/warnings from reports.
Basic Steam store information for a game.
std::string name
std::vector< std::string > genres
std::string publisher
std::string developer
std::string drmNotice
std::string controllerSupport
Steam Deck compatibility information from Valve.
SteamDeckCompatibility compatibility
std::string compatibilityString