game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
performance_profile_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// performance_profile_service.cpp
4// ==============================================================================
5// Per-Game Performance Profile Management Implementation
6// ==============================================================================
7
9#include "logger.h"
10
11#include <algorithm>
12#include <ctime>
13#include <filesystem>
14#include <fstream>
15#include <iomanip>
16#include <sstream>
17#include <utility>
18#include <uuid/uuid.h>
19
20namespace fs = std::filesystem;
21
22// ==============================================================================
23// Helper Functions
24// ==============================================================================
25
26static std::string generateUUID()
27{
28 uuid_t uuid;
29 uuid_generate(uuid);
30 char str[37];
31 uuid_unparse_lower(uuid, str);
32 return std::string(str);
33}
34
35// Simple JSON escaping
36static std::string jsonEscape(const std::string& str);
37
38// ---- JSON parsing helpers (work on raw text produced by saveGameProfiles) ----
39
40// Extract string value for "key": "value" within [start, end) of json
41static std::string jsonParseStr(const std::string& json, const std::string& key, size_t start = 0,
42 size_t end = std::string::npos)
43{
44 if (end == std::string::npos)
45 end = json.size();
46 std::string needle = "\"" + key + "\": \"";
47 size_t pos = json.find(needle, start);
48 if (pos == std::string::npos || pos >= end)
49 return "";
50 size_t vs = pos + needle.size();
51 size_t ve = vs;
52 while (ve < end)
53 {
54 if (json[ve] == '\\')
55 {
56 ve += 2;
57 continue;
58 }
59 if (json[ve] == '"')
60 break;
61 ++ve;
62 }
63 return json.substr(vs, ve - vs);
64}
65
66// Extract integer value for "key": N within [start, end)
67// Parse a 64-bit integer value. Used for time_t (Unix timestamp) fields:
68// std::stoi is 32-bit and throws std::out_of_range on any timestamp past
69// 2038-01-19 (Y2038), which would silently collapse to the default.
70static long long jsonParseLong(const std::string& json, const std::string& key, size_t start = 0,
71 size_t end = std::string::npos, long long def = 0)
72{
73 if (end == std::string::npos)
74 end = json.size();
75 std::string needle = "\"" + key + "\": ";
76 size_t pos = json.find(needle, start);
77 if (pos == std::string::npos || pos >= end)
78 return def;
79 size_t vs = pos + needle.size();
80 try
81 {
82 return std::stoll(json.substr(vs, end - vs));
83 }
84 catch (...)
85 {
86 return def;
87 }
88}
89
90static int jsonParseInt(const std::string& json, const std::string& key, size_t start = 0,
91 size_t end = std::string::npos, int def = 0)
92{
93 if (end == std::string::npos)
94 end = json.size();
95 std::string needle = "\"" + key + "\": ";
96 size_t pos = json.find(needle, start);
97 if (pos == std::string::npos || pos >= end)
98 return def;
99 size_t vs = pos + needle.size();
100 try
101 {
102 return std::stoi(json.substr(vs, end - vs));
103 }
104 catch (...)
105 {
106 return def;
107 }
108}
109
110// Extract double value for "key": N within [start, end)
111static double jsonParseDouble(const std::string& json, const std::string& key, size_t start = 0,
112 size_t end = std::string::npos, double def = 0.0)
113{
114 if (end == std::string::npos)
115 end = json.size();
116 std::string needle = "\"" + key + "\": ";
117 size_t pos = json.find(needle, start);
118 if (pos == std::string::npos || pos >= end)
119 return def;
120 size_t vs = pos + needle.size();
121 try
122 {
123 return std::stod(json.substr(vs, end - vs));
124 }
125 catch (...)
126 {
127 return def;
128 }
129}
130
131// Extract boolean value for "key": true/false within [start, end)
132static bool jsonParseBool(const std::string& json, const std::string& key, size_t start = 0,
133 size_t end = std::string::npos, bool def = false)
134{
135 if (end == std::string::npos)
136 end = json.size();
137 std::string needle = "\"" + key + "\": ";
138 size_t pos = json.find(needle, start);
139 if (pos == std::string::npos || pos >= end)
140 return def;
141 size_t vs = pos + needle.size();
142 if (vs + 4 <= end && json.compare(vs, 4, "true") == 0)
143 return true;
144 if (vs + 5 <= end && json.compare(vs, 5, "false") == 0)
145 return false;
146 return def;
147}
148
149// Return [objStart, objEnd) of the object following "key": { within [start, end)
150// Returns {npos, npos} if not found
151static std::pair<size_t, size_t> jsonFindObject(const std::string& json, const std::string& key,
152 size_t start = 0, size_t end = std::string::npos)
153{
154 if (end == std::string::npos)
155 end = json.size();
156 std::string needle = "\"" + key + "\": {";
157 size_t pos = json.find(needle, start);
158 if (pos == std::string::npos || pos >= end)
159 return {std::string::npos, std::string::npos};
160 size_t objStart = pos + needle.size() - 1; // points at opening '{'
161 int depth = 1;
162 size_t i = objStart + 1;
163 while (i < end && depth > 0)
164 {
165 if (json[i] == '{')
166 ++depth;
167 else if (json[i] == '}')
168 --depth;
169 ++i;
170 }
171 return {objStart, i}; // [objStart, i) includes { and }
172}
173
174// Parse a PerformanceProfile from JSON object text spanning [ps, pe)
175static PerformanceProfile jsonParseProfile(const std::string& json, size_t ps, size_t pe)
176{
178 p.id = jsonParseStr(json, "id", ps, pe);
179 p.name = jsonParseStr(json, "name", ps, pe);
180 p.description = jsonParseStr(json, "description", ps, pe);
181 // Range-validate the preset before casting to the enum (values 0..6 =
182 // Custom..Silent); a corrupt/out-of-range value falls back to Custom.
183 const int presetRaw = jsonParseInt(json, "preset", ps, pe, 0);
184 p.preset = (presetRaw >= static_cast<int>(PerformancePreset::Custom) &&
185 presetRaw <= static_cast<int>(PerformancePreset::Silent))
186 ? static_cast<PerformancePreset>(presetRaw)
188 // 64-bit parse so timestamps past 2038 are preserved (Y2038).
189 p.createdAt = static_cast<time_t>(jsonParseLong(json, "createdAt", ps, pe, 0));
190 p.lastUsedAt = static_cast<time_t>(jsonParseLong(json, "lastUsedAt", ps, pe, 0));
191 p.useCount = jsonParseInt(json, "useCount", ps, pe, 0);
192
193 auto [frs, fre] = jsonFindObject(json, "framerate", ps, pe);
194 if (frs != std::string::npos)
195 {
196 p.framerate.fpsLimit = jsonParseInt(json, "fpsLimit", frs, fre, 0);
197 p.framerate.refreshRate = jsonParseInt(json, "refreshRate", frs, fre, 0);
198 p.framerate.enableVRR = jsonParseBool(json, "enableVRR", frs, fre, false);
199 p.framerate.useGamescope = jsonParseBool(json, "useGamescope", frs, fre, false);
200 }
201
202 auto [scs, sce] = jsonFindObject(json, "scaling", ps, pe);
203 if (scs != std::string::npos)
204 {
205 p.scaling.internalWidth = jsonParseInt(json, "internalWidth", scs, sce, 0);
206 p.scaling.internalHeight = jsonParseInt(json, "internalHeight", scs, sce, 0);
207 p.scaling.enableFSR = jsonParseBool(json, "enableFSR", scs, sce, false);
208 p.scaling.fsrSharpness = jsonParseInt(json, "fsrSharpness", scs, sce, 5);
209 }
210
211 auto [wrs, wre] = jsonFindObject(json, "wrappers", ps, pe);
212 if (wrs != std::string::npos)
213 {
214 p.wrappers.enableMangoHud = jsonParseBool(json, "enableMangoHud", wrs, wre, false);
215 p.wrappers.enableGameMode = jsonParseBool(json, "enableGameMode", wrs, wre, false);
217 jsonParseBool(json, "enableGamePerformance", wrs, wre, false);
218 p.wrappers.enableVkBasalt = jsonParseBool(json, "enableVkBasalt", wrs, wre, false);
219 }
220
221 auto [sns, sne] = jsonFindObject(json, "sync", ps, pe);
222 if (sns != std::string::npos)
223 {
224 p.sync.autoDetect = jsonParseBool(json, "autoDetect", sns, sne, true);
225 p.sync.enableFsync = jsonParseBool(json, "enableFsync", sns, sne, true);
226 p.sync.enableEsync = jsonParseBool(json, "enableEsync", sns, sne, true);
227 p.sync.enableNTSync = jsonParseBool(json, "enableNTSync", sns, sne, false);
228 }
229
230 return p;
231}
232
233// Simple JSON escaping (definition follows declaration above)
234static std::string jsonEscape(const std::string& str)
235{
236 std::string result;
237 result.reserve(str.size() + 10);
238 for (char c : str)
239 {
240 switch (c)
241 {
242 case '"':
243 result += "\\\"";
244 break;
245 case '\\':
246 result += "\\\\";
247 break;
248 case '\n':
249 result += "\\n";
250 break;
251 case '\r':
252 result += "\\r";
253 break;
254 case '\t':
255 result += "\\t";
256 break;
257 default:
258 result += c;
259 }
260 }
261 return result;
262}
263
264// ==============================================================================
265// Implementation
266// ==============================================================================
267
269{
270 public:
271 Impl() = default;
272
273 bool initialize(const std::string& dataDir)
274 {
275 dataDir_ = dataDir;
276
277 // Create data directories
278 try
279 {
280 fs::create_directories(dataDir_);
281 fs::create_directories(dataDir_ + "/profiles");
282 fs::create_directories(dataDir_ + "/global");
283 }
284 catch (const std::exception& e)
285 {
286 Logger::error("Failed to create profile directories: {}", e.what());
287 return false;
288 }
289
290 // Load existing profiles
293
294 initialized_ = true;
295 return true;
296 }
297
299 {
300 std::string profilesDir = dataDir_ + "/profiles";
301 if (!fs::exists(profilesDir))
302 return;
303
304 try
305 {
306 for (const auto& entry : fs::directory_iterator(profilesDir))
307 {
308 if (entry.is_regular_file() && entry.path().extension() == ".json")
309 {
310 loadGameProfiles(entry.path().stem().string());
311 }
312 }
313 }
314 catch (const std::exception& e)
315 {
316 Logger::warn("Error loading profiles: {}", e.what());
317 }
318 }
319
320 void loadGameProfiles(const std::string& gameId)
321 {
322 fs::path gameIdPath(gameId);
323 if (gameIdPath.is_absolute())
324 {
325 Logger::error("[PerfProfile] Rejected absolute gameId: {}", gameId);
326 return;
327 }
328 for (const auto& component : gameIdPath)
329 {
330 if (component == "..")
331 {
332 Logger::error("[PerfProfile] Rejected gameId with path traversal: {}", gameId);
333 return;
334 }
335 }
336 std::string filePath = dataDir_ + "/profiles/" + gameId + ".json";
337 if (!fs::exists(filePath))
338 return;
339
340 std::ifstream file(filePath);
341 if (!file.is_open())
342 return;
343
344 std::stringstream buffer;
345 buffer << file.rdbuf();
346 std::string json = buffer.str();
347
348 // Parse JSON (simplified parser)
350 data.gameId = gameId;
351
352 // Extract top-level scalar fields
353 data.activeProfileId = jsonParseStr(json, "activeProfileId");
354 data.avgFps = jsonParseDouble(json, "avgFps");
355 data.avgFrametime = jsonParseDouble(json, "avgFrametime");
356 data.sessionCount = jsonParseInt(json, "sessionCount");
357
358 // Parse the profiles array: find "profiles": [ ... ]
359 size_t arrStart = json.find("\"profiles\": [");
360 if (arrStart != std::string::npos)
361 {
362 size_t bracket = json.find('[', arrStart);
363 int depth = 1;
364 size_t i = bracket + 1;
365 while (i < json.size() && depth > 0)
366 {
367 if (json[i] == '{' && depth == 1)
368 {
369 // Found start of a profile object — find its matching '}'
370 size_t objStart = i;
371 int objDepth = 1;
372 size_t j = objStart + 1;
373 while (j < json.size() && objDepth > 0)
374 {
375 if (json[j] == '{')
376 ++objDepth;
377 else if (json[j] == '}')
378 --objDepth;
379 ++j;
380 }
381 // [objStart, j) is the profile object
382 PerformanceProfile p = jsonParseProfile(json, objStart, j);
383 if (!p.id.empty())
384 data.profiles.push_back(std::move(p));
385 i = j;
386 continue;
387 }
388 if (json[i] == '[')
389 ++depth;
390 else if (json[i] == ']')
391 --depth;
392 ++i;
393 }
394 }
395
396 gameProfiles_[gameId] = data;
397 }
398
400 {
401 std::string globalDir = dataDir_ + "/global";
402 if (!fs::exists(globalDir))
403 return;
404
405 try
406 {
407 for (const auto& entry : fs::directory_iterator(globalDir))
408 {
409 if (!entry.is_regular_file() || entry.path().extension() != ".json")
410 continue;
411
412 std::ifstream gf(entry.path());
413 if (!gf.is_open())
414 continue;
415 std::stringstream gbuf;
416 gbuf << gf.rdbuf();
417 std::string gjson = gbuf.str();
418
420 if (!p.id.empty())
421 globalProfiles_.push_back(std::move(p));
422 }
423 }
424 catch (const std::exception& e)
425 {
426 Logger::warn("Error loading global profiles: {}", e.what());
427 }
428 }
429
430 bool saveGameProfiles(const std::string& gameId)
431 {
432 auto it = gameProfiles_.find(gameId);
433 if (it == gameProfiles_.end())
434 return false;
435
436 fs::path gameIdPath(gameId);
437 if (gameIdPath.is_absolute())
438 {
439 Logger::error("[PerfProfile] Rejected absolute gameId: {}", gameId);
440 return false;
441 }
442 for (const auto& component : gameIdPath)
443 {
444 if (component == "..")
445 {
446 Logger::error("[PerfProfile] Rejected gameId with path traversal: {}", gameId);
447 return false;
448 }
449 }
450 const auto& data = it->second;
451 std::string filePath = dataDir_ + "/profiles/" + gameId + ".json";
452
453 std::ofstream file(filePath);
454 if (!file.is_open())
455 {
456 Logger::error("Failed to save profiles for game {}", gameId);
457 return false;
458 }
459
460 // Write JSON
461 file << "{\n";
462 file << " \"gameId\": \"" << jsonEscape(gameId) << "\",\n";
463 file << " \"activeProfileId\": \"" << jsonEscape(data.activeProfileId) << "\",\n";
464 file << " \"avgFps\": " << data.avgFps << ",\n";
465 file << " \"avgFrametime\": " << data.avgFrametime << ",\n";
466 file << " \"sessionCount\": " << data.sessionCount << ",\n";
467 file << " \"profiles\": [\n";
468
469 for (size_t i = 0; i < data.profiles.size(); ++i)
470 {
471 const auto& p = data.profiles[i];
472 file << " {\n";
473 file << " \"id\": \"" << jsonEscape(p.id) << "\",\n";
474 file << " \"name\": \"" << jsonEscape(p.name) << "\",\n";
475 file << " \"description\": \"" << jsonEscape(p.description) << "\",\n";
476 file << " \"preset\": " << static_cast<int>(p.preset) << ",\n";
477
478 // Framerate settings
479 file << " \"framerate\": {\n";
480 file << " \"fpsLimit\": " << p.framerate.fpsLimit << ",\n";
481 file << " \"refreshRate\": " << p.framerate.refreshRate << ",\n";
482 file << " \"enableVRR\": " << (p.framerate.enableVRR ? "true" : "false")
483 << ",\n";
484 file << " \"useGamescope\": " << (p.framerate.useGamescope ? "true" : "false")
485 << "\n";
486 file << " },\n";
487
488 // Scaling settings
489 file << " \"scaling\": {\n";
490 file << " \"internalWidth\": " << p.scaling.internalWidth << ",\n";
491 file << " \"internalHeight\": " << p.scaling.internalHeight << ",\n";
492 file << " \"enableFSR\": " << (p.scaling.enableFSR ? "true" : "false") << ",\n";
493 file << " \"fsrSharpness\": " << p.scaling.fsrSharpness << "\n";
494 file << " },\n";
495
496 // Wrapper settings
497 file << " \"wrappers\": {\n";
498 file << " \"enableMangoHud\": " << (p.wrappers.enableMangoHud ? "true" : "false")
499 << ",\n";
500 file << " \"enableGameMode\": " << (p.wrappers.enableGameMode ? "true" : "false")
501 << ",\n";
502 file << " \"enableGamePerformance\": "
503 << (p.wrappers.enableGamePerformance ? "true" : "false") << ",\n";
504 file << " \"enableVkBasalt\": " << (p.wrappers.enableVkBasalt ? "true" : "false")
505 << "\n";
506 file << " },\n";
507
508 // Sync settings
509 file << " \"sync\": {\n";
510 file << " \"autoDetect\": " << (p.sync.autoDetect ? "true" : "false") << ",\n";
511 file << " \"enableFsync\": " << (p.sync.enableFsync ? "true" : "false") << ",\n";
512 file << " \"enableEsync\": " << (p.sync.enableEsync ? "true" : "false") << ",\n";
513 file << " \"enableNTSync\": " << (p.sync.enableNTSync ? "true" : "false")
514 << "\n";
515 file << " },\n";
516
517 file << " \"createdAt\": " << p.createdAt << ",\n";
518 file << " \"lastUsedAt\": " << p.lastUsedAt << ",\n";
519 file << " \"useCount\": " << p.useCount << "\n";
520 file << " }";
521 if (i < data.profiles.size() - 1)
522 file << ",";
523 file << "\n";
524 }
525
526 file << " ]\n";
527 file << "}\n";
528
529 return true;
530 }
531
532 bool initialized_ = false;
533 std::string dataDir_;
534 std::map<std::string, GamePerformanceData> gameProfiles_;
535 std::vector<PerformanceProfile> globalProfiles_;
537};
538
539// ==============================================================================
540// Public Interface Implementation
541// ==============================================================================
542
544
546
547bool PerformanceProfileService::initialize(const std::string& dataDir)
548{
549 return impl_->initialize(dataDir);
550}
551
553{
554 return impl_->initialized_;
555}
556
557bool PerformanceProfileService::createProfile(const std::string& gameId,
558 const PerformanceProfile& profile)
559{
560 if (!impl_->initialized_)
561 return false;
562
563 // Get or create game data
564 auto& data = impl_->gameProfiles_[gameId];
565 data.gameId = gameId;
566
567 // Check for duplicate name
568 for (const auto& existing : data.profiles)
569 {
570 if (existing.name == profile.name)
571 {
572 Logger::warn("Profile with name '{}' already exists for game {}", profile.name, gameId);
573 return false;
574 }
575 }
576
577 // Create profile with generated ID if not set
578 PerformanceProfile newProfile = profile;
579 if (newProfile.id.empty())
580 {
581 newProfile.id = generateUUID();
582 }
583 newProfile.createdAt = std::time(nullptr);
584
585 data.profiles.push_back(newProfile);
586
587 // Set as active if it's the first profile
588 if (data.profiles.size() == 1 && data.activeProfileId.empty())
589 {
590 data.activeProfileId = newProfile.id;
591 }
592
593 // Save
594 bool saved = impl_->saveGameProfiles(gameId);
595
596 if (saved && impl_->onProfileChanged_)
597 {
598 impl_->onProfileChanged_(gameId, newProfile.id);
599 }
600
601 return saved;
602}
603
604bool PerformanceProfileService::updateProfile(const std::string& gameId,
605 const PerformanceProfile& profile)
606{
607 if (!impl_->initialized_)
608 return false;
609
610 auto it = impl_->gameProfiles_.find(gameId);
611 if (it == impl_->gameProfiles_.end())
612 return false;
613
614 auto& data = it->second;
615 for (auto& existing : data.profiles)
616 {
617 if (existing.id == profile.id)
618 {
619 existing = profile;
620 return impl_->saveGameProfiles(gameId);
621 }
622 }
623
624 return false;
625}
626
627bool PerformanceProfileService::deleteProfile(const std::string& gameId,
628 const std::string& profileId)
629{
630 if (!impl_->initialized_)
631 return false;
632
633 auto it = impl_->gameProfiles_.find(gameId);
634 if (it == impl_->gameProfiles_.end())
635 return false;
636
637 auto& data = it->second;
638 auto profileIt =
639 std::find_if(data.profiles.begin(), data.profiles.end(),
640 [&profileId](const PerformanceProfile& p) { return p.id == profileId; });
641
642 if (profileIt == data.profiles.end())
643 return false;
644
645 // Don't allow deleting the only profile
646 if (data.profiles.size() == 1)
647 {
648 Logger::warn("Cannot delete the last profile for game {}", gameId);
649 return false;
650 }
651
652 // If deleting active profile, switch to another
653 if (data.activeProfileId == profileId)
654 {
655 for (const auto& p : data.profiles)
656 {
657 if (p.id != profileId)
658 {
659 data.activeProfileId = p.id;
660 break;
661 }
662 }
663 }
664
665 data.profiles.erase(profileIt);
666 return impl_->saveGameProfiles(gameId);
667}
668
669std::string PerformanceProfileService::duplicateProfile(const std::string& gameId,
670 const std::string& sourceProfileId,
671 const std::string& newName)
672{
673 auto source = getProfile(gameId, sourceProfileId);
674 if (!source)
675 return "";
676
677 PerformanceProfile duplicate = *source;
678 duplicate.id = generateUUID();
679 duplicate.name = newName;
680 duplicate.createdAt = std::time(nullptr);
681 duplicate.lastUsedAt = 0;
682 duplicate.useCount = 0;
683
684 if (createProfile(gameId, duplicate))
685 {
686 return duplicate.id;
687 }
688
689 return "";
690}
691
692std::vector<PerformanceProfile>
693PerformanceProfileService::getProfiles(const std::string& gameId) const
694{
695 auto it = impl_->gameProfiles_.find(gameId);
696 if (it != impl_->gameProfiles_.end())
697 {
698 return it->second.profiles;
699 }
700 return {};
701}
702
703std::optional<PerformanceProfile>
704PerformanceProfileService::getProfile(const std::string& gameId, const std::string& profileId) const
705{
706 auto it = impl_->gameProfiles_.find(gameId);
707 if (it == impl_->gameProfiles_.end())
708 return std::nullopt;
709
710 for (const auto& p : it->second.profiles)
711 {
712 if (p.id == profileId)
713 {
714 return p;
715 }
716 }
717
718 return std::nullopt;
719}
720
721std::optional<PerformanceProfile>
722PerformanceProfileService::getActiveProfile(const std::string& gameId) const
723{
724 auto it = impl_->gameProfiles_.find(gameId);
725 if (it == impl_->gameProfiles_.end())
726 return std::nullopt;
727
728 return getProfile(gameId, it->second.activeProfileId);
729}
730
731bool PerformanceProfileService::setActiveProfile(const std::string& gameId,
732 const std::string& profileId)
733{
734 auto it = impl_->gameProfiles_.find(gameId);
735 if (it == impl_->gameProfiles_.end())
736 return false;
737
738 // Verify profile exists
739 bool found = false;
740 for (auto& p : it->second.profiles)
741 {
742 if (p.id == profileId)
743 {
744 found = true;
745 p.lastUsedAt = std::time(nullptr);
746 p.useCount++;
747 break;
748 }
749 }
750
751 if (!found)
752 return false;
753
754 it->second.activeProfileId = profileId;
755 bool saved = impl_->saveGameProfiles(gameId);
756
757 if (saved && impl_->onProfileChanged_)
758 {
759 impl_->onProfileChanged_(gameId, profileId);
760 }
761
762 return saved;
763}
764
766 const std::string& name) const
767{
768 PerformanceProfile profile;
769 profile.preset = preset;
770 profile.name = name.empty() ? performancePresetName(preset) : name;
771
772 switch (preset)
773 {
775 profile.framerate.fpsLimit = 30;
776 profile.framerate.halfRateShading = true;
777 profile.scaling.enableFSR = true;
778 profile.scaling.internalWidth = 1280;
779 profile.scaling.internalHeight = 720;
780 profile.power.tdpLimit = 8;
781 profile.power.allowBoost = false;
782 profile.wrappers.enableGameMode = false;
783 break;
784
786 profile.framerate.fpsLimit = 60;
787 profile.framerate.enableVRR = true;
788 profile.wrappers.enableGameMode = true;
789 profile.sync.autoDetect = true;
790 break;
791
793 profile.framerate.fpsLimit = 0; // Unlimited
794 profile.framerate.enableVRR = true;
795 profile.wrappers.enableGameMode = true;
796 profile.wrappers.enableGamePerformance = true;
797 profile.power.allowBoost = true;
798 profile.sync.enableFsync = true;
799 break;
800
802 profile.framerate.fpsLimit = 60;
803 profile.framerate.enableVRR = true;
804 profile.scaling.enableFSR = false; // Native resolution
805 profile.wrappers.enableGameMode = true;
806 profile.wrappers.enableVkBasalt = true;
807 break;
808
810 profile.framerate.fpsLimit = 60;
811 profile.scaling.enableFSR = false;
812 profile.scaling.enableDLSS = false;
813 profile.wrappers.enableGameMode = false;
814 profile.wrappers.enableGamePerformance = false;
815 profile.wrappers.enableVkBasalt = false;
816 profile.sync.autoDetect = true;
817 profile.description = "Maximum compatibility - disables most optimizations";
818 break;
819
821 profile.framerate.fpsLimit = 30;
822 profile.power.tdpLimit = 5;
823 profile.power.allowBoost = false;
824 profile.power.fanCurvePreset = 1; // Silent curve
825 profile.description = "Prioritizes quiet operation over performance";
826 break;
827
829 default:
830 // Return empty/default profile
831 break;
832 }
833
834 return profile;
835}
836
841
843PerformanceProfileService::createSmartDefault(const std::string& /* gameId */,
844 const std::string& protondbTier) const
845{
847 profile.name = "Optimized";
848
849 // Adjust based on ProtonDB tier
850 if (protondbTier == "native")
851 {
852 // Native Linux - maximum performance
853 profile.framerate.fpsLimit = 0;
854 profile.sync.autoDetect = false; // Not needed for native
855 }
856 else if (protondbTier == "platinum" || protondbTier == "gold")
857 {
858 // Works well - enable performance features
859 profile.wrappers.enableGamePerformance = true;
860 profile.framerate.enableVRR = true;
861 }
862 else if (protondbTier == "silver")
863 {
864 // May have issues - be conservative
865 profile.framerate.fpsLimit = 60;
866 profile.wrappers.enableVkBasalt = false;
867 }
868 else if (protondbTier == "bronze" || protondbTier == "borked")
869 {
870 // Known issues - compatibility mode
872 }
873
874 return profile;
875}
876
877std::map<std::string, std::string>
879{
880 std::map<std::string, std::string> envVars;
881
882 // MangoHud
883 if (profile.wrappers.enableMangoHud)
884 {
885 envVars["MANGOHUD"] = "1";
886 if (!profile.wrappers.mangoHudConfig.empty())
887 {
888 envVars["MANGOHUD_CONFIG"] = profile.wrappers.mangoHudConfig;
889 }
890 }
891
892 // GameMode
893 if (profile.wrappers.enableGameMode)
894 {
895 envVars["GAMEMODERUNEXEC"] = "1";
896 }
897
898 // game-performance (CachyOS)
900 {
901 envVars["GAME_PERFORMANCE"] = "1";
902 }
903
904 // VkBasalt
905 if (profile.wrappers.enableVkBasalt)
906 {
907 envVars["ENABLE_VKBASALT"] = "1";
908 if (!profile.wrappers.vkBasaltEffects.empty())
909 {
910 envVars["VKBASALT_EFFECTS"] = profile.wrappers.vkBasaltEffects;
911 }
912 }
913
914 // Sync settings
915 if (!profile.sync.autoDetect)
916 {
917 if (profile.sync.enableFsync)
918 {
919 envVars["WINEFSYNC"] = "1";
920 envVars["PROTON_NO_FSYNC"] = "0";
921 }
922 else
923 {
924 envVars["PROTON_NO_FSYNC"] = "1";
925 }
926
927 if (profile.sync.enableEsync && !profile.sync.enableFsync)
928 {
929 envVars["WINEESYNC"] = "1";
930 envVars["PROTON_NO_ESYNC"] = "0";
931 }
932
933 if (profile.sync.enableNTSync)
934 {
935 envVars["PROTON_USE_NTSYNC"] = "1";
936 }
937 }
938
939 // FSR
940 if (profile.scaling.enableFSR)
941 {
942 envVars["WINE_FULLSCREEN_FSR"] = "1";
943 envVars["WINE_FULLSCREEN_FSR_STRENGTH"] = std::to_string(profile.scaling.fsrSharpness);
944 }
945
946 // Custom environment variables
947 for (const auto& [key, value] : profile.environmentVariables)
948 {
949 envVars[key] = value;
950 }
951
952 return envVars;
953}
954
955std::vector<std::string>
957{
958 std::vector<std::string> args;
959
960 // Resolution
961 if (profile.scaling.outputWidth > 0 && profile.scaling.outputHeight > 0)
962 {
963 args.push_back("-W");
964 args.push_back(std::to_string(profile.scaling.outputWidth));
965 args.push_back("-H");
966 args.push_back(std::to_string(profile.scaling.outputHeight));
967 }
968
969 if (profile.scaling.internalWidth > 0 && profile.scaling.internalHeight > 0)
970 {
971 args.push_back("-w");
972 args.push_back(std::to_string(profile.scaling.internalWidth));
973 args.push_back("-h");
974 args.push_back(std::to_string(profile.scaling.internalHeight));
975 }
976
977 // Refresh rate
978 if (profile.framerate.refreshRate > 0)
979 {
980 args.push_back("-r");
981 args.push_back(std::to_string(profile.framerate.refreshRate));
982 }
983
984 // FPS limit
985 if (profile.framerate.fpsLimit > 0)
986 {
987 args.push_back("--fps-limit");
988 args.push_back(std::to_string(profile.framerate.fpsLimit));
989 }
990
991 // Unfocused FPS
992 if (profile.framerate.gamescopeUnfocusedFps > 0)
993 {
994 args.push_back("--fps-limit-when-unfocused");
995 args.push_back(std::to_string(profile.framerate.gamescopeUnfocusedFps));
996 }
997
998 // VRR
999 if (profile.framerate.enableVRR)
1000 {
1001 args.push_back("--adaptive-sync");
1002 }
1003
1004 // FSR
1005 if (profile.scaling.enableFSR)
1006 {
1007 args.push_back("--fsr-sharpness");
1008 args.push_back(std::to_string(profile.scaling.fsrSharpness));
1009 }
1010
1011 // Integer scaling
1012 if (profile.scaling.enableIntegerScale)
1013 {
1014 args.push_back("--integer-scale");
1015 }
1016
1017 return args;
1018}
1019
1020void PerformanceProfileService::recordMetrics(const std::string& gameId,
1021 const std::string& /* profileId */, double avgFps,
1022 double avgFrametime)
1023{
1024 auto it = impl_->gameProfiles_.find(gameId);
1025 if (it == impl_->gameProfiles_.end())
1026 return;
1027
1028 auto& data = it->second;
1029
1030 // Update rolling average
1031 data.avgFps = (data.avgFps * data.sessionCount + avgFps) / (data.sessionCount + 1);
1032 data.avgFrametime =
1033 (data.avgFrametime * data.sessionCount + avgFrametime) / (data.sessionCount + 1);
1034 data.sessionCount++;
1035
1036 impl_->saveGameProfiles(gameId);
1037}
1038
1039std::vector<PerformanceProfile> PerformanceProfileService::getGlobalProfiles() const
1040{
1041 return impl_->globalProfiles_;
1042}
1043
1045{
1046 PerformanceProfile newProfile = profile;
1047 if (newProfile.id.empty())
1048 {
1049 newProfile.id = generateUUID();
1050 }
1051 newProfile.createdAt = std::time(nullptr);
1052
1053 impl_->globalProfiles_.push_back(newProfile);
1054
1055 // Save to file
1056 std::string filePath = impl_->dataDir_ + "/global/" + newProfile.id + ".json";
1057 std::ofstream file(filePath);
1058 if (file.is_open())
1059 {
1060 file << exportProfileToJson(newProfile);
1061 return true;
1062 }
1063
1064 return false;
1065}
1066
1068 const std::string& globalProfileId)
1069{
1070 // Find global profile
1071 auto globalIt = std::find_if(impl_->globalProfiles_.begin(), impl_->globalProfiles_.end(),
1072 [&globalProfileId](const PerformanceProfile& p)
1073 { return p.id == globalProfileId; });
1074
1075 if (globalIt == impl_->globalProfiles_.end())
1076 return false;
1077
1078 // Add game to linked list
1079 if (std::find(globalIt->linkedGameIds.begin(), globalIt->linkedGameIds.end(), gameId) ==
1080 globalIt->linkedGameIds.end())
1081 {
1082 globalIt->linkedGameIds.push_back(gameId);
1083 }
1084
1085 return true;
1086}
1087
1089{
1090 std::ostringstream json;
1091 json << "{\n";
1092 json << " \"id\": \"" << jsonEscape(profile.id) << "\",\n";
1093 json << " \"name\": \"" << jsonEscape(profile.name) << "\",\n";
1094 json << " \"description\": \"" << jsonEscape(profile.description) << "\",\n";
1095 json << " \"preset\": " << static_cast<int>(profile.preset) << ",\n";
1096 json << " \"framerate\": {\n";
1097 json << " \"fpsLimit\": " << profile.framerate.fpsLimit << ",\n";
1098 json << " \"refreshRate\": " << profile.framerate.refreshRate << ",\n";
1099 json << " \"enableVRR\": " << (profile.framerate.enableVRR ? "true" : "false") << ",\n";
1100 json << " \"useGamescope\": " << (profile.framerate.useGamescope ? "true" : "false") << "\n";
1101 json << " },\n";
1102 json << " \"scaling\": {\n";
1103 json << " \"internalWidth\": " << profile.scaling.internalWidth << ",\n";
1104 json << " \"internalHeight\": " << profile.scaling.internalHeight << ",\n";
1105 json << " \"enableFSR\": " << (profile.scaling.enableFSR ? "true" : "false") << ",\n";
1106 json << " \"fsrSharpness\": " << profile.scaling.fsrSharpness << "\n";
1107 json << " },\n";
1108 json << " \"wrappers\": {\n";
1109 json << " \"enableMangoHud\": " << (profile.wrappers.enableMangoHud ? "true" : "false")
1110 << ",\n";
1111 json << " \"enableGameMode\": " << (profile.wrappers.enableGameMode ? "true" : "false")
1112 << ",\n";
1113 json << " \"enableGamePerformance\": "
1114 << (profile.wrappers.enableGamePerformance ? "true" : "false") << ",\n";
1115 json << " \"enableVkBasalt\": " << (profile.wrappers.enableVkBasalt ? "true" : "false")
1116 << "\n";
1117 json << " },\n";
1118 json << " \"sync\": {\n";
1119 json << " \"autoDetect\": " << (profile.sync.autoDetect ? "true" : "false") << ",\n";
1120 json << " \"enableFsync\": " << (profile.sync.enableFsync ? "true" : "false") << ",\n";
1121 json << " \"enableEsync\": " << (profile.sync.enableEsync ? "true" : "false") << ",\n";
1122 json << " \"enableNTSync\": " << (profile.sync.enableNTSync ? "true" : "false") << "\n";
1123 json << " },\n";
1124 json << " \"createdAt\": " << profile.createdAt << ",\n";
1125 json << " \"lastUsedAt\": " << profile.lastUsedAt << ",\n";
1126 json << " \"useCount\": " << profile.useCount << "\n";
1127 json << "}\n";
1128 return json.str();
1129}
1130
1131std::optional<PerformanceProfile>
1133{
1134 PerformanceProfile profile = jsonParseProfile(json, 0, json.size());
1135 if (profile.id.empty())
1136 return std::nullopt;
1137 return profile;
1138}
1139
1141 const std::string& filePath) const
1142{
1143 auto it = impl_->gameProfiles_.find(gameId);
1144 if (it == impl_->gameProfiles_.end())
1145 return false;
1146
1147 std::ofstream file(filePath);
1148 if (!file.is_open())
1149 return false;
1150
1151 // Write all profiles as JSON array
1152 file << "[\n";
1153 const auto& profiles = it->second.profiles;
1154 for (size_t i = 0; i < profiles.size(); ++i)
1155 {
1156 file << exportProfileToJson(profiles[i]);
1157 if (i < profiles.size() - 1)
1158 file << ",";
1159 file << "\n";
1160 }
1161 file << "]\n";
1162
1163 return true;
1164}
1165
1167 const std::string& filePath)
1168{
1169 if (!fs::exists(filePath))
1170 return 0;
1171
1172 std::ifstream file(filePath);
1173 if (!file.is_open())
1174 return 0;
1175
1176 std::stringstream buf;
1177 buf << file.rdbuf();
1178 std::string json = buf.str();
1179
1180 // Parse JSON array [ { profile }, ... ]
1181 int imported = 0;
1182 size_t i = json.find('[');
1183 if (i == std::string::npos)
1184 return 0;
1185 ++i;
1186
1187 while (i < json.size())
1188 {
1189 // Skip whitespace and commas between objects
1190 while (i < json.size() && (json[i] == ' ' || json[i] == '\n' || json[i] == '\r' ||
1191 json[i] == '\t' || json[i] == ','))
1192 ++i;
1193 if (i >= json.size() || json[i] == ']')
1194 break;
1195 if (json[i] != '{')
1196 {
1197 ++i;
1198 continue;
1199 }
1200
1201 size_t objStart = i;
1202 int depth = 1;
1203 size_t j = objStart + 1;
1204 while (j < json.size() && depth > 0)
1205 {
1206 if (json[j] == '{')
1207 ++depth;
1208 else if (json[j] == '}')
1209 --depth;
1210 ++j;
1211 }
1212
1213 PerformanceProfile p = jsonParseProfile(json, objStart, j);
1214 if (!p.id.empty())
1215 {
1216 // Assign a new ID to avoid collisions
1217 p.id = generateUUID();
1218 impl_->gameProfiles_[gameId].profiles.push_back(std::move(p));
1219 ++imported;
1220 }
1221 i = j;
1222 }
1223
1224 if (imported > 0)
1225 impl_->saveGameProfiles(gameId);
1226
1227 return imported;
1228}
1229
1231{
1232 impl_->onProfileChanged_ = std::move(callback);
1233}
1234
1236{
1237 int count = 0;
1238 for (const auto& [gameId, data] : impl_->gameProfiles_)
1239 {
1240 count += static_cast<int>(data.profiles.size());
1241 }
1242 count += static_cast<int>(impl_->globalProfiles_.size());
1243 return count;
1244}
1245
1247{
1248 return static_cast<int>(impl_->gameProfiles_.size());
1249}
1250
1251std::optional<PerformanceProfile>
1253{
1254 auto it = impl_->gameProfiles_.find(gameId);
1255 if (it == impl_->gameProfiles_.end())
1256 return std::nullopt;
1257
1258 const auto& profiles = it->second.profiles;
1259 if (profiles.empty())
1260 return std::nullopt;
1261
1262 auto maxIt = std::max_element(profiles.begin(), profiles.end(),
1263 [](const PerformanceProfile& a, const PerformanceProfile& b)
1264 { return a.useCount < b.useCount; });
1265
1266 return *maxIt;
1267}
1268
1270{
1271 std::ostringstream ss;
1272
1273 if (framerate.fpsLimit > 0)
1274 {
1275 ss << framerate.fpsLimit << " FPS";
1276 }
1277 else
1278 {
1279 ss << "Unlocked FPS";
1280 }
1281
1282 if (framerate.enableVRR)
1283 {
1284 ss << ", VRR";
1285 }
1286
1287 if (scaling.enableFSR)
1288 {
1289 ss << ", FSR";
1290 }
1291
1292 if (wrappers.enableGameMode)
1293 {
1294 ss << ", GameMode";
1295 }
1296
1297 if (wrappers.enableMangoHud)
1298 {
1299 ss << ", HUD";
1300 }
1301
1302 return ss.str();
1303}
1304
1306{
1307 switch (preset)
1308 {
1310 return "Battery Life";
1312 return "Balanced";
1314 return "Performance";
1316 return "Quality";
1318 return "Compatibility";
1320 return "Silent";
1322 default:
1323 return "Custom";
1324 }
1325}
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
std::map< std::string, GamePerformanceData > gameProfiles_
bool saveGameProfiles(const std::string &gameId)
std::vector< PerformanceProfile > globalProfiles_
void loadGameProfiles(const std::string &gameId)
bool initialize(const std::string &dataDir)
PerformanceProfile getDefaultProfile() const
Get the default profile template.
std::vector< std::string > profileToGamescopeArgs(const PerformanceProfile &profile) const
Convert a profile to Gamescope arguments.
bool initialize(const std::string &dataDir)
Initialize the service with a data directory.
void setOnProfileChanged(OnProfileChanged callback)
std::optional< PerformanceProfile > getActiveProfile(const std::string &gameId) const
Get the active profile for a game.
bool setActiveProfile(const std::string &gameId, const std::string &profileId)
Set the active profile for a game.
std::function< void(const std::string &gameId, const std::string &profileId)> OnProfileChanged
int getTotalProfileCount() const
Get total number of profiles.
std::optional< PerformanceProfile > getMostUsedProfile(const std::string &gameId) const
Get most used profile for a game.
std::map< std::string, std::string > profileToEnvVars(const PerformanceProfile &profile) const
Convert a profile to environment variables.
bool createGlobalProfile(const PerformanceProfile &profile)
Create a global profile.
std::optional< PerformanceProfile > getProfile(const std::string &gameId, const std::string &profileId) const
Get a specific profile.
bool deleteProfile(const std::string &gameId, const std::string &profileId)
Delete a profile.
PerformanceProfile createFromPreset(PerformancePreset preset, const std::string &name="") const
Create a profile from a preset.
bool updateProfile(const std::string &gameId, const PerformanceProfile &profile)
Update an existing profile.
int getGamesWithProfilesCount() const
Get number of games with custom profiles.
std::vector< PerformanceProfile > getProfiles(const std::string &gameId) const
Get all profiles for a game.
bool exportGameProfiles(const std::string &gameId, const std::string &filePath) const
Export all profiles for a game.
bool isInitialized() const
Check if service is initialized.
bool linkToGlobalProfile(const std::string &gameId, const std::string &globalProfileId)
Link a game to use a global profile.
void recordMetrics(const std::string &gameId, const std::string &profileId, double avgFps, double avgFrametime)
Record performance metrics for a profile.
PerformanceProfile createSmartDefault(const std::string &gameId, const std::string &protondbTier="") const
Create game-specific default profile based on system info.
bool createProfile(const std::string &gameId, const PerformanceProfile &profile)
Create a new performance profile for a game.
std::string exportProfileToJson(const PerformanceProfile &profile) const
Export a profile to JSON.
std::vector< PerformanceProfile > getGlobalProfiles() const
Get global profiles (shared across games).
std::string duplicateProfile(const std::string &gameId, const std::string &sourceProfileId, const std::string &newName)
Duplicate an existing profile.
std::optional< PerformanceProfile > importProfileFromJson(const std::string &json) const
Import a profile from JSON.
int importGameProfiles(const std::string &gameId, const std::string &filePath)
Import profiles for a game.
nlohmann::json gjson
Definition game.cpp:19
nlohmann::json json
static std::string generateUUID()
static std::pair< size_t, size_t > jsonFindObject(const std::string &json, const std::string &key, size_t start=0, size_t end=std::string::npos)
std::string performancePresetName(PerformancePreset preset)
Get human-readable preset name.
static int jsonParseInt(const std::string &json, const std::string &key, size_t start=0, size_t end=std::string::npos, int def=0)
static std::string jsonParseStr(const std::string &json, const std::string &key, size_t start=0, size_t end=std::string::npos)
static long long jsonParseLong(const std::string &json, const std::string &key, size_t start=0, size_t end=std::string::npos, long long def=0)
static double jsonParseDouble(const std::string &json, const std::string &key, size_t start=0, size_t end=std::string::npos, double def=0.0)
static std::string jsonEscape(const std::string &str)
static PerformanceProfile jsonParseProfile(const std::string &json, size_t ps, size_t pe)
static bool jsonParseBool(const std::string &json, const std::string &key, size_t start=0, size_t end=std::string::npos, bool def=false)
std::string performancePresetName(PerformancePreset preset)
Get human-readable preset name.
PerformancePreset
Built-in performance presets.
@ Silent
Minimize fan noise (thermal throttle acceptable).
@ BatteryLife
Maximize battery life (30 FPS, low TDP).
@ Quality
Maximize visual quality.
@ Custom
User-defined settings.
@ Performance
Maximize performance.
@ Balanced
Balance performance and efficiency.
@ Compatibility
Maximum compatibility (disable optimizations).
bool halfRateShading
Enable half-rate shading (power saving).
bool enableVRR
Enable Variable Refresh Rate.
int refreshRate
Target refresh rate (0 = native).
int fpsLimit
FPS limit (0 = unlimited).
int gamescopeUnfocusedFps
FPS when unfocused (0 = same as focused).
bool useGamescope
Use Gamescope compositor.
Performance data and profiles for a specific game.
double avgFrametime
Average frametime in ms.
double avgFps
Average FPS across sessions.
int sessionCount
Number of sessions with metrics.
std::string activeProfileId
Currently active profile ID.
std::string gameId
Game this data belongs to.
std::vector< PerformanceProfile > profiles
Available profiles.
Complete performance profile for a game.
time_t lastUsedAt
When profile was last applied.
std::string description
Optional description.
std::string getSummary() const
Get a summary string of the profile settings.
std::string id
Unique profile ID.
std::map< std::string, std::string > environmentVariables
int useCount
Number of times profile was used.
time_t createdAt
When profile was created.
std::string name
Display name (e.g., "High Performance").
bool allowBoost
Allow CPU/GPU boost clocks.
int tdpLimit
TDP limit in watts (0 = default).
int fanCurvePreset
Fan curve preset (0 = default).
bool enableFSR
AMD FSR upscaling.
int outputHeight
Output/display height (0 = native).
int internalWidth
Internal render width (0 = native).
bool enableDLSS
NVIDIA DLSS (if available).
int internalHeight
Internal render height (0 = native).
int outputWidth
Output/display width (0 = native).
int fsrSharpness
FSR sharpness (0-20, 0 = max sharp).
bool enableIntegerScale
Force integer scaling.
bool autoDetect
Auto-detect best sync method.
bool enableNTSync
Use NTSync (experimental, kernel 6.14+).
bool enableEsync
Use Esync if Fsync unavailable.
bool enableFsync
Use Fsync if available.
std::string vkBasaltEffects
VkBasalt effects to use.
std::string mangoHudConfig
Custom MangoHud config string.
bool enableGameMode
Feral GameMode.
bool enableVkBasalt
VkBasalt post-processing.
bool enableGamePerformance
CachyOS game-performance.
bool enableMangoHud
MangoHud overlay.