game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game.cpp
4// ==============================================================================
5// Implementation of Game class and serialization
6// ==============================================================================
7
8#include "game.h"
9#include "logger.h"
10#include <algorithm>
11#include <cstdint>
12#include <ctime>
13#include <fstream>
14#include <iomanip>
15#include <nlohmann/json.hpp>
16#include <set>
17#include <sstream>
18
19using gjson = nlohmann::json;
20
21// ==============================================================================
22// Helper Methods
23// ==============================================================================
24
25std::string Game::getSourceName() const
26{
27 switch (source)
28 {
30 return "Local";
32 return "Steam";
33 case GameSource::GOG:
34 return "GOG";
36 return "Epic Games";
38 return "itch.io";
40 return "Lutris";
42 return "Flatpak";
44 default:
45 return "Unknown";
46 }
47}
48
49std::string Game::getRunnerName() const
50{
51 switch (runner)
52 {
54 return "Native";
56 return "Wine";
58 return "Proton";
60 return "DOSBox";
62 return "ScummVM";
63 default:
64 return "Unknown";
65 }
66}
67
68std::string Game::getPlatformName() const
69{
70 switch (platform)
71 {
73 return "Native Linux";
75 return "Wine";
77 return "Proton";
79 return "Steam";
81 return "GOG";
83 return "Epic Games";
85 return "DOSBox";
87 return "ScummVM";
89 return "RetroArch";
90 default:
91 return "Unknown";
92 }
93}
94
95std::string Game::getStatusName() const
96{
97 switch (status)
98 {
100 return "Not Installed";
102 return "Installed";
104 return "Running";
106 return "Installing";
108 return "Updating";
109 default:
110 return "Unknown";
111 }
112}
113
114std::string Game::getFormattedPlayTime() const
115{
116 // Convert seconds to hours and minutes
117 int64_t totalSeconds =
118 std::max(static_cast<int64_t>(0), static_cast<int64_t>(statistics.totalPlayTimeSeconds));
119 int64_t hours = totalSeconds / 3600;
120 int64_t minutes = (totalSeconds % 3600) / 60;
121
122 std::ostringstream oss;
123
124 if (hours > 0)
125 {
126 oss << hours << "h";
127 if (minutes > 0)
128 {
129 oss << " " << minutes << "m";
130 }
131 }
132 else if (minutes > 0)
133 {
134 oss << minutes << "m";
135 }
136 else
137 {
138 oss << "< 1m";
139 }
140
141 return oss.str();
142}
143
145{
146 const char* units[] = {"B", "KB", "MB", "GB", "TB"};
147 int unitIndex = 0;
148 double size = static_cast<double>(installSizeBytes);
149
150 while (size >= 1024.0 && unitIndex < 4)
151 {
152 size /= 1024.0;
153 unitIndex++;
154 }
155
156 std::ostringstream oss;
157 oss << std::fixed << std::setprecision(1) << size << " " << units[unitIndex];
158 return oss.str();
159}
160
161// ==============================================================================
162// Performance Cache Implementation
163// ==============================================================================
164
165// Helper function to convert string to lowercase
166static std::string toLower(const std::string& str)
167{
168 std::string result = str;
169 for (char& c : result)
170 {
171 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
172 }
173 return result;
174}
175
176const std::string& Game::getNameLower() const
177{
179 {
180 // Compute all caches at once to avoid repeated cache checks
185 cacheInitialized_ = true;
186 }
187 return nameLowerCache_;
188}
189
190const std::string& Game::getDeveloperLower() const
191{
193 {
194 getNameLower(); // Initialize all caches
195 }
197}
198
199const std::string& Game::getPublisherLower() const
200{
202 {
203 getNameLower(); // Initialize all caches
204 }
206}
207
208const std::string& Game::getDescriptionLower() const
209{
211 {
212 getNameLower(); // Initialize all caches
213 }
215}
216
217// ==============================================================================
218// Image Path Implementation
219// ==============================================================================
220
221std::string Game::getImagePath(ImageType type) const
222{
223 // Check new imagePaths struct first, with fallback chain
224 switch (type)
225 {
227 // Primary: library_600x900.jpg (vertical cover)
228 if (!metadata.imagePaths.verticalCover.empty())
229 return metadata.imagePaths.verticalCover;
230 // Legacy fallback
231 if (!metadata.coverArtPath.empty())
232 return metadata.coverArtPath;
233 // Fallback chain: header (most common), then hero, then capsule
234 if (!metadata.imagePaths.header.empty())
235 return metadata.imagePaths.header;
236 if (!metadata.imagePaths.heroImage.empty())
237 return metadata.imagePaths.heroImage;
238 if (!metadata.imagePaths.capsule.empty())
239 return metadata.imagePaths.capsule;
240 return "";
241
243 // Primary: library_hero.jpg (wide banner)
244 if (!metadata.imagePaths.heroImage.empty())
245 return metadata.imagePaths.heroImage;
246 // Legacy fallback
247 if (!metadata.bannerPath.empty())
248 return metadata.bannerPath;
249 // Fallback: header is also wide format
250 if (!metadata.imagePaths.header.empty())
251 return metadata.imagePaths.header;
252 return "";
253
254 case ImageType::Logo:
255 return metadata.imagePaths.logo;
256
258 // Primary: header.jpg or library_header.jpg
259 if (!metadata.imagePaths.header.empty())
260 return metadata.imagePaths.header;
261 // Fallback: hero image is also wide
262 if (!metadata.imagePaths.heroImage.empty())
263 return metadata.imagePaths.heroImage;
264 return "";
265
267 if (!metadata.imagePaths.capsule.empty())
268 return metadata.imagePaths.capsule;
269 // Fallback: header has similar aspect ratio
270 if (!metadata.imagePaths.header.empty())
271 return metadata.imagePaths.header;
272 return "";
273
274 case ImageType::Icon:
275 return metadata.imagePaths.icon;
276
277 default:
278 return "";
279 }
280}
281
282// ==============================================================================
283// Completion Status & Session Tracking Implementation
284// ==============================================================================
285
287{
288 switch (completionStatus)
289 {
291 return "Not Played";
293 return "Playing";
295 return "Beaten";
297 return "Completed";
299 return "On Hold";
301 return "Abandoned";
303 return "Played";
304 default:
305 return "Unknown";
306 }
307}
308
309double Game::getRemainingPlaytime(int targetStyle) const
310{
311 if (!hltbInfo.found)
312 return -1.0;
313
314 double targetHours = 0.0;
315 switch (targetStyle)
316 {
317 case 0:
318 targetHours = hltbInfo.mainStoryHours;
319 break;
320 case 1:
321 targetHours = hltbInfo.mainPlusExtrasHours;
322 break;
323 case 2:
324 targetHours = hltbInfo.completionistHours;
325 break;
326 default:
327 targetHours = hltbInfo.allStylesHours;
328 break;
329 }
330
331 if (targetHours <= 0.0)
332 return -1.0;
333
334 double playedHours = statistics.totalPlayTimeSeconds / 3600.0;
335 return targetHours - playedHours;
336}
337
338double Game::getCompletionPercentage(int targetStyle) const
339{
340 if (!hltbInfo.found)
341 return 0.0;
342
343 double targetHours = 0.0;
344 switch (targetStyle)
345 {
346 case 0:
347 targetHours = hltbInfo.mainStoryHours;
348 break;
349 case 1:
350 targetHours = hltbInfo.mainPlusExtrasHours;
351 break;
352 case 2:
353 targetHours = hltbInfo.completionistHours;
354 break;
355 default:
356 targetHours = hltbInfo.allStylesHours;
357 break;
358 }
359
360 if (targetHours <= 0.0)
361 return 0.0;
362
363 double playedHours = statistics.totalPlayTimeSeconds / 3600.0;
364 return (playedHours / targetHours) * 100.0;
365}
366
368{
369 if (recentSessions.empty())
370 return 0.0;
371
372 double totalDuration = 0.0;
373 int completedSessions = 0;
374
375 for (const auto& session : recentSessions)
376 {
377 if (!session.isActive() && session.durationSeconds > 0)
378 {
379 totalDuration += session.durationSeconds;
380 completedSessions++;
381 }
382 }
383
384 return completedSessions > 0 ? totalDuration / completedSessions : 0.0;
385}
386
387// ==============================================================================
388// PlaySession Implementation
389// ==============================================================================
390
392{
393 auto totalSeconds = static_cast<int64_t>(durationSeconds);
394 int hours = static_cast<int>(totalSeconds / 3600);
395 int minutes = static_cast<int>((totalSeconds % 3600) / 60);
396
397 std::ostringstream oss;
398 if (hours > 0)
399 {
400 oss << hours << "h";
401 if (minutes > 0)
402 oss << " " << minutes << "m";
403 }
404 else if (minutes > 0)
405 {
406 oss << minutes << "m";
407 }
408 else
409 {
410 oss << "< 1m";
411 }
412 return oss.str();
413}
414
415// ==============================================================================
416// HowLongToBeatInfo Implementation
417// ==============================================================================
418
420{
421 if (lastUpdated == 0)
422 return true;
423
424 time_t now = std::time(nullptr);
425 // Stale after 30 days (2,592,000 seconds)
426 return (now - lastUpdated) > 2592000;
427}
428
429std::string HowLongToBeatInfo::formatHours(double hours)
430{
431 if (hours <= 0.0)
432 return "N/A";
433
434 std::ostringstream oss;
435 if (hours < 1.0)
436 {
437 int minutes = static_cast<int>(hours * 60);
438 oss << minutes << "m";
439 }
440 else if (hours < 100.0)
441 {
442 oss << std::fixed << std::setprecision(1) << hours << "h";
443 }
444 else
445 {
446 oss << static_cast<int>(hours) << "h";
447 }
448 return oss.str();
449}
450
451// ==============================================================================
452// JSON Serialization (for SQLite storage)
453// ==============================================================================
454//
455// Implementation uses nlohmann::json end-to-end. The previous hand-rolled
456// `extractJsonString` / `extractJsonInt` / `jsonEscape` family was removed
457// because:
458// - It couldn't preserve unknown keys, so any field added by a newer
459// launcher version (or by manual user edit) was silently dropped on
460// the next save — irrecoverable data loss.
461// - The reader was an ad-hoc text scanner, not a parser; nested objects
462// and edge-case escape sequences could mis-parse.
463//
464// The new implementation parses with nlohmann::json, populates the typed
465// struct, and stashes any keys we don't know about into
466// `unknownJsonExtras` (a serialised JSON object). On the next serialise,
467// the unknown keys are merged back into the output. Round-trip-clean.
468
469namespace
470{
471
472/// Set of keys that the typed struct knows about. Keys not in this set are
473/// stashed into `unknownJsonExtras` for round-trip preservation. Wrapped
474/// in Meyer's-singleton accessors below: file-scope `static const std::set
475/// <std::string>` is bugprone-throwing-static-initialization /
476/// CERT ERR58-CPP because std::string allocations within set construction
477/// aren't catchable at static init.
478const std::set<std::string>& kKnownRunnerConfigKeys()
479{
480 static const std::set<std::string> keys = {
481 "type",
482 "version",
483 "executablePath",
484 "workingDirectory",
485 "arguments",
486 "winePrefix",
487 "winePath",
488 "wineDLL",
489 "protonVersion",
490 "useSteamDefaults",
491 "useSteamLaunch",
492 "enableMangoHud",
493 "mangoHudConfigFile",
494 "enableGameMode",
495 "enableGamePerformance",
496 "enableVkBasalt",
497 "enableGamescope",
498 "gamescopeWidth",
499 "gamescopeHeight",
500 "gamescopeInternalWidth",
501 "gamescopeInternalHeight",
502 "gamescopeRefreshRate",
503 "gamescopeFullscreen",
504 "gamescopeBorderless",
505 "gamescopeEnableFSR",
506 "gamescopeFSRSharpness",
507 "gamescopeEnableVRR",
508 "gamescopeEnableHDR",
509 "gamescopeEnableITM",
510 "gamescopeITMSDRNits",
511 "gamescopeIntegerScaling",
512 "gamescopeForceGrabCursor",
513 "enableFsync",
514 "autoDetectSync",
515 "enableDetailedLogging",
516 "useVirtualDesktop",
517 "virtualDesktopWidth",
518 "virtualDesktopHeight",
519 "excludeProcesses",
520 "environmentVariables",
521 };
522 return keys;
523}
524
525const std::set<std::string>& kKnownMetadataKeys()
526{
527 static const std::set<std::string> keys = {
528 "coverArtPath",
529 "bannerPath",
530 "imagePaths",
531 "description",
532 "genres",
533 "tags",
534 "developer",
535 "publisher",
536 "releaseYear",
537 "userRating",
538 "isSteamGame",
539 "steamAppId",
540 "steamInstalled",
541 "steamLaunchOptions",
542 "steamBuildId",
543 "steamPlaytime2Weeks",
544 "steamLastLaunch",
545 "steamLastExit",
546 "steamType",
547 "steamCategories",
548 "steamUserCategories",
549 "protondbTier",
550 "protondbConfidence",
551 "protondbScore",
552 "protondbLastUpdated",
553 "cloudSave",
554 "dlcCount",
555 "dlc",
556 };
557 return keys;
558}
559
560/// Type-tolerant getter helpers — return defaultVal when the key is missing
561/// or the value is the wrong type. nlohmann::json::value(...) throws on
562/// type mismatch; this wrapper makes deserialisation forgiving in the same
563/// way the prior text-scanner was forgiving.
564std::string jstr(const gjson& j, const char* key, const char* def = "")
565{
566 auto it = j.find(key);
567 if (it != j.end() && it->is_string())
568 return it->get<std::string>();
569 return def;
570}
571int jint(const gjson& j, const char* key, int def = 0)
572{
573 auto it = j.find(key);
574 if (it != j.end() && it->is_number_integer())
575 return it->get<int>();
576 if (it != j.end() && it->is_number_float())
577 return static_cast<int>(it->get<double>());
578 return def;
579}
580double jdouble(const gjson& j, const char* key, double def = 0.0)
581{
582 auto it = j.find(key);
583 if (it != j.end() && it->is_number())
584 return it->get<double>();
585 return def;
586}
587bool jbool(const gjson& j, const char* key, bool def = false)
588{
589 auto it = j.find(key);
590 if (it != j.end() && it->is_boolean())
591 return it->get<bool>();
592 return def;
593}
594int64_t jint64(const gjson& j, const char* key, int64_t def = 0)
595{
596 auto it = j.find(key);
597 if (it != j.end() && it->is_number_integer())
598 return it->get<int64_t>();
599 return def;
600}
601
602/// Extract any keys not in `known` into a JSON object string. Used to
603/// preserve forward-compatible fields we don't recognise yet. Returns empty
604/// string when there are no unknown keys.
605std::string captureUnknownKeys(const gjson& src, const std::set<std::string>& known)
606{
607 if (!src.is_object())
608 return "";
609 gjson extras = gjson::object();
610 for (auto it = src.begin(); it != src.end(); ++it)
611 {
612 if (known.find(it.key()) == known.end())
613 extras[it.key()] = it.value();
614 }
615 if (extras.empty())
616 return "";
617 return extras.dump();
618}
619
620/// Inverse of captureUnknownKeys: merge stashed unknowns into the JSON
621/// object we're about to serialise. Known keys we just wrote take
622/// precedence — the stash is ONLY for keys we don't know about, so a
623/// collision means a user edit-and-save took ownership of that key.
624void mergeUnknownKeys(gjson& dst, const std::string& extrasStr)
625{
626 if (extrasStr.empty())
627 return;
628 try
629 {
630 gjson extras = gjson::parse(extrasStr);
631 if (!extras.is_object())
632 return;
633 for (auto it = extras.begin(); it != extras.end(); ++it)
634 {
635 if (!dst.contains(it.key()))
636 dst[it.key()] = it.value();
637 }
638 }
639 catch (const gjson::exception& e)
640 {
641 Logger::warn("[Game] unknownJsonExtras stash is malformed; skipping merge: {}", e.what());
642 }
643}
644
645} // namespace
646
648{
649 gjson j;
650
651 // Runner type and version
652 j["type"] = runnerConfig.runnerType;
653 j["version"] = runnerConfig.runnerVersion;
654
655 // Executable settings
656 j["executablePath"] = runnerConfig.executablePath;
657 j["workingDirectory"] = runnerConfig.workingDirectory;
658 j["arguments"] = runnerConfig.arguments;
659
660 // Wine/Proton settings
661 j["winePrefix"] = runnerConfig.winePrefix;
662 j["winePath"] = runnerConfig.winePath;
663 j["wineDLL"] = runnerConfig.wineDLL;
664 j["protonVersion"] = runnerConfig.protonVersion;
665 j["useSteamDefaults"] = runnerConfig.useSteamDefaults;
666 j["useSteamLaunch"] = runnerConfig.useSteamLaunch;
667
668 // Performance wrappers
669 j["enableMangoHud"] = runnerConfig.enableMangoHud;
670 j["mangoHudConfigFile"] = runnerConfig.mangoHudConfigFile;
671 j["enableGameMode"] = runnerConfig.enableGameMode;
672 j["enableGamePerformance"] = runnerConfig.enableGamePerformance;
673 j["enableVkBasalt"] = runnerConfig.enableVkBasalt;
674
675 // Gamescope
676 j["enableGamescope"] = runnerConfig.enableGamescope;
677 j["gamescopeWidth"] = runnerConfig.gamescopeWidth;
678 j["gamescopeHeight"] = runnerConfig.gamescopeHeight;
679 j["gamescopeInternalWidth"] = runnerConfig.gamescopeInternalWidth;
680 j["gamescopeInternalHeight"] = runnerConfig.gamescopeInternalHeight;
681 j["gamescopeRefreshRate"] = runnerConfig.gamescopeRefreshRate;
682 j["gamescopeFullscreen"] = runnerConfig.gamescopeFullscreen;
683 j["gamescopeBorderless"] = runnerConfig.gamescopeBorderless;
684 j["gamescopeEnableFSR"] = runnerConfig.gamescopeEnableFSR;
685 j["gamescopeFSRSharpness"] = runnerConfig.gamescopeFSRSharpness;
686 j["gamescopeEnableVRR"] = runnerConfig.gamescopeEnableVRR;
687 j["gamescopeEnableHDR"] = runnerConfig.gamescopeEnableHDR;
688 j["gamescopeEnableITM"] = runnerConfig.gamescopeEnableITM;
689 j["gamescopeITMSDRNits"] = runnerConfig.gamescopeITMSDRNits;
690 j["gamescopeIntegerScaling"] = runnerConfig.gamescopeIntegerScaling;
691 j["gamescopeForceGrabCursor"] = runnerConfig.gamescopeForceGrabCursor;
692
693 // Sync options
694 j["enableFsync"] = runnerConfig.enableFsync;
695 j["autoDetectSync"] = runnerConfig.autoDetectSync;
696
697 // Debug
698 j["enableDetailedLogging"] = runnerConfig.enableDetailedLogging;
699
700 // Virtual desktop
701 j["useVirtualDesktop"] = runnerConfig.useVirtualDesktop;
702 j["virtualDesktopWidth"] = runnerConfig.virtualDesktopWidth;
703 j["virtualDesktopHeight"] = runnerConfig.virtualDesktopHeight;
704
705 // Exclude processes as JSON array
706 j["excludeProcesses"] = runnerConfig.excludeProcesses;
707
708 // Environment variables. The wire format is an array of {k,v} objects
709 // (preserved from the prior format for backward compatibility — a
710 // direct JSON object would be cleaner but would break existing rows).
711 gjson envArr = gjson::array();
712 for (const auto& [key, value] : runnerConfig.environmentVariables)
713 {
714 envArr.push_back({{"k", key}, {"v", value}});
715 }
716 j["environmentVariables"] = std::move(envArr);
717
718 // Round-trip-preserve any keys we don't recognise. mergeUnknownKeys
719 // never overrides keys we just wrote — only adds the unknowns.
720 mergeUnknownKeys(j, runnerConfig.unknownJsonExtras);
721 return j.dump();
722}
723
724void Game::deserializeRunnerConfig(const std::string& json)
725{
726 if (json.empty())
727 return;
728
729 gjson j;
730 try
731 {
732 j = gjson::parse(json);
733 }
734 catch (const gjson::exception& e)
735 {
736 Logger::warn("[Game] runner_config blob malformed; keeping defaults: {}", e.what());
737 return;
738 }
739 if (!j.is_object())
740 {
741 Logger::warn("[Game] runner_config blob is not a JSON object; keeping defaults");
742 return;
743 }
744
745 runnerConfig.runnerType = jstr(j, "type");
746 runnerConfig.runnerVersion = jstr(j, "version");
747 runnerConfig.executablePath = jstr(j, "executablePath");
748 runnerConfig.workingDirectory = jstr(j, "workingDirectory");
749 runnerConfig.arguments = jstr(j, "arguments");
750
751 runnerConfig.winePrefix = jstr(j, "winePrefix");
752 runnerConfig.winePath = jstr(j, "winePath");
753 runnerConfig.wineDLL = jstr(j, "wineDLL");
754 runnerConfig.protonVersion = jstr(j, "protonVersion");
755 runnerConfig.useSteamDefaults = jbool(j, "useSteamDefaults", true);
756 runnerConfig.useSteamLaunch = jbool(j, "useSteamLaunch");
757
758 runnerConfig.enableMangoHud = jbool(j, "enableMangoHud");
759 runnerConfig.mangoHudConfigFile = jstr(j, "mangoHudConfigFile");
760 runnerConfig.enableGameMode = jbool(j, "enableGameMode");
761 runnerConfig.enableGamePerformance = jbool(j, "enableGamePerformance");
762 runnerConfig.enableVkBasalt = jbool(j, "enableVkBasalt");
763
764 runnerConfig.enableGamescope = jbool(j, "enableGamescope");
765 runnerConfig.gamescopeWidth = jint(j, "gamescopeWidth", 0);
766 runnerConfig.gamescopeHeight = jint(j, "gamescopeHeight", 0);
767 runnerConfig.gamescopeInternalWidth = jint(j, "gamescopeInternalWidth", 0);
768 runnerConfig.gamescopeInternalHeight = jint(j, "gamescopeInternalHeight", 0);
769 runnerConfig.gamescopeRefreshRate = jint(j, "gamescopeRefreshRate", 0);
770 runnerConfig.gamescopeFullscreen = jbool(j, "gamescopeFullscreen", true);
771 runnerConfig.gamescopeBorderless = jbool(j, "gamescopeBorderless");
772 runnerConfig.gamescopeEnableFSR = jbool(j, "gamescopeEnableFSR");
773 runnerConfig.gamescopeFSRSharpness = jint(j, "gamescopeFSRSharpness", 5);
774 runnerConfig.gamescopeEnableVRR = jbool(j, "gamescopeEnableVRR");
775 runnerConfig.gamescopeEnableHDR = jbool(j, "gamescopeEnableHDR");
776 runnerConfig.gamescopeEnableITM = jbool(j, "gamescopeEnableITM");
777 runnerConfig.gamescopeITMSDRNits = jint(j, "gamescopeITMSDRNits", 0);
778 runnerConfig.gamescopeIntegerScaling = jbool(j, "gamescopeIntegerScaling");
779 runnerConfig.gamescopeForceGrabCursor = jbool(j, "gamescopeForceGrabCursor");
780
781 runnerConfig.enableFsync = jbool(j, "enableFsync", true);
782 runnerConfig.autoDetectSync = jbool(j, "autoDetectSync", true);
783
784 runnerConfig.enableDetailedLogging = jbool(j, "enableDetailedLogging");
785
786 runnerConfig.useVirtualDesktop = jbool(j, "useVirtualDesktop");
787 runnerConfig.virtualDesktopWidth = jint(j, "virtualDesktopWidth", 1920);
788 runnerConfig.virtualDesktopHeight = jint(j, "virtualDesktopHeight", 1080);
789
790 runnerConfig.excludeProcesses.clear();
791 if (auto it = j.find("excludeProcesses"); it != j.end() && it->is_array())
792 {
793 for (const auto& v : *it)
794 if (v.is_string())
795 runnerConfig.excludeProcesses.push_back(v.get<std::string>());
796 }
797
798 runnerConfig.environmentVariables.clear();
799 if (auto it = j.find("environmentVariables"); it != j.end() && it->is_array())
800 {
801 for (const auto& entry : *it)
802 {
803 if (!entry.is_object())
804 continue;
805 std::string key = jstr(entry, "k");
806 std::string val = jstr(entry, "v");
807 if (!key.empty())
808 runnerConfig.environmentVariables[key] = val;
809 }
810 }
811
812 // Capture any forward-compat keys we don't recognise so the next save()
813 // round-trips them cleanly. captureUnknownKeys returns "" if no extras.
814 runnerConfig.unknownJsonExtras = captureUnknownKeys(j, kKnownRunnerConfigKeys());
815}
816
817std::string Game::serializeMetadata() const
818{
819 gjson j;
820
821 // Deprecated paths (kept for backward compatibility with rows written
822 // before ImagePaths landed; readers prefer ImagePaths if both exist).
823 j["coverArtPath"] = metadata.coverArtPath;
824 j["bannerPath"] = metadata.bannerPath;
825
826 j["imagePaths"] = {
827 {"verticalCover", metadata.imagePaths.verticalCover},
828 {"heroImage", metadata.imagePaths.heroImage},
829 {"logo", metadata.imagePaths.logo},
830 {"header", metadata.imagePaths.header},
831 {"capsule", metadata.imagePaths.capsule},
832 {"icon", metadata.imagePaths.icon},
833 };
834
835 j["description"] = metadata.description;
836 j["genres"] = metadata.genres;
837 j["tags"] = metadata.tags;
838 j["developer"] = metadata.developer;
839 j["publisher"] = metadata.publisher;
840 j["releaseYear"] = metadata.releaseYear;
841 j["userRating"] = metadata.userRating;
842
843 j["isSteamGame"] = metadata.isSteamGame;
844 j["steamAppId"] = metadata.steamAppId;
845 j["steamInstalled"] = metadata.steamInstalled;
846 j["steamLaunchOptions"] = metadata.steamLaunchOptions;
847 j["steamBuildId"] = metadata.steamBuildId;
848 j["steamPlaytime2Weeks"] = metadata.steamPlaytime2Weeks;
849 j["steamLastLaunch"] = static_cast<int64_t>(metadata.steamLastLaunch);
850 j["steamLastExit"] = static_cast<int64_t>(metadata.steamLastExit);
851 j["steamType"] = metadata.steamType;
852 j["steamCategories"] = metadata.steamCategories;
853 j["steamUserCategories"] = metadata.steamUserCategories;
854
855 j["protondbTier"] = metadata.protondbTier;
856 j["protondbConfidence"] = metadata.protondbConfidence;
857 j["protondbScore"] = metadata.protondbScore;
858 j["protondbLastUpdated"] = static_cast<int64_t>(metadata.protondbLastUpdated);
859
860 j["cloudSave"] = {
861 {"enabled", metadata.cloudSave.enabled},
862 {"supported", metadata.cloudSave.supported},
863 {"lastSyncState", metadata.cloudSave.lastSyncState},
864 {"storageBytes", metadata.cloudSave.storageBytes},
865 {"lastSyncTime", static_cast<int64_t>(metadata.cloudSave.lastSyncTime)},
866 };
867
868 // DLC array. dlcCount is informational and recoverable from dlc.size(),
869 // but kept in the wire format for backward compatibility.
870 j["dlcCount"] = metadata.dlc.size();
871 gjson dlcArr = gjson::array();
872 for (const auto& dlc : metadata.dlc)
873 {
874 dlcArr.push_back({
875 {"appId", dlc.appId},
876 {"name", dlc.name},
877 {"installed", dlc.installed},
878 {"sizeBytes", dlc.sizeBytes},
879 });
880 }
881 j["dlc"] = std::move(dlcArr);
882
883 // Round-trip-preserve forward-compat keys.
884 mergeUnknownKeys(j, metadata.unknownJsonExtras);
885 return j.dump();
886}
887
888void Game::deserializeMetadata(const std::string& json)
889{
890 if (json.empty())
891 return;
892
893 gjson j;
894 try
895 {
896 j = gjson::parse(json);
897 }
898 catch (const gjson::exception& e)
899 {
900 Logger::warn("[Game] metadata blob malformed; keeping defaults: {}", e.what());
901 return;
902 }
903 if (!j.is_object())
904 {
905 Logger::warn("[Game] metadata blob is not a JSON object; keeping defaults");
906 return;
907 }
908
909 metadata.coverArtPath = jstr(j, "coverArtPath");
910 metadata.bannerPath = jstr(j, "bannerPath");
911
912 if (auto it = j.find("imagePaths"); it != j.end() && it->is_object())
913 {
914 const auto& ip = *it;
915 metadata.imagePaths.verticalCover = jstr(ip, "verticalCover");
916 metadata.imagePaths.heroImage = jstr(ip, "heroImage");
917 metadata.imagePaths.logo = jstr(ip, "logo");
918 metadata.imagePaths.header = jstr(ip, "header");
919 metadata.imagePaths.capsule = jstr(ip, "capsule");
920 metadata.imagePaths.icon = jstr(ip, "icon");
921 }
922
923 metadata.description = jstr(j, "description");
924 metadata.genres.clear();
925 if (auto it = j.find("genres"); it != j.end() && it->is_array())
926 for (const auto& v : *it)
927 if (v.is_string())
928 metadata.genres.push_back(v.get<std::string>());
929 metadata.tags.clear();
930 if (auto it = j.find("tags"); it != j.end() && it->is_array())
931 for (const auto& v : *it)
932 if (v.is_string())
933 metadata.tags.push_back(v.get<std::string>());
934
935 metadata.developer = jstr(j, "developer");
936 metadata.publisher = jstr(j, "publisher");
937 metadata.releaseYear = jint(j, "releaseYear");
938 metadata.userRating = static_cast<float>(jdouble(j, "userRating"));
939
940 metadata.isSteamGame = jbool(j, "isSteamGame");
941 metadata.steamAppId = jint(j, "steamAppId");
942 metadata.steamInstalled = jbool(j, "steamInstalled", true);
943 metadata.steamLaunchOptions = jstr(j, "steamLaunchOptions");
944 metadata.steamBuildId = jstr(j, "steamBuildId");
945 metadata.steamPlaytime2Weeks = static_cast<uint32_t>(jint(j, "steamPlaytime2Weeks"));
946 metadata.steamLastLaunch = static_cast<time_t>(jint64(j, "steamLastLaunch"));
947 metadata.steamLastExit = static_cast<time_t>(jint64(j, "steamLastExit"));
948 metadata.steamType = jstr(j, "steamType");
949 metadata.steamCategories.clear();
950 if (auto it = j.find("steamCategories"); it != j.end() && it->is_array())
951 for (const auto& v : *it)
952 if (v.is_string())
953 metadata.steamCategories.push_back(v.get<std::string>());
954 metadata.steamUserCategories.clear();
955 if (auto it = j.find("steamUserCategories"); it != j.end() && it->is_array())
956 for (const auto& v : *it)
957 if (v.is_string())
958 metadata.steamUserCategories.push_back(v.get<std::string>());
959
960 metadata.protondbTier = jstr(j, "protondbTier");
961 metadata.protondbConfidence = jstr(j, "protondbConfidence");
962 metadata.protondbScore = static_cast<float>(jdouble(j, "protondbScore"));
963 metadata.protondbLastUpdated = static_cast<time_t>(jint64(j, "protondbLastUpdated"));
964
965 if (auto it = j.find("cloudSave"); it != j.end() && it->is_object())
966 {
967 const auto& cs = *it;
968 metadata.cloudSave.enabled = jbool(cs, "enabled");
969 metadata.cloudSave.supported = jbool(cs, "supported");
970 metadata.cloudSave.lastSyncState = jint(cs, "lastSyncState");
971 metadata.cloudSave.storageBytes = static_cast<uint64_t>(jint64(cs, "storageBytes"));
972 metadata.cloudSave.lastSyncTime = static_cast<time_t>(jint64(cs, "lastSyncTime"));
973 }
974
975 metadata.dlc.clear();
976 if (auto it = j.find("dlc"); it != j.end() && it->is_array())
977 {
978 for (const auto& entry : *it)
979 {
980 if (!entry.is_object())
981 continue;
982 DLCInfo dlc;
983 dlc.appId = jint(entry, "appId");
984 dlc.name = jstr(entry, "name");
985 dlc.installed = jbool(entry, "installed");
986 dlc.sizeBytes = static_cast<uint64_t>(jint64(entry, "sizeBytes"));
987 if (dlc.appId > 0 || !dlc.name.empty())
988 metadata.dlc.push_back(std::move(dlc));
989 }
990 }
991
992 metadata.unknownJsonExtras = captureUnknownKeys(j, kKnownMetadataKeys());
993}
994
995// ==============================================================================
996// ActualRuntimeInfo - Read from /proc
997// ==============================================================================
998
1000{
1001 ActualRuntimeInfo info;
1002 info.pid = processId;
1003
1004 if (processId <= 0)
1005 {
1006 return info;
1007 }
1008
1009 // Read /proc/<pid>/environ
1010 std::string environPath = "/proc/" + std::to_string(processId) + "/environ";
1011 std::ifstream environFile(environPath, std::ios::binary);
1012 if (environFile.is_open())
1013 {
1014 std::string content((std::istreambuf_iterator<char>(environFile)),
1015 std::istreambuf_iterator<char>());
1016 environFile.close();
1017
1018 // Parse null-separated key=value pairs
1019 size_t start = 0;
1020 while (start < content.size())
1021 {
1022 size_t end = content.find('\0', start);
1023 if (end == std::string::npos)
1024 end = content.size();
1025
1026 std::string entry = content.substr(start, end - start);
1027 size_t eqPos = entry.find('=');
1028 if (eqPos != std::string::npos)
1029 {
1030 std::string key = entry.substr(0, eqPos);
1031 std::string value = entry.substr(eqPos + 1);
1032 info.envVars[key] = value;
1033 }
1034
1035 start = end + 1;
1036 }
1037 }
1038
1039 // Read /proc/<pid>/cmdline
1040 std::string cmdlinePath = "/proc/" + std::to_string(processId) + "/cmdline";
1041 std::ifstream cmdlineFile(cmdlinePath, std::ios::binary);
1042 if (cmdlineFile.is_open())
1043 {
1044 std::string content((std::istreambuf_iterator<char>(cmdlineFile)),
1045 std::istreambuf_iterator<char>());
1046 cmdlineFile.close();
1047
1048 // Replace null separators with spaces for readability
1049 for (char& c : content)
1050 {
1051 if (c == '\0')
1052 c = ' ';
1053 }
1054 // Trim trailing space
1055 while (!content.empty() && content.back() == ' ')
1056 content.pop_back();
1057
1058 info.commandLine = content;
1059 }
1060
1061 // Valid if we got at least the environment or command line
1062 info.valid = !info.envVars.empty() || !info.commandLine.empty();
1063
1064 return info;
1065}
1066
1067std::map<std::string, std::string> ActualRuntimeInfo::getKeyEnvironment() const
1068{
1069 std::map<std::string, std::string> result;
1070 const auto& keys = getKeyEnvVars();
1071
1072 for (const auto& key : keys)
1073 {
1074 auto it = envVars.find(key);
1075 if (it != envVars.end())
1076 {
1077 result[key] = it->second;
1078 }
1079 }
1080
1081 return result;
1082}
1083
1084std::vector<std::string>
1085ActualRuntimeInfo::compareWithConfigured(const std::vector<std::string>& configured) const
1086{
1087 std::vector<std::string> differences;
1088
1089 // Build map of configured env vars
1090 std::map<std::string, std::string> configuredMap;
1091 for (const auto& entry : configured)
1092 {
1093 size_t eqPos = entry.find('=');
1094 if (eqPos != std::string::npos)
1095 {
1096 configuredMap[entry.substr(0, eqPos)] = entry.substr(eqPos + 1);
1097 }
1098 }
1099
1100 // Check each configured var against actual
1101 for (const auto& [key, expectedValue] : configuredMap)
1102 {
1103 auto actualIt = envVars.find(key);
1104 if (actualIt == envVars.end())
1105 {
1106 differences.push_back(key + ": MISSING (expected '" + expectedValue + "')");
1107 }
1108 else if (actualIt->second != expectedValue)
1109 {
1110 differences.push_back(key + ": MISMATCH expected '" + expectedValue + "', actual '" +
1111 actualIt->second + "'");
1112 }
1113 }
1114
1115 // Also check for key gaming vars that are set but weren't configured
1116 const auto& keyVars = getKeyEnvVars();
1117 for (const auto& key : keyVars)
1118 {
1119 if (configuredMap.find(key) == configuredMap.end())
1120 {
1121 auto actualIt = envVars.find(key);
1122 if (actualIt != envVars.end())
1123 {
1124 differences.push_back(key + ": EXTRA (not configured, actual '" + actualIt->second +
1125 "')");
1126 }
1127 }
1128 }
1129
1130 return differences;
1131}
std::string publisherLowerCache_
Cached lowercase publisher for case-insensitive search (computed on first access).
Definition game.h:831
std::string nameLowerCache_
Cached lowercase name for case-insensitive search (computed on first access).
Definition game.h:827
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
std::string getPlatformName() const
Get human-readable platform name.
Definition game.cpp:68
void deserializeMetadata(const std::string &json)
Deserialize metadata from JSON.
Definition game.cpp:888
std::vector< PlaySession > recentSessions
Recent play sessions (last 20 kept in memory).
Definition game.h:811
std::string getFormattedInstallSize() const
Format install size as human-readable string.
Definition game.cpp:144
CompletionStatus completionStatus
User's completion status.
Definition game.h:810
bool cacheInitialized_
True if caches have been computed.
Definition game.h:835
const std::string & getDeveloperLower() const
Get lowercase developer (cached for performance).
Definition game.cpp:190
std::string name
Display name shown in UI.
Definition game.h:774
const std::string & getNameLower() const
Get lowercase name (cached for performance).
Definition game.cpp:176
std::string getSourceName() const
Get human-readable source name.
Definition game.cpp:25
std::string serializeRunnerConfig() const
Serialize runner configuration to JSON.
Definition game.cpp:647
std::string descriptionLowerCache_
Cached lowercase description for case-insensitive search (computed on first access).
Definition game.h:833
GameStatistics statistics
Play statistics and usage tracking.
Definition game.h:786
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
double getAverageSessionDuration() const
Get average session duration for this game.
Definition game.cpp:367
const std::string & getPublisherLower() const
Get lowercase publisher (cached for performance).
Definition game.cpp:199
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
std::string getFormattedPlayTime() const
Format total play time as human-readable string.
Definition game.cpp:114
std::string getCompletionStatusName() const
Get human-readable completion status name.
Definition game.cpp:286
GameStatus status
Current installation and execution status.
Definition game.h:778
std::string getStatusName() const
Get human-readable status name.
Definition game.cpp:95
HowLongToBeatInfo hltbInfo
Time-to-beat estimates.
Definition game.h:812
uint64_t installSizeBytes
Installation size in bytes.
Definition game.h:820
std::string developerLowerCache_
Cached lowercase developer for case-insensitive search (computed on first access).
Definition game.h:829
double getRemainingPlaytime(int targetStyle=0) const
Get estimated remaining playtime based on HLTB data.
Definition game.cpp:309
std::string serializeMetadata() const
Serialize metadata to JSON.
Definition game.cpp:817
void deserializeRunnerConfig(const std::string &json)
Deserialize runner configuration from JSON.
Definition game.cpp:724
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
double getCompletionPercentage(int targetStyle=0) const
Get completion percentage based on HLTB estimate.
Definition game.cpp:338
std::string getRunnerName() const
Get human-readable runner name.
Definition game.cpp:49
std::string getImagePath(ImageType type) const
Get path for a specific image type.
Definition game.cpp:221
const std::string & getDescriptionLower() const
Get lowercase description (cached for performance).
Definition game.cpp:208
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
nlohmann::json gjson
Definition game.cpp:19
static std::string toLower(const std::string &str)
Definition game.cpp:166
@ Steam
Steam store/platform.
Definition game.h:41
@ Local
Manually added game (not from a store).
Definition game.h:40
@ Itch
itch.io indie games
Definition game.h:44
@ Lutris
Lutris community scripts.
Definition game.h:45
@ Unknown
Unknown or unspecified source.
Definition game.h:47
@ GOG
GOG.com (DRM-free games).
Definition game.h:42
@ Flatpak
Flatpak package.
Definition game.h:46
@ Epic
Epic Games Store.
Definition game.h:43
@ ScummVM
ScummVM game (adventure game engine).
Definition game.h:69
@ RetroArch
RetroArch/emulated game (console emulation).
Definition game.h:70
@ Steam
Steam game (launched via Steam client).
Definition game.h:65
@ Proton
Windows game via Proton (Steam's Wine fork).
Definition game.h:64
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:62
@ GOG
GOG game (DRM-free game from GOG.com).
Definition game.h:66
@ Wine
Windows game via Wine compatibility layer.
Definition game.h:63
@ Epic
Epic Games Store game.
Definition game.h:67
@ DOSBox
DOS game via DOSBox emulator.
Definition game.h:68
ImageType
Types of game images available.
Definition game.h:478
@ HeroImage
Wide banner/hero image (landscape).
Definition game.h:480
@ Capsule
Store capsule image (616x353).
Definition game.h:483
@ VerticalCover
Vertical cover art (600x900, portrait).
Definition game.h:479
@ Icon
Small square icon.
Definition game.h:484
@ Logo
Game logo with transparency (PNG).
Definition game.h:481
@ Header
Small header image (460x215).
Definition game.h:482
@ Installing
Game is being installed.
Definition game.h:103
@ NotInstalled
Game is in library but not installed.
Definition game.h:98
@ Running
Game is currently running.
Definition game.h:101
@ Updating
Game is being updated.
Definition game.h:104
@ Installed
Game is installed and ready to play.
Definition game.h:99
@ ScummVM
ScummVM engine.
Definition game.h:86
@ Proton
Proton (Steam's Wine fork).
Definition game.h:84
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:82
@ Wine
Wine compatibility layer.
Definition game.h:83
@ DOSBox
DOSBox emulator.
Definition game.h:85
@ Played
Played but no clear completion criteria (e.g., multiplayer).
Definition game.h:122
@ Completed
100% completion (achievements, side content, etc.)
Definition game.h:119
@ Abandoned
Stopped playing, unlikely to return.
Definition game.h:121
@ Beaten
Main story/campaign completed.
Definition game.h:118
@ OnHold
Temporarily paused.
Definition game.h:120
@ Playing
Currently playing.
Definition game.h:117
@ NotPlayed
Never played (backlog).
Definition game.h:116
nlohmann::json json
int64_t jint64(const gjson &j, const char *key, int64_t def=0)
Definition game.cpp:594
const std::set< std::string > & kKnownMetadataKeys()
Definition game.cpp:525
double jdouble(const gjson &j, const char *key, double def=0.0)
Definition game.cpp:580
const std::set< std::string > & kKnownRunnerConfigKeys()
Set of keys that the typed struct knows about.
Definition game.cpp:478
std::string captureUnknownKeys(const gjson &src, const std::set< std::string > &known)
Extract any keys not in known into a JSON object string.
Definition game.cpp:605
void mergeUnknownKeys(gjson &dst, const std::string &extrasStr)
Inverse of captureUnknownKeys: merge stashed unknowns into the JSON object we're about to serialise.
Definition game.cpp:624
int jint(const gjson &j, const char *key, int def=0)
Definition game.cpp:571
std::string jstr(const gjson &j, const char *key, const char *def="")
Type-tolerant getter helpers — return defaultVal when the key is missing or the value is the wrong ty...
Definition game.cpp:564
bool jbool(const gjson &j, const char *key, bool def=false)
Definition game.cpp:587
Actual environment and command line read from a running process.
Definition game.h:379
static const std::vector< std::string > & getKeyEnvVars()
Definition game.h:386
std::vector< std::string > compareWithConfigured(const std::vector< std::string > &configured) const
Compare configured vs actual environment.
Definition game.cpp:1085
int pid
Process ID this info was read from.
Definition game.h:380
static ActualRuntimeInfo readFromProcess(int processId)
Read actual runtime info from a process.
Definition game.cpp:999
std::map< std::string, std::string > envVars
All environment variables.
Definition game.h:382
std::map< std::string, std::string > getKeyEnvironment() const
Get only gaming-related environment variables.
Definition game.cpp:1067
std::string commandLine
Full command line from /proc/pid/cmdline.
Definition game.h:381
bool valid
Whether the read was successful.
Definition game.h:383
Information about downloadable content (DLC).
Definition game.h:536
int appId
Steam App ID of the DLC.
Definition game.h:537
bool installed
True if DLC is installed.
Definition game.h:539
uint64_t sizeBytes
Installation size in bytes.
Definition game.h:540
std::string name
DLC display name.
Definition game.h:538
bool isStale() const
Check if data is stale (older than 30 days).
Definition game.cpp:419
time_t lastUpdated
When this data was fetched.
Definition game.h:683
static std::string formatHours(double hours)
Get formatted time string for a playstyle.
Definition game.cpp:429
std::string getFormattedDuration() const
Get formatted duration string.
Definition game.cpp:391
double durationSeconds
Session duration in seconds.
Definition game.h:634