diff --git a/build/Makefile b/build/Makefile index 635a9fc..87b7431 100644 --- a/build/Makefile +++ b/build/Makefile @@ -861,6 +861,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/settings_schema.cpp \ $(THESEUS_SRC)/desktop/desktop_settings.cpp \ $(THESEUS_SRC)/desktop/guide.cpp \ + $(THESEUS_SRC)/desktop/console_mode.cpp \ $(THESEUS_SRC)/desktop/ui_overlay.cpp \ $(THESEUS_SRC)/desktop/ui_overlay_style.cpp \ $(THESEUS_SRC)/desktop/ui_font.cpp \ diff --git a/theseus/desktop/console_mode.cpp b/theseus/desktop/console_mode.cpp new file mode 100644 index 0000000..70c5eeb --- /dev/null +++ b/theseus/desktop/console_mode.cpp @@ -0,0 +1,129 @@ +// console_mode.cpp: console mode's state and the guide's leave and power +// options (console_mode.h). + +#include "console_mode.h" +#include "host.h" +#include "app_paths.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +extern SDL_Window* g_pSDLWindow; +extern bool g_displayChangeRequested; +void SaveDesktopSettings(); + +bool g_consoleMode = false; +bool g_consoleFlag = false; +bool g_consoleSupervised = false; + +bool Console_Active() { return g_consoleMode || g_consoleFlag; } + +void Console_GoToDesktop() +{ + if (!g_pSDLWindow) return; + // A fullscreen window won't minimize everywhere, so drop it first. The + // restore puts it back. + SDL_SetWindowFullscreen(g_pSDLWindow, 0); + SDL_MinimizeWindow(g_pSDLWindow); +} + +bool Console_Power(int action) +{ + SaveDesktopSettings(); + fflush(stdout); + fflush(stderr); + return Host_Power(action); +} + +// What a child's exit code asks the watchdog for. Anything else nonzero is a crash. +enum { RELAUNCH_SAME = 75, RELAUNCH_DASHBOARD, RELAUNCH_DEVELOPMENT }; + +// The watchdog's own lines go to the terminal and the end of theseus.log. +// The child is gone by then, and its next run keeps this log as theseus.prev.log. +static void WatchdogLog(const char* fmt, ...) +{ + char line[512]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + fprintf(stderr, "[Console] %s\n", line); + char path[1024]; + snprintf(path, sizeof(path), "%s/theseus.log", Plat_UserDataDir()); + if (FILE* f = fopen(path, "a")) { + fprintf(f, "[Console] %s\n", line); + fclose(f); + } +} + +static bool IsModeFlag(const char* a) +{ + return !strcmp(a, "--dashboard") || !strcmp(a, "--development") || !strcmp(a, "--preview"); +} + +bool Console_Supervise(int argc, char** argv, int* code) +{ + bool console = false; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--supervised")) g_consoleSupervised = true; + if (!strcmp(argv[i], "--console")) console = true; + } + if (!console || g_consoleSupervised) return false; + + std::vector args(argv, argv + argc); + args.push_back("--supervised"); + time_t lastCrash = 0; + for (;;) { + std::vector list; + for (size_t i = 0; i < args.size(); i++) list.push_back(args[i].c_str()); + list.push_back(NULL); + + int exitCode = 0; + char how[128]; + int outcome = Host_RunSelf(list.data(), &exitCode, how, sizeof(how)); + if (outcome == HOST_CHILD_FAILED) { + WatchdogLog("couldn't start UIX Desktop"); + *code = 1; + return true; + } + if (outcome == HOST_CHILD_EXITED && exitCode == 0) { + *code = 0; + return true; + } + if (outcome == HOST_CHILD_EXITED && exitCode >= RELAUNCH_SAME && exitCode <= RELAUNCH_DEVELOPMENT) { + if (exitCode != RELAUNCH_SAME) { + std::vector kept; + for (size_t i = 0; i < args.size(); i++) + if (!IsModeFlag(args[i].c_str())) kept.push_back(args[i]); + kept.push_back(exitCode == RELAUNCH_DASHBOARD ? "--dashboard" : "--development"); + args.swap(kept); + } + WatchdogLog("restarting UIX Desktop"); + continue; + } + time_t now = time(NULL); + if (lastCrash && now - lastCrash < 60) { + WatchdogLog("UIX Desktop crashed again within a minute (%s). Not starting it again.", how); + *code = 1; + return true; + } + lastCrash = now; + WatchdogLog("UIX Desktop crashed (%s). Starting it again.", how); + } +} + +void Console_RestartViaWatchdog(const char* mode) +{ + if (!g_consoleSupervised || Host_ExecKeepsProcess()) return; + int code = !mode ? RELAUNCH_SAME : !strcmp(mode, "--development") ? RELAUNCH_DEVELOPMENT : RELAUNCH_DASHBOARD; + fflush(stdout); + fflush(stderr); + // Like exec: nothing else runs on the way out. + _Exit(code); +} diff --git a/theseus/desktop/console_mode.h b/theseus/desktop/console_mode.h new file mode 100644 index 0000000..95362a7 --- /dev/null +++ b/theseus/desktop/console_mode.h @@ -0,0 +1,26 @@ +// console_mode.h: UIX Desktop standing in for the machine's own front end. +// Fullscreen, no frame, straight into the dashboard. The OS shell stays +// where it was underneath. +#pragma once + +extern bool g_consoleMode; // desktop.ini ConsoleMode +extern bool g_consoleFlag; // --console, this run only +extern bool g_consoleSupervised; // --supervised: a watchdog started us + +// Either of the two. +bool Console_Active(); + +// Minimizes the window. It comes back fullscreen when it's restored. +void Console_GoToDesktop(); +// Saves settings and flushes the log, then asks the host (host.h HOST_POWER_). +bool Console_Power(int action); + +// --console starts a small watchdog first: it runs the app as its child +// (adding --supervised) and starts it again after a crash, unless it +// crashed twice within a minute. True when this process was the watchdog +// and main should return code. +bool Console_Supervise(int argc, char** argv, int* code); +// Under the watchdog where exec can't keep the process, a restart is the +// watchdog's job: this exits asking for one. mode is the new mode flag, or +// NULL for the same. Returns when it isn't the case. +void Console_RestartViaWatchdog(const char* mode); diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index 8245087..ee058ec 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -11,6 +11,8 @@ #include "media_player.h" #include "virtual_games.h" #include "pads.h" +#include "console_mode.h" +#include "host.h" extern char s_xemuPath[512]; extern char s_pcsx2Path[512]; @@ -52,6 +54,15 @@ static void ApplyStartupMode() { g_startupMode = s_startupModeSaved; } bool g_hideDuplicateGames = true; static void ApplyDuplicates() { g_vgames.generation++; } +// What the OS says, not desktop.ini: the login entry is the setting. +static bool s_startAtLogin = false; +static void ApplyStartAtLogin() +{ + if (!Host_SetStartAtLogin(s_startAtLogin)) + fprintf(stderr, "[Console] couldn't %s the login entry\n", s_startAtLogin ? "add" : "remove"); + s_startAtLogin = Host_StartAtLogin(); +} + static void ApplyMsaa() { g_msaaChangeRequested = true; } static void ApplyVsync() { g_vsyncChangeRequested = true; } static void ApplyDisplay() { g_displayChangeRequested = true; } @@ -133,6 +144,10 @@ static const SettingDef kDefs[] = { S_BOOL("ShowSteamTab", "Desktop", "Games", "Steam Tab", g_showSteamTab, "1", 0), { "StartupMode", "Desktop", "General", "When UIX Desktop Starts", SK_ENUM, &s_startupModeSaved, 0, "", 0, ENUM(kStartupVals, kStartupLbl, kStartupTok), 0, 0, 0, NULL, ApplyStartupMode }, + { "ConsoleMode", "Desktop", "General", "Console Mode", SK_BOOL, &g_consoleMode, 0, "0", 0, + NOENUM, 0, 0, 0, NULL, ApplyDisplay }, + { "StartAtLogin", "Desktop", "General", "Start at Login", SK_BOOL, &s_startAtLogin, 0, "0", SF_LIVE, + NOENUM, 0, 0, 0, NULL, ApplyStartAtLogin }, S_BOOL("UseOnScreenKeyboard", "Desktop", "General", "On-Screen Keyboard Only", g_bUseOnScreenKeyboard, "0", 0), S_BOOL("ShowBootAnimation", "Desktop", "General", "Boot Animation", g_bShowBootAnimation, "1", 0), { "MSAA", "Desktop", "Display", "MSAA", SK_ENUM, &g_msaaSamples, 0, "4", SF_STRICT, @@ -214,9 +229,15 @@ const SettingDef* DesktopSettings_Find(const char* key) return NULL; } +void DesktopSettings_ReadLive() +{ + s_startAtLogin = Host_StartAtLogin(); +} + void LoadDesktopSettings() { Settings_Load(DesktopSettings_Table(), AppPath("Configs/desktop.ini")); + DesktopSettings_ReadLive(); ApplyStartupMode(); TheseusSetProjectionDirty(); } diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index ebabcdd..c8c363a 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -37,6 +37,7 @@ #include "launchers/steam.h" #include "settings_backup.h" #include "launchers/stores.h" +#include "console_mode.h" #include #include #include @@ -65,6 +66,7 @@ extern char** g_argv; // Starts this program over with one mode flag in place of any other. static void RestartWithMode(const char* flag) { + Console_RestartViaWatchdog(flag); std::vector args; args.push_back(g_argv[0]); for (int i = 1; i < g_argc; i++) { @@ -81,6 +83,7 @@ static void RestartWithMode(const char* flag) // Starts this program over the way it was started. static void Restart() { + Console_RestartViaWatchdog(NULL); execv(g_argv[0], g_argv); fprintf(stderr, "[Guide] restart failed: %s\n", strerror(errno)); } @@ -252,6 +255,8 @@ static const char* SettingHelp(const SettingDef& d) { static const struct { const char* key; const char* help; } kHelp[] = { { "StartupMode", "What happens when UIX Desktop starts." }, + { "StartAtLogin", "Starts UIX Desktop in Console Mode when you sign in. Only for you, nothing system wide." }, + { "ConsoleMode", "Fullscreen with no frame, straight into the dashboard. For a TV or a games machine." }, { "UseOnScreenKeyboard", "Text fields ignore the physical keyboard and use the pad keyboard." }, { "ShowBootAnimation", "Play the Xbox boot animation once at startup." }, { "MenuBarAutoHide", "In Development Mode the tool bar shows when the pointer reaches the top." }, @@ -288,7 +293,7 @@ static const char* kSections[SEC_COUNT] = { enum View { GV_PAGE, GV_ACCOUNTS, GV_LIBRARY, GV_ADDGAME, GV_BROWSE, GV_PLAYLISTS, GV_PLAYLIST, GV_LOGS, GV_SHORTCUTS, GV_ABOUT, GV_TOOLS, GV_EXIT, GV_WELCOME, GV_GAMES, GV_GAME, GV_LETTERS, GV_APPS, - GV_COLLECTIONS, GV_GAMECOLL, GV_BACKUPS, GV_RESTORE }; + GV_COLLECTIONS, GV_GAMECOLL, GV_BACKUPS, GV_RESTORE, GV_POWER }; // What a game list shows. enum GameList { GL_FAVORITES, GL_RECENT, GL_HIDDEN, GL_ALL, GL_LETTER, GL_SEARCH, GL_COLLECTION }; @@ -309,6 +314,7 @@ enum Act { GA_FINDEMU, GA_RUNNER, GA_APPS, GA_APP, GA_APPGAMES, GA_GAMEOPT, GA_STORE, GA_COLLECTION, GA_GAMECOLL, GA_INCOLL, GA_NEWCOLL, GA_BACKUP, GA_BACKUPS, GA_PICKBACKUP, GA_RESTORE, GA_OPENBACKUPS, + GA_DESKTOP, GA_POWER, GA_POWERNOW, GA_CANCEL, GA_SYSSETTINGS, GA_COUNT }; @@ -398,6 +404,7 @@ static struct Guide { int sort; // All Games' order, a SORT_ std::vector backups; // GV_BACKUPS' rows, newest first std::string backup; // the one GV_RESTORE offers + int power; // the HOST_POWER_ GV_POWER asks about std::vector collNames; // the game page's Collections rows, kept while it's open unsigned gameLayout; // g_vgames.layout when game was picked @@ -1038,6 +1045,11 @@ static void Build() Add("Playlist Maker", "F6", "Make and edit playlists.", GA_WINDOW, WIN_PLAYLISTS); if (g_padModeEnabled) Add("Use the Tools with the Pad", "", "The tool windows' own controller menu.", GA_PADTOOLS); + if (Host_HasSystemSettings()) { + Caption("This machine"); + Add("System Settings", g.result[GA_SYSSETTINGS].c_str(), "Opens your computer's own settings.", + GA_SYSSETTINGS); + } if (g_startupMode == 2 || g_extractedMode) { Caption("Development mode"); Add("Inspector", "F1", "Development mode.", GA_WINDOW, WIN_INSPECTOR); @@ -1046,9 +1058,29 @@ static void Build() break; case GV_EXIT: Add("Back to the Dashboard", "", "Closes the guide.", GA_RESUME); + if (!Console_Active()) { + Add("Exit UIX Desktop", "", "Quit to your desktop.", GA_QUIT); + break; + } + Add("Go to Desktop", "", "Puts UIX Desktop away. It keeps running.", GA_DESKTOP); Add("Exit UIX Desktop", "", "Quit to your desktop.", GA_QUIT); + Caption("Power"); + Add("Sleep", g.result[GA_POWER].c_str(), "Sleeps the machine. UIX Desktop is still here when it wakes.", + GA_POWER, HOST_POWER_SLEEP); + Add("Restart", "", "Restarts the machine.", GA_POWER, HOST_POWER_RESTART); + Add("Shut Down", "", "Turns the machine off.", GA_POWER, HOST_POWER_SHUTDOWN); + break; + case GV_POWER: { + bool restart = g.power == HOST_POWER_RESTART; + Para(restart ? "This restarts the whole machine. Other apps are asked to close first, and anything " + "unsaved in them could be lost." + : "This turns the whole machine off. Other apps are asked to close first, and anything " + "unsaved in them could be lost."); + Add(restart ? "Restart Now" : "Shut Down Now", g.result[GA_POWERNOW].c_str(), NULL, GA_POWERNOW, g.power); + Add("Cancel", "", NULL, GA_CANCEL); break; } + } if (g.cursor >= (int)g.rows.size()) g.cursor = g.rows.empty() ? 0 : (int)g.rows.size() - 1; if (g.cursor < 0) g.cursor = 0; SnapCursor(1); @@ -1065,6 +1097,7 @@ static const char* ViewTitle() case GV_COLLECTIONS: return "Collections"; case GV_BACKUPS: return "Restore a Backup"; case GV_RESTORE: return g.backup.c_str(); + case GV_POWER: return g.power == HOST_POWER_RESTART ? "Restart" : "Shut Down"; case GV_GAMECOLL: return "Collections"; case GV_GAMES: { static char title[32], full[96]; @@ -1112,6 +1145,7 @@ static void Open(bool welcome) g.held = Joy_GuideButtons(&g.device); g.repeatHeld = 0; g_padModeActive = false; + DesktopSettings_ReadLive(); if (welcome) { g.view = GV_WELCOME; g.stack.clear(); @@ -1818,6 +1852,50 @@ static void Select() if (CopyLog()) g.copied = GA_COPYLOG; else Refuse(); Build(); break; + case GA_DESKTOP: + Close(); + Console_GoToDesktop(); + break; + case GA_POWER: + g.result[GA_POWER].clear(); + if (r.arg != HOST_POWER_SLEEP) { + g.power = r.arg; + g.result[GA_POWERNOW].clear(); + Push(GV_POWER); + // Cancel is the safe place to start. + g.cursor = (int)g.rows.size() - 1; + break; + } + if (Console_Power(HOST_POWER_SLEEP)) { + Close(); + } else { + g.result[GA_POWER] = "Didn't work"; + Refuse(); + Build(); + } + break; + case GA_POWERNOW: + if (!Console_Power(r.arg)) { + g.result[GA_POWERNOW] = "Didn't work"; + Refuse(); + Build(); + } + break; + case GA_CANCEL: + Back(); + break; + case GA_SYSSETTINGS: + if (!Host_OpenSystemSettings()) { + g.result[GA_SYSSETTINGS] = "Didn't open"; + Refuse(); + Build(); + break; + } + g.result[GA_SYSSETTINGS].clear(); + Close(); + // A fullscreen console would sit on top of it. + if (Console_Active()) Console_GoToDesktop(); + break; case GA_QUIT: { SDL_Event quit; quit.type = SDL_QUIT; @@ -2109,6 +2187,41 @@ static std::string Fit(int font, float size, const std::string& text, float widt return "..."; } +// Only on battery or charging; a desktop on mains power shows nothing. The +// OS is asked every half minute, not every frame. +static void DrawBattery(float right, float y) +{ + static Uint32 s_asked = 0; + static SDL_PowerState s_state = SDL_POWERSTATE_UNKNOWN; + static int s_pct = -1; + if (!s_asked || SDL_GetTicks() - s_asked > 30000) { + s_asked = SDL_GetTicks(); + s_state = SDL_GetPowerInfo(NULL, &s_pct); + // Development only: UIX_DEV_BATTERY=40, or 40c for charging, pretends there's one. + if (const char* fake = getenv("UIX_DEV_BATTERY")) { + s_pct = atoi(fake); + s_state = strchr(fake, 'c') ? SDL_POWERSTATE_CHARGING : SDL_POWERSTATE_ON_BATTERY; + } + } + if (s_state != SDL_POWERSTATE_ON_BATTERY && s_state != SDL_POWERSTATE_CHARGING) return; + char text[32]; + if (s_pct < 0) snprintf(text, sizeof(text), s_state == SDL_POWERSTATE_CHARGING ? "Charging" : "Battery"); + else snprintf(text, sizeof(text), s_state == SDL_POWERSTATE_CHARGING ? "%d%%, charging" : "%d%%", s_pct); + unsigned int faint = ui_style_color(UI_COLOR_FAINT); + float tx = right - ui_overlay_text_width(UI_FONT_REGULAR, 8.5f, text); + ui_overlay_text(UI_FONT_REGULAR, 8.5f, right, y, UI_ALIGN_RIGHT, faint, text); + // A little battery: outline, nub and how full it is. + const float w = 15, h = 7, bx = tx - w - 7, by = y + 2; + ui_overlay_rect(bx, by, w, 1, 0, faint); + ui_overlay_rect(bx, by + h - 1, w, 1, 0, faint); + ui_overlay_rect(bx, by, 1, h, 0, faint); + ui_overlay_rect(bx + w - 1, by, 1, h, 0, faint); + ui_overlay_rect(bx + w, by + 2, 2, h - 4, 0, faint); + int pct = s_pct < 0 ? 100 : s_pct; + ui_overlay_rect(bx + 2, by + 2, (w - 4) * pct / 100.0f, h - 4, 0, + pct <= 15 && s_state == SDL_POWERSTATE_ON_BATTERY ? ui_style_color(UI_COLOR_WARNING) : faint); +} + static void DrawHeader(const char* title) { ui_overlay_text_glow(UI_FONT_BOLD, 17.0f, CONTENT_L, HEADER_Y + 4, UI_ALIGN_LEFT, @@ -2118,6 +2231,7 @@ static void DrawHeader(const char* title) ui_overlay_text(UI_FONT_BOLD, 10.0f, CONTENT_R, HEADER_Y + 3, UI_ALIGN_RIGHT, ui_style_color(UI_COLOR_NAME), line); ui_overlay_text(UI_FONT_REGULAR, 8.5f, CONTENT_R, HEADER_Y + 17, UI_ALIGN_RIGHT, ui_style_color(UI_COLOR_FAINT), Host_Name()); + DrawBattery(CONTENT_R - ui_overlay_text_width(UI_FONT_REGULAR, 8.5f, Host_Name()) - 14, HEADER_Y + 17); ui_overlay_rect(CONTENT_L - 4, RULE_Y, CONTENT_R - CONTENT_L + 8, 1, 0, ui_style_color(UI_COLOR_RULE)); } diff --git a/theseus/desktop/host.h b/theseus/desktop/host.h index b110ae9..ce6885c 100644 --- a/theseus/desktop/host.h +++ b/theseus/desktop/host.h @@ -100,6 +100,34 @@ enum { HOST_REG_USER, HOST_REG_MACHINE }; bool Host_RegistryValue(int hive, const char* subKey, const char* value, char* out, size_t outSize); // Names of the keys right under subKey, up to max. 0 when there are none or off Windows. int Host_RegistrySubkeys(int hive, const char* subKey, char (*out)[256], int max); +// Write a text value or delete one, under HKEY_CURRENT_USER only. Always false off Windows. +bool Host_RegistrySetString(const char* subKey, const char* value, const char* data); +bool Host_RegistryDelete(const char* subKey, const char* value); + +// Start at login, for this user only: a LaunchAgent on macOS, an XDG +// autostart entry on Linux, the HKCU Run key on Windows. It runs this +// program with --console. Turning it off removes just that entry. +bool Host_StartAtLogin(); +bool Host_SetStartAtLogin(bool on); + +// Sleep, restart or shut down the machine, the way the OS's own menu does. +// UIX_DEV_POWER_DRYRUN=1 only logs what it would do. False when the OS refused. +enum { HOST_POWER_SLEEP, HOST_POWER_RESTART, HOST_POWER_SHUTDOWN }; +bool Host_Power(int action); + +// Runs this program again with args (args[0] is skipped; NULL ends them), +// no shell, and waits for it. HOST_CHILD_EXITED with its exit code, or +// HOST_CHILD_CRASHED with what killed it in how. Asking us to stop while +// it runs passes the request on to the child. +enum { HOST_CHILD_FAILED = -1, HOST_CHILD_EXITED, HOST_CHILD_CRASHED }; +int Host_RunSelf(const char* const* args, int* code, char* how, size_t howSize); +// True where exec swaps the program in place and keeps the process (macOS, +// Linux). Windows starts a new one and ends this one instead. +bool Host_ExecKeepsProcess(); + +// The OS's own settings app. Has is false when there isn't one we can open. +bool Host_HasSystemSettings(); +bool Host_OpenSystemSettings(); // Audio CD in the first optical drive: track count and per-track lengths // in seconds. -1 when there's no readable disc. int Host_CdReadToc(int* durations, int maxTracks, bool* allAudio); diff --git a/theseus/desktop/host_posix_app.cpp b/theseus/desktop/host_posix_app.cpp index 77e3072..2460f74 100644 --- a/theseus/desktop/host_posix_app.cpp +++ b/theseus/desktop/host_posix_app.cpp @@ -586,6 +586,302 @@ void Host_OpenFolder(const char* dir) { bool Host_RegistryString(const char*, const char*, char*, size_t) { return false; } bool Host_RegistryValue(int, const char*, const char*, char*, size_t) { return false; } int Host_RegistrySubkeys(int, const char*, char (*)[256], int) { return 0; } +bool Host_RegistrySetString(const char*, const char*, const char*) { return false; } +bool Host_RegistryDelete(const char*, const char*) { return false; } + +// Start at login. Both entries live under the user's home, so a run with a +// throwaway HOME never touches the real account. +static std::string LoginEntryPath() { + const char* home = getenv("HOME"); + std::string h = home ? home : ""; +#ifdef __APPLE__ + return h + "/Library/LaunchAgents/com.teamuix.theseus.plist"; +#else + const char* xdg = getenv("XDG_CONFIG_HOME"); + std::string base = (xdg && *xdg == '/') ? std::string(xdg) : h + "/.config"; + return base + "/autostart/uix-desktop.desktop"; +#endif +} + +static bool MakeDirs(const std::string& dir) { + for (size_t i = 1; i <= dir.size(); i++) + if (i == dir.size() || dir[i] == '/') + if (mkdir(dir.substr(0, i).c_str(), 0755) != 0 && errno != EEXIST) return false; + return true; +} + +// Beside it first, then over it, so a half written entry never runs. +static bool WriteWhole(const std::string& path, const std::string& text) { + if (!MakeDirs(path.substr(0, path.rfind('/')))) return false; + std::string tmp = path + ".tmp"; + FILE* f = fopen(tmp.c_str(), "w"); + if (!f) return false; + bool ok = fwrite(text.data(), 1, text.size(), f) == text.size(); + ok = (fclose(f) == 0) && ok; + if (ok && rename(tmp.c_str(), path.c_str()) == 0) return true; + unlink(tmp.c_str()); + return false; +} + +#ifdef __APPLE__ +static std::string XmlEscape(const std::string& in) { + std::string out; + for (char c : in) { + if (c == '&') out += "&"; + else if (c == '<') out += "<"; + else if (c == '>') out += ">"; + else out += c; + } + return out; +} + +static std::string LoginEntryText(const std::string& exe) { + return "\n" + "\n" + "\n\n" + "\tLabel\n\tcom.teamuix.theseus\n" + "\tProgramArguments\n\t\n" + "\t\t" + XmlEscape(exe) + "\n" + "\t\t--console\n" + "\t\n" + "\tRunAtLoad\n\t\n" + "\tLimitLoadToSessionType\n\tAqua\n" + "\n\n"; +} +#else +// Exec= quoting from the desktop entry spec: the argument in double quotes +// with " ` $ \ backslashed, then every backslash doubled for the string +// itself, and % as %%. +static std::string ExecQuote(const std::string& in) { + std::string q = "\""; + for (char c : in) { + if (c == '"' || c == '`' || c == '$' || c == '\\') q += '\\'; + q += c; + } + q += '"'; + std::string out; + for (char c : q) { + if (c == '\\') out += "\\\\"; + else if (c == '%') out += "%%"; + else out += c; + } + return out; +} + +static std::string LoginEntryText(const std::string& exe) { + return "[Desktop Entry]\n" + "Type=Application\n" + "Name=UIX Desktop\n" + "Comment=Starts UIX Desktop in Console Mode\n" + "Exec=" + ExecQuote(exe) + " --console\n" + "Terminal=false\n" + "X-GNOME-Autostart-enabled=true\n"; +} +#endif + +static bool PowerDryRun() { + const char* v = getenv("UIX_DEV_POWER_DRYRUN"); + return v && *v && strcmp(v, "0") != 0; +} + +bool Host_Power(int action) { + static const char* const kNames[] = { "sleep", "restart", "shut down" }; + if (action < HOST_POWER_SLEEP || action > HOST_POWER_SHUTDOWN) return false; +#ifdef __APPLE__ + // System Events asks every app to quit first, the same as the Apple menu. + const char* const kSleep[] = { "pmset", "sleepnow", NULL }; + const char* const kRestart[] = { "osascript", "-e", "tell application \"System Events\" to restart", NULL }; + const char* const kShutdown[] = { "osascript", "-e", "tell application \"System Events\" to shut down", NULL }; +#else + // logind lets the active local session do these without a password. + const char* const kSleep[] = { "systemctl", "suspend", NULL }; + const char* const kRestart[] = { "systemctl", "reboot", NULL }; + const char* const kShutdown[] = { "systemctl", "poweroff", NULL }; +#endif + const char* const* argv = action == HOST_POWER_SLEEP ? kSleep : action == HOST_POWER_RESTART ? kRestart : kShutdown; + std::string line; + for (int i = 0; argv[i]; i++) { + if (i) line += ' '; + line += strchr(argv[i], ' ') ? "'" + std::string(argv[i]) + "'" : argv[i]; + } + if (PowerDryRun()) { + fprintf(stderr, "[Power] would %s: %s\n", kNames[action], line.c_str()); + return true; + } + fprintf(stderr, "[Power] %s: %s\n", kNames[action], line.c_str()); + fflush(stderr); + pid_t pid = fork(); + if (pid == 0) { + RestoreHostLibraryPath(); +#ifndef __APPLE__ + if (getenv("FLATPAK_ID")) { + const char* host[8] = { "flatpak-spawn", "--host" }; + for (int i = 0; argv[i] && i < 5; i++) host[i + 2] = argv[i]; + execvp(host[0], (char* const*)host); + } +#endif + execvp(argv[0], (char* const*)argv); + _exit(127); + } + if (pid < 0) return false; + // These answer quickly when they're refused. Still going after a few + // seconds means it's happening. + for (int i = 0; i < 30; i++) { + int status; + pid_t r = waitpid(pid, &status, WNOHANG); + if (r == pid) { + bool ok = WIFEXITED(status) && WEXITSTATUS(status) == 0; + if (!ok) fprintf(stderr, "[Power] %s was refused\n", kNames[action]); + return ok; + } + if (r < 0) return false; + usleep(100 * 1000); + } + return true; +} + +// The supervisor hands a stop on to the child and keeps waiting for it. +static volatile pid_t s_selfChild = 0; +static void ForwardStop(int sig) { + if (s_selfChild > 0) kill(s_selfChild, sig); +} + +int Host_RunSelf(const char* const* args, int* code, char* how, size_t howSize) { + *code = 0; + if (howSize) how[0] = '\0'; + char exe[1024]; + if (!Host_ExePath(exe, sizeof(exe))) return HOST_CHILD_FAILED; + std::vector argv; + argv.push_back(exe); + for (int i = 1; args[i]; i++) argv.push_back(args[i]); + argv.push_back(NULL); + + struct sigaction sa = {}, old[3]; + sa.sa_handler = ForwardStop; + sigemptyset(&sa.sa_mask); + static const int kStops[3] = { SIGTERM, SIGINT, SIGHUP }; + for (int i = 0; i < 3; i++) sigaction(kStops[i], &sa, &old[i]); + + pid_t pid = fork(); + if (pid == 0) { + for (int i = 0; i < 3; i++) sigaction(kStops[i], &old[i], NULL); + execv(exe, (char* const*)argv.data()); + _exit(127); + } + int result = HOST_CHILD_FAILED; + if (pid > 0) { + s_selfChild = pid; + int status = 0; + pid_t r; + while ((r = waitpid(pid, &status, 0)) < 0 && errno == EINTR) {} + s_selfChild = 0; + if (r == pid && WIFSIGNALED(status)) { + *code = WTERMSIG(status); + snprintf(how, howSize, "%s, signal %d", SignalName(*code), *code); + result = HOST_CHILD_CRASHED; + } else if (r == pid && WIFEXITED(status)) { + *code = WEXITSTATUS(status); + snprintf(how, howSize, "exit code %d", *code); + result = HOST_CHILD_EXITED; + } + } + for (int i = 0; i < 3; i++) sigaction(kStops[i], &old[i], NULL); + return result; +} + +bool Host_ExecKeepsProcess() { return true; } + +#ifndef __APPLE__ +static bool OnPath(const char* name) { + const char* path = getenv("PATH"); + if (!path) return false; + std::string dirs = path; + size_t at = 0; + while (at <= dirs.size()) { + size_t end = dirs.find(':', at); + if (end == std::string::npos) end = dirs.size(); + std::string full = dirs.substr(at, end - at) + "/" + name; + if (end > at && access(full.c_str(), X_OK) == 0) return true; + at = end + 1; + } + return false; +} + +// What opens the settings: GNOME's, then Plasma's, then whatever claims +// settings:// links. Empty when none of them is here. +static const char* const* SettingsCommand() { + static const char* const kGnome[] = { "gnome-control-center", NULL }; + static const char* const kPlasma[] = { "systemsettings", NULL }; + static const char* const kLink[] = { "xdg-open", "settings://", NULL }; + static int s_found = -1; + if (s_found < 0) { + s_found = 0; + if (OnPath("gnome-control-center")) s_found = 1; + else if (OnPath("systemsettings")) s_found = 2; + else if (OnPath("xdg-open") && OnPath("xdg-mime")) { + FILE* p = popen("xdg-mime query default x-scheme-handler/settings 2>/dev/null", "r"); + char line[256] = ""; + if (p) { + if (!fgets(line, sizeof(line), p)) line[0] = '\0'; + pclose(p); + } + if (strstr(line, ".desktop")) s_found = 3; + } + } + return s_found == 1 ? kGnome : s_found == 2 ? kPlasma : s_found == 3 ? kLink : NULL; +} +#endif + +bool Host_HasSystemSettings() { +#ifdef __APPLE__ + return true; +#else + return SettingsCommand() != NULL; +#endif +} + +bool Host_OpenSystemSettings() { +#ifdef __APPLE__ + const char* const argv[] = { "open", "x-apple.systempreferences:", NULL }; +#else + const char* const* argv = SettingsCommand(); + if (!argv) return false; +#endif + pid_t pid = fork(); + if (pid == 0) { + RestoreHostLibraryPath(); + execvp(argv[0], (char* const*)argv); + _exit(127); + } + return pid > 0; +} + +bool Host_StartAtLogin() { + struct stat st; + return stat(LoginEntryPath().c_str(), &st) == 0; +} + +bool Host_SetStartAtLogin(bool on) { + std::string path = LoginEntryPath(); + if (!on) { + if (unlink(path.c_str()) == 0 || errno == ENOENT) { + fprintf(stderr, "[Console] login entry removed: %s\n", path.c_str()); + return true; + } + return false; + } + char exe[1024]; + if (!Host_ExePath(exe, sizeof(exe))) return false; + std::string target = exe; +#ifndef __APPLE__ + // An AppImage runs from a mount that's gone next login; the file itself stays. + const char* appimage = getenv("APPIMAGE"); + if (appimage && *appimage) target = appimage; +#endif + if (!WriteWhole(path, LoginEntryText(target))) return false; + fprintf(stderr, "[Console] login entry written: %s\n", path.c_str()); + return true; +} void Host_SetEnv(const char* name, const char* value) { if (value) setenv(name, value, 1); diff --git a/theseus/desktop/host_win_app.cpp b/theseus/desktop/host_win_app.cpp index 6d6bf49..a12b9c5 100644 --- a/theseus/desktop/host_win_app.cpp +++ b/theseus/desktop/host_win_app.cpp @@ -538,6 +538,168 @@ bool Host_RegistryValue(int hive, const char* subKey, const char* value, char* o return ok; } +bool Host_RegistrySetString(const char* subKey, const char* value, const char* data) { + HKEY hKey; + if (RegCreateKeyExA(HKEY_CURRENT_USER, subKey, 0, NULL, 0, KEY_SET_VALUE, NULL, &hKey, NULL) != ERROR_SUCCESS) + return false; + bool ok = RegSetValueExA(hKey, value, 0, REG_SZ, (const BYTE*)data, (DWORD)strlen(data) + 1) == ERROR_SUCCESS; + RegCloseKey(hKey); + return ok; +} + +bool Host_RegistryDelete(const char* subKey, const char* value) { + HKEY hKey; + LONG r = RegOpenKeyExA(HKEY_CURRENT_USER, subKey, 0, KEY_SET_VALUE, &hKey); + if (r == ERROR_FILE_NOT_FOUND) return true; + if (r != ERROR_SUCCESS) return false; + r = RegDeleteValueA(hKey, value); + RegCloseKey(hKey); + return r == ERROR_SUCCESS || r == ERROR_FILE_NOT_FOUND; +} + +// Start at login: one value under the user's own Run key. +static const char kRunKey[] = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; +static const char kRunValue[] = "UIX Desktop"; + +bool Host_StartAtLogin() { + char cur[MAX_PATH + 32]; + return Host_RegistryValue(HOST_REG_USER, kRunKey, kRunValue, cur, sizeof(cur)); +} + +bool Host_SetStartAtLogin(bool on) { + if (!on) return Host_RegistryDelete(kRunKey, kRunValue); + char exe[MAX_PATH], cmd[MAX_PATH + 32]; + if (!Host_ExePath(exe, sizeof(exe))) return false; + snprintf(cmd, sizeof(cmd), "\"%s\" --console", exe); + return Host_RegistrySetString(kRunKey, kRunValue, cmd); +} + +// One argument the way CommandLineToArgvW will read it back. +static void AppendArg(std::string& cmd, const char* arg) { + if (!cmd.empty()) cmd += ' '; + if (*arg && !strpbrk(arg, " \t\n\v\"")) { + cmd += arg; + return; + } + cmd += '"'; + for (const char* p = arg;; p++) { + size_t slashes = 0; + while (*p == '\\') { p++; slashes++; } + if (!*p) { + cmd.append(slashes * 2, '\\'); + break; + } + if (*p == '"') cmd.append(slashes * 2 + 1, '\\'); + else cmd.append(slashes, '\\'); + cmd += *p; + } + cmd += '"'; +} + +// The supervisor hands Ctrl+C and a console close on to the child. +static volatile HANDLE s_selfChild = NULL; +static BOOL WINAPI ForwardStop(DWORD) { + HANDLE h = s_selfChild; + if (h) TerminateProcess(h, 0); + return TRUE; +} + +int Host_RunSelf(const char* const* args, int* code, char* how, size_t howSize) { + *code = 0; + if (howSize) how[0] = '\0'; + char exe[MAX_PATH]; + if (!Host_ExePath(exe, sizeof(exe))) return HOST_CHILD_FAILED; + std::string cmd; + AppendArg(cmd, exe); + for (int i = 1; args[i]; i++) AppendArg(cmd, args[i]); + std::vector line(cmd.begin(), cmd.end()); + line.push_back('\0'); + + STARTUPINFOA si = {}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi = {}; + if (!CreateProcessA(exe, line.data(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) return HOST_CHILD_FAILED; + CloseHandle(pi.hThread); + s_selfChild = pi.hProcess; + SetConsoleCtrlHandler(ForwardStop, TRUE); + WaitForSingleObject(pi.hProcess, INFINITE); + SetConsoleCtrlHandler(ForwardStop, FALSE); + s_selfChild = NULL; + DWORD status = 0; + GetExitCodeProcess(pi.hProcess, &status); + CloseHandle(pi.hProcess); + *code = (int)status; + // An unhandled exception ends the process with its NTSTATUS, 0xC... + if ((status & 0xF0000000UL) == 0xC0000000UL || status == CRASH_FATAL_APP_EXIT) { + snprintf(how, howSize, "%s, 0x%08lX", ExceptionName(status), (unsigned long)status); + return HOST_CHILD_CRASHED; + } + snprintf(how, howSize, "exit code %lu", (unsigned long)status); + return HOST_CHILD_EXITED; +} + +bool Host_ExecKeepsProcess() { return false; } + +bool Host_HasSystemSettings() { return true; } + +bool Host_OpenSystemSettings() { + return (INT_PTR)ShellExecuteA(NULL, "open", "ms-settings:", NULL, NULL, SW_SHOWNORMAL) > 32; +} + +static bool PowerDryRun() { + const char* v = getenv("UIX_DEV_POWER_DRYRUN"); + return v && *v && strcmp(v, "0") != 0; +} + +// Restart and shut down need the shutdown privilege switched on first. +static bool EnableShutdownPrivilege() { + HANDLE token; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) return false; + TOKEN_PRIVILEGES tp = {}; + tp.PrivilegeCount = 1; + tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + bool ok = LookupPrivilegeValueA(NULL, SE_SHUTDOWN_NAME, &tp.Privileges[0].Luid) && + AdjustTokenPrivileges(token, FALSE, &tp, 0, NULL, NULL) && GetLastError() == ERROR_SUCCESS; + CloseHandle(token); + return ok; +} + +bool Host_Power(int action) { + static const char* const kNames[] = { "sleep", "restart", "shut down" }; + static const char* const kCalls[] = { + "SetSuspendState(FALSE, FALSE, FALSE)", + "ExitWindowsEx(EWX_REBOOT)", + "ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF)", + }; + if (action < HOST_POWER_SLEEP || action > HOST_POWER_SHUTDOWN) return false; + if (PowerDryRun()) { + fprintf(stderr, "[Power] would %s: %s\n", kNames[action], kCalls[action]); + return true; + } + fprintf(stderr, "[Power] %s: %s\n", kNames[action], kCalls[action]); + fflush(stderr); + if (action == HOST_POWER_SLEEP) { + // powrprof isn't always loaded, so look it up rather than link it. + typedef BOOLEAN (WINAPI *SuspendFn)(BOOLEAN, BOOLEAN, BOOLEAN); + HMODULE dll = LoadLibraryA("powrprof.dll"); + SuspendFn suspend = dll ? (SuspendFn)GetProcAddress(dll, "SetSuspendState") : NULL; + bool ok = suspend && suspend(FALSE, FALSE, FALSE); + if (dll) FreeLibrary(dll); + if (!ok) fprintf(stderr, "[Power] sleep was refused (error %lu)\n", GetLastError()); + return ok; + } + if (!EnableShutdownPrivilege()) { + fprintf(stderr, "[Power] no shutdown privilege (error %lu)\n", GetLastError()); + return false; + } + UINT how = action == HOST_POWER_RESTART ? EWX_REBOOT : (EWX_SHUTDOWN | EWX_POWEROFF); + if (!ExitWindowsEx(how, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED)) { + fprintf(stderr, "[Power] %s was refused (error %lu)\n", kNames[action], GetLastError()); + return false; + } + return true; +} + static HANDLE OpenCdromDevice() { char path[] = "\\\\.\\D:"; for (char c = 'D'; c <= 'H'; ++c) { diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index d03cab5..7084e87 100644 --- a/theseus/desktop/sdl_main.cpp +++ b/theseus/desktop/sdl_main.cpp @@ -29,6 +29,7 @@ #include "esde.h" #include "esde_vgames.h" #include "guide.h" +#include "console_mode.h" #include "host.h" #include @@ -481,7 +482,9 @@ static void PreSwapOverlays() { s_lastMove = SDL_GetTicks(); if (!g_mediaFullscreen) { - const bool hide = g_padModeActive || (SDL_GetTicks() - s_lastMove > 3000); + // Console mode starts with it hidden; it comes back once the mouse moves. + const bool hide = g_padModeActive || (Console_Active() && !s_lastMove) || + (SDL_GetTicks() - s_lastMove > 3000); const int want = hide ? SDL_DISABLE : SDL_ENABLE; if (want != s_shown) { SDL_ShowCursor(want); s_shown = want; } } else { @@ -764,9 +767,24 @@ void ApplyDisplayMode() { SDL_SetWindowPosition(g_pSDLWindow, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); } + // Console mode is never a window: a windowed choice becomes borderless + // fullscreen, and the frame stays off even if fullscreen is refused. + static bool s_consoleFrame = false; + int mode = g_windowMode; + // Development only: UIX_DEV_WINDOWED=1 keeps console mode in a window for testing. + static const bool s_devWindowed = getenv("UIX_DEV_WINDOWED") != NULL; + if (Console_Active() && !s_devWindowed) { + if (mode == 0) mode = 1; + SDL_SetWindowBordered(g_pSDLWindow, SDL_FALSE); + s_consoleFrame = true; + } else if (s_consoleFrame) { + SDL_SetWindowBordered(g_pSDLWindow, SDL_TRUE); + s_consoleFrame = false; + } + Uint32 flags = 0; - if (g_windowMode == 1) flags = SDL_WINDOW_FULLSCREEN_DESKTOP; - else if (g_windowMode == 2) flags = SDL_WINDOW_FULLSCREEN; + if (mode == 1) flags = SDL_WINDOW_FULLSCREEN_DESKTOP; + else if (mode == 2) flags = SDL_WINDOW_FULLSCREEN; if (flags) SDL_SetWindowFullscreen(g_pSDLWindow, flags); // Reset here rather than waiting on SDL_WINDOWEVENT_SIZE_CHANGED, which @@ -931,6 +949,11 @@ int g_mediaPlaybackExited = 0; // Preloader UI and XIP extraction are now in preloader.cpp int main(int argc, char* argv[]) { + // --console: this process only watches over the real one. No log, no SDL, no window. + { + int code = 0; + if (Console_Supervise(argc, argv, &code)) return code; + } g_argc = argc; g_argv = argv; s_execPath = argv[0]; @@ -1289,10 +1312,12 @@ int main(int argc, char* argv[]) { // Check for CLI flags float cliUiScale = 0.0f; // 0 = unset, default 1.0 if not specified bool cliFullscreen = false; + bool cliMode = false; for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--dashboard") == 0) g_startupMode = 1; - else if (strcmp(argv[i], "--development") == 0) g_startupMode = 2; - else if (strcmp(argv[i], "--preview") == 0) g_startupMode = 1; // legacy compat + if (strcmp(argv[i], "--dashboard") == 0) { g_startupMode = 1; cliMode = true; } + else if (strcmp(argv[i], "--development") == 0) { g_startupMode = 2; cliMode = true; } + else if (strcmp(argv[i], "--preview") == 0) { g_startupMode = 1; cliMode = true; } // legacy compat + else if (strcmp(argv[i], "--console") == 0) g_consoleFlag = true; else if (strcmp(argv[i], "--muted") == 0) g_audioMuted = true; else if (strcmp(argv[i], "--minimized") == 0) g_startMinimized = true; else if (strcmp(argv[i], "--graphics-debug") == 0) g_graphicsDebug = true; @@ -1314,6 +1339,8 @@ int main(int argc, char* argv[]) { // otherwise. ApplyDisplayMode handles either path. if (cliFullscreen) g_windowMode = 2; if (g_pSDLWindow) ApplyDisplayMode(); + // Console mode goes straight in. Only the very first run still gets the Welcome. + if (Console_Active() && !cliMode) g_startupMode = 1; if (cliUiScale > 0.0f) { ImGui::GetIO().FontGlobalScale = cliUiScale; fprintf(stderr, "[ui] FontGlobalScale = %.2f\n", cliUiScale); @@ -1434,6 +1461,10 @@ int main(int argc, char* argv[]) { // audible when the window is active. ApplyEffectiveMute // honors the manual g_audioMuted on top, so a user // Ctrl+M still wins. + // Back from Go to Desktop: fullscreen again. + if (event.window.event == SDL_WINDOWEVENT_RESTORED && Console_Active() && + !(SDL_GetWindowFlags(g_pSDLWindow) & SDL_WINDOW_FULLSCREEN)) + g_displayChangeRequested = true; switch (event.window.event) { case SDL_WINDOWEVENT_FOCUS_LOST: case SDL_WINDOWEVENT_MINIMIZED: @@ -1636,6 +1667,21 @@ int main(int argc, char* argv[]) { Pads_Update(); Frame_PhaseEnd(FP_EVENTS); + // Development only: UIX_DEV_CRASH_AFTER= crashes on purpose, + // to try the console watchdog. + { + static int s_crashMs = -1; + if (s_crashMs < 0) { + const char* env = getenv("UIX_DEV_CRASH_AFTER"); + s_crashMs = env ? (int)(atof(env) * 1000.0) : 0; + } + if (s_crashMs > 0 && SDL_GetTicks() > (Uint32)s_crashMs) { + fprintf(stderr, "[Console] UIX_DEV_CRASH_AFTER: crashing on purpose\n"); + volatile int* nowhere = NULL; + *nowhere = 1; + } + } + // All panels are floating ImGui windows in the main window now. { SDL_Window* focusedWin = SDL_GetKeyboardFocus(); @@ -1670,6 +1716,7 @@ int main(int argc, char* argv[]) { // Show window again if it was hidden (game launch) if (g_pSDLWindow) SDL_ShowWindow(g_pSDLWindow); + Console_RestartViaWatchdog("--preview"); execv(g_argv[0], newArgv); // fallthrough if execv fails fprintf(stderr, "[Desktop] execv failed: %s\n", strerror(errno)); diff --git a/theseus/desktop/settings_schema.cpp b/theseus/desktop/settings_schema.cpp index f84e191..0d8f9e4 100644 --- a/theseus/desktop/settings_schema.cpp +++ b/theseus/desktop/settings_schema.cpp @@ -262,7 +262,7 @@ bool Settings_Load(const SettingsTable& t, const char* path) const char* eq = strchr(s, '='); if (!eq) continue; const SettingDef* d = FindIn(t, s, (size_t)(eq - s)); - if (d) Setting_Parse(*d, eq + 1); + if (d && !(d->flags & SF_LIVE)) Setting_Parse(*d, eq + 1); } for (int i = 0; i < t.count; i++) if (t.defs[i].flags & SF_SHARED) NoteSynced(t.defs[i]); @@ -318,6 +318,7 @@ bool Settings_Save(const SettingsTable& t, const char* path) int idx = (int)(d - t.defs); if (written[idx]) continue; // a duplicate would shadow the real value written[idx] = 1; + if (d->flags & SF_LIVE) continue; if ((d->flags & SF_SHARED) && !ChangedHere(*d)) { Setting_Parse(*d, line.c_str() + eq + 1); out.push_back(line); @@ -337,7 +338,7 @@ bool Settings_Save(const SettingsTable& t, const char* path) std::vector newSecs; std::vector > newSecLines; for (int i = 0; i < t.count; i++) { - if (written[i]) continue; + if (written[i] || (t.defs[i].flags & SF_LIVE)) continue; const SettingDef& d = t.defs[i]; Setting_Format(d, val, sizeof(val)); std::string kv = std::string(d.key) + "=" + val; diff --git a/theseus/desktop/settings_schema.h b/theseus/desktop/settings_schema.h index 54d80bf..1557c4b 100644 --- a/theseus/desktop/settings_schema.h +++ b/theseus/desktop/settings_schema.h @@ -13,6 +13,7 @@ enum SettingFlags { SF_STRICT = 1 << 4, // enum: refuse values that aren't in the list SF_PERCENT = 1 << 5, // 0..1 float shown as a percentage SF_CLAMP = 1 << 6, // pull loaded values into minV..maxV + SF_LIVE = 1 << 7, // the OS holds it; never read from or written to the file }; struct SettingDef { @@ -44,6 +45,8 @@ struct SettingsTable { // The desktop table (desktop_settings.cpp). const SettingsTable& DesktopSettings_Table(); const SettingDef* DesktopSettings_Find(const char* key); +// Reads the SF_LIVE rows back from the OS. +void DesktopSettings_ReadLive(); // Text <-> value. Parse returns false and leaves the value alone when the // text isn't acceptable.