game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
settings_controller.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// settings_controller.cpp
4// ==============================================================================
5// Thread Safety Design:
6// - All public getters return copies to prevent data races
7// - Callbacks are invoked OUTSIDE mutex locks via notifyChangedUnsafe()
8// - Setters: lock -> modify state -> copy callback -> unlock -> invoke callback
9// ==============================================================================
10
12#include "logger.h"
13#include "util/atomic_write.h"
14
15#include <algorithm>
16#include <cstdlib>
17#include <filesystem>
18#include <fstream>
19#include <mutex>
20#include <nlohmann/json.hpp>
21#include <optional>
22#include <vector>
23
24namespace fs = std::filesystem;
25
26namespace core
27{
28
29// ==============================================================================
30// Implementation
31// ==============================================================================
32
34{
35 public:
37 {
39 }
40
42 {
44 dirty_ = false;
45 rawConfigJson_ = nlohmann::json::object();
46 rawStateJson_ = nlohmann::json::object();
47 }
48
49 // Schema version pinned in both files. Bump when the on-disk shape
50 // changes incompatibly (new required field, removed key, etc.).
51 // A file with `schema_version > kSchemaVersion` is refused (downgrade
52 // safety): we never overwrite settings written by a newer launcher.
53 static constexpr int kSchemaVersion = 1;
54
55 // Settings data
57
58 // Raw JSON stashed at load time. Preserved across save() so unknown
59 // keys (added by a newer launcher version, or by manual user edits)
60 // round-trip cleanly instead of being silently discarded.
61 nlohmann::json rawConfigJson_;
62 nlohmann::json rawStateJson_;
63
64 // State
65 bool dirty_ = false;
66 mutable std::mutex mutex_;
67
68 // Callbacks
72
73 // ----- XDG-compliant directory layout -----
74 //
75 // Per https://specifications.freedesktop.org/basedir-spec/latest/ :
76 // $XDG_CONFIG_HOME (default ~/.config) — user preferences
77 // $XDG_STATE_HOME (default ~/.local/state) — implicit runtime state
78 // $XDG_DATA_HOME (default ~/.local/share) — durable data (DB, etc.)
79 //
80 // Settings are split:
81 // - Config (settings.json) lives in $XDG_CONFIG_HOME — user-set
82 // preferences: theme, default runner, HA URL, gaming-layout prefs.
83 // - State (window-state.json) lives in $XDG_STATE_HOME — implicit
84 // UI state: panel visibility, window geometry, last-view mode.
85 //
86 // Legacy single-file location ($XDG_DATA_HOME/gamelauncher/settings.json)
87 // is read on first launch as a migration source, then the next save
88 // writes to the new split locations.
89
90 static std::string envOrEmpty(const char* name)
91 {
92 const char* v = std::getenv(name);
93 return (v && v[0] != '\0') ? std::string(v) : std::string();
94 }
95
96 std::string getConfigDirectory() const
97 {
98#ifdef _WIN32
99 std::string appdata = envOrEmpty("APPDATA");
100 return !appdata.empty() ? appdata + "/gamelauncher" : ".";
101#else
102 std::string xdg = envOrEmpty("XDG_CONFIG_HOME");
103 if (!xdg.empty())
104 return xdg + "/gamelauncher";
105 std::string home = envOrEmpty("HOME");
106 return !home.empty() ? home + "/.config/gamelauncher" : ".";
107#endif
108 }
109
110 std::string getStateDirectory() const
111 {
112#ifdef _WIN32
113 // Windows lacks a direct XDG_STATE_HOME analogue; LocalAppData is
114 // the closest convention for "state that should persist but is
115 // not roamed". %LOCALAPPDATA% rather than %APPDATA% (which is
116 // roaming).
117 std::string lad = envOrEmpty("LOCALAPPDATA");
118 return !lad.empty() ? lad + "/gamelauncher" : getConfigDirectory();
119#else
120 std::string xdg = envOrEmpty("XDG_STATE_HOME");
121 if (!xdg.empty())
122 return xdg + "/gamelauncher";
123 std::string home = envOrEmpty("HOME");
124 return !home.empty() ? home + "/.local/state/gamelauncher" : ".";
125#endif
126 }
127
128 // Legacy single-file location used by launcher versions ≤ pre-XDG-split.
129 // Read-only at this point — migration source only.
130 std::string getLegacyDataDirectory() const
131 {
132#ifdef _WIN32
133 std::string appdata = envOrEmpty("APPDATA");
134 return !appdata.empty() ? appdata + "/gamelauncher" : ".";
135#else
136 std::string xdg = envOrEmpty("XDG_DATA_HOME");
137 if (!xdg.empty())
138 return xdg + "/gamelauncher";
139 std::string home = envOrEmpty("HOME");
140 return !home.empty() ? home + "/.local/share/gamelauncher" : ".";
141#endif
142 }
143
144 std::string getSettingsFilePath() const
145 {
146 return getConfigDirectory() + "/settings.json";
147 }
148 std::string getStateFilePath() const
149 {
150 return getStateDirectory() + "/window-state.json";
151 }
152 std::string getLegacySettingsFilePath() const
153 {
154 return getLegacyDataDirectory() + "/settings.json";
155 }
156 std::string getLegacyConfFilePath() const
157 {
158 return getLegacyDataDirectory() + "/settings.conf";
159 }
160
161 // ---- Section appliers shared between new-paths and legacy migration ----
162 //
163 // Each helper takes a JSON object (the top-level document) and applies
164 // the section it owns onto AppSettings. Missing sections / missing keys
165 // / wrong types are tolerated — defaults survive.
166
167 static bool checkSchemaVersionSafe(const nlohmann::json& j, const std::string& path)
168 {
169 if (!j.contains("schema_version"))
170 return true; // unversioned == v0, accepted
171 if (!j["schema_version"].is_number_integer())
172 return true;
173 int v = j["schema_version"].get<int>();
174 if (v > kSchemaVersion)
175 {
176 Logger::error("Settings file '{}' has schema_version {} (this build "
177 "supports up to {}). Refusing to overwrite — keeping "
178 "defaults loaded so you don't lose data.",
179 path, v, kSchemaVersion);
180 return false;
181 }
182 return true;
183 }
184
185 static void applyAppSection(const nlohmann::json& j, AppSettings& s)
186 {
187 if (!j.contains("application") || !j["application"].is_object())
188 return;
189 const auto& app = j["application"];
190 auto getBool = [&](const char* k, bool& dst)
191 {
192 if (app.contains(k) && app[k].is_boolean())
193 dst = app[k].get<bool>();
194 };
195 auto getInt = [&](const char* k, int& dst, int lo, int hi)
196 {
197 if (app.contains(k) && app[k].is_number_integer())
198 dst = std::clamp(app[k].get<int>(), lo, hi);
199 };
200 auto getStr = [&](const char* k, std::string& dst)
201 {
202 if (app.contains(k) && app[k].is_string())
203 dst = app[k].get<std::string>();
204 };
205 getBool("autoScan", s.autoScan);
206 getBool("notifications", s.notifications);
207 getBool("startMinimized", s.startMinimized);
208 getBool("minimizeToTray", s.minimizeToTray);
209 getBool("confirmDelete", s.confirmDelete);
210 getBool("steamMinimized", s.steamMinimized);
211 getBool("autoApplyDefaults", s.autoApplyDefaults);
212 getBool("useSteamLaunchByDefault", s.useSteamLaunchByDefault);
213 getBool("isolateMangoHudLogs", s.isolateMangoHudLogs);
214 getBool("silentSteamSync", s.silentSteamSync);
215 getBool("showToolbarGameStatus", s.showToolbarGameStatus);
216 getBool("toolbarLocked", s.toolbarLocked);
217 getInt("toolbarSearchWidth", s.toolbarSearchWidth, 80, 300);
218 getInt("toolbarZoomWidth", s.toolbarZoomWidth, 30, 100);
219 getStr("toolbarSectionOrder", s.toolbarSectionOrder);
220 getStr("defaultRunner", s.defaultRunner);
221 getStr("customScanDirectories", s.customScanDirectories);
222 getInt("gameLaunchTimeoutSeconds", s.gameLaunchTimeoutSeconds, 1, 300);
223 }
224
225 static void applyThemeSection(const nlohmann::json& j, AppSettings& s)
226 {
227 if (!j.contains("theme") || !j["theme"].is_object())
228 return;
229 const auto& theme = j["theme"];
230 if (theme.contains("themeId") && theme["themeId"].is_string())
231 s.themeId = theme["themeId"].get<std::string>();
232 if (theme.contains("customAccentColor") && theme["customAccentColor"].is_string())
233 s.customAccentColor = theme["customAccentColor"].get<std::string>();
234 if (theme.contains("uiZoom") && theme["uiZoom"].is_number_integer())
235 s.uiZoom = std::clamp(theme["uiZoom"].get<int>(), 75, 150);
236 if (theme.contains("fontFamily") && theme["fontFamily"].is_string())
237 s.fontFamily = theme["fontFamily"].get<std::string>();
238 }
239
240 static void applyGamingLayoutSection(const nlohmann::json& j, AppSettings& s)
241 {
242 if (!j.contains("gamingLayout") || !j["gamingLayout"].is_object())
243 return;
244 const auto& gl = j["gamingLayout"];
245 if (gl.contains("autoSwitchToRunningGame") && gl["autoSwitchToRunningGame"].is_boolean())
246 s.autoSwitchToRunningGame = gl["autoSwitchToRunningGame"].get<bool>();
247 if (gl.contains("autoGamingLayout") && gl["autoGamingLayout"].is_boolean())
248 s.autoGamingLayout = gl["autoGamingLayout"].get<bool>();
249 if (gl.contains("gamingLayoutWidthPercent") &&
250 gl["gamingLayoutWidthPercent"].is_number_integer())
252 std::clamp(gl["gamingLayoutWidthPercent"].get<int>(), 10, 50);
253 if (gl.contains("gamingLayoutEdge") && gl["gamingLayoutEdge"].is_number_integer())
254 s.gamingLayoutEdge = std::clamp(gl["gamingLayoutEdge"].get<int>(), 0, 2);
255 if (gl.contains("gamingLayoutFullHeight") && gl["gamingLayoutFullHeight"].is_boolean())
256 s.gamingLayoutFullHeight = gl["gamingLayoutFullHeight"].get<bool>();
257 if (gl.contains("restoreLayoutOnExit") && gl["restoreLayoutOnExit"].is_boolean())
258 s.restoreLayoutOnExit = gl["restoreLayoutOnExit"].get<bool>();
259 }
260
261 static void applyHomeAssistantSection(const nlohmann::json& j, AppSettings& s)
262 {
263 // homeAssistant lives in the panelState object historically; both
264 // file shapes must accept it there. The XDG split treats it as
265 // config-class state (HA URL is a user preference), so we read
266 // from `panelState.{enableHomeAssistant,homeAssistantUrl}` whether
267 // the panelState block came from the config file or the state file.
268 if (!j.contains("panelState") || !j["panelState"].is_object())
269 return;
270 const auto& ps = j["panelState"];
271 if (ps.contains("enableHomeAssistant") && ps["enableHomeAssistant"].is_boolean())
272 s.enableHomeAssistant = ps["enableHomeAssistant"].get<bool>();
273 if (ps.contains("homeAssistantUrl") && ps["homeAssistantUrl"].is_string())
274 {
275 std::string url = ps["homeAssistantUrl"].get<std::string>();
276 // Only accept http:// and https:// to prevent file:// or other scheme injection.
277 if (url.size() > 7 &&
278 (url.compare(0, 7, "http://") == 0 || url.compare(0, 8, "https://") == 0))
279 s.homeAssistantUrl = url;
280 }
281 }
282
283 static void applyPanelStateSection(const nlohmann::json& j, AppSettings& s)
284 {
285 if (!j.contains("panelState") || !j["panelState"].is_object())
286 return;
287 const auto& ps = j["panelState"];
288 if (ps.contains("panelSidebarVisible") && ps["panelSidebarVisible"].is_boolean())
289 s.panelSidebarVisible = ps["panelSidebarVisible"].get<bool>();
290 if (ps.contains("panelGamesVisible") && ps["panelGamesVisible"].is_boolean())
291 s.panelGamesVisible = ps["panelGamesVisible"].get<bool>();
292 if (ps.contains("panelDetailsVisible") && ps["panelDetailsVisible"].is_boolean())
293 s.panelDetailsVisible = ps["panelDetailsVisible"].get<bool>();
294 if (ps.contains("panelMonitorVisible") && ps["panelMonitorVisible"].is_boolean())
295 s.panelMonitorVisible = ps["panelMonitorVisible"].get<bool>();
296 if (ps.contains("panelHAVisible") && ps["panelHAVisible"].is_boolean())
297 s.panelHAVisible = ps["panelHAVisible"].get<bool>();
298 if (ps.contains("splitterSizes") && ps["splitterSizes"].is_string())
299 s.splitterSizes = ps["splitterSizes"].get<std::string>();
300 if (ps.contains("rememberWindowLayout") && ps["rememberWindowLayout"].is_boolean())
301 s.rememberWindowLayout = ps["rememberWindowLayout"].get<bool>();
302 if (ps.contains("windowGeometry") && ps["windowGeometry"].is_string())
303 s.windowGeometry = ps["windowGeometry"].get<std::string>();
304 if (ps.contains("windowState") && ps["windowState"].is_string())
305 s.windowState = ps["windowState"].get<std::string>();
306 if (ps.contains("lastViewMode") && ps["lastViewMode"].is_number_integer())
307 s.lastViewMode = std::clamp(ps["lastViewMode"].get<int>(), 0, 2);
308 if (ps.contains("lastSidebarCategory") && ps["lastSidebarCategory"].is_number_integer())
309 s.lastSidebarCategory = std::max(0, ps["lastSidebarCategory"].get<int>());
310 if (ps.contains("defaultLibraryView") && ps["defaultLibraryView"].is_number_integer())
311 s.defaultLibraryView = std::clamp(ps["defaultLibraryView"].get<int>(), -1, 6);
312 }
313
314 /// Try to read+parse a JSON file. Returns nullopt on missing-or-malformed.
315 /// Logs (info/error respectively) so the caller can stay terse.
316 static std::optional<nlohmann::json> readJsonFile(const std::string& path)
317 {
318 std::ifstream file(path);
319 if (!file.is_open())
320 return std::nullopt;
321 try
322 {
323 return nlohmann::json::parse(file);
324 }
325 catch (const nlohmann::json::exception& e)
326 {
327 Logger::error("Settings: failed to parse {}: {}", path, e.what());
328 return std::nullopt;
329 }
330 }
331
332 // Note: This should only be called while NOT holding the mutex
333 // Caller is responsible for setting dirty_ = true before calling
334 void notifyChangedUnsafe(const std::string& section, const std::string& key,
335 const OnSettingsChanged& callback)
336 {
337 if (callback)
338 {
340 event.section = section;
341 event.key = key;
342 callback(event);
343 }
344 }
345};
346
347// ==============================================================================
348// Constructor / Destructor
349// ==============================================================================
350
351SettingsController::SettingsController() : impl_(std::make_unique<Impl>()) {}
352
354
356SettingsController& SettingsController::operator=(SettingsController&&) noexcept = default;
357
358// ==============================================================================
359// Load/Save
360// ==============================================================================
361
363{
364 std::unique_lock<std::mutex> lock(impl_->mutex_);
365
366 auto& s = impl_->appSettings_;
367 const std::string configPath = impl_->getSettingsFilePath();
368 const std::string statePath = impl_->getStateFilePath();
369 const std::string legacyJsonPath = impl_->getLegacySettingsFilePath();
370 const std::string legacyConfPath = impl_->getLegacyConfFilePath();
371
372 bool loadedAny = false;
373
374 // ----- Pass 1: new XDG split locations -----
375 if (auto cfg = Impl::readJsonFile(configPath))
376 {
377 if (!Impl::checkSchemaVersionSafe(*cfg, configPath))
378 {
379 // Refuse to overwrite a future-version file. Keep defaults
380 // loaded; caller will still see the launcher functional but
381 // settings won't persist further changes.
382 return false;
383 }
384 impl_->rawConfigJson_ = *cfg;
385 Impl::applyAppSection(*cfg, s);
389 Logger::info("Settings (config) loaded from: {}", configPath);
390 loadedAny = true;
391 }
392 if (auto st = Impl::readJsonFile(statePath))
393 {
394 if (!Impl::checkSchemaVersionSafe(*st, statePath))
395 {
396 return false;
397 }
398 impl_->rawStateJson_ = *st;
400 Logger::info("Settings (state) loaded from: {}", statePath);
401 loadedAny = true;
402 }
403
404 if (loadedAny)
405 {
406 impl_->dirty_ = false;
407 OnSettingsLoaded callbackCopy = impl_->onSettingsLoaded_;
408 lock.unlock();
409 if (callbackCopy)
410 callbackCopy();
411 return true;
412 }
413
414 // ----- Pass 2: legacy single-file location ($XDG_DATA_HOME) -----
415 //
416 // Pre-XDG-split builds wrote a single settings.json containing all
417 // sections at $XDG_DATA_HOME/gamelauncher/settings.json. Read it and
418 // mark dirty so the next save() splits it into the new locations.
419 if (auto legacy = Impl::readJsonFile(legacyJsonPath))
420 {
421 // Legacy file lacks schema_version (always treated as 0); the
422 // schema-version safety only matters going forward.
423 if (!Impl::checkSchemaVersionSafe(*legacy, legacyJsonPath))
424 {
425 return false;
426 }
427 Logger::info("Settings: migrating from legacy single-file location {} "
428 "to XDG split (config={}, state={}). Legacy file preserved "
429 "in case manual rollback is needed.",
430 legacyJsonPath, configPath, statePath);
431
432 // Seed both raw caches so the upcoming save() preserves any keys we
433 // don't currently recognise (forward-compat). Then scrub each cache
434 // so it only retains keys that BELONG to its file: state-only keys
435 // (windowGeometry, splitterSizes, view modes, panel-visibility) get
436 // removed from the config raw cache, and config-only keys
437 // (enableHomeAssistant, homeAssistantUrl) get removed from the state
438 // raw cache. Without this scrub, every subsequent save() would
439 // permanently double-write the same panelState fields into both
440 // files — disk overhead is small, but a future "config wins" merge
441 // would silently revert window state on every load.
442 impl_->rawConfigJson_ = *legacy;
443 impl_->rawStateJson_ = *legacy;
444
445 // Authoritative key partitioning. Each list is the set of
446 // panelState child keys that belong in that file going forward.
447 static constexpr const char* kConfigPanelStateKeys[] = {
448 "enableHomeAssistant",
449 "homeAssistantUrl",
450 };
451 static constexpr const char* kStatePanelStateKeys[] = {
452 "panelSidebarVisible", "panelGamesVisible", "panelDetailsVisible",
453 "panelMonitorVisible", "panelHAVisible", "splitterSizes",
454 "rememberWindowLayout", "windowGeometry", "windowState",
455 "lastViewMode", "lastSidebarCategory", "defaultLibraryView",
456 };
457 auto retainOnly = [](nlohmann::json& parent, const char* objKey,
458 const char* const* keepKeys, size_t keepCount)
459 {
460 if (!parent.contains(objKey) || !parent[objKey].is_object())
461 return;
462 nlohmann::json filtered = nlohmann::json::object();
463 for (size_t i = 0; i < keepCount; ++i)
464 {
465 const char* k = keepKeys[i];
466 if (parent[objKey].contains(k))
467 filtered[k] = parent[objKey][k];
468 }
469 parent[objKey] = std::move(filtered);
470 };
471 retainOnly(impl_->rawConfigJson_, "panelState", kConfigPanelStateKeys,
472 sizeof(kConfigPanelStateKeys) / sizeof(kConfigPanelStateKeys[0]));
473 retainOnly(impl_->rawStateJson_, "panelState", kStatePanelStateKeys,
474 sizeof(kStatePanelStateKeys) / sizeof(kStatePanelStateKeys[0]));
475 // Top-level sections that don't belong in the state file at all.
476 for (const char* k : {"application", "theme", "gamingLayout"})
477 {
478 impl_->rawStateJson_.erase(k);
479 }
480
481 Impl::applyAppSection(*legacy, s);
482 Impl::applyThemeSection(*legacy, s);
486
487 impl_->dirty_ = true; // ensure next save() splits to new dirs
488 OnSettingsLoaded callbackCopy = impl_->onSettingsLoaded_;
489 lock.unlock();
490 if (callbackCopy)
491 callbackCopy();
492 return true;
493 }
494
495 // ----- Pass 3: ancient .conf format (key=value INI) -----
496 std::ifstream legacyFile(legacyConfPath);
497 if (!legacyFile.is_open())
498 {
499 Logger::info("No settings file found, using defaults");
500 return false;
501 }
502
503 Logger::info("Found legacy settings.conf, migrating to JSON format");
504
505 std::string line;
506 while (std::getline(legacyFile, line))
507 {
508 if (line.empty() || line[0] == '#' || line[0] == '[')
509 continue;
510
511 // Guard against DoS from extremely long lines in a crafted config file
512 if (line.size() > 4096)
513 {
514 Logger::warn("Settings: Legacy config line too long ({}), skipping", line.size());
515 continue;
516 }
517
518 size_t pos = line.find('=');
519 if (pos == std::string::npos)
520 continue;
521
522 std::string key = line.substr(0, pos);
523 std::string value = line.substr(pos + 1);
524
525 // Application Settings
526 if (key == "autoScan")
527 impl_->appSettings_.autoScan = (value == "1");
528 else if (key == "notifications")
529 impl_->appSettings_.notifications = (value == "1");
530 else if (key == "startMinimized")
531 impl_->appSettings_.startMinimized = (value == "1");
532 else if (key == "minimizeToTray")
533 impl_->appSettings_.minimizeToTray = (value == "1");
534 else if (key == "confirmDelete")
535 impl_->appSettings_.confirmDelete = (value == "1");
536 else if (key == "steamMinimized")
537 impl_->appSettings_.steamMinimized = (value == "1");
538 else if (key == "autoApplyDefaults")
539 impl_->appSettings_.autoApplyDefaults = (value == "1");
540 else if (key == "useSteamLaunchByDefault")
541 impl_->appSettings_.useSteamLaunchByDefault = (value == "1");
542 else if (key == "isolateMangoHudLogs")
543 impl_->appSettings_.isolateMangoHudLogs = (value == "1");
544 else if (key == "silentSteamSync")
545 impl_->appSettings_.silentSteamSync = (value == "1");
546 else if (key == "showToolbarGameStatus")
547 impl_->appSettings_.showToolbarGameStatus = (value == "1");
548 else if (key == "toolbarLocked")
549 impl_->appSettings_.toolbarLocked = (value == "1");
550 else if (key == "toolbarSearchWidth")
551 {
552 try
553 {
554 impl_->appSettings_.toolbarSearchWidth = std::clamp(std::stoi(value), 80, 300);
555 }
556 catch (...)
557 {
558 }
559 }
560 else if (key == "toolbarZoomWidth")
561 {
562 try
563 {
564 impl_->appSettings_.toolbarZoomWidth = std::clamp(std::stoi(value), 30, 100);
565 }
566 catch (...)
567 {
568 }
569 }
570 else if (key == "toolbarSectionOrder")
571 impl_->appSettings_.toolbarSectionOrder = value;
572 else if (key == "defaultRunner")
573 impl_->appSettings_.defaultRunner = value;
574 else if (key == "custom_scan_directories")
575 impl_->appSettings_.customScanDirectories = value;
576 else if (key == "game_launch_timeout_seconds")
577 {
578 try
579 {
580 impl_->appSettings_.gameLaunchTimeoutSeconds = std::clamp(std::stoi(value), 1, 300);
581 }
582 catch (...)
583 {
584 }
585 }
586 else if (key == "themeId")
587 impl_->appSettings_.themeId = value;
588 else if (key == "customAccentColor")
589 impl_->appSettings_.customAccentColor = value;
590 else if (key == "uiZoom")
591 {
592 try
593 {
594 impl_->appSettings_.uiZoom = std::clamp(std::stoi(value), 75, 150);
595 }
596 catch (...)
597 {
598 }
599 }
600 else if (key == "fontFamily")
601 impl_->appSettings_.fontFamily = value;
602 else if (key == "autoSwitchToRunningGame")
603 impl_->appSettings_.autoSwitchToRunningGame = (value == "1");
604 else if (key == "autoGamingLayout")
605 impl_->appSettings_.autoGamingLayout = (value == "1");
606 else if (key == "gamingLayoutWidthPercent")
607 {
608 try
609 {
610 impl_->appSettings_.gamingLayoutWidthPercent = std::clamp(std::stoi(value), 10, 50);
611 }
612 catch (...)
613 {
614 }
615 }
616 else if (key == "gamingLayoutEdge")
617 {
618 try
619 {
620 impl_->appSettings_.gamingLayoutEdge = std::clamp(std::stoi(value), 0, 2);
621 }
622 catch (...)
623 {
624 }
625 }
626 else if (key == "gamingLayoutFullHeight")
627 impl_->appSettings_.gamingLayoutFullHeight = (value == "1");
628 else if (key == "restoreLayoutOnExit")
629 impl_->appSettings_.restoreLayoutOnExit = (value == "1");
630 else if (key == "panelSidebarVisible")
631 impl_->appSettings_.panelSidebarVisible = (value == "1");
632 else if (key == "panelGamesVisible")
633 impl_->appSettings_.panelGamesVisible = (value == "1");
634 else if (key == "panelDetailsVisible")
635 impl_->appSettings_.panelDetailsVisible = (value == "1");
636 else if (key == "panelMonitorVisible")
637 impl_->appSettings_.panelMonitorVisible = (value == "1");
638 else if (key == "panelHAVisible")
639 impl_->appSettings_.panelHAVisible = (value == "1");
640 else if (key == "enableHomeAssistant")
641 impl_->appSettings_.enableHomeAssistant = (value == "1");
642 else if (key == "homeAssistantUrl")
643 {
644 if (value.size() > 7 &&
645 (value.compare(0, 7, "http://") == 0 || value.compare(0, 8, "https://") == 0))
646 impl_->appSettings_.homeAssistantUrl = value;
647 }
648 else if (key == "splitterSizes")
649 impl_->appSettings_.splitterSizes = value;
650 else if (key == "rememberWindowLayout")
651 impl_->appSettings_.rememberWindowLayout = (value == "1");
652 else if (key == "windowGeometry")
653 impl_->appSettings_.windowGeometry = value;
654 else if (key == "windowState")
655 impl_->appSettings_.windowState = value;
656 else if (key == "lastViewMode")
657 {
658 try
659 {
660 impl_->appSettings_.lastViewMode = std::clamp(std::stoi(value), 0, 2);
661 }
662 catch (...)
663 {
664 }
665 }
666 else if (key == "lastSidebarCategory")
667 {
668 try
669 {
670 impl_->appSettings_.lastSidebarCategory = std::max(0, std::stoi(value));
671 }
672 catch (...)
673 {
674 }
675 }
676 else if (key == "defaultLibraryView")
677 {
678 try
679 {
680 impl_->appSettings_.defaultLibraryView = std::clamp(std::stoi(value), -1, 6);
681 }
682 catch (...)
683 {
684 }
685 }
686 }
687
688 legacyFile.close();
689
690 // Mark dirty so the next save writes JSON format (completing migration)
691 impl_->dirty_ = true;
692
693 Logger::info("Legacy settings migrated from: {}", legacyConfPath);
694
695 OnSettingsLoaded callbackCopy = impl_->onSettingsLoaded_;
696 lock.unlock();
697 if (callbackCopy)
698 callbackCopy();
699 return true;
700}
701
703{
704 std::unique_lock<std::mutex> lock(impl_->mutex_);
705
706 const std::string configPath = impl_->getSettingsFilePath();
707 const std::string statePath = impl_->getStateFilePath();
708
709 // Ensure both directories exist with owner-only perms. Permission failure
710 // here is non-fatal — a writable existing dir without explicit perm change
711 // still works; we just log a warning.
712 auto ensureDir = [](const std::string& dir)
713 {
714 fs::path p = fs::path(dir).parent_path();
715 if (p.empty())
716 return;
717 std::error_code ec;
718 fs::create_directories(p, ec);
719 if (!ec)
720 {
721 std::error_code permEc;
722 fs::permissions(p, fs::perms::owner_all, fs::perm_options::replace, permEc);
723 if (permEc)
724 Logger::warn("Settings: could not chmod 0700 on {}: {}", p.string(),
725 permEc.message());
726 }
727 };
728 ensureDir(configPath);
729 ensureDir(statePath);
730
731 const auto& s = impl_->appSettings_;
732
733 // ----- Build the config-file JSON, preserving unknown keys.
734 //
735 // The starting point is whatever we parsed at load time (or that load
736 // migrated from legacy). Overwriting only the sections we own means
737 // any extra fields a future launcher version added — or that the user
738 // edited manually — survive across save/load round-trips. This is the
739 // round-trip-clean policy recommended for forward-compatible config.
740 nlohmann::json cfg = impl_->rawConfigJson_;
741 if (!cfg.is_object())
742 cfg = nlohmann::json::object();
743 cfg["schema_version"] = Impl::kSchemaVersion;
744
745 cfg["application"] = {{"autoScan", s.autoScan},
746 {"notifications", s.notifications},
747 {"startMinimized", s.startMinimized},
748 {"minimizeToTray", s.minimizeToTray},
749 {"confirmDelete", s.confirmDelete},
750 {"steamMinimized", s.steamMinimized},
751 {"autoApplyDefaults", s.autoApplyDefaults},
752 {"useSteamLaunchByDefault", s.useSteamLaunchByDefault},
753 {"isolateMangoHudLogs", s.isolateMangoHudLogs},
754 {"silentSteamSync", s.silentSteamSync},
755 {"showToolbarGameStatus", s.showToolbarGameStatus},
756 {"toolbarLocked", s.toolbarLocked},
757 {"toolbarSearchWidth", s.toolbarSearchWidth},
758 {"toolbarZoomWidth", s.toolbarZoomWidth},
759 {"toolbarSectionOrder", s.toolbarSectionOrder},
760 {"defaultRunner", s.defaultRunner},
761 {"customScanDirectories", s.customScanDirectories},
762 {"gameLaunchTimeoutSeconds", s.gameLaunchTimeoutSeconds}};
763 cfg["theme"] = {{"themeId", s.themeId},
764 {"customAccentColor", s.customAccentColor},
765 {"uiZoom", s.uiZoom},
766 {"fontFamily", s.fontFamily}};
767 cfg["gamingLayout"] = {{"autoSwitchToRunningGame", s.autoSwitchToRunningGame},
768 {"autoGamingLayout", s.autoGamingLayout},
769 {"gamingLayoutWidthPercent", s.gamingLayoutWidthPercent},
770 {"gamingLayoutEdge", s.gamingLayoutEdge},
771 {"gamingLayoutFullHeight", s.gamingLayoutFullHeight},
772 {"restoreLayoutOnExit", s.restoreLayoutOnExit}};
773 // HomeAssistant lives inside panelState in the wire format for back-compat,
774 // but is config-class data — write it into the config file. (The state
775 // file gets the rest of panelState below.)
776 nlohmann::json haState = nlohmann::json::object();
777 if (cfg.contains("panelState") && cfg["panelState"].is_object())
778 haState = cfg["panelState"];
779 haState["enableHomeAssistant"] = s.enableHomeAssistant;
780 haState["homeAssistantUrl"] = s.homeAssistantUrl;
781 cfg["panelState"] = haState;
782
783 // ----- Build the state-file JSON, preserving unknown keys.
784 nlohmann::json st = impl_->rawStateJson_;
785 if (!st.is_object())
786 st = nlohmann::json::object();
787 st["schema_version"] = Impl::kSchemaVersion;
788
789 nlohmann::json psState = nlohmann::json::object();
790 if (st.contains("panelState") && st["panelState"].is_object())
791 psState = st["panelState"];
792 psState["panelSidebarVisible"] = s.panelSidebarVisible;
793 psState["panelGamesVisible"] = s.panelGamesVisible;
794 psState["panelDetailsVisible"] = s.panelDetailsVisible;
795 psState["panelMonitorVisible"] = s.panelMonitorVisible;
796 psState["panelHAVisible"] = s.panelHAVisible;
797 psState["splitterSizes"] = s.splitterSizes;
798 psState["rememberWindowLayout"] = s.rememberWindowLayout;
799 psState["windowGeometry"] = s.windowGeometry;
800 psState["windowState"] = s.windowState;
801 psState["lastViewMode"] = s.lastViewMode;
802 psState["lastSidebarCategory"] = s.lastSidebarCategory;
803 psState["defaultLibraryView"] = s.defaultLibraryView;
804 st["panelState"] = psState;
805
806 // ----- Durable atomic save.
807 //
808 // atomicWriteFile does write -> fsync(fd) -> rename -> fsync(parent_dir)
809 // per rename(2)+fsync(2) best practice. Both files succeed or both fail
810 // observably; partial failure leaves whichever was written successfully
811 // in place, which is acceptable since the two files are independent.
812 auto serializedCfg = cfg.dump(2);
813 serializedCfg.push_back('\n');
814 auto serializedSt = st.dump(2);
815 serializedSt.push_back('\n');
816
817 std::string err;
818 if (!core::atomicWriteFile(configPath, serializedCfg, &err))
819 {
820 Logger::error("Failed to save config to {}: {}", configPath, err);
821 return false;
822 }
823 if (!core::atomicWriteFile(statePath, serializedSt, &err))
824 {
825 Logger::error("Failed to save state to {}: {}", statePath, err);
826 return false;
827 }
828 // Refresh the raw caches from what we just wrote so subsequent saves
829 // build on top of the on-disk shape (preserves any unknown keys we just
830 // round-tripped through).
831 impl_->rawConfigJson_ = cfg;
832 impl_->rawStateJson_ = st;
833 impl_->dirty_ = false;
834
835 Logger::info("Settings saved (config={}, state={})", configPath, statePath);
836
837 OnSettingsSaved callbackCopy = impl_->onSettingsSaved_;
838 lock.unlock();
839
840 if (callbackCopy)
841 {
842 callbackCopy();
843 }
844
845 return true;
846}
847
849{
850 OnSettingsChanged callbackCopy;
851 {
852 std::lock_guard<std::mutex> lock(impl_->mutex_);
853 impl_->initializeDefaults();
854 impl_->dirty_ = true;
855 callbackCopy = impl_->onSettingsChanged_;
856 }
857 impl_->notifyChangedUnsafe("all", "", callbackCopy);
858}
859
861{
862 std::lock_guard<std::mutex> lock(impl_->mutex_);
863 return impl_->dirty_;
864}
865
866// ==============================================================================
867// Getters
868// ==============================================================================
869
871{
872 std::lock_guard<std::mutex> lock(impl_->mutex_);
873 return impl_->appSettings_; // Return copy for thread safety
874}
875
876// Candidate settings.json paths in priority order, matching where the live
877// SettingsController reads/writes: the XDG *config* directory first (the
878// authoritative post-v1.1.0 location written by saveSettings()), then the
879// legacy XDG *data* directory as a migration fallback for installs that have
880// not re-saved since the config-dir split.
881//
882// This MUST stay consistent with Impl::getConfigDirectory() /
883// getLegacyDataDirectory(); the two used to diverge, which caused saved
884// toggles (useSteamLaunchByDefault / isolateMangoHudLogs / steamMinimized) to
885// be silently ignored at launch because the static readers looked only in the
886// legacy data dir. See BUG-1 in the 2026-07 audit.
887static std::vector<std::string> settingsFileSearchPaths()
888{
889 const auto env = [](const char* name) -> std::string
890 {
891 const char* v = std::getenv(name);
892 return (v && v[0] != '\0') ? std::string(v) : std::string();
893 };
894 std::vector<std::string> paths;
895#ifdef _WIN32
896 const std::string appdata = env("APPDATA");
897 if (!appdata.empty())
898 paths.push_back(appdata + "/gamelauncher/settings.json");
899#else
900 // Config dir (authoritative).
901 const std::string xdgConfig = env("XDG_CONFIG_HOME");
902 const std::string home = env("HOME");
903 if (!xdgConfig.empty())
904 paths.push_back(xdgConfig + "/gamelauncher/settings.json");
905 else if (!home.empty())
906 paths.push_back(home + "/.config/gamelauncher/settings.json");
907 // Legacy data dir (migration fallback).
908 const std::string xdgData = env("XDG_DATA_HOME");
909 if (!xdgData.empty())
910 paths.push_back(xdgData + "/gamelauncher/settings.json");
911 else if (!home.empty())
912 paths.push_back(home + "/.local/share/gamelauncher/settings.json");
913#endif
914 if (paths.empty())
915 paths.push_back("settings.json");
916 return paths;
917}
918
919// Read a single boolean value from the application settings file without
920// holding a SettingsController instance. Returns @p defaultValue when no
921// settings file is found, all are malformed, or the key isn't present yet.
922//
923// Used by code paths invoked from static contexts (game_process.cpp,
924// MangoHudLogReader::getDefaultLogDirectory) that can't depend on the
925// (UI-owned) SettingsController. Disk read is one-shot per launch — no
926// caching since the cost is negligible relative to launching a game.
927static bool readBoolSettingFromDisk(const char* key, bool defaultValue)
928{
929 for (const std::string& path : settingsFileSearchPaths())
930 {
931 std::ifstream file(path);
932 if (!file.is_open())
933 continue;
934 try
935 {
936 nlohmann::json j = nlohmann::json::parse(file);
937 if (j.contains("application") && j["application"].is_object())
938 {
939 const auto& app = j["application"];
940 if (app.contains(key))
941 return app[key].get<bool>();
942 }
943 }
944 catch (const std::exception&)
945 {
946 // Malformed file — try the next candidate.
947 }
948 // File existed and parsed but lacked the key: stop here and use the
949 // default rather than reading a staler legacy file.
950 return defaultValue;
951 }
952 return defaultValue;
953}
954
956{
957 // Default mirrors AppSettings::useSteamLaunchByDefault.
958 return readBoolSettingFromDisk("useSteamLaunchByDefault", true);
959}
960
962{
963 // Default mirrors AppSettings::isolateMangoHudLogs.
964 return readBoolSettingFromDisk("isolateMangoHudLogs", true);
965}
966
968{
969 // Default mirrors AppSettings::steamMinimized.
970 return readBoolSettingFromDisk("steamMinimized", true);
971}
972
973// ==============================================================================
974// Setters
975// ==============================================================================
976
978{
979 OnSettingsChanged callbackCopy;
980 {
981 std::lock_guard<std::mutex> lock(impl_->mutex_);
982 impl_->appSettings_ = settings;
983 impl_->dirty_ = true;
984 callbackCopy = impl_->onSettingsChanged_;
985 }
986 impl_->notifyChangedUnsafe("app", "", callbackCopy);
987}
988
989// ==============================================================================
990// Individual Setting Accessors
991// ==============================================================================
992
994{
995 std::lock_guard<std::mutex> lock(impl_->mutex_);
996 return impl_->appSettings_.autoScan;
997}
998
1000{
1001 OnSettingsChanged callbackCopy;
1002 {
1003 std::lock_guard<std::mutex> lock(impl_->mutex_);
1004 impl_->appSettings_.autoScan = enabled;
1005 impl_->dirty_ = true;
1006 callbackCopy = impl_->onSettingsChanged_;
1007 }
1008 impl_->notifyChangedUnsafe("app", "autoScan", callbackCopy);
1009}
1010
1012{
1013 std::lock_guard<std::mutex> lock(impl_->mutex_);
1014 return impl_->appSettings_.notifications;
1015}
1016
1018{
1019 OnSettingsChanged callbackCopy;
1020 {
1021 std::lock_guard<std::mutex> lock(impl_->mutex_);
1022 impl_->appSettings_.notifications = enabled;
1023 impl_->dirty_ = true;
1024 callbackCopy = impl_->onSettingsChanged_;
1025 }
1026 impl_->notifyChangedUnsafe("app", "notifications", callbackCopy);
1027}
1028
1030{
1031 std::lock_guard<std::mutex> lock(impl_->mutex_);
1032 return impl_->appSettings_.startMinimized;
1033}
1034
1036{
1037 OnSettingsChanged callbackCopy;
1038 {
1039 std::lock_guard<std::mutex> lock(impl_->mutex_);
1040 impl_->appSettings_.startMinimized = enabled;
1041 impl_->dirty_ = true;
1042 callbackCopy = impl_->onSettingsChanged_;
1043 }
1044 impl_->notifyChangedUnsafe("app", "startMinimized", callbackCopy);
1045}
1046
1048{
1049 std::lock_guard<std::mutex> lock(impl_->mutex_);
1050 return impl_->appSettings_.minimizeToTray;
1051}
1052
1054{
1055 OnSettingsChanged callbackCopy;
1056 {
1057 std::lock_guard<std::mutex> lock(impl_->mutex_);
1058 impl_->appSettings_.minimizeToTray = enabled;
1059 impl_->dirty_ = true;
1060 callbackCopy = impl_->onSettingsChanged_;
1061 }
1062 impl_->notifyChangedUnsafe("app", "minimizeToTray", callbackCopy);
1063}
1064
1066{
1067 std::lock_guard<std::mutex> lock(impl_->mutex_);
1068 return impl_->appSettings_.confirmDelete;
1069}
1070
1072{
1073 OnSettingsChanged callbackCopy;
1074 {
1075 std::lock_guard<std::mutex> lock(impl_->mutex_);
1076 impl_->appSettings_.confirmDelete = enabled;
1077 impl_->dirty_ = true;
1078 callbackCopy = impl_->onSettingsChanged_;
1079 }
1080 impl_->notifyChangedUnsafe("app", "confirmDelete", callbackCopy);
1081}
1082
1084{
1085 std::lock_guard<std::mutex> lock(impl_->mutex_);
1086 return impl_->appSettings_.steamMinimized;
1087}
1088
1090{
1091 OnSettingsChanged callbackCopy;
1092 {
1093 std::lock_guard<std::mutex> lock(impl_->mutex_);
1094 impl_->appSettings_.steamMinimized = enabled;
1095 impl_->dirty_ = true;
1096 callbackCopy = impl_->onSettingsChanged_;
1097 }
1098 impl_->notifyChangedUnsafe("app", "steamMinimized", callbackCopy);
1099}
1100
1102{
1103 std::lock_guard<std::mutex> lock(impl_->mutex_);
1104 return impl_->appSettings_.autoApplyDefaults;
1105}
1106
1108{
1109 OnSettingsChanged callbackCopy;
1110 {
1111 std::lock_guard<std::mutex> lock(impl_->mutex_);
1112 impl_->appSettings_.autoApplyDefaults = enabled;
1113 impl_->dirty_ = true;
1114 callbackCopy = impl_->onSettingsChanged_;
1115 }
1116 impl_->notifyChangedUnsafe("app", "autoApplyDefaults", callbackCopy);
1117}
1118
1120{
1121 std::lock_guard<std::mutex> lock(impl_->mutex_);
1122 return impl_->appSettings_.silentSteamSync;
1123}
1124
1126{
1127 OnSettingsChanged callbackCopy;
1128 {
1129 std::lock_guard<std::mutex> lock(impl_->mutex_);
1130 impl_->appSettings_.silentSteamSync = enabled;
1131 impl_->dirty_ = true;
1132 callbackCopy = impl_->onSettingsChanged_;
1133 }
1134 impl_->notifyChangedUnsafe("app", "silentSteamSync", callbackCopy);
1135}
1136
1138{
1139 std::lock_guard<std::mutex> lock(impl_->mutex_);
1140 return impl_->appSettings_.defaultRunner;
1141}
1142
1143void SettingsController::setDefaultRunner(const std::string& runner)
1144{
1145 OnSettingsChanged callbackCopy;
1146 {
1147 std::lock_guard<std::mutex> lock(impl_->mutex_);
1148 impl_->appSettings_.defaultRunner = runner;
1149 impl_->dirty_ = true;
1150 callbackCopy = impl_->onSettingsChanged_;
1151 }
1152 impl_->notifyChangedUnsafe("app", "defaultRunner", callbackCopy);
1153}
1154
1156{
1157 std::lock_guard<std::mutex> lock(impl_->mutex_);
1158 return impl_->appSettings_.customScanDirectories;
1159}
1160
1162{
1163 OnSettingsChanged callbackCopy;
1164 {
1165 std::lock_guard<std::mutex> lock(impl_->mutex_);
1166 impl_->appSettings_.customScanDirectories = dirs;
1167 impl_->dirty_ = true;
1168 callbackCopy = impl_->onSettingsChanged_;
1169 }
1170 impl_->notifyChangedUnsafe("app", "custom_scan_directories", callbackCopy);
1171}
1172
1174{
1175 std::lock_guard<std::mutex> lock(impl_->mutex_);
1176 return impl_->appSettings_.gameLaunchTimeoutSeconds;
1177}
1178
1180{
1181 OnSettingsChanged callbackCopy;
1182 {
1183 std::lock_guard<std::mutex> lock(impl_->mutex_);
1184 impl_->appSettings_.gameLaunchTimeoutSeconds = std::clamp(seconds, 1, 300);
1185 impl_->dirty_ = true;
1186 callbackCopy = impl_->onSettingsChanged_;
1187 }
1188 impl_->notifyChangedUnsafe("app", "game_launch_timeout_seconds", callbackCopy);
1189}
1190
1191// ==============================================================================
1192// Path Helpers
1193// ==============================================================================
1194
1196{
1197 return impl_->getSettingsFilePath();
1198}
1199
1200// Public API: still returns the data directory (for callers persisting
1201// non-settings data like the games database). The internal helper is now
1202// `getLegacyDataDirectory` because settings have moved to XDG_CONFIG_HOME,
1203// but the games.db continues to belong in XDG_DATA_HOME per the spec.
1205{
1206 return impl_->getLegacyDataDirectory();
1207}
1208
1210{
1211 std::vector<std::string> versions;
1212
1213 // Check common Proton installation paths
1214 const char* home = std::getenv("HOME");
1215 if (!home)
1216 return versions;
1217
1218 std::vector<std::string> searchPaths = {
1219 std::string(home) + "/.steam/steam/compatibilitytools.d",
1220 std::string(home) + "/.local/share/Steam/compatibilitytools.d",
1221 "/usr/share/steam/compatibilitytools.d"};
1222
1223 for (const auto& searchPath : searchPaths)
1224 {
1225 if (!fs::exists(searchPath))
1226 continue;
1227
1228 for (const auto& entry : fs::directory_iterator(searchPath))
1229 {
1230 if (entry.is_directory())
1231 {
1232 std::string name = entry.path().filename().string();
1233 // Filter for Proton-like directories
1234 if (name.find("Proton") != std::string::npos ||
1235 name.find("proton") != std::string::npos ||
1236 name.find("GE-Proton") != std::string::npos)
1237 {
1238 versions.push_back(name);
1239 }
1240 }
1241 }
1242 }
1243
1244 // Also check Steam's built-in Proton versions
1245 std::vector<std::string> steamProtonPaths = {
1246 std::string(home) + "/.steam/steam/steamapps/common",
1247 std::string(home) + "/.local/share/Steam/steamapps/common"};
1248
1249 for (const auto& steamPath : steamProtonPaths)
1250 {
1251 if (!fs::exists(steamPath))
1252 continue;
1253
1254 for (const auto& entry : fs::directory_iterator(steamPath))
1255 {
1256 if (entry.is_directory())
1257 {
1258 std::string name = entry.path().filename().string();
1259 if (name.find("Proton") != std::string::npos)
1260 {
1261 versions.push_back(name);
1262 }
1263 }
1264 }
1265 }
1266
1267 // Sort and remove duplicates
1268 std::sort(versions.begin(), versions.end());
1269 versions.erase(std::unique(versions.begin(), versions.end()), versions.end());
1270
1271 return versions;
1272}
1273
1274std::vector<std::string> SettingsController::getAvailableWineVersions() const
1275{
1276 std::vector<std::string> versions;
1277
1278 const char* home = std::getenv("HOME");
1279 if (!home)
1280 return versions;
1281
1282 // Check Lutris Wine builds
1283 std::string lutrisPath = std::string(home) + "/.local/share/lutris/runners/wine";
1284 if (fs::exists(lutrisPath))
1285 {
1286 for (const auto& entry : fs::directory_iterator(lutrisPath))
1287 {
1288 if (entry.is_directory())
1289 {
1290 versions.push_back(entry.path().filename().string());
1291 }
1292 }
1293 }
1294
1295 // Check system Wine
1296 if (fs::exists("/usr/bin/wine"))
1297 {
1298 versions.push_back("system");
1299 }
1300
1301 return versions;
1302}
1303
1304// ==============================================================================
1305// Event Subscriptions
1306// ==============================================================================
1307
1309{
1310 std::lock_guard<std::mutex> lock(impl_->mutex_);
1311 impl_->onSettingsChanged_ = std::move(callback);
1312}
1313
1315{
1316 std::lock_guard<std::mutex> lock(impl_->mutex_);
1317 impl_->onSettingsSaved_ = std::move(callback);
1318}
1319
1321{
1322 std::lock_guard<std::mutex> lock(impl_->mutex_);
1323 impl_->onSettingsLoaded_ = std::move(callback);
1324}
1325
1326} // namespace core
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
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::string getLegacySettingsFilePath() const
static bool checkSchemaVersionSafe(const nlohmann::json &j, const std::string &path)
static std::string envOrEmpty(const char *name)
static void applyThemeSection(const nlohmann::json &j, AppSettings &s)
static std::optional< nlohmann::json > readJsonFile(const std::string &path)
Try to read+parse a JSON file.
static void applyAppSection(const nlohmann::json &j, AppSettings &s)
void notifyChangedUnsafe(const std::string &section, const std::string &key, const OnSettingsChanged &callback)
static void applyGamingLayoutSection(const nlohmann::json &j, AppSettings &s)
static void applyHomeAssistantSection(const nlohmann::json &j, AppSettings &s)
static void applyPanelStateSection(const nlohmann::json &j, AppSettings &s)
void setOnSettingsSaved(OnSettingsSaved callback)
void setConfirmDeleteEnabled(bool enabled)
std::function< void()> OnSettingsSaved
AppSettings getAppSettings() const
Get application settings (returns copy for thread safety).
std::string getDataDirectory() const
Get application data directory.
std::vector< std::string > getAvailableProtonVersions() const
Get available Proton versions.
void setAutoApplyDefaultsEnabled(bool enabled)
void resetToDefaults()
Reset all settings to defaults.
bool saveSettings()
Save settings to disk.
std::string getDefaultRunner() const
void setStartMinimizedEnabled(bool enabled)
std::vector< std::string > getAvailableWineVersions() const
Get available Wine versions.
bool hasUnsavedChanges() const
Check if settings have unsaved changes.
std::function< void(const SettingsChangedEvent &)> OnSettingsChanged
void setOnSettingsChanged(OnSettingsChanged callback)
std::function< void()> OnSettingsLoaded
void setSteamMinimizedEnabled(bool enabled)
void setAppSettings(const AppSettings &settings)
Set application settings.
std::string getSettingsFilePath() const
Get the settings file path.
static bool readSteamMinimizedFromDisk()
Read just steamMinimized directly from the settings file.
bool loadSettings()
Load settings from disk.
void setOnSettingsLoaded(OnSettingsLoaded callback)
static bool readUseSteamLaunchByDefaultFromDisk()
Read just useSteamLaunchByDefault directly from the settings file.
void setSilentSteamSyncEnabled(bool enabled)
void setCustomScanDirectories(const std::string &dirs)
std::string getCustomScanDirectories() const
void setAutoScanEnabled(bool enabled)
void setDefaultRunner(const std::string &runner)
static bool readIsolateMangoHudLogsFromDisk()
Read just isolateMangoHudLogs directly from the settings file.
void setNotificationsEnabled(bool enabled)
void setMinimizeToTrayEnabled(bool enabled)
static std::vector< std::string > settingsFileSearchPaths()
bool atomicWriteFile(const std::filesystem::path &targetPath, std::string_view contents, std::string *errOut=nullptr)
Atomically and durably write contents to targetPath.
static bool readBoolSettingFromDisk(const char *key, bool defaultValue)
std::string toolbarSectionOrder
std::string customScanDirectories
std::string customAccentColor