From 3ce8c988c8df89ac747513152d4cd5e79ebd696a Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:09:48 -0500 Subject: [PATCH 01/46] Copied logs hide sign-in tokens too Copy Log already hid the home folder and IPs. Tokens in URLs and auth headers (api_key, X-Plex-Token, Token="...", AccessToken) now show as [redacted], so older logs are safe to paste as well. --- theseus/desktop/log_redact.cpp | 50 ++++++++++++++++++++++++++++++++-- theseus/desktop/log_redact.h | 4 +-- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/theseus/desktop/log_redact.cpp b/theseus/desktop/log_redact.cpp index d9a71b4..a544672 100644 --- a/theseus/desktop/log_redact.cpp +++ b/theseus/desktop/log_redact.cpp @@ -1,8 +1,9 @@ -// log_redact.cpp: home folder and IP address masking for copied logs. +// log_redact.cpp: home folder, IP address and sign-in token masking for copied logs. #include "log_redact.h" #include #include +#include static bool IsHex(char c) { return isxdigit((unsigned char)c) != 0; } @@ -50,8 +51,53 @@ static size_t MatchV6(const char* p, bool* keep) return (size_t)(s - p); } -std::string Log_Redact(const std::string& in, const char* home) +// Sign-in tokens in URLs and auth headers: api_key=..., X-Plex-Token=..., +// Token="...". The name stays so a log still says what was sent. +static const char* const kTokenKeys[] = { + "api_key", "apikey", "x-plex-token", "x-emby-token", "access_token", + "accesstoken", "token", "refresh_token", "password", "pw", +}; + +static bool TokenKeyAt(const std::string& s, size_t i, size_t* keyLen) +{ + for (size_t k = 0; k < sizeof(kTokenKeys) / sizeof(kTokenKeys[0]); k++) { + size_t n = strlen(kTokenKeys[k]); + if (i + n > s.size() || strncasecmp(s.c_str() + i, kTokenKeys[k], n) != 0) continue; + // Whole words only, so "devicetoken" or "tokenizer" aren't touched. + if (i > 0 && (isalnum((unsigned char)s[i - 1]) || s[i - 1] == '_' || s[i - 1] == '-')) continue; + char c = i + n < s.size() ? s[i + n] : 0; + if (c == '=' || c == ':' || c == '"') { *keyLen = n; return true; } + } + return false; +} + +static std::string MaskTokens(const std::string& in) +{ + std::string out; + out.reserve(in.size()); + for (size_t i = 0; i < in.size();) { + size_t n; + if (!TokenKeyAt(in, i, &n)) { out += in[i++]; continue; } + out.append(in, i, n); + i += n; + // Separator: = or : with optional quotes and spaces around it. + size_t j = i; + while (j < in.size() && (in[j] == '"' || in[j] == '\\')) j++; + if (j >= in.size() || (in[j] != '=' && in[j] != ':')) { continue; } + j++; + while (j < in.size() && (in[j] == ' ' || in[j] == '"' || in[j] == '\'')) j++; + size_t v = j; + while (v < in.size() && !strchr("&\"' \t\r\n,;}>)", in[v])) v++; + out.append(in, i, j - i); + if (v > j) out += "[redacted]"; + i = v; + } + return out; +} + +std::string Log_Redact(const std::string& raw, const char* home) { + std::string in = MaskTokens(raw); std::string text; size_t hl = home ? strlen(home) : 0; while (hl > 1 && (home[hl - 1] == '/' || home[hl - 1] == '\\')) hl--; diff --git a/theseus/desktop/log_redact.h b/theseus/desktop/log_redact.h index 27017fd..c590dbf 100644 --- a/theseus/desktop/log_redact.h +++ b/theseus/desktop/log_redact.h @@ -2,6 +2,6 @@ #pragma once #include -// The home folder becomes ~ and IP addresses become [ip] (loopback and -// 0.0.0.0 stay, they say nothing about anyone). +// The home folder becomes ~, IP addresses become [ip] (loopback and 0.0.0.0 +// stay, they say nothing about anyone) and sign-in tokens become [redacted]. std::string Log_Redact(const std::string& text, const char* home); From c07af7a17cee8e2b3bd5679fc4bfb80ae89832b6 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:11:59 -0500 Subject: [PATCH 02/46] Find xemu in RetroBat and the other usual places Find only knew a couple of default folders, so RetroBat, scoop, user installs, Flatpak and AppImage xemus never turned up. It now looks in all of them, the guide has a Find xemu row under the path, and a bare xemu line uses the same search at launch. Needs a Windows and Linux test. --- build/Makefile | 3 +- theseus/desktop/desktop_settings.cpp | 2 +- theseus/desktop/guide.cpp | 30 +++++++ theseus/desktop/launchers/emu_find.cpp | 117 +++++++++++++++++++++++++ theseus/desktop/launchers/emu_find.h | 22 +++++ theseus/desktop/launchers/xemu.cpp | 116 +++++++++++++++++------- theseus/desktop/launchers/xemu.h | 9 +- theseus/desktop/menu_bar.cpp | 11 ++- theseus/desktop/title_maker.cpp | 57 +++--------- 9 files changed, 285 insertions(+), 82 deletions(-) create mode 100644 theseus/desktop/launchers/emu_find.cpp create mode 100644 theseus/desktop/launchers/emu_find.h diff --git a/build/Makefile b/build/Makefile index b1263cf..9700942 100644 --- a/build/Makefile +++ b/build/Makefile @@ -452,7 +452,7 @@ LINT_DIRS = $(THESEUS_SRC)/desktop $(THESEUS_SRC)/shared $(THESEUS_SRC)/engin $(THESEUS_SRC)/render $(THESEUS_SRC)/toolbox LINT_VENDOR = --exclude-dir=third-party --exclude-dir=xdk --exclude-dir=imgui \ --exclude='stb_*.h' --exclude='minimp3.h' --exclude='imfilebrowser.h' -LINT_HOST_DATA = title_maker.cpp retroarch.cpp steam.cpp hdd_browser.cpp cdaudio.cpp +LINT_HOST_DATA = title_maker.cpp retroarch.cpp steam.cpp xemu.cpp hdd_browser.cpp cdaudio.cpp LINT_HOSTTEST = THESEUS_HOST_(WIN|MAC|LINUX) .PHONY: lint-platform lint-platform: @@ -872,6 +872,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/launchers/steam.cpp \ $(THESEUS_SRC)/desktop/launchers/retroarch.cpp \ $(THESEUS_SRC)/desktop/launchers/xemu.cpp \ + $(THESEUS_SRC)/desktop/launchers/emu_find.cpp \ $(THESEUS_SRC)/desktop/title_sanitize.cpp \ $(THESEUS_SRC)/desktop/udata_synth.cpp \ $(THESEUS_SRC)/desktop/desktop_stubs.cpp \ diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index eb5efca..a52fe87 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -109,7 +109,7 @@ static const char* kModeLbl[] = { "Windowed", "Borderless", "Fullscreen" }; { key, "CRT", "Display", label, SK_FLOAT, &g_crt.field, 0, def, 0, NOENUM, lo, hi, 0.05f, NULL, NULL } static const SettingDef kDefs[] = { - S_PATH("XemuPath", "Desktop", "General", "xemu Path", s_xemuPath, 0), + S_PATH("XemuPath", "Desktop", "Games", "xemu Path", s_xemuPath, 0), S_PATH("QcowPath", "Desktop", "General", "qcow2 HDD Image", g_qcowPath, 0), S_PATH("SteamPath", "Desktop", "Games", "Steam Folder", s_steamPath, 0), S_PATH("RetroArchPath", "Desktop", "Games", "RetroArch Folder", s_retroarchPath, 0), diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 662ef8c..f59a324 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -26,6 +26,7 @@ #include "plex_client.h" #include "jellyfin_client.h" #include "xcloud_client.h" +#include "launchers/xemu.h" #include "guide.h" #include "ui_overlay.h" #include @@ -268,6 +269,7 @@ enum Act { GA_PLEX, GA_PLEXOUT, GA_JELLYFIN, GA_JELLYFINOUT, GA_XBOX, GA_XBOXOUT, GA_TEXT, GA_NAME, GA_JELLYFINURL, GA_GAMELIST, GA_GAME, GA_LAUNCH, GA_FAVORITE, GA_HIDE, GA_LETTER, GA_SEARCH, + GA_FINDEMU, GA_COUNT }; @@ -338,6 +340,7 @@ static struct Guide { int copied; std::string result[GA_COUNT]; std::string browseDir, pickedPath, pickedName, added; + std::string found[4]; // what each Find row turned up std::vector entries; bool browseStale; int category, playlist; @@ -425,6 +428,18 @@ static VirtualGame* PickedGame() static const char* kGameListNames[] = { "Favorites", "Recently Played", "Hidden Games", "All Games", "", "" }; +// Emulators the guide can look for, each under its path setting. +static const struct { + const char* key; + const char* findLabel; + const char* findHelp; + bool (*find)(char* out, size_t outSize); +} kEmus[] = { + { "XemuPath", "Find xemu", "Looks in the usual install folders, RetroBat, scoop, Flatpak and AppImages.", + Xemu_Find }, +}; +static const int kEmuCount = (int)(sizeof(kEmus) / sizeof(kEmus[0])); + static void Build() { g.rows.clear(); @@ -439,6 +454,9 @@ static void Build() Setting_Display(d, val, sizeof(val)); bool typed = d.kind == SK_PATH || d.kind == SK_STRING; Add(d.label, val, SettingHelp(d), typed ? GA_TEXT : GA_SETTING, i); + for (int e = 0; e < kEmuCount; e++) + if (strcmp(d.key, kEmus[e].key) == 0) + Add(kEmus[e].findLabel, g.found[e].c_str(), kEmus[e].findHelp, GA_FINDEMU, e); } break; } @@ -1030,6 +1048,18 @@ static void Select() EditOpen(ED_SETTING, r.arg, d.label, (const char*)d.ptr, (size_t)d.size - 1, (d.flags & SF_SECRET) != 0); break; } + case GA_FINDEMU: { + char path[512]; + const SettingDef* d = DesktopSettings_Find(kEmus[r.arg].key); + if (d && kEmus[r.arg].find(path, sizeof(path)) && Setting_SetText(*d, path)) { + SaveDesktopSettings(); + g.found[r.arg] = "Found"; + } else { + g.found[r.arg] = "Not found"; + } + Build(); + break; + } case GA_NAME: EditOpen(ED_NAME, 0, "Name", g.pickedName, 100, false); break; diff --git a/theseus/desktop/launchers/emu_find.cpp b/theseus/desktop/launchers/emu_find.cpp new file mode 100644 index 0000000..e6c49c7 --- /dev/null +++ b/theseus/desktop/launchers/emu_find.cpp @@ -0,0 +1,117 @@ +// emu_find.cpp: walks the launcher modules' lists of install folders. + +#include "emu_find.h" + +#include +#include +#include +#include +#include + +#include "host.h" +#include "platform_env.h" + +namespace { + +bool IsFile(const char* path) { + HostFileInfo info; + return Host_Stat(path, &info); +} + +// One list entry with its fill-ins done. False when a variable it needs isn't set. +bool Expand(const char* place, char drive, char* out, size_t outSize) { + if (outSize) out[0] = '\0'; + std::string s; + const char* p = place; + if (p[0] == '~' && (p[1] == '/' || p[1] == '\\' || !p[1])) { + const char* home = PlatformHomeDir(); + if (!*home) return false; + s = home; + p++; + } else if (p[0] == '$') { + const char* end = p + 1; + while (*end && *end != '/' && *end != '\\') end++; + std::string name(p + 1, end - p - 1); + const char* v = getenv(name.c_str()); + if (!v || !*v) return false; + s = v; + p = end; + } else if (p[0] == '?' && p[1] == ':') { + s = drive; + p++; + } + s += p; + if (s.size() >= outSize) return false; + memcpy(out, s.c_str(), s.size() + 1); + return true; +} + +} // namespace + +bool Emu_FirstExisting(const char* const* places, char* out, size_t outSize) { + char buf[1024]; + for (int i = 0; places && places[i]; i++) { + bool anyDrive = places[i][0] == '?'; + for (char d = 'C'; d <= (anyDrive ? 'Z' : 'C'); d++) { + if (!Expand(places[i], d, buf, sizeof(buf)) || !IsFile(buf)) continue; + snprintf(out, outSize, "%s", buf); + return true; + } + } + return false; +} + +bool Emu_OnPath(const char* exe, char* out, size_t outSize) { + const char* path = getenv("PATH"); + if (!path || !exe || !*exe) return false; + // Windows lists PATH with ';' because its paths carry a ':'. + char listSep = Host_PathSep == '\\' ? ';' : ':'; + char buf[1024]; + while (*path) { + const char* end = strchr(path, listSep); + size_t n = end ? (size_t)(end - path) : strlen(path); + if (n > 0 && n + strlen(exe) + 2 < sizeof(buf)) { + memcpy(buf, path, n); + snprintf(buf + n, sizeof(buf) - n, "%c%s", Host_PathSep, exe); + HostFileInfo info; + if (Host_Stat(buf, &info) && !(info.attrs & HOST_ATTR_DIR)) { + snprintf(out, outSize, "%s", buf); + return true; + } + } + if (!end) break; + path = end + 1; + } + return false; +} + +bool Emu_FindAppImage(const char* const* dirs, const char* prefix, char* out, size_t outSize) { + size_t plen = strlen(prefix); + char dir[1024], name[512]; + for (int i = 0; dirs && dirs[i]; i++) { + if (!Expand(dirs[i], 'C', dir, sizeof(dir))) continue; + HostDir* d = Host_OpenDir(dir); + if (!d) continue; + bool isDir = false, found = false; + while (!found && Host_ReadDirType(d, name, sizeof(name), &isDir)) { + size_t n = strlen(name); + if (isDir || n < plen + 9) continue; + if (strncasecmp(name, prefix, plen) != 0) continue; + if (strcasecmp(name + n - 9, ".AppImage") != 0) continue; + snprintf(out, outSize, "%s/%s", dir, name); + found = true; + } + Host_CloseDir(d); + if (found) return true; + } + return false; +} + +void Emu_AppBinary(const char* path, const char* bin, char* out, size_t outSize) { + size_t n = strlen(path); + while (n > 1 && path[n - 1] == '/') n--; + if (n > 4 && strncasecmp(path + n - 4, ".app", 4) == 0) + snprintf(out, outSize, "%.*s/Contents/MacOS/%s", (int)n, path, bin); + else + snprintf(out, outSize, "%s", path); +} diff --git a/theseus/desktop/launchers/emu_find.h b/theseus/desktop/launchers/emu_find.h new file mode 100644 index 0000000..d12defe --- /dev/null +++ b/theseus/desktop/launchers/emu_find.h @@ -0,0 +1,22 @@ +// emu_find.h: looking for an emulator someone installed. The launcher +// modules hold the per-OS lists of where to look; this walks them. + +#pragma once + +#include + +// The first place on the list that exists. Each entry is a path, with these +// filled in: a leading ~ is the home folder, $NAME up to the next slash is +// that environment variable, and a leading ?: tries every drive C: to Z:. +bool Emu_FirstExisting(const char* const* places, char* out, size_t outSize); + +// A program by name on PATH. +bool Emu_OnPath(const char* exe, char* out, size_t outSize); + +// An AppImage whose name starts with prefix (any case) in one of the folders. +// Folders use the same fill-ins as Emu_FirstExisting. +bool Emu_FindAppImage(const char* const* dirs, const char* prefix, char* out, size_t outSize); + +// The program inside a macOS app bundle: /Applications/X.app gives +// /Applications/X.app/Contents/MacOS/bin. Anything else comes back as is. +void Emu_AppBinary(const char* path, const char* bin, char* out, size_t outSize); diff --git a/theseus/desktop/launchers/xemu.cpp b/theseus/desktop/launchers/xemu.cpp index e02ff8b..a368b87 100644 --- a/theseus/desktop/launchers/xemu.cpp +++ b/theseus/desktop/launchers/xemu.cpp @@ -1,23 +1,69 @@ // xemu.cpp: xemu launcher module. Title Maker stores an ISO as a bare // `xemu -machine ... -dvd_path "..."` when no xemu path is set. Flatpak -// xemu never puts xemu on PATH and snap's /snap/bin isn't always on it, so -// a bare xemu that PATH can't find is pointed at whichever is installed. -// Flatpak xemu can read the whole disk, so the ISO path works. Neither -// exists off Linux, so there the spec runs as is. +// xemu never puts xemu on PATH and Windows installs rarely do, so a bare +// xemu that PATH can't find is pointed at whichever install Xemu_Find +// turns up. Flatpak xemu can read the whole disk, so the ISO path works. #include "launcher.h" #include "xemu.h" +#include "emu_find.h" #include #include #include -#include + +#include "platform.h" +#include "host.h" + +extern char s_xemuPath[512]; namespace { +#ifdef THESEUS_HOST_WIN +const char* kExe = "xemu.exe"; +const char* const kPlaces[] = { + "$ProgramFiles\\xemu\\xemu.exe", + "$ProgramFiles(x86)\\xemu\\xemu.exe", + "$LOCALAPPDATA\\Programs\\xemu\\xemu.exe", + "$LOCALAPPDATA\\xemu\\xemu.exe", + "~\\scoop\\apps\\xemu\\current\\xemu.exe", + "$APPDATA\\EmuDeck\\Emulators\\xemu\\xemu.exe", + "?:\\RetroBat\\emulators\\xemu\\xemu.exe", + "?:\\LaunchBox\\Emulators\\xemu\\xemu.exe", + "?:\\Emulators\\xemu\\xemu.exe", + "?:\\xemu\\xemu.exe", + NULL +}; +const char* const kAppImageDirs[] = { NULL }; +#elif defined(THESEUS_HOST_MAC) +const char* kExe = "xemu"; +const char* const kPlaces[] = { + "/Applications/xemu.app", + "~/Applications/xemu.app", + "/opt/homebrew/bin/xemu", + "/usr/local/bin/xemu", + NULL +}; +const char* const kAppImageDirs[] = { NULL }; +#else +const char* kExe = "xemu"; +const char* const kPlaces[] = { + "/usr/bin/xemu", + "/usr/local/bin/xemu", + "~/.local/bin/xemu", + "/snap/bin/xemu", + "/var/lib/flatpak/exports/bin/app.xemu.xemu", + "~/.local/share/flatpak/exports/bin/app.xemu.xemu", + NULL +}; +const char* const kAppImageDirs[] = { + "~/Applications", "~/AppImages", "~/.local/bin", "~/Desktop", "~/Downloads", "/opt", NULL +}; +#endif + bool Exists(const char* path) { - struct stat st; - return stat(path, &st) == 0; + HostFileInfo info; + return Host_Stat(path, &info); } // The text after a leading bare "xemu", or NULL when the spec isn't one. @@ -29,36 +75,24 @@ const char* AfterBareXemu(const char* spec) { return spec + 4; } -bool OnPath(const char* exe) { - const char* path = getenv("PATH"); - if (!path) return false; - char dir[1024]; - while (*path) { - const char* end = strchr(path, ':'); - size_t n = end ? (size_t)(end - path) : strlen(path); - if (n > 0 && n < sizeof(dir) - 32) { - memcpy(dir, path, n); - snprintf(dir + n, sizeof(dir) - n, "/%s", exe); - if (Exists(dir)) return true; - } - if (!end) break; - path = end + 1; - } - return false; -} - bool Claims(const char* spec) { return AfterBareXemu(spec) != NULL; } bool Build(const char* spec, char* outCmd, size_t outSize) { const char* rest = AfterBareXemu(spec); - if (!rest || OnPath("xemu")) return false; - const char* runner = NULL; - if (Exists("/snap/bin/xemu")) runner = "/snap/bin/xemu"; - else if (Xemu_FlatpakInstalled()) runner = "flatpak run app.xemu.xemu"; - if (!runner) return false; - int n = snprintf(outCmd, outSize, "%s%s", runner, rest); + char found[1024]; + if (!rest || Emu_OnPath(kExe, found, sizeof(found))) return false; + int n; + if (Xemu_Find(found, sizeof(found))) { + char bin[1100]; + Emu_AppBinary(found, "xemu", bin, sizeof(bin)); + n = snprintf(outCmd, outSize, "\"%s\"%s", bin, rest); + } else if (Xemu_FlatpakInstalled()) { + n = snprintf(outCmd, outSize, "flatpak run app.xemu.xemu%s", rest); + } else { + return false; + } return n > 0 && (size_t)n < outSize; } @@ -81,6 +115,26 @@ bool Xemu_FlatpakInstalled() { return Exists(userApp); } +bool Xemu_Find(char* out, size_t outSize) { + if (outSize) out[0] = '\0'; + return Emu_OnPath(kExe, out, outSize) || + Emu_FirstExisting(kPlaces, out, outSize) || + Emu_FindAppImage(kAppImageDirs, "xemu", out, outSize); +} + +bool Xemu_IsoLaunch(const char* iso, char* out, size_t outSize) { + int n; + if (s_xemuPath[0]) { + char bin[1024]; + Emu_AppBinary(s_xemuPath, "xemu", bin, sizeof(bin)); + n = snprintf(out, outSize, "\"%s\" -machine xbox,short-animation=on -dvd_path \"%s\"", bin, iso); + } else { + // Bare xemu is found at launch. + n = snprintf(out, outSize, "xemu -machine xbox,short-animation=on -dvd_path \"%s\"", iso); + } + return n > 0 && (size_t)n < outSize; +} + void Launcher_RegisterXemu() { Launcher_Register(&kXemuLauncher); } diff --git a/theseus/desktop/launchers/xemu.h b/theseus/desktop/launchers/xemu.h index 93a78f6..4a0db4f 100644 --- a/theseus/desktop/launchers/xemu.h +++ b/theseus/desktop/launchers/xemu.h @@ -1,5 +1,5 @@ // xemu.h: xemu launcher module. ISO entries are stored as `xemu ...` when -// no xemu path is set; this finds a Flatpak or snap xemu at launch. +// no xemu path is set; this finds xemu wherever it's installed at launch. #pragma once @@ -7,3 +7,10 @@ // Flatpak xemu (app.xemu.xemu), system or user install. bool Xemu_FlatpakInstalled(); + +// Where xemu is installed: PATH, the usual install folders, RetroBat, scoop, +// Flatpak, snap and AppImages. On macOS it's the .app. False when it's nowhere. +bool Xemu_Find(char* out, size_t outSize); + +// The games.ini Launch line for an Xbox ISO. False when it won't fit. +bool Xemu_IsoLaunch(const char* iso, char* out, size_t outSize); diff --git a/theseus/desktop/menu_bar.cpp b/theseus/desktop/menu_bar.cpp index ffd0b62..9c5d3f7 100644 --- a/theseus/desktop/menu_bar.cpp +++ b/theseus/desktop/menu_bar.cpp @@ -22,6 +22,7 @@ static const char* ShippedVersionPath() { #include "plex_client.h" #include "jellyfin_client.h" #include "xcloud_client.h" +#include "launchers/xemu.h" #include "media_player.h" #include "milkdrop_window.h" #include "xbox_buttons.h" @@ -586,11 +587,19 @@ void RenderSettingsWindow() { // Paths ImGui::Text("xemu Path:"); - ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 70); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 120); ImGui::InputText("##xemupath", s_xemuPath, sizeof(s_xemuPath)); ImGui::SameLine(); if (ImGui::Button("Save##xemu")) SaveDesktopSettings(); + ImGui::SameLine(); + if (ImGui::Button("Find##xemu")) { + char found[512]; + if (Xemu_Find(found, sizeof(found))) { + snprintf(s_xemuPath, sizeof(s_xemuPath), "%s", found); + SaveDesktopSettings(); + } + } ImGui::Spacing(); ImGui::Text("qcow2 HDD Image:"); diff --git a/theseus/desktop/title_maker.cpp b/theseus/desktop/title_maker.cpp index 722e940..dc0220f 100644 --- a/theseus/desktop/title_maker.cpp +++ b/theseus/desktop/title_maker.cpp @@ -861,37 +861,18 @@ void RenderTitleMaker() { } ImGui::SameLine(); if (ImGui::SmallButton("Find##xemu")) { - const char* tryPaths[] = { -#ifdef THESEUS_HOST_MAC - "/Applications/xemu.app", - "/opt/homebrew/bin/xemu", - "/usr/local/bin/xemu", -#elif defined(THESEUS_HOST_WIN) - "C:\\Program Files\\xemu\\xemu.exe", - "C:\\Program Files (x86)\\xemu\\xemu.exe", -#else - "/usr/bin/xemu", - "/usr/local/bin/xemu", - "/snap/bin/xemu", -#endif - NULL - }; - bool found = false; - for (int i = 0; tryPaths[i] && !found; i++) { - struct stat st; - if (stat(tryPaths[i], &st) == 0) { - strncpy(s_xemuPath, tryPaths[i], sizeof(s_xemuPath) - 1); - found = true; - } - } - if (!found && Xemu_FlatpakInstalled()) { + char found[512]; + if (Xemu_Find(found, sizeof(found))) { + snprintf(s_xemuPath, sizeof(s_xemuPath), "%s", found); + SaveDesktopSettings(); + snprintf(s_statusMsg, sizeof(s_statusMsg), "Found xemu: %s", found); + } else if (Xemu_FlatpakInstalled()) { s_xemuPath[0] = 0; strncpy(s_statusMsg, "Flatpak xemu found, leave the path empty", sizeof(s_statusMsg) - 1); - s_statusTime = 3.0f; - } else if (!found) { + } else { strncpy(s_statusMsg, "xemu not found in common locations", sizeof(s_statusMsg) - 1); - s_statusTime = 3.0f; } + s_statusTime = 3.0f; } if (s_xemuPath[0] == 0 && !Xemu_FlatpakInstalled()) ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.2f, 1.0f), "Set xemu path to enable ISO launching"); @@ -1237,28 +1218,10 @@ void RenderTitleMaker() { char titleIdHex[16]; snprintf(titleIdHex, sizeof(titleIdHex), "%08x", s_isoInfo.titleId); - // Build xemu launch command char xemuLaunchCmd[sizeof(VirtualGame::launch)] = ""; - int cmdLen; - { - char xemuBin[512] = ""; - if (s_xemuPath[0]) { - size_t plen = strlen(s_xemuPath); - if (plen > 4 && strcmp(s_xemuPath + plen - 4, ".app") == 0) - snprintf(xemuBin, sizeof(xemuBin), "%s/Contents/MacOS/xemu", s_xemuPath); - else - strncpy(xemuBin, s_xemuPath, sizeof(xemuBin) - 1); - } - // Bare xemu is found at launch, Flatpak and snap included. - if (xemuBin[0]) - cmdLen = snprintf(xemuLaunchCmd, sizeof(xemuLaunchCmd), - "\"%s\" -machine xbox,short-animation=on -dvd_path \"%s\"", xemuBin, s_isoPath); - else - cmdLen = snprintf(xemuLaunchCmd, sizeof(xemuLaunchCmd), - "xemu -machine xbox,short-animation=on -dvd_path \"%s\"", s_isoPath); - } + bool fits = Xemu_IsoLaunch(s_isoPath, xemuLaunchCmd, sizeof(xemuLaunchCmd)); // A cut off line loses its closing quote and never launches. - if (cmdLen < 0 || cmdLen >= (int)sizeof(xemuLaunchCmd)) { + if (!fits) { snprintf(s_statusMsg, sizeof(s_statusMsg), "ISO path too long to launch: %s", s_isoPath); s_statusTime = 6.0f; } else { From e28f74577a7f74bfaeb49b1c45aea0c6ff200221 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:12:02 -0500 Subject: [PATCH 03/46] Songs keep their track order, and playlists keep theirs Without a track number tag, songs sorted by title, which threw away the order in names like "01 - Intro". They sort by file name now, numbers counted as numbers. Songs from an .m3u stay in the playlist's order instead of being re-sorted. Relates to #27. --- theseus/desktop/audio_sdl.cpp | 37 ++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/theseus/desktop/audio_sdl.cpp b/theseus/desktop/audio_sdl.cpp index b169e64..4ab62dc 100644 --- a/theseus/desktop/audio_sdl.cpp +++ b/theseus/desktop/audio_sdl.cpp @@ -988,15 +988,42 @@ static void SongToDB(const Song& s, DBEntry& e) e.album = s.album; } +// Numbers inside names compare as numbers, so "2 - Song" comes before +// "10 - Song", and case doesn't matter. +static bool NaturalLess(const std::string& a, const std::string& b) +{ + size_t i = 0, j = 0; + while (i < a.size() && j < b.size()) { + unsigned char ca = (unsigned char)a[i], cb = (unsigned char)b[j]; + if (isdigit(ca) && isdigit(cb)) { + size_t ie = i, je = j; + while (ie < a.size() && a[ie] == '0') ie++; + while (je < b.size() && b[je] == '0') je++; + size_t ia = ie, jb = je; + while (ia < a.size() && isdigit((unsigned char)a[ia])) ia++; + while (jb < b.size() && isdigit((unsigned char)b[jb])) jb++; + if (ia - ie != jb - je) return ia - ie < jb - je; + int c = a.compare(ie, ia - ie, b, je, jb - je); + if (c != 0) return c < 0; + i = ia; j = jb; + continue; + } + int la = tolower(ca), lb = tolower(cb); + if (la != lb) return la < lb; + i++; j++; + } + return a.size() - i < b.size() - j; +} + +// Track number from the tags first. Without one, the file name decides, +// since that's where rippers and stores put the order ("01 - Intro.mp3"). static void SortSoundtrackSongs(Soundtrack& st) { - std::sort(st.songs.begin(), st.songs.end(), [](const Song& a, const Song& b) { + std::stable_sort(st.songs.begin(), st.songs.end(), [](const Song& a, const Song& b) { int an = a.trackNumber > 0 ? a.trackNumber : 0x7fffffff; int bn = b.trackNumber > 0 ? b.trackNumber : 0x7fffffff; if (an != bn) return an < bn; - const std::string& aname = !a.title.empty() ? a.title : a.name; - const std::string& bname = !b.title.empty() ? b.title : b.name; - return aname < bname; + return NaturalLess(a.name, b.name); }); } @@ -1122,7 +1149,7 @@ int DashMusic_Scan(const char* musicRoot) const char* nm = slash ? slash + 1 : entries[i].c_str(); soundtrack.songs.push_back(BuildSong(entries[i], StripExtension(nm))); } - SortSoundtrackSongs(soundtrack); + // A playlist file is already in the order its author wants. s_soundtracks.push_back(soundtrack); }; From a2b98ac3c2a4b25ed8b2c5ec76d638154b75edb6 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:14:08 -0500 Subject: [PATCH 04/46] Added PCSX2 as a launcher PS2 discs needed a hand written script to start. Now Add PS2 Disc in the Title Maker and Add a Game in the guide store a pcsx2 line, and PCSX2 is found at launch the same way xemu is. Add a Game also spots Xbox ISOs and hands them to xemu. Needs a Windows and Linux test. --- build/Makefile | 5 +- theseus/desktop/desktop_settings.cpp | 2 + theseus/desktop/guide.cpp | 56 +++++++++++- theseus/desktop/launchers/pcsx2.cpp | 122 +++++++++++++++++++++++++ theseus/desktop/launchers/pcsx2.h | 21 +++++ theseus/desktop/launchers/registry.cpp | 2 + theseus/desktop/title_maker.cpp | 59 ++++++++++++ 7 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 theseus/desktop/launchers/pcsx2.cpp create mode 100644 theseus/desktop/launchers/pcsx2.h diff --git a/build/Makefile b/build/Makefile index 9700942..d7b80fe 100644 --- a/build/Makefile +++ b/build/Makefile @@ -446,13 +446,13 @@ clean: # talks to the OS by name: is host_win* only, the compiler's OS # macros are platform.h and host_* only, and THESEUS_HOST_* is too, apart # from LINT_HOST_DATA. Those files keep per-OS data, not OS calls: default -# install paths for Steam, RetroArch and xemu, and the Linux CD ioctls. +# install paths for Steam, RetroArch, xemu and PCSX2, and the Linux CD ioctls. # Vendored headers (stb, minimp3, imfilebrowser, imgui) are left alone. LINT_DIRS = $(THESEUS_SRC)/desktop $(THESEUS_SRC)/shared $(THESEUS_SRC)/engine \ $(THESEUS_SRC)/render $(THESEUS_SRC)/toolbox LINT_VENDOR = --exclude-dir=third-party --exclude-dir=xdk --exclude-dir=imgui \ --exclude='stb_*.h' --exclude='minimp3.h' --exclude='imfilebrowser.h' -LINT_HOST_DATA = title_maker.cpp retroarch.cpp steam.cpp xemu.cpp hdd_browser.cpp cdaudio.cpp +LINT_HOST_DATA = title_maker.cpp retroarch.cpp steam.cpp xemu.cpp pcsx2.cpp hdd_browser.cpp cdaudio.cpp LINT_HOSTTEST = THESEUS_HOST_(WIN|MAC|LINUX) .PHONY: lint-platform lint-platform: @@ -872,6 +872,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/launchers/steam.cpp \ $(THESEUS_SRC)/desktop/launchers/retroarch.cpp \ $(THESEUS_SRC)/desktop/launchers/xemu.cpp \ + $(THESEUS_SRC)/desktop/launchers/pcsx2.cpp \ $(THESEUS_SRC)/desktop/launchers/emu_find.cpp \ $(THESEUS_SRC)/desktop/title_sanitize.cpp \ $(THESEUS_SRC)/desktop/udata_synth.cpp \ diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index a52fe87..0b451bb 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -12,6 +12,7 @@ #include "virtual_games.h" extern char s_xemuPath[512]; +extern char s_pcsx2Path[512]; extern char g_qcowPath[512]; extern char s_steamPath[512]; extern char s_retroarchPath[512]; @@ -110,6 +111,7 @@ static const char* kModeLbl[] = { "Windowed", "Borderless", "Fullscreen" }; static const SettingDef kDefs[] = { S_PATH("XemuPath", "Desktop", "Games", "xemu Path", s_xemuPath, 0), + S_PATH("Pcsx2Path", "Desktop", "Games", "PCSX2 Path", s_pcsx2Path, 0), S_PATH("QcowPath", "Desktop", "General", "qcow2 HDD Image", g_qcowPath, 0), S_PATH("SteamPath", "Desktop", "Games", "Steam Folder", s_steamPath, 0), S_PATH("RetroArchPath", "Desktop", "Games", "RetroArch Folder", s_retroarchPath, 0), diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index f59a324..a819f6b 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -27,6 +27,8 @@ #include "jellyfin_client.h" #include "xcloud_client.h" #include "launchers/xemu.h" +#include "launchers/pcsx2.h" +#include "xiso.h" #include "guide.h" #include "ui_overlay.h" #include @@ -143,6 +145,10 @@ extern char s_esdePath[512]; static const char* kCategories[] = { "Games", "Applications", "Homebrew", "Emulators", "Dashboards" }; static const int kCategoryCount = (int)(sizeof(kCategories) / sizeof(kCategories[0])); +// What an added file runs with. A disc image needs an emulator in front. +enum Runner { RUN_SELF, RUN_XEMU, RUN_PCSX2, RUN_COUNT }; +static const char* kRunners[RUN_COUNT] = { "Itself", "xemu", "PCSX2" }; + // A file browser entry. macOS apps are folders, but you pick them like files. struct BrowseEntry { std::string name; bool dir; }; @@ -269,7 +275,7 @@ enum Act { GA_PLEX, GA_PLEXOUT, GA_JELLYFIN, GA_JELLYFINOUT, GA_XBOX, GA_XBOXOUT, GA_TEXT, GA_NAME, GA_JELLYFINURL, GA_GAMELIST, GA_GAME, GA_LAUNCH, GA_FAVORITE, GA_HIDE, GA_LETTER, GA_SEARCH, - GA_FINDEMU, + GA_FINDEMU, GA_RUNNER, GA_COUNT }; @@ -343,7 +349,7 @@ static struct Guide { std::string found[4]; // what each Find row turned up std::vector entries; bool browseStale; - int category, playlist; + int category, playlist, runner; int gameList, game; char letter; // GL_LETTER's initial, '#' for digits and the rest std::string search; // GL_SEARCH's text @@ -437,6 +443,8 @@ static const struct { } kEmus[] = { { "XemuPath", "Find xemu", "Looks in the usual install folders, RetroBat, scoop, Flatpak and AppImages.", Xemu_Find }, + { "Pcsx2Path", "Find PCSX2", "Looks in the usual install folders, RetroBat, scoop, Flatpak, Lutris and AppImages.", + Pcsx2_Find }, }; static const int kEmuCount = (int)(sizeof(kEmus) / sizeof(kEmus[0])); @@ -521,6 +529,10 @@ static void Build() g.pickedPath.empty() ? "Taken from the file name." : "Taken from the file name. Select it to rename it.", g.pickedPath.empty() ? GA_NONE : GA_NAME); Add("Category", kCategories[g.category], "Left and right change it.", GA_CATEGORY); + Add("Runs With", kRunners[g.runner], + g.runner == RUN_SELF ? "Programs, shortcuts and scripts run themselves. Left and right change it." + : "The emulator is found when the game starts. Left and right change it.", + GA_RUNNER); Add("Add to Launcher", g.added.c_str(), g.pickedPath.empty() ? "Choose a file first." : "Adds it under the category above.", GA_ADDGAME); break; @@ -1022,6 +1034,11 @@ static bool Adjust(int dir) Build(); return true; } + if (r.act == GA_RUNNER) { + g.runner = (g.runner + (dir < 0 ? RUN_COUNT - 1 : 1)) % RUN_COUNT; + Build(); + return true; + } if (r.act != GA_SETTING) return false; const SettingDef& d = DesktopSettings_Table().defs[r.arg]; if (!Setting_Cycle(d, dir < 0 ? -1 : 1)) return false; @@ -1041,6 +1058,7 @@ static void Select() break; case GA_SETTING: case GA_CATEGORY: + case GA_RUNNER: Adjust(1); break; case GA_TEXT: { @@ -1142,6 +1160,16 @@ static void Select() } g.pickedPath = full; g.pickedName = NameFromPath(full); + g.runner = RUN_SELF; + if (Pcsx2_IsDisc(full.c_str())) { + // An Xbox disc names itself; anything else is a PS2 guess. + XisoTitleInfo xiso = XisoGetTitleInfo(full.c_str()); + g.runner = xiso.valid ? RUN_XEMU : RUN_PCSX2; + char clean[128] = ""; + if (xiso.valid) Title_SanitizeName(xiso.titleName, clean, sizeof(clean)); + if (clean[0]) g.pickedName = clean; + XisoFreeTitleInfo(&xiso); + } g.added.clear(); Back(); break; @@ -1151,8 +1179,28 @@ static void Select() if (VGames_FindByName(g.pickedName.c_str()) >= 0) { g.added = "Already there"; Build(); break; } char genID[16]; snprintf(genID, sizeof(genID), "%08x", (unsigned)time(NULL)); - std::string launch = "\"" + g.pickedPath + "\""; - VGames_Add(g.pickedName.c_str(), genID, launch.c_str(), "E", kCategories[g.category]); + char launch[sizeof(VirtualGame::launch)]; + bool fits = true; + XisoTitleInfo xiso = {}; + if (g.runner == RUN_XEMU) { + fits = Xemu_IsoLaunch(g.pickedPath.c_str(), launch, sizeof(launch)); + xiso = XisoGetTitleInfo(g.pickedPath.c_str()); + if (xiso.valid) snprintf(genID, sizeof(genID), "%08x", xiso.titleId); + } else if (g.runner == RUN_PCSX2) { + fits = Pcsx2_DiscLaunch(g.pickedPath.c_str(), launch, sizeof(launch)); + } else { + int n = snprintf(launch, sizeof(launch), "\"%s\"", g.pickedPath.c_str()); + fits = n > 0 && n < (int)sizeof(launch); + } + if (!fits) { XisoFreeTitleInfo(&xiso); g.added = "Path too long"; Build(); break; } + VGames_Add(g.pickedName.c_str(), genID, launch, "E", kCategories[g.category]); + if (xiso.titleImageRGBA) { + char icon[1024]; + Host_MakeDir(VGAMES_ICONS); + snprintf(icon, sizeof(icon), "%s/%s.jpg", VGAMES_ICONS, genID); + XisoSaveTitleImage(&xiso, icon); + } + XisoFreeTitleInfo(&xiso); VGames_Save(); UDataSynth_RebuildAll(); g.added = "Added"; diff --git a/theseus/desktop/launchers/pcsx2.cpp b/theseus/desktop/launchers/pcsx2.cpp new file mode 100644 index 0000000..2ba3845 --- /dev/null +++ b/theseus/desktop/launchers/pcsx2.cpp @@ -0,0 +1,122 @@ +// pcsx2.cpp: PCSX2 launcher module. Claims a bare `pcsx2 ...` line and puts +// the real program in front: the PCSX2 path setting when it's set, +// otherwise whatever Pcsx2_Find turns up. -batch makes PCSX2 quit when the +// game stops, so the dashboard comes back and the play time counts. + +#include "launcher.h" +#include "pcsx2.h" +#include "emu_find.h" + +#include +#include +#include + +#include "platform.h" +#include "host.h" + +char s_pcsx2Path[512] = ""; + +namespace { + +#ifdef THESEUS_HOST_WIN +const char* const kExes[] = { "pcsx2-qt.exe", NULL }; +const char* const kPlaces[] = { + "$ProgramFiles\\PCSX2\\pcsx2-qt.exe", + "$LOCALAPPDATA\\Programs\\PCSX2\\pcsx2-qt.exe", + "$ProgramFiles(x86)\\PCSX2\\pcsx2-qt.exe", + "~\\scoop\\apps\\pcsx2\\current\\pcsx2-qt.exe", + "?:\\RetroBat\\emulators\\pcsx2\\pcsx2-qt.exe", + "?:\\RetroBat\\emulators\\pcsx2\\pcsx2-qtx64-avx2.exe", + "?:\\RetroBat\\emulators\\pcsx2\\pcsx2-qtx64.exe", + "?:\\LaunchBox\\Emulators\\PCSX2\\pcsx2-qt.exe", + "?:\\Emulators\\PCSX2\\pcsx2-qt.exe", + "?:\\PCSX2\\pcsx2-qt.exe", + NULL +}; +const char* const kAppImageDirs[] = { NULL }; +#elif defined(THESEUS_HOST_MAC) +const char* const kExes[] = { "pcsx2-qt", NULL }; +const char* const kPlaces[] = { + "/Applications/PCSX2.app", + "~/Applications/PCSX2.app", + NULL +}; +const char* const kAppImageDirs[] = { NULL }; +#else +const char* const kExes[] = { "pcsx2-qt", "pcsx2", NULL }; +const char* const kPlaces[] = { + "/var/lib/flatpak/exports/bin/net.pcsx2.PCSX2", + "~/.local/share/flatpak/exports/bin/net.pcsx2.PCSX2", + "/snap/bin/pcsx2", + NULL +}; +const char* const kAppImageDirs[] = { + "~/Applications", "~/AppImages", "~/.local/bin", "~/.local/share/lutris/runners/pcsx2", + "~/Desktop", "~/Downloads", "/opt", NULL +}; +#endif + +const char* const kDiscExts[] = { ".iso", ".chd", ".cso", ".zso", ".mdf", NULL }; + +// The text after a leading bare "pcsx2", or NULL when the spec isn't one. +const char* AfterBarePcsx2(const char* spec) { + if (!spec) return NULL; + while (*spec == ' ' || *spec == '\t') spec++; + if (strncmp(spec, "pcsx2", 5) != 0) return NULL; + if (spec[5] != ' ' && spec[5] != '\t' && spec[5] != 0) return NULL; + return spec + 5; +} + +bool Claims(const char* spec) { + return AfterBarePcsx2(spec) != NULL; +} + +bool Build(const char* spec, char* outCmd, size_t outSize) { + const char* rest = AfterBarePcsx2(spec); + if (!rest) return false; + char found[512]; + const char* where = s_pcsx2Path; + if (!where[0]) { + if (!Pcsx2_Find(found, sizeof(found))) return false; + where = found; + } + char bin[1024]; + Emu_AppBinary(where, "PCSX2", bin, sizeof(bin)); + int n = snprintf(outCmd, outSize, "\"%s\"%s", bin, rest); + return n > 0 && (size_t)n < outSize; +} + +const Launcher kPcsx2Launcher = { + "pcsx2", + "PCSX2", + Claims, + 300, + Build, +}; + +} // namespace + +bool Pcsx2_Find(char* out, size_t outSize) { + if (outSize) out[0] = '\0'; + for (int i = 0; kExes[i]; i++) + if (Emu_OnPath(kExes[i], out, outSize)) return true; + return Emu_FirstExisting(kPlaces, out, outSize) || + Emu_FindAppImage(kAppImageDirs, "pcsx2", out, outSize); +} + +bool Pcsx2_IsDisc(const char* path) { + const char* dot = path ? strrchr(path, '.') : NULL; + if (!dot) return false; + for (int i = 0; kDiscExts[i]; i++) + if (strcasecmp(dot, kDiscExts[i]) == 0) return true; + return false; +} + +bool Pcsx2_DiscLaunch(const char* disc, char* out, size_t outSize) { + int n = snprintf(out, outSize, "pcsx2 -batch -fastboot -fullscreen -- \"%s\"", disc); + return n > 0 && (size_t)n < outSize; +} + +void Launcher_RegisterPcsx2() { + Launcher_Register(&kPcsx2Launcher); +} diff --git a/theseus/desktop/launchers/pcsx2.h b/theseus/desktop/launchers/pcsx2.h new file mode 100644 index 0000000..daa3c0c --- /dev/null +++ b/theseus/desktop/launchers/pcsx2.h @@ -0,0 +1,21 @@ +// pcsx2.h: PCSX2 launcher module. PS2 discs are stored as a bare +// `pcsx2 ...` line and the PCSX2 install is looked up at launch, so moving +// or updating PCSX2 never breaks a game. + +#pragma once + +#include + +// desktop.ini [Desktop] Pcsx2Path. Empty means find it at launch. +extern char s_pcsx2Path[512]; + +// Where PCSX2 is installed: PATH, the usual install folders, RetroBat, scoop, +// Flatpak, Lutris and AppImages. On macOS it's the .app. False when it's nowhere. +bool Pcsx2_Find(char* out, size_t outSize); + +// A disc image PCSX2 can boot, by extension. An .iso can be an Xbox disc +// too, so check for that first. +bool Pcsx2_IsDisc(const char* path); + +// The games.ini Launch line for a PS2 disc. False when it won't fit. +bool Pcsx2_DiscLaunch(const char* disc, char* out, size_t outSize); diff --git a/theseus/desktop/launchers/registry.cpp b/theseus/desktop/launchers/registry.cpp index 7e8c128..aae2172 100644 --- a/theseus/desktop/launchers/registry.cpp +++ b/theseus/desktop/launchers/registry.cpp @@ -58,8 +58,10 @@ void Launcher_Build(const char* spec, char* outCmd, size_t outSize) { // Each module's RegisterFoo lives in its own .cpp. extern void Launcher_RegisterRetroArch(); extern void Launcher_RegisterXemu(); +extern void Launcher_RegisterPcsx2(); void Launchers_RegisterAll() { Launcher_RegisterRetroArch(); Launcher_RegisterXemu(); + Launcher_RegisterPcsx2(); } diff --git a/theseus/desktop/title_maker.cpp b/theseus/desktop/title_maker.cpp index dc0220f..c9a12a5 100644 --- a/theseus/desktop/title_maker.cpp +++ b/theseus/desktop/title_maker.cpp @@ -16,6 +16,7 @@ #include "launchers/steam.h" #include "launchers/retroarch.h" #include "launchers/xemu.h" +#include "launchers/pcsx2.h" #include "imgui.h" #include "imfilebrowser.h" #include "stb_image.h" @@ -34,6 +35,8 @@ bool g_titleMakerOpen = false; +extern int Title_SanitizeName(const char*, char*, size_t); + // ============================================================================ // Helpers // ============================================================================ @@ -750,6 +753,8 @@ void RenderTitleMaker() { static bool s_appBrowserInit = false; static ImGui::FileBrowser s_isoBrowser(ImGuiFileBrowserFlags_CloseOnEsc); static bool s_isoBrowserInit = false; + static ImGui::FileBrowser s_ps2Browser(ImGuiFileBrowserFlags_CloseOnEsc); + static bool s_ps2BrowserInit = false; static ImGui::FileBrowser s_steamBrowser( ImGuiFileBrowserFlags_CloseOnEsc | ImGuiFileBrowserFlags_SelectDirectory); static bool s_steamBrowserInit = false; @@ -774,6 +779,11 @@ void RenderTitleMaker() { s_isoBrowser.SetTypeFilters({ ".iso", ".ISO" }); s_isoBrowserInit = true; } + if (!s_ps2BrowserInit) { + s_ps2Browser.SetTitle("Select PS2 Disc"); + s_ps2Browser.SetTypeFilters({ ".iso", ".chd", ".cso", ".zso", ".mdf", ".ISO", ".CHD", ".CSO" }); + s_ps2BrowserInit = true; + } if (!s_steamBrowserInit) { s_steamBrowser.SetTitle("Select Steam install folder (contains steamapps/)"); s_steamBrowserInit = true; @@ -878,6 +888,29 @@ void RenderTitleMaker() { ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.2f, 1.0f), "Set xemu path to enable ISO launching"); } + // PCSX2 path setting. Empty is fine: PS2 discs find PCSX2 at launch. + { + ImGui::Text("PCSX2:"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 150); + ImGui::InputText("##pcsx2path", s_pcsx2Path, sizeof(s_pcsx2Path)); + ImGui::SameLine(); + if (ImGui::SmallButton("Save##pcsx2")) + SaveDesktopSettings(); + ImGui::SameLine(); + if (ImGui::SmallButton("Find##pcsx2")) { + char found[512]; + if (Pcsx2_Find(found, sizeof(found))) { + snprintf(s_pcsx2Path, sizeof(s_pcsx2Path), "%s", found); + SaveDesktopSettings(); + snprintf(s_statusMsg, sizeof(s_statusMsg), "Found PCSX2: %s", found); + } else { + strncpy(s_statusMsg, "PCSX2 not found in common locations", sizeof(s_statusMsg) - 1); + } + s_statusTime = 3.0f; + } + } + ImGui::Separator(); // Search and category filter @@ -1147,6 +1180,32 @@ void RenderTitleMaker() { if (ImGui::Button("Add ISO")) { ImGui::OpenPopup("AddISOPopup"); } + ImGui::SameLine(); + if (ImGui::Button("Add PS2 Disc")) s_ps2Browser.Open(); + s_ps2Browser.Display(); + if (s_ps2Browser.HasSelected()) { + std::string disc = s_ps2Browser.GetSelected().string(); + s_ps2Browser.ClearSelected(); + char name[128], clean[128]; + TM_DeriveRomTitle(disc.c_str(), name, sizeof(name)); + Title_SanitizeName(name, clean, sizeof(clean)); + char launch[sizeof(VirtualGame::launch)]; + if (!clean[0]) { + snprintf(s_statusMsg, sizeof(s_statusMsg), "No usable name in %s", disc.c_str()); + } else if (VGames_FindByName(clean) >= 0) { + snprintf(s_statusMsg, sizeof(s_statusMsg), "Already in the library: %s", clean); + } else if (!Pcsx2_DiscLaunch(disc.c_str(), launch, sizeof(launch))) { + snprintf(s_statusMsg, sizeof(s_statusMsg), "Disc path too long to launch: %s", disc.c_str()); + } else { + char genID[16]; + snprintf(genID, sizeof(genID), "%08x", (unsigned)time(NULL)); + VGames_Add(clean, genID, launch, "E", "Games"); + VGames_Save(); UDataSynth_RebuildAll(); + snprintf(s_statusMsg, sizeof(s_statusMsg), "Added: %s", clean); + s_needsScan = true; + } + s_statusTime = 4.0f; + } // ISO file browser + result window { From 403de67ea20802a89fbe4e8c19d4b8b14ca802e0 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:15:26 -0500 Subject: [PATCH 05/46] Controllers can come and go while it runs It only ever opened the first pad it found. Now every pad is opened as it connects and closed as it leaves, and the one pressed last drives the dashboard. UIX_DEV_PAD can plug in virtual pads to try it. Needs a test with real pads. --- build/Makefile | 1 + theseus/desktop/joystick.cpp | 61 ++------- theseus/desktop/joystick.h | 21 --- theseus/desktop/pads.cpp | 239 +++++++++++++++++++++++++++++++++++ theseus/desktop/pads.h | 12 ++ theseus/desktop/sdl_main.cpp | 17 +-- 6 files changed, 275 insertions(+), 76 deletions(-) delete mode 100755 theseus/desktop/joystick.h create mode 100644 theseus/desktop/pads.cpp create mode 100644 theseus/desktop/pads.h diff --git a/build/Makefile b/build/Makefile index b1263cf..53f0d91 100644 --- a/build/Makefile +++ b/build/Makefile @@ -848,6 +848,7 @@ DESKTOP_SRCS_SYSTEM = \ $(THESEUS_SRC)/desktop/dashinit.cpp \ $(THESEUS_SRC)/desktop/config.cpp \ $(THESEUS_SRC)/desktop/joystick.cpp \ + $(THESEUS_SRC)/desktop/pads.cpp \ $(THESEUS_SRC)/shared/keyboard_node.cpp \ $(THESEUS_SRC)/engine/locale_node.cpp \ $(THESEUS_SRC)/shared/timezone.cpp \ diff --git a/theseus/desktop/joystick.cpp b/theseus/desktop/joystick.cpp index 3ad42ef..e9b528b 100755 --- a/theseus/desktop/joystick.cpp +++ b/theseus/desktop/joystick.cpp @@ -10,6 +10,7 @@ #include "node.h" #include #include "guide.h" +#include "pads.h" #define REPEAT_DELAY 0.3f #define REPEAT_INTERVAL 0.12f @@ -85,14 +86,10 @@ class CJoystick : public CNode void Bind(); - void CheckDevice(); - void EnableGlobalInput(int bEnable); void CallFunction(const char *szFunc, bool bRemote = false); - static SDL_GameController* c_controller; - static CJoystick *c_pLastActivePad; static CJoystick *c_pActivePad; @@ -117,15 +114,13 @@ class CJoystick : public CNode void ProcessSecretKeySequence(int flags); void ButtonEvent(bool down, const char *downName, const char *upName, char key); void MoveEvent(char key, const char *name); - static void PollSDL(SDL_GameController* gc, JoySnapshot* out); + static void PollSDL(JoySnapshot* out); void ProcessMediaKeys(); }; -SDL_GameController* CJoystick::c_controller = NULL; - // The keyboard reads the pad itself while up: nav is off for the duration, // so ImGui's key state isn't fed. -SDL_GameController* Joy_GetController() { return CJoystick::c_controller; } +SDL_GameController* Joy_GetController() { return Pads_Active(); } CJoystick *CJoystick::c_pActivePad = NULL; CJoystick *CJoystick::c_pLastActivePad = NULL; @@ -272,8 +267,7 @@ void CJoystick::Bind() c_pActivePad = this; if (m_bFirstPoll) return; - CheckDevice(); - PollSDL(c_controller, &m_prevState); + PollSDL(&m_prevState); } // CJoystick::OnSetProperty(prd, value) @@ -344,38 +338,6 @@ bool CJoystick::OnSetProperty(const PRD *pprd, const void *pvValue) return false; } -// ============================================================================ -// Controller Detection -// ============================================================================ -void CJoystick::CheckDevice() -{ - // Check if current controller was disconnected - if (c_controller && !SDL_GameControllerGetAttached(c_controller)) - { - fprintf(stdout, "[Input] Controller disconnected\n"); - SDL_GameControllerClose(c_controller); - c_controller = NULL; - } - - // Try to find a controller if we don't have one - if (!c_controller) - { - for (int i = 0; i < SDL_NumJoysticks(); i++) - { - if (SDL_IsGameController(i)) - { - c_controller = SDL_GameControllerOpen(i); - if (c_controller) - { - fprintf(stdout, "[Input] SDL controller opened: %s\n", - SDL_GameControllerName(c_controller)); - break; - } - } - } - } -} - // CJoystick::EnableGlobalInput(on) [script fn 'EnableGlobalInput', FND 0x00181fb0, sig 14] // Reconstructed from 5960 retail XBE @ 0x00040b70: sets the global input switch. void CJoystick::EnableGlobalInput(int bEnable) @@ -437,8 +399,9 @@ static void ReadPad(SDL_GameController* gc, bool holdB, JoySnapshot* out) } } -void CJoystick::PollSDL(SDL_GameController* gc, JoySnapshot* out) +void CJoystick::PollSDL(JoySnapshot* out) { + SDL_GameController* gc = Pads_Active(); memset(out, 0, sizeof(*out)); // Tools have the pad: leave it zeroed and the dashboard sits still. @@ -567,6 +530,11 @@ static void DevPadScript(JoySnapshot* out) int used = 0; if (sscanf(env, " %f:%15[a-z]%n", &t, name, &used) != 2) break; env += used; + // "a@2" presses a virtual pad's button and "plug=ps" plugs one + // in; pads.cpp does those. + bool virtualPad = false; + for (; *env && *env != ' '; env++) virtualPad = true; + if (virtualPad) continue; for (size_t i = 0; i < sizeof(kNames) / sizeof(kNames[0]); i++) if (strcmp(kNames[i].name, name) == 0) { Press p = { (Uint32)(t * 1000.0f), kNames[i].kind, kNames[i].idx }; @@ -673,7 +641,7 @@ unsigned Joy_GuideButtons(int* device) { extern SDL_Window* g_pSDLWindow; extern bool ImGui_WantsKeyboard(); - SDL_GameController* gc = CJoystick::c_controller; + SDL_GameController* gc = Pads_Active(); const bool holdB = GuideChord(gc); JoySnapshot pad; @@ -835,10 +803,9 @@ void CJoystick::Advance(float nSeconds) if (!g_bInputEnable || this != c_pActivePad) return; - CheckDevice(); if (m_bFirstPoll) { - PollSDL(c_controller, &m_prevState); + PollSDL(&m_prevState); m_nextPollTime = TheseusGetNow(); m_bFirstPoll = false; } @@ -849,7 +816,7 @@ void CJoystick::Advance(float nSeconds) ProcessMediaKeys(); JoySnapshot now; - PollSDL(c_controller, &now); + PollSDL(&now); if (!EqualSnapshots(&now, &m_prevState) && ResetScreenSaver()) { m_prevState = now; diff --git a/theseus/desktop/joystick.h b/theseus/desktop/joystick.h deleted file mode 100755 index 82955db..0000000 --- a/theseus/desktop/joystick.h +++ /dev/null @@ -1,21 +0,0 @@ -// joystick.h: desktop CJoystick declarations. Companion to -// desktop/joystick.cpp. - -#pragma once -#include "node.h" -#include - -class CJoystick : public CNode -{ -public: - static CJoystick* c_pActivePad; - static CJoystick* c_pLastActivePad; - static SDL_GameController* c_controller; - - void Bind(); // this binds to itself - - void OnMoveUp(); - void OnMoveDown(); - void OnADown(); - void OnBDown(); -}; diff --git a/theseus/desktop/pads.cpp b/theseus/desktop/pads.cpp new file mode 100644 index 0000000..5870761 --- /dev/null +++ b/theseus/desktop/pads.cpp @@ -0,0 +1,239 @@ +// pads.cpp: every controller SDL sees, opened as it connects and closed as +// it leaves, so pads can come and go mid-session. A new press makes a pad +// the active one; when the active one leaves, the one used most recently +// takes over. + +#include "std.h" +#include +#include +#include +#include "pads.h" + +struct Pad { + SDL_GameController* gc; + SDL_JoystickID id; + Uint32 used; // when it was last pressed, on s_clock + Uint32 held; // its buttons and directions last frame +}; + +static std::vector s_pads; +static SDL_JoystickID s_active = -1; +static Uint32 s_clock = 0; + +static int Find(SDL_JoystickID id) +{ + for (size_t i = 0; i < s_pads.size(); i++) + if (s_pads[i].id == id) return (int)i; + return -1; +} + +static void Open(int index) +{ + if (!SDL_IsGameController(index)) return; + SDL_JoystickID id = SDL_JoystickGetDeviceInstanceID(index); + if (id < 0 || Find(id) >= 0) return; + SDL_GameController* gc = SDL_GameControllerOpen(index); + if (!gc) { + fprintf(stderr, "[Input] Couldn't open controller %d: %s\n", index, SDL_GetError()); + return; + } + Pad p = { gc, id, 0, 0 }; + s_pads.push_back(p); + if (s_active < 0) s_active = id; + const char* name = SDL_GameControllerName(gc); + fprintf(stdout, "[Input] Controller connected: %s (%d connected)\n", name ? name : "?", (int)s_pads.size()); +} + +static void Close(int i) +{ + const char* name = SDL_GameControllerName(s_pads[i].gc); + fprintf(stdout, "[Input] Controller disconnected: %s (%d left)\n", name ? name : "?", (int)s_pads.size() - 1); + SDL_JoystickID id = s_pads[i].id; + SDL_GameControllerClose(s_pads[i].gc); + s_pads.erase(s_pads.begin() + i); + if (id != s_active) return; + int best = -1; + for (size_t k = 0; k < s_pads.size(); k++) + if (best < 0 || s_pads[k].used >= s_pads[best].used) best = (int)k; + s_active = best < 0 ? -1 : s_pads[best].id; +} + +// Anything connected that isn't open yet: the pads there at startup, and +// any whose added event another loop (the boot animation) ate. +static void OpenNew() +{ + static int s_seen = -1; + int n = SDL_NumJoysticks(); + if (n == s_seen) return; + s_seen = n; + for (int i = 0; i < n; i++) Open(i); +} + +void Pads_HandleEvent(const SDL_Event* e) +{ + if (e->type == SDL_CONTROLLERDEVICEADDED) { + Open(e->cdevice.which); + } else if (e->type == SDL_CONTROLLERDEVICEREMOVED) { + int i = Find(e->cdevice.which); + if (i >= 0) Close(i); + } +} + +// Buttons, triggers and sticks past half, one bit each. +static Uint32 Held(SDL_GameController* gc) +{ + Uint32 bits = 0; + for (int b = 0; b < SDL_CONTROLLER_BUTTON_MAX && b < 20; b++) + if (SDL_GameControllerGetButton(gc, (SDL_GameControllerButton)b)) bits |= 1u << b; + if (SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERLEFT) > 8000) bits |= 1u << 20; + if (SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) > 8000) bits |= 1u << 21; + for (int a = 0; a < 4; a++) { + int v = SDL_GameControllerGetAxis(gc, (SDL_GameControllerAxis)a); + if (v < -16384) bits |= 1u << (22 + a * 2); + if (v > 16384) bits |= 1u << (23 + a * 2); + } + return bits; +} + +static void DevVirtualPads(); + +void Pads_Update() +{ + DevVirtualPads(); + OpenNew(); + for (int i = (int)s_pads.size() - 1; i >= 0; i--) + if (!SDL_GameControllerGetAttached(s_pads[i].gc)) Close(i); + + for (size_t i = 0; i < s_pads.size(); i++) { + Pad& p = s_pads[i]; + Uint32 held = Held(p.gc); + if (held & ~p.held) { + p.used = ++s_clock; + s_active = p.id; + } + p.held = held; + } +} + +void Pads_Shutdown() +{ + for (size_t i = 0; i < s_pads.size(); i++) SDL_GameControllerClose(s_pads[i].gc); + s_pads.clear(); + s_active = -1; +} + +int Pads_Count() { return (int)s_pads.size(); } + +SDL_GameController* Pads_Active() +{ + int i = Find(s_active); + return i < 0 ? NULL : s_pads[i].gc; +} + +// Development only: UIX_DEV_PAD="5:plug 6:plug=ps 8:a@2 9:unplug@1" plugs +// in virtual pads (xbox, ps or switch), holds their buttons for 150 ms and +// pulls them out again, so hot plug and several pads can be tried without +// a real one. Pads are numbered from 1 in the order they were plugged in. +#if SDL_VERSION_ATLEAST(2, 24, 0) +struct DevPad { SDL_Joystick* joy; SDL_JoystickID id; }; +static std::vector s_devPads; + +static int SDLCALL DevRumble(void* user, Uint16 low, Uint16 high) +{ + fprintf(stdout, "[DevPad] Pad %d rumble %u %u\n", (int)(intptr_t)user, low, high); + return 0; +} + +static void DevPlug(const std::string& kind) +{ + SDL_VirtualJoystickDesc d; + SDL_zero(d); + d.version = SDL_VIRTUAL_JOYSTICK_DESC_VERSION; + d.type = SDL_JOYSTICK_TYPE_GAMECONTROLLER; + d.naxes = SDL_CONTROLLER_AXIS_MAX; + d.nbuttons = SDL_CONTROLLER_BUTTON_MAX; + d.vendor_id = 0x045E; d.product_id = 0x0B12; d.name = "Virtual Xbox Pad"; + if (kind == "ps") { d.vendor_id = 0x054C; d.product_id = 0x0CE6; d.name = "Virtual PlayStation Pad"; } + if (kind == "switch") { d.vendor_id = 0x057E; d.product_id = 0x2009; d.name = "Virtual Switch Pad"; } + d.userdata = (void*)(intptr_t)(s_devPads.size() + 1); + d.Rumble = DevRumble; + int index = SDL_JoystickAttachVirtualEx(&d); + SDL_Joystick* joy = index < 0 ? NULL : SDL_JoystickOpen(index); + if (!joy) { fprintf(stderr, "[DevPad] Couldn't plug in a pad: %s\n", SDL_GetError()); return; } + DevPad p = { joy, SDL_JoystickInstanceID(joy) }; + s_devPads.push_back(p); +} + +static void DevUnplug(int n) +{ + if (n < 1 || n > (int)s_devPads.size() || !s_devPads[n - 1].joy) return; + DevPad& p = s_devPads[n - 1]; + for (int i = 0; i < SDL_NumJoysticks(); i++) + if (SDL_JoystickGetDeviceInstanceID(i) == p.id) { SDL_JoystickDetachVirtual(i); break; } + SDL_JoystickClose(p.joy); + p.joy = NULL; +} + +static void DevPress(int n, const std::string& name, bool down) +{ + if (n < 1 || n > (int)s_devPads.size() || !s_devPads[n - 1].joy) return; + SDL_Joystick* joy = s_devPads[n - 1].joy; + static const struct { const char* name; int button; } kButtons[] = { + { "a", SDL_CONTROLLER_BUTTON_A }, { "b", SDL_CONTROLLER_BUTTON_B }, + { "x", SDL_CONTROLLER_BUTTON_X }, { "y", SDL_CONTROLLER_BUTTON_Y }, + { "back", SDL_CONTROLLER_BUTTON_BACK }, { "guide", SDL_CONTROLLER_BUTTON_GUIDE }, + { "start", SDL_CONTROLLER_BUTTON_START }, + { "white", SDL_CONTROLLER_BUTTON_LEFTSHOULDER }, { "black", SDL_CONTROLLER_BUTTON_RIGHTSHOULDER }, + { "up", SDL_CONTROLLER_BUTTON_DPAD_UP }, { "down", SDL_CONTROLLER_BUTTON_DPAD_DOWN }, + { "left", SDL_CONTROLLER_BUTTON_DPAD_LEFT }, { "right", SDL_CONTROLLER_BUTTON_DPAD_RIGHT }, + }; + if (name == "lt" || name == "rt") { + SDL_JoystickSetVirtualAxis(joy, name == "lt" ? SDL_CONTROLLER_AXIS_TRIGGERLEFT : SDL_CONTROLLER_AXIS_TRIGGERRIGHT, + down ? 32767 : 0); + return; + } + for (size_t i = 0; i < sizeof(kButtons) / sizeof(kButtons[0]); i++) + if (name == kButtons[i].name) SDL_JoystickSetVirtualButton(joy, kButtons[i].button, down ? 1 : 0); +} + +static void DevVirtualPads() +{ + struct Step { Uint32 at; std::string name, arg; int pad, state; }; + static std::vector s_steps; + static bool s_parsed = false; + if (!s_parsed) { + s_parsed = true; + const char* env = getenv("UIX_DEV_PAD"); + while (env && *env) { + float t = 0; + char name[16] = "", rest[32] = ""; + int used = 0; + if (sscanf(env, " %f:%15[a-z]%n", &t, name, &used) != 2) break; + env += used; + if (sscanf(env, "%31[^ ]%n", rest, &used) == 1) env += used; + Step st = { (Uint32)(t * 1000.0f), name, "", 1, 0 }; + if (rest[0] == '=') st.arg = rest + 1; + else if (rest[0] == '@') st.pad = atoi(rest + 1); + else if (strcmp(name, "plug") != 0 && strcmp(name, "unplug") != 0) continue; + if (st.name == "unplug" && rest[0] != '@') st.pad = 0; + s_steps.push_back(st); + } + } + const Uint32 now = SDL_GetTicks(); + for (size_t i = 0; i < s_steps.size(); i++) { + Step& st = s_steps[i]; + if (st.state == 2 || now < st.at) continue; + if (st.name == "plug") { DevPlug(st.arg); st.state = 2; } + else if (st.name == "unplug") { + int n = st.pad; + for (int k = (int)s_devPads.size(); !n && k > 0; k--) if (s_devPads[k - 1].joy) n = k; + DevUnplug(n); + st.state = 2; + } + else if (st.state == 0) { DevPress(st.pad, st.name, true); st.state = 1; } + else if (now >= st.at + 150) { DevPress(st.pad, st.name, false); st.state = 2; } + } +} +#else +static void DevVirtualPads() {} +#endif diff --git a/theseus/desktop/pads.h b/theseus/desktop/pads.h new file mode 100644 index 0000000..3723079 --- /dev/null +++ b/theseus/desktop/pads.h @@ -0,0 +1,12 @@ +// pads.h: the controllers (pads.cpp). Pads can come and go any time; the +// one pressed last is the active pad. +#pragma once +#include + +void Pads_HandleEvent(const SDL_Event* event); // pads connecting and leaving +void Pads_Update(); // once a frame, after the events +void Pads_Shutdown(); + +int Pads_Count(); +// The pad pressed last, NULL with none connected. +SDL_GameController* Pads_Active(); diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index 98959a4..6f3fbea 100644 --- a/theseus/desktop/sdl_main.cpp +++ b/theseus/desktop/sdl_main.cpp @@ -9,7 +9,7 @@ #include "shape_render.h" #include "asset_loader.h" #include "audio_sdl.h" -#include "joystick.h" +#include "pads.h" #include "milkdrop_window.h" #include "xcloud_client.h" #include "xiso.h" @@ -1405,6 +1405,7 @@ int main(int argc, char* argv[]) { // Let ImGui handle events first ImGui_ImplSDL2_ProcessEvent(&event); Guide_HandleEvent(&event); + Pads_HandleEvent(&event); switch (event.type) { case SDL_QUIT: @@ -1627,6 +1628,7 @@ int main(int argc, char* argv[]) { break; } } + Pads_Update(); Frame_PhaseEnd(FP_EVENTS); // All panels are floating ImGui windows in the main window now. @@ -1682,17 +1684,15 @@ int main(int argc, char* argv[]) { if (g_xcloudClosed) { bool leave = (SDL_GetTicks() - g_xcloudClosedAtMs > kXcloudClosedAutoMs); - if (CJoystick::c_controller) { - SDL_GameController* gc = CJoystick::c_controller; + if (SDL_GameController* gc = Pads_Active()) { if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_A) || SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B) || SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_START)) leave = true; } if (leave) { g_xcloudFullscreen = false; g_xcloudClosed = false; } - } else if (CJoystick::c_controller) { + } else if (SDL_GameController* gc = Pads_Active()) { // Streaming: the controller belongs to the game. SDL already // normalizes any pad to the Xbox layout. - SDL_GameController* gc = CJoystick::c_controller; auto btn = [gc](SDL_GameControllerButton x){ return SDL_GameControllerGetButton(gc, x) != 0; }; auto ax = [gc](SDL_GameControllerAxis x){ return SDL_GameControllerGetAxis(gc, x) / 32767.0f; }; XcloudGamepad gp{}; @@ -1798,9 +1798,9 @@ int main(int argc, char* argv[]) { const Uint8* keys = SDL_GetKeyboardState(NULL); bool kbXY = keys[SDL_SCANCODE_X] && keys[SDL_SCANCODE_Y]; bool padXY = false; - if (CJoystick::c_controller) { - padXY = SDL_GameControllerGetButton(CJoystick::c_controller, SDL_CONTROLLER_BUTTON_X) - && SDL_GameControllerGetButton(CJoystick::c_controller, SDL_CONTROLLER_BUTTON_Y); + if (SDL_GameController* gc = Pads_Active()) { + padXY = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_X) + && SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_Y); } static bool s_prevXY = false; bool xy = kbXY || padXY; @@ -1881,6 +1881,7 @@ int main(int argc, char* argv[]) { // Cleanup XapEditor_Cleanup(); Guide_Shutdown(); + Pads_Shutdown(); { extern void ImGui_ImplBgfx_Shutdown(); ImGui_ImplBgfx_Shutdown(); From 1ae5049e4d28a63326cbef77353db30a4fdd7be4 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:15:33 -0500 Subject: [PATCH 06/46] Portable mode A portable.txt beside the app keeps settings and library in a UserData folder next to it, and THESEUS_DATA_DIR points the user data folder anywhere. Noted in the README with the AppImage .home folder that does the same. --- README.md | 2 ++ theseus/desktop/app_paths.cpp | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/README.md b/README.md index 7df248c..bf93417 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ Launch it and you land on the dashboard. On first run UIX Desktop creates your * | Linux | `$XDG_DATA_HOME/theseus/`, which is usually `~/.local/share/theseus/` | | Windows | `%APPDATA%\Theseus\` | +**Portable mode:** put an empty `portable.txt` next to the app (beside `theseus.exe` on Windows, beside `theseus` in the Linux tarball) and everything lives in a `UserData` folder right there instead, handy for a USB stick or one folder per setup. An AppImage does the same with a folder named after it plus `.home` (`UIX-Desktop-v0.4.1-x86_64.AppImage.home`). Setting `THESEUS_DATA_DIR` points the user data folder anywhere you like and beats both. + **Settings (F4) > General > Open User Directory** takes you straight there. Inside: | Path | What's there | diff --git a/theseus/desktop/app_paths.cpp b/theseus/desktop/app_paths.cpp index 4e826ec..371783c 100644 --- a/theseus/desktop/app_paths.cpp +++ b/theseus/desktop/app_paths.cpp @@ -42,6 +42,21 @@ const char* Plat_UserDataDir() { if (s_init) return s_dir; s_init = true; + // THESEUS_DATA_DIR wins. Then portable mode: a portable.txt beside the + // app keeps everything in UserData next to it (a USB stick, one folder + // per setup). Otherwise the OS's usual per-user folder. + const char* env = getenv("THESEUS_DATA_DIR"); + if (env && *env) { + snprintf(s_dir, sizeof(s_dir), "%s", env); + return s_dir; + } + char marker[1024]; + snprintf(marker, sizeof(marker), "%s/portable.txt", Plat_ExeDir()); + struct stat st; + if (stat(marker, &st) == 0) { + snprintf(s_dir, sizeof(s_dir), "%s/UserData", Plat_ExeDir()); + return s_dir; + } Host_UserDataDir(s_dir, sizeof(s_dir)); return s_dir; } From 9f4896790f12642757b47cc25e0032da64786ab5 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:16:59 -0500 Subject: [PATCH 07/46] Every connected pad drives the dashboard Only the last pad pressed was read, so a second pad did nothing until it took over. Now any pad's buttons count and the sticks read off whichever pad pushes furthest. LT+B still has to be on one pad, and a stream still gets just the active pad. --- theseus/desktop/joystick.cpp | 115 ++++++++++++++++------------------- theseus/desktop/osk.cpp | 25 ++++---- theseus/desktop/pads.cpp | 28 ++++++++- theseus/desktop/pads.h | 9 ++- theseus/desktop/sdl_main.cpp | 14 ++--- 5 files changed, 104 insertions(+), 87 deletions(-) diff --git a/theseus/desktop/joystick.cpp b/theseus/desktop/joystick.cpp index e9b528b..c83088a 100755 --- a/theseus/desktop/joystick.cpp +++ b/theseus/desktop/joystick.cpp @@ -118,10 +118,6 @@ class CJoystick : public CNode void ProcessMediaKeys(); }; -// The keyboard reads the pad itself while up: nav is off for the duration, -// so ImGui's key state isn't fed. -SDL_GameController* Joy_GetController() { return Pads_Active(); } - CJoystick *CJoystick::c_pActivePad = NULL; CJoystick *CJoystick::c_pLastActivePad = NULL; @@ -348,60 +344,54 @@ void CJoystick::EnableGlobalInput(int bEnable) // ============================================================================ // Input Polling // ============================================================================ -static bool GuideChord(SDL_GameController* gc); +static bool GuideChord(); static void DevPadScript(JoySnapshot* out); -// The pad's buttons and sticks as a snapshot. holdB drops the B of LT+B. -static void ReadPad(SDL_GameController* gc, bool holdB, JoySnapshot* out) +// Every pad's buttons and sticks as one snapshot. holdB drops the B of LT+B. +static void ReadPad(bool holdB, JoySnapshot* out) { - if (gc) - { - // Face buttons -> analogDown[0..3] = A,B,X,Y - out->analogDown[0] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_A); - out->analogDown[1] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B) && !holdB; - out->analogDown[2] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_X); - out->analogDown[3] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_Y); - // Black(RB), White(LB) -> analogDown[4,5] - out->analogDown[4] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); - out->analogDown[5] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); - // Triggers -> analogDown[6,7] - Sint16 lt = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERLEFT); - Sint16 rt = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERRIGHT); - out->analogDown[6] = (lt > 8000); - out->analogDown[7] = (rt > 8000); - - // Digital buttons -> digitalDown[0..7] = DPadU,D,L,R,Start,Back,LThumb,RThumb - out->digitalDown[0] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_UP); - out->digitalDown[1] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_DOWN); - out->digitalDown[2] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_LEFT); - out->digitalDown[3] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); - out->digitalDown[4] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_START); - out->digitalDown[5] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_BACK); - out->digitalDown[6] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_LEFTSTICK); - out->digitalDown[7] = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_RIGHTSTICK); - - // Thumbsticks (SDL Y is inverted vs Xbox) - float lx = (float)SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_LEFTX) / 32767.0f; - float ly = (float)(-SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_LEFTY)) / 32767.0f; - float rx = (float)SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_RIGHTX) / 32767.0f; - float ry = (float)(-SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_RIGHTY)) / 32767.0f; - - // Dead zone - if (lx > -0.9f && lx < 0.9f) lx = 0.0f; - if (ly > -0.9f && ly < 0.9f) ly = 0.0f; - if (rx > -0.9f && rx < 0.9f) rx = 0.0f; - if (ry > -0.9f && ry < 0.9f) ry = 0.0f; - - out->thumbLX = lx; - out->thumbLY = ly; - out->thumbRX = rx; - out->thumbRY = ry; - } + // Face buttons -> analogDown[0..3] = A,B,X,Y + out->analogDown[0] = Pads_Button(SDL_CONTROLLER_BUTTON_A); + out->analogDown[1] = Pads_Button(SDL_CONTROLLER_BUTTON_B) && !holdB; + out->analogDown[2] = Pads_Button(SDL_CONTROLLER_BUTTON_X); + out->analogDown[3] = Pads_Button(SDL_CONTROLLER_BUTTON_Y); + // Black(RB), White(LB) -> analogDown[4,5] + out->analogDown[4] = Pads_Button(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); + out->analogDown[5] = Pads_Button(SDL_CONTROLLER_BUTTON_LEFTSHOULDER); + // Triggers -> analogDown[6,7] + out->analogDown[6] = Pads_Axis(SDL_CONTROLLER_AXIS_TRIGGERLEFT) > 8000; + out->analogDown[7] = Pads_Axis(SDL_CONTROLLER_AXIS_TRIGGERRIGHT) > 8000; + + // Digital buttons -> digitalDown[0..7] = DPadU,D,L,R,Start,Back,LThumb,RThumb + out->digitalDown[0] = Pads_Button(SDL_CONTROLLER_BUTTON_DPAD_UP); + out->digitalDown[1] = Pads_Button(SDL_CONTROLLER_BUTTON_DPAD_DOWN); + out->digitalDown[2] = Pads_Button(SDL_CONTROLLER_BUTTON_DPAD_LEFT); + out->digitalDown[3] = Pads_Button(SDL_CONTROLLER_BUTTON_DPAD_RIGHT); + out->digitalDown[4] = Pads_Button(SDL_CONTROLLER_BUTTON_START); + out->digitalDown[5] = Pads_Button(SDL_CONTROLLER_BUTTON_BACK); + out->digitalDown[6] = Pads_Button(SDL_CONTROLLER_BUTTON_LEFTSTICK); + out->digitalDown[7] = Pads_Button(SDL_CONTROLLER_BUTTON_RIGHTSTICK); + + // Thumbsticks (SDL Y is inverted vs Xbox) + float lx = (float)Pads_Axis(SDL_CONTROLLER_AXIS_LEFTX) / 32767.0f; + float ly = (float)(-Pads_Axis(SDL_CONTROLLER_AXIS_LEFTY)) / 32767.0f; + float rx = (float)Pads_Axis(SDL_CONTROLLER_AXIS_RIGHTX) / 32767.0f; + float ry = (float)(-Pads_Axis(SDL_CONTROLLER_AXIS_RIGHTY)) / 32767.0f; + + // Dead zone + if (lx > -0.9f && lx < 0.9f) lx = 0.0f; + if (ly > -0.9f && ly < 0.9f) ly = 0.0f; + if (rx > -0.9f && rx < 0.9f) rx = 0.0f; + if (ry > -0.9f && ry < 0.9f) ry = 0.0f; + + out->thumbLX = lx; + out->thumbLY = ly; + out->thumbRX = rx; + out->thumbRY = ry; } void CJoystick::PollSDL(JoySnapshot* out) { - SDL_GameController* gc = Pads_Active(); memset(out, 0, sizeof(*out)); // Tools have the pad: leave it zeroed and the dashboard sits still. @@ -410,9 +400,9 @@ void CJoystick::PollSDL(JoySnapshot* out) // So does the guide, while it's open. if (Guide_TakesInput()) return; - const bool guideHoldsB = GuideChord(gc); + const bool guideHoldsB = GuideChord(); - ReadPad(gc, guideHoldsB, out); + ReadPad(guideHoldsB, out); // --- Keyboard overlay (OR on top) --- extern bool ImGui_WantsKeyboard(); @@ -483,18 +473,20 @@ void CJoystick::PollSDL(JoySnapshot* out) // Guide button, LT+B or F7 asks for the guide. The B of LT+B never reaches // the scene, or it would also back out of whatever is under the guide. -static bool GuideChord(SDL_GameController* gc) +static bool GuideChord() { extern bool g_guideRequested; extern SDL_Window* g_pSDLWindow; static bool s_guide = false, s_chord = false, s_f7 = false; static bool s_holdB = false; - bool guide = false, chord = false, b = false; - if (gc) { - guide = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_GUIDE) != 0; - b = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B) != 0; - chord = b && SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERLEFT) > 8000; + // Any pad's Guide; LT and B both on the same pad. + bool guide = Pads_Button(SDL_CONTROLLER_BUTTON_GUIDE), chord = false; + const bool b = Pads_Button(SDL_CONTROLLER_BUTTON_B); + for (int i = 0; i < Pads_Count(); i++) { + SDL_GameController* gc = Pads_Get(i); + if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B) && + SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERLEFT) > 8000) chord = true; } extern bool ImGui_WantsKeyboard(); const bool f7 = SDL_GetKeyboardFocus() == g_pSDLWindow && !ImGui_WantsKeyboard() && @@ -641,12 +633,11 @@ unsigned Joy_GuideButtons(int* device) { extern SDL_Window* g_pSDLWindow; extern bool ImGui_WantsKeyboard(); - SDL_GameController* gc = Pads_Active(); - const bool holdB = GuideChord(gc); + const bool holdB = GuideChord(); JoySnapshot pad; memset(&pad, 0, sizeof(pad)); - ReadPad(gc, holdB, &pad); + ReadPad(holdB, &pad); DevPadScript(&pad); DevEventScript(); unsigned bits = 0; diff --git a/theseus/desktop/osk.cpp b/theseus/desktop/osk.cpp index 2f46244..41cce1b 100644 --- a/theseus/desktop/osk.cpp +++ b/theseus/desktop/osk.cpp @@ -7,6 +7,7 @@ #include "std.h" #include "imgui.h" #include "imgui_internal.h" +#include "pads.h" extern bool g_padModeActive; @@ -75,12 +76,12 @@ static void Commit(ImGuiIO& io) { static bool s_oskUp = false; bool OSK_IsActive() { return s_oskUp; } -// Read the pad straight from SDL: ImGui's key state is not fed while we +// Read the pads straight from SDL: ImGui's key state is not fed while we // hold it, so we edge detect ourselves. struct PadEdge { bool prev[SDL_CONTROLLER_BUTTON_MAX]; - bool Pressed(SDL_GameController* gc, SDL_GameControllerButton b) { - const bool now = gc && SDL_GameControllerGetButton(gc, b); + bool Pressed(SDL_GameControllerButton b) { + const bool now = Pads_Button(b); const bool hit = now && !prev[b]; prev[b] = now; return hit; @@ -95,25 +96,23 @@ void RenderOnScreenKeyboard() { if (!io.WantTextInput) { s_oskUp = false; return; } s_oskUp = true; - // We hold the pad, so the field below keeps focus and stays still. - extern SDL_GameController* Joy_GetController(); - SDL_GameController* gc = Joy_GetController(); + // We hold the pads, so the field below keeps focus and stays still. - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) s_col--; - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) s_col++; - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_DPAD_UP)) s_row--; - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_DPAD_DOWN)) s_row++; + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_DPAD_LEFT)) s_col--; + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) s_col++; + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_DPAD_UP)) s_row--; + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_DPAD_DOWN)) s_row++; if (s_row < 0) s_row = kRowCount; if (s_row > kRowCount) s_row = 0; if (s_col < 0) s_col = RowLen(s_row) - 1; if (s_col >= RowLen(s_row)) s_col = 0; - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_A)) Commit(io); - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_X)) { + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_A)) Commit(io); + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_X)) { io.AddKeyEvent(ImGuiKey_Backspace, true); io.AddKeyEvent(ImGuiKey_Backspace, false); } - if (s_pad.Pressed(gc, SDL_CONTROLLER_BUTTON_B)) { // done, hand the pad back + if (s_pad.Pressed(SDL_CONTROLLER_BUTTON_B)) { // done, hand the pad back io.AddKeyEvent(ImGuiKey_Enter, true); io.AddKeyEvent(ImGuiKey_Enter, false); s_oskUp = false; diff --git a/theseus/desktop/pads.cpp b/theseus/desktop/pads.cpp index 5870761..4f18d56 100644 --- a/theseus/desktop/pads.cpp +++ b/theseus/desktop/pads.cpp @@ -1,7 +1,7 @@ // pads.cpp: every controller SDL sees, opened as it connects and closed as -// it leaves, so pads can come and go mid-session. A new press makes a pad -// the active one; when the active one leaves, the one used most recently -// takes over. +// it leaves, so pads can come and go mid-session. All of them drive the +// dashboard together. A new press makes a pad the active one; when the +// active one leaves, the one used most recently takes over. #include "std.h" #include @@ -130,6 +130,28 @@ SDL_GameController* Pads_Active() return i < 0 ? NULL : s_pads[i].gc; } +SDL_GameController* Pads_Get(int i) +{ + return i < 0 || i >= (int)s_pads.size() ? NULL : s_pads[i].gc; +} + +bool Pads_Button(SDL_GameControllerButton button) +{ + for (size_t i = 0; i < s_pads.size(); i++) + if (SDL_GameControllerGetButton(s_pads[i].gc, button)) return true; + return false; +} + +Sint16 Pads_Axis(SDL_GameControllerAxis axis) +{ + int best = 0; + for (size_t i = 0; i < s_pads.size(); i++) { + int v = SDL_GameControllerGetAxis(s_pads[i].gc, axis); + if (abs(v) > abs(best)) best = v; + } + return (Sint16)best; +} + // Development only: UIX_DEV_PAD="5:plug 6:plug=ps 8:a@2 9:unplug@1" plugs // in virtual pads (xbox, ps or switch), holds their buttons for 150 ms and // pulls them out again, so hot plug and several pads can be tried without diff --git a/theseus/desktop/pads.h b/theseus/desktop/pads.h index 3723079..07488f5 100644 --- a/theseus/desktop/pads.h +++ b/theseus/desktop/pads.h @@ -8,5 +8,12 @@ void Pads_Update(); // once a frame, after the event void Pads_Shutdown(); int Pads_Count(); -// The pad pressed last, NULL with none connected. +SDL_GameController* Pads_Get(int i); +// The pad pressed last, NULL with none connected. Things only one player +// can hold, like a stream, go to this one. SDL_GameController* Pads_Active(); + +// Every pad drives the dashboard: a button counts held on any pad, and a +// stick or trigger reads off whichever pad pushes it furthest. +bool Pads_Button(SDL_GameControllerButton button); +Sint16 Pads_Axis(SDL_GameControllerAxis axis); diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index 6f3fbea..b66c6fd 100644 --- a/theseus/desktop/sdl_main.cpp +++ b/theseus/desktop/sdl_main.cpp @@ -1684,11 +1684,8 @@ int main(int argc, char* argv[]) { if (g_xcloudClosed) { bool leave = (SDL_GetTicks() - g_xcloudClosedAtMs > kXcloudClosedAutoMs); - if (SDL_GameController* gc = Pads_Active()) { - if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_A) || - SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B) || - SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_START)) leave = true; - } + if (Pads_Button(SDL_CONTROLLER_BUTTON_A) || Pads_Button(SDL_CONTROLLER_BUTTON_B) || + Pads_Button(SDL_CONTROLLER_BUTTON_START)) leave = true; if (leave) { g_xcloudFullscreen = false; g_xcloudClosed = false; } } else if (SDL_GameController* gc = Pads_Active()) { // Streaming: the controller belongs to the game. SDL already @@ -1798,9 +1795,10 @@ int main(int argc, char* argv[]) { const Uint8* keys = SDL_GetKeyboardState(NULL); bool kbXY = keys[SDL_SCANCODE_X] && keys[SDL_SCANCODE_Y]; bool padXY = false; - if (SDL_GameController* gc = Pads_Active()) { - padXY = SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_X) - && SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_Y); + for (int i = 0; i < Pads_Count(); i++) { + SDL_GameController* gc = Pads_Get(i); + if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_X) && + SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_Y)) padXY = true; } static bool s_prevXY = false; bool xy = kbXY || padXY; From 2205c438dfa096fb19f3c7844d7e7fc56e70114d Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:17:40 -0500 Subject: [PATCH 08/46] Icons from .ico files and Windows programs The Title Maker only took jpg, png and bmp, so a program's icon had to be pulled out by hand. It now reads the biggest picture from an .ico, .exe or .dll on any OS, and a program added in the guide or picked as a launch path brings its icon along. --- build/Makefile | 1 + theseus/desktop/exe_icon.cpp | 285 ++++++++++++++++++++++++++++++ theseus/desktop/exe_icon.h | 19 ++ theseus/desktop/guide.cpp | 8 +- theseus/desktop/icon_compress.cpp | 10 +- theseus/desktop/icon_compress.h | 3 + theseus/desktop/title_maker.cpp | 19 +- 7 files changed, 338 insertions(+), 7 deletions(-) create mode 100644 theseus/desktop/exe_icon.cpp create mode 100644 theseus/desktop/exe_icon.h diff --git a/build/Makefile b/build/Makefile index d7b80fe..8e20dfb 100644 --- a/build/Makefile +++ b/build/Makefile @@ -892,6 +892,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/esde.cpp \ $(THESEUS_SRC)/desktop/esde_vgames.cpp \ $(THESEUS_SRC)/desktop/icon_compress.cpp \ + $(THESEUS_SRC)/desktop/exe_icon.cpp \ $(THESEUS_SRC)/desktop/game_art.cpp \ $(THESEUS_SRC)/desktop/playlist.cpp \ $(THESEUS_SRC)/desktop/playlist_maker.cpp \ diff --git a/theseus/desktop/exe_icon.cpp b/theseus/desktop/exe_icon.cpp new file mode 100644 index 0000000..8a329e3 --- /dev/null +++ b/theseus/desktop/exe_icon.cpp @@ -0,0 +1,285 @@ +// exe_icon.cpp: reads icons out of .ico files and Windows programs. +// +// An .ico is a list of pictures, each a PNG or a bottom-up bitmap with an +// AND mask under it. A program keeps the same pictures as RT_ICON resources +// and the list as an RT_GROUP_ICON, so we walk the PE resource tree, take +// the first group (the one Explorer shows) and decode its biggest picture. + +#include "exe_icon.h" +#include "icon_compress.h" + +#include +#include +#include +#include +#include +#include + +#include "stb_image.h" +#include "host.h" + +namespace { + +const int kMaxDim = 1024; +const uint32_t kRtIcon = 3, kRtGroupIcon = 14; + +uint16_t U16(const unsigned char* p) { return (uint16_t)(p[0] | p[1] << 8); } +uint32_t U32(const unsigned char* p) { return (uint32_t)p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } + +// A file read in pieces, so a 2 GB game exe never lands in memory whole. +struct Reader { + FILE* f; + uint64_t size; + bool Read(uint64_t off, void* dst, size_t n) const { + if (off > size || n > size - off) return false; + if (Host_Seek(f, (int64_t)off, SEEK_SET) < 0) return false; + return fread(dst, 1, n, f) == n; + } +}; + +// One bitmap picture (no file header), bottom-up, with its AND mask. +unsigned char* DecodeDib(const unsigned char* p, size_t size, int* outW, int* outH) { + if (size < 40) return NULL; + uint32_t hdr = U32(p); + int32_t w = (int32_t)U32(p + 4), h2 = (int32_t)U32(p + 8); + int bpp = U16(p + 14); + uint32_t comp = U32(p + 16), used = U32(p + 32); + if (hdr < 40 || hdr > size || w <= 0 || h2 <= 0 || w > kMaxDim) return NULL; + int h = h2 / 2; + if (h <= 0 || h > kMaxDim) return NULL; + if (comp != 0 && !(comp == 3 && bpp == 32)) return NULL; + if (bpp != 1 && bpp != 4 && bpp != 8 && bpp != 24 && bpp != 32) return NULL; + + size_t colors = bpp <= 8 ? (used ? used : (size_t)1 << bpp) : 0; + if (colors > 256) return NULL; + size_t palOff = hdr + (comp == 3 && hdr == 40 ? 12 : 0); + size_t pixOff = palOff + colors * 4; + size_t stride = (((size_t)w * bpp + 31) / 32) * 4; + size_t maskStride = (((size_t)w + 31) / 32) * 4; + if (pixOff + stride * h > size) return NULL; + const unsigned char* pal = p + palOff; + const unsigned char* pix = p + pixOff; + // Some 32-bit pictures skip the mask; alpha carries it then. + const unsigned char* mask = pixOff + stride * h + maskStride * h <= size ? pix + stride * h : NULL; + + unsigned char* out = (unsigned char*)malloc((size_t)w * h * 4); + if (!out) return NULL; + bool anyAlpha = false; + for (int y = 0; y < h; y++) { + const unsigned char* row = pix + stride * (h - 1 - y); + unsigned char* o = out + (size_t)y * w * 4; + for (int x = 0; x < w; x++, o += 4) { + if (bpp == 32) { + o[0] = row[x * 4 + 2]; o[1] = row[x * 4 + 1]; o[2] = row[x * 4 + 0]; o[3] = row[x * 4 + 3]; + if (o[3]) anyAlpha = true; + continue; + } + if (bpp == 24) { + o[0] = row[x * 3 + 2]; o[1] = row[x * 3 + 1]; o[2] = row[x * 3 + 0]; + } else { + unsigned idx; + if (bpp == 8) idx = row[x]; + else if (bpp == 4) idx = (row[x / 2] >> (x & 1 ? 0 : 4)) & 15; + else idx = (row[x / 8] >> (7 - (x & 7))) & 1; + if (idx >= colors) idx = 0; + o[0] = pal[idx * 4 + 2]; o[1] = pal[idx * 4 + 1]; o[2] = pal[idx * 4 + 0]; + } + o[3] = 255; + } + } + if (mask && (bpp != 32 || !anyAlpha)) { + for (int y = 0; y < h; y++) { + const unsigned char* row = mask + maskStride * (h - 1 - y); + for (int x = 0; x < w; x++) { + bool clear = (row[x / 8] >> (7 - (x & 7))) & 1; + out[((size_t)y * w + x) * 4 + 3] = clear ? 0 : 255; + } + } + } else if (bpp == 32 && !anyAlpha) { + for (size_t i = 0; i < (size_t)w * h; i++) out[i * 4 + 3] = 255; + } + *outW = w; + *outH = h; + return out; +} + +// One picture from an icon list: PNG or bitmap. +unsigned char* DecodeImage(const unsigned char* p, size_t size, int* w, int* h) { + static const unsigned char kPng[8] = { 0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n' }; + if (size >= 8 && memcmp(p, kPng, 8) == 0) { + int ch = 0; + unsigned char* px = stbi_load_from_memory(p, (int)size, w, h, &ch, 4); + if (!px) return NULL; + // Hand back malloc'd memory like the bitmap path does. + size_t n = (size_t)*w * *h * 4; + unsigned char* out = (unsigned char*)malloc(n); + if (out) memcpy(out, px, n); + stbi_image_free(px); + return out; + } + return DecodeDib(p, size, w, h); +} + +// Keeps the biggest picture seen so far, deeper color breaking a tie. +struct Best { + unsigned char* px = NULL; + int w = 0, h = 0, rank = 0; + void Offer(const unsigned char* data, size_t size, int bits) { + int w2 = 0, h2 = 0; + unsigned char* p = DecodeImage(data, size, &w2, &h2); + if (!p) return; + int rank2 = w2 * h2 * 64 + (bits > 63 ? 63 : bits); + if (rank2 <= rank) { free(p); return; } + free(px); + px = p; w = w2; h = h2; rank = rank2; + } +}; + +// A resource directory entry by id; the first entry when id is 0. +bool FindEntry(const Reader& r, uint64_t base, uint32_t dirOff, uint32_t id, uint32_t* entryData) { + unsigned char d[16]; + if (!r.Read(base + dirOff, d, 16)) return false; + unsigned count = (unsigned)U16(d + 12) + U16(d + 14); + if (count > 4096) return false; + for (unsigned i = 0; i < count; i++) { + unsigned char e[8]; + if (!r.Read(base + dirOff + 16 + i * 8, e, 8)) return false; + uint32_t name = U32(e); + if (id == 0 || (!(name & 0x80000000u) && name == id)) { + *entryData = U32(e + 4); + return true; + } + } + return false; +} + +struct Pe { + Reader r; + uint64_t rsrc; // file offset of the resource tree + struct Sec { uint32_t va, vsize, raw, rawSize; }; + std::vector secs; + + bool RvaToOffset(uint32_t rva, uint64_t* off) const { + for (size_t i = 0; i < secs.size(); i++) { + uint32_t span = secs[i].vsize > secs[i].rawSize ? secs[i].vsize : secs[i].rawSize; + if (rva >= secs[i].va && rva - secs[i].va < span) { + *off = (uint64_t)secs[i].raw + (rva - secs[i].va); + return true; + } + } + return false; + } + + bool Open() { + unsigned char mz[64]; + if (!r.Read(0, mz, 64) || mz[0] != 'M' || mz[1] != 'Z') return false; + uint32_t peOff = U32(mz + 0x3c); + unsigned char coff[24]; + if (!r.Read(peOff, coff, 24) || memcmp(coff, "PE\0\0", 4) != 0) return false; + unsigned nsec = U16(coff + 6), optSize = U16(coff + 20); + if (nsec == 0 || nsec > 96 || optSize < 96) return false; + std::vector opt(optSize); + if (!r.Read(peOff + 24, &opt[0], optSize)) return false; + uint16_t magic = U16(&opt[0]); + size_t ddOff = magic == 0x20b ? 112 : magic == 0x10b ? 96 : 0; + if (!ddOff || ddOff + 3 * 8 > optSize || U32(&opt[ddOff - 4]) < 3) return false; + uint32_t rsrcRva = U32(&opt[ddOff + 2 * 8]); + if (!rsrcRva) return false; + for (unsigned i = 0; i < nsec; i++) { + unsigned char s[40]; + if (!r.Read(peOff + 24 + optSize + i * 40, s, 40)) return false; + Sec sec = { U32(s + 12), U32(s + 8), U32(s + 20), U32(s + 16) }; + secs.push_back(sec); + } + return RvaToOffset(rsrcRva, &rsrc); + } + + // The data of resource type/id, first language. id 0 takes the first one. + bool Resource(uint32_t type, uint32_t id, std::vector& out) const { + uint32_t e; + if (!FindEntry(r, rsrc, 0, type, &e) || !(e & 0x80000000u)) return false; + if (!FindEntry(r, rsrc, e & 0x7fffffffu, id, &e) || !(e & 0x80000000u)) return false; + if (!FindEntry(r, rsrc, e & 0x7fffffffu, 0, &e) || (e & 0x80000000u)) return false; + unsigned char data[8]; + if (!r.Read(rsrc + e, data, 8)) return false; + uint32_t size = U32(data + 4); + uint64_t off; + if (size == 0 || size > (8u << 20) || !RvaToOffset(U32(data), &off)) return false; + out.resize(size); + return r.Read(off, &out[0], size); + } +}; + +unsigned char* FromPe(FILE* f, uint64_t size, int* w, int* h) { + Pe pe; + pe.r.f = f; + pe.r.size = size; + std::vector group; + if (!pe.Open() || !pe.Resource(kRtGroupIcon, 0, group) || group.size() < 6) return NULL; + unsigned count = U16(&group[4]); + Best best; + for (unsigned i = 0; i < count && 6 + (i + 1) * 14 <= group.size(); i++) { + const unsigned char* e = &group[6 + i * 14]; + std::vector img; + if (pe.Resource(kRtIcon, U16(e + 12), img)) + best.Offer(&img[0], img.size(), U16(e + 6)); + } + *w = best.w; + *h = best.h; + return best.px; +} + +bool HasExt(const char* path, const char* ext) { + size_t n = strlen(path), e = strlen(ext); + return n > e && strcasecmp(path + n - e, ext) == 0; +} + +} // namespace + +bool ExeIcon_IsIconSource(const char* path) { + return path && (HasExt(path, ".ico") || HasExt(path, ".exe") || HasExt(path, ".dll")); +} + +unsigned char* ExeIcon_FromIco(const unsigned char* data, size_t size, int* w, int* h) { + if (size < 6 || U16(data) != 0 || (U16(data + 2) != 1 && U16(data + 2) != 2)) return NULL; + unsigned count = U16(data + 4); + Best best; + for (unsigned i = 0; i < count && 6 + (i + 1) * 16 <= size; i++) { + const unsigned char* e = data + 6 + i * 16; + uint32_t len = U32(e + 8), off = U32(e + 12); + if (off < 6 || off > size || len > size - off) continue; + best.Offer(data + off, len, U16(e + 6)); + } + *w = best.w; + *h = best.h; + return best.px; +} + +unsigned char* ExeIcon_Load(const char* path, int* w, int* h) { + *w = *h = 0; + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + unsigned char* px = NULL; + HostFileInfo info; + unsigned char magic[2]; + if (Host_StatOpenFile(f, &info) && fread(magic, 1, 2, f) == 2) { + if (magic[0] == 'M' && magic[1] == 'Z') { + px = FromPe(f, info.size, w, h); + } else if (info.size >= 6 && info.size <= (16u << 20)) { + std::vector data((size_t)info.size); + if (Host_Seek(f, 0, SEEK_SET) == 0 && fread(&data[0], 1, data.size(), f) == data.size()) + px = ExeIcon_FromIco(&data[0], data.size(), w, h); + } + } + fclose(f); + return px; +} + +bool ExeIcon_Save(const char* path, const char* dst) { + int w = 0, h = 0; + unsigned char* px = ExeIcon_Load(path, &w, &h); + if (!px) return false; + bool ok = Icons_FitPixels(px, w, h, dst, 256, 90); + free(px); + return ok; +} diff --git a/theseus/desktop/exe_icon.h b/theseus/desktop/exe_icon.h new file mode 100644 index 0000000..2ee1e5c --- /dev/null +++ b/theseus/desktop/exe_icon.h @@ -0,0 +1,19 @@ +// exe_icon.h: the picture inside an .ico file, or the icon a Windows .exe +// or .dll carries. Plain file reading, so it works the same on every OS. + +#pragma once + +#include + +// .ico, .exe or .dll, by extension. +bool ExeIcon_IsIconSource(const char* path); + +// The biggest picture in it as RGBA (w * h * 4 bytes, free() it). NULL when +// there's no icon or it won't decode. +unsigned char* ExeIcon_Load(const char* path, int* w, int* h); + +// Same, for an .ico already in memory. +unsigned char* ExeIcon_FromIco(const unsigned char* data, size_t size, int* w, int* h); + +// The biggest icon into Configs/icons as dst (a .jpg). False when there's none. +bool ExeIcon_Save(const char* path, const char* dst); diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index a819f6b..0120caa 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -29,6 +29,7 @@ #include "launchers/xemu.h" #include "launchers/pcsx2.h" #include "xiso.h" +#include "exe_icon.h" #include "guide.h" #include "ui_overlay.h" #include @@ -1194,11 +1195,14 @@ static void Select() } if (!fits) { XisoFreeTitleInfo(&xiso); g.added = "Path too long"; Build(); break; } VGames_Add(g.pickedName.c_str(), genID, launch, "E", kCategories[g.category]); + char icon[1024]; + snprintf(icon, sizeof(icon), "%s/%s.jpg", VGAMES_ICONS, genID); if (xiso.titleImageRGBA) { - char icon[1024]; Host_MakeDir(VGAMES_ICONS); - snprintf(icon, sizeof(icon), "%s/%s.jpg", VGAMES_ICONS, genID); XisoSaveTitleImage(&xiso, icon); + } else if (g.runner == RUN_SELF && ExeIcon_IsIconSource(g.pickedPath.c_str())) { + Host_MakeDir(VGAMES_ICONS); + ExeIcon_Save(g.pickedPath.c_str(), icon); } XisoFreeTitleInfo(&xiso); VGames_Save(); diff --git a/theseus/desktop/icon_compress.cpp b/theseus/desktop/icon_compress.cpp index 7de0c4e..d86c94f 100644 --- a/theseus/desktop/icon_compress.cpp +++ b/theseus/desktop/icon_compress.cpp @@ -146,17 +146,23 @@ bool Icons_FitFile(const char* src, const char* dst, int maxDim, int quality) int w = 0, h = 0, ch = 0; unsigned char* rgba = stbi_load(src, &w, &h, &ch, 4); if (!rgba || w <= 0 || h <= 0) { if (rgba) stbi_image_free(rgba); return false; } + bool ok = Icons_FitPixels(rgba, w, h, dst, maxDim, quality); + stbi_image_free(rgba); + return ok; +} +bool Icons_FitPixels(const unsigned char* rgba, int w, int h, const char* dst, int maxDim, int quality) +{ + if (!rgba || w <= 0 || h <= 0) return false; // Box art with a transparent edge would otherwise keep whatever color sat under it. unsigned char* rgb = (unsigned char*)malloc((size_t)w * h * 3); - if (!rgb) { stbi_image_free(rgba); return false; } + if (!rgb) return false; for (size_t i = 0, n = (size_t)w * h; i < n; i++) { unsigned a = rgba[i * 4 + 3]; rgb[i * 3 + 0] = (unsigned char)(rgba[i * 4 + 0] * a / 255); rgb[i * 3 + 1] = (unsigned char)(rgba[i * 4 + 1] * a / 255); rgb[i * 3 + 2] = (unsigned char)(rgba[i * 4 + 2] * a / 255); } - stbi_image_free(rgba); int big = (w > h) ? w : h; int dw = w, dh = h; diff --git a/theseus/desktop/icon_compress.h b/theseus/desktop/icon_compress.h index cb3cf43..aa489a7 100644 --- a/theseus/desktop/icon_compress.h +++ b/theseus/desktop/icon_compress.h @@ -19,3 +19,6 @@ IconCompressResult Icons_Compress(int maxDim, int quality); // Fit one image (any size, png or jpg) into maxDim on the long side and write // it as a jpg at dst. Transparency lands on black. False when src won't decode. bool Icons_FitFile(const char* src, const char* dst, int maxDim, int quality); + +// Same, for RGBA pixels already in memory. +bool Icons_FitPixels(const unsigned char* rgba, int w, int h, const char* dst, int maxDim, int quality); diff --git a/theseus/desktop/title_maker.cpp b/theseus/desktop/title_maker.cpp index c9a12a5..3de0480 100644 --- a/theseus/desktop/title_maker.cpp +++ b/theseus/desktop/title_maker.cpp @@ -11,6 +11,7 @@ #include "esde.h" #include "esde_vgames.h" #include "icon_compress.h" +#include "exe_icon.h" #include "udata_synth.h" #include "xiso.h" #include "launchers/steam.h" @@ -767,7 +768,8 @@ void RenderTitleMaker() { if (!s_iconBrowserInit) { s_iconBrowser.SetTitle("Select Icon Image"); - s_iconBrowser.SetTypeFilters({ ".jpg", ".jpeg", ".png", ".bmp", ".JPG", ".PNG" }); + s_iconBrowser.SetTypeFilters({ ".jpg", ".jpeg", ".png", ".bmp", ".ico", ".exe", ".dll", + ".JPG", ".PNG", ".ICO", ".EXE", ".DLL" }); s_iconBrowserInit = true; } if (!s_appBrowserInit) { @@ -1364,10 +1366,13 @@ void RenderTitleMaker() { char dstPath[512]; snprintf(dstPath, sizeof(dstPath), "%s/%s.jpg", VGAMES_ICONS, sel.titleID); - TM_CopyFile(iconSrc.c_str(), dstPath); + // An .ico or a program gives its biggest icon. + bool saved = ExeIcon_IsIconSource(iconSrc.c_str()) ? ExeIcon_Save(iconSrc.c_str(), dstPath) + : TM_CopyFile(iconSrc.c_str(), dstPath); s_iconTexIdx = -1; // force icon reload - snprintf(s_statusMsg, sizeof(s_statusMsg), "Icon saved: %s", dstPath); + if (saved) snprintf(s_statusMsg, sizeof(s_statusMsg), "Icon saved: %s", dstPath); + else snprintf(s_statusMsg, sizeof(s_statusMsg), "No icon in %s", iconSrc.c_str()); s_statusTime = 3.0f; } @@ -1376,6 +1381,14 @@ void RenderTitleMaker() { std::string appPath = s_appBrowser.GetSelected().string(); s_appBrowser.ClearSelected(); strncpy(s_editLaunch, appPath.c_str(), sizeof(s_editLaunch) - 1); + // A program with no icon yet lends its own. + if (s_selectedIdx >= 0 && s_selectedIdx < s_entryCount && ExeIcon_IsIconSource(appPath.c_str()) && + !VGames_GetIconPath(s_entries[s_selectedIdx].vgIndex)) { + TM_EnsureDir(VGAMES_ICONS); + char dstPath[512]; + snprintf(dstPath, sizeof(dstPath), "%s/%s.jpg", VGAMES_ICONS, s_entries[s_selectedIdx].titleID); + if (ExeIcon_Save(appPath.c_str(), dstPath)) s_iconTexIdx = -1; + } } ImGui::EndTabItem(); From 6577846e33e9184a6b1fce364e95ebb4abf4ace8 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:17:13 -0500 Subject: [PATCH 09/46] Kept access tokens out of the log Playing from Jellyfin wrote the stream URL with its api_key into theseus.log, and Plex stream URLs carry X-Plex-Token the same way. Tokens and keys in URLs, auth headers and dumped JSON bodies now show as [redacted], and copied logs get the same pass. --- theseus/desktop/desktop_nodes.cpp | 2 +- theseus/desktop/jellyfin_client.cpp | 5 ++- theseus/desktop/log_redact.cpp | 58 ++++++++++++++++++++++++++++- theseus/desktop/log_redact.h | 3 ++ theseus/desktop/media_player.cpp | 3 +- theseus/desktop/plex_client.cpp | 3 +- theseus/desktop/xcloud_client.cpp | 11 +++--- 7 files changed, 73 insertions(+), 12 deletions(-) diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index c2db6b1..162cb4b 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3647,7 +3647,7 @@ class CPlexLibrary : public CNode } if (!MediaPlayer_Open(url.c_str())) { fprintf(stderr, "[Plex] MediaPlayer_Open failed for %s\n", - url.c_str()); + ratingKey.c_str()); return; } extern bool g_mediaFullscreen; diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index b1b1503..87743e6 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -5,6 +5,7 @@ #include "http_util.h" #include "json_util.h" #include "client_util.h" +#include "log_redact.h" #include #include @@ -196,7 +197,7 @@ static void QuickConnectWorker() std::string code = Json_GetString(r.body, "Code"); std::string secret = Json_GetString(r.body, "Secret"); if (code.empty() || secret.empty()) { - fprintf(stderr, "[Jellyfin] QC init bad json: %s\n", r.body.c_str()); + fprintf(stderr, "[Jellyfin] QC init bad json: %s\n", Log_RedactSecrets(r.body).c_str()); s_qcInFlight = false; return; } @@ -260,7 +261,7 @@ static void QuickConnectWorker() } if (accessToken.empty() || userId.empty()) { - fprintf(stderr, "[Jellyfin] auth response missing fields: %s\n", a.body.c_str()); + fprintf(stderr, "[Jellyfin] auth response missing fields: %s\n", Log_RedactSecrets(a.body).c_str()); } else { strncpy(g_jellyfinToken, accessToken.c_str(), sizeof(g_jellyfinToken) - 1); g_jellyfinToken[sizeof(g_jellyfinToken) - 1] = 0; diff --git a/theseus/desktop/log_redact.cpp b/theseus/desktop/log_redact.cpp index d9a71b4..e2eae6e 100644 --- a/theseus/desktop/log_redact.cpp +++ b/theseus/desktop/log_redact.cpp @@ -1,4 +1,4 @@ -// log_redact.cpp: home folder and IP address masking for copied logs. +// log_redact.cpp: token, home folder and IP address masking for logs. #include "log_redact.h" #include @@ -50,8 +50,62 @@ static size_t MatchV6(const char* p, bool* keep) return (size_t)(s - p); } -std::string Log_Redact(const std::string& in, const char* home) +static bool EndsWithKey(const std::string& s, size_t end, const char* key) { + size_t n = strlen(key); + if (end < n) return false; + for (size_t i = 0; i < n; i++) + if (tolower((unsigned char)s[end - n + i]) != key[i]) return false; + return true; +} + +// A key that names a secret: anything ending in token, plus api_key / apikey. +static bool SecretKeyEndsAt(const std::string& s, size_t end) +{ + return EndsWithKey(s, end, "token") || EndsWithKey(s, end, "api_key") || + EndsWithKey(s, end, "apikey") || EndsWithKey(s, end, "secret"); +} + +std::string Log_RedactSecrets(const std::string& in) +{ + std::string out; + out.reserve(in.size()); + size_t i = 0; + while (i < in.size()) { + char c = in[i]; + size_t v = std::string::npos; + // key=value (query strings, Token="..." in auth headers) + if (c == '=' && SecretKeyEndsAt(in, i)) v = i + 1; + // "key": "value" (JSON) + if (c == '"' && i > 0 && SecretKeyEndsAt(in, i)) { + size_t j = i + 1; + while (j < in.size() && in[j] == ' ') j++; + if (j < in.size() && in[j] == ':') { + j++; + while (j < in.size() && in[j] == ' ') j++; + if (j < in.size() && in[j] == '"') v = j; + } + } + if (v == std::string::npos) { out += c; i++; continue; } + out.append(in, i, v - i); + bool quoted = v < in.size() && in[v] == '"'; + size_t e = v + (quoted ? 1 : 0); + while (e < in.size()) { + char d = in[e]; + if (quoted ? d == '"' : (d == '&' || d == '"' || d == '\'' || d == ',' || isspace((unsigned char)d))) break; + e++; + } + size_t start = v + (quoted ? 1 : 0); + if (quoted) out += '"'; + if (e > start) out += "[redacted]"; + i = e; + } + return out; +} + +std::string Log_Redact(const std::string& raw, const char* home) +{ + std::string in = Log_RedactSecrets(raw); std::string text; size_t hl = home ? strlen(home) : 0; while (hl > 1 && (home[hl - 1] == '/' || home[hl - 1] == '\\')) hl--; diff --git a/theseus/desktop/log_redact.h b/theseus/desktop/log_redact.h index 27017fd..dd15adc 100644 --- a/theseus/desktop/log_redact.h +++ b/theseus/desktop/log_redact.h @@ -5,3 +5,6 @@ // The home folder becomes ~ and IP addresses become [ip] (loopback and // 0.0.0.0 stay, they say nothing about anyone). std::string Log_Redact(const std::string& text, const char* home); + +// Access tokens and API keys in URLs, auth headers and JSON become [redacted]. +std::string Log_RedactSecrets(const std::string& text); diff --git a/theseus/desktop/media_player.cpp b/theseus/desktop/media_player.cpp index 88c1ccb..587f7ab 100644 --- a/theseus/desktop/media_player.cpp +++ b/theseus/desktop/media_player.cpp @@ -8,6 +8,7 @@ // can't lie about the current buffer size. #include "media_player.h" +#include "log_redact.h" #include #include @@ -190,7 +191,7 @@ bool MediaPlayer_Open(const char* path) { s_hasVideo = false; s_videoWidth = 0; s_videoHeight = 0; - fprintf(stderr, "[MediaPlayer] Opening: %s\n", path); + fprintf(stderr, "[MediaPlayer] Opening: %s\n", Log_RedactSecrets(path).c_str()); return true; } diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index 67f23dc..3416c52 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -6,6 +6,7 @@ #include "http_util.h" #include "json_util.h" #include "client_util.h" +#include "log_redact.h" #include #include @@ -155,7 +156,7 @@ static void PinAuthWorker() int pinId = Json_GetInt(r.body, "id"); std::string code = Json_GetString(r.body, "code"); if (pinId == 0 || code.empty()) { - fprintf(stderr, "[Plex] pin create returned bad json: %s\n", r.body.c_str()); + fprintf(stderr, "[Plex] pin create returned bad json: %s\n", Log_RedactSecrets(r.body).c_str()); s_pinInFlight = false; return; } diff --git a/theseus/desktop/xcloud_client.cpp b/theseus/desktop/xcloud_client.cpp index b7804b5..e7ce2b5 100644 --- a/theseus/desktop/xcloud_client.cpp +++ b/theseus/desktop/xcloud_client.cpp @@ -11,6 +11,7 @@ #include "http_util.h" #include "json_util.h" #include "client_util.h" +#include "log_redact.h" #include #include @@ -100,7 +101,7 @@ static std::string GetPassportToken() HttpHeaders h = { { "Content-Type", "application/x-www-form-urlencoded" } }; HttpResponse r = Http_Post("https://login.live.com/oauth20_token.srf", body, h); if (!r.ok()) { - fprintf(stderr, "[xCloud] passport token HTTP %ld body=%.200s\n", r.status, r.body.c_str()); + fprintf(stderr, "[xCloud] passport token HTTP %ld body=%.200s\n", r.status, Log_RedactSecrets(r.body).c_str()); return ""; } return Json_GetString(r.body, "access_token"); @@ -596,7 +597,7 @@ static void RunWebRtcTransport(const StreamEndpoint& ep, const std::string& sess "\"unreliableinput\":{\"minVersion\":9,\"maxVersion\":9}}}"; } fprintf(stderr, "[xCloud] offer %zu bytes, POST /sdp...\n", offerSdp.size()); HttpResponse pr = Http_Post(sdpBase + "/sdp", offBody, hdr); - fprintf(stderr, "[xCloud] POST /sdp status=%ld body=%.300s\n", pr.status, pr.body.c_str()); + fprintf(stderr, "[xCloud] POST /sdp status=%ld body=%.300s\n", pr.status, Log_RedactSecrets(pr.body).c_str()); if (!pr.ok()) { SetStreamPhase("POST /sdp failed: HTTP " + std::to_string(pr.status)); return; } // Poll for the answer (204 until ready), then apply it. @@ -604,12 +605,12 @@ static void RunWebRtcTransport(const StreamEndpoint& ep, const std::string& sess for (int i = 0; i < 40 && answerSdp.empty() && !s_streamCancel; i++) { HttpResponse r = Http_Get(sdpBase + "/sdp", hdr); if (i == 0 || (r.status != 204 && r.status != 200)) - fprintf(stderr, "[xCloud] GET /sdp status=%ld body=%.300s\n", r.status, r.body.c_str()); + fprintf(stderr, "[xCloud] GET /sdp status=%ld body=%.300s\n", r.status, Log_RedactSecrets(r.body).c_str()); if (r.ok() && r.status != 204) { std::string ex = Json_GetString(r.body, "exchangeResponse"); if (!ex.empty()) answerSdp = Json_GetString(ex, "sdp"); if (answerSdp.empty()) - fprintf(stderr, "[xCloud] /sdp response had no exchangeResponse.sdp: %.300s\n", r.body.c_str()); + fprintf(stderr, "[xCloud] /sdp response had no exchangeResponse.sdp: %.300s\n", Log_RedactSecrets(r.body).c_str()); } if (answerSdp.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(500)); } @@ -744,7 +745,7 @@ static void StreamSessionWorker(std::string type, std::string id) std::string msg = Json_GetString(pr.body, "message"); SetStreamPhase(code.empty() ? ("play failed: HTTP " + std::to_string(pr.status)) : (code + (msg.empty() ? "" : ": " + msg))); - fprintf(stderr, "[xCloud] play HTTP %ld body=%.400s\n", pr.status, pr.body.c_str()); + fprintf(stderr, "[xCloud] play HTTP %ld body=%.400s\n", pr.status, Log_RedactSecrets(pr.body).c_str()); s_streamRunning = false; return; } std::string sessionPath = Json_GetString(pr.body, "sessionPath"); From 7c391b65d1e7ccff6c47e2ddaba5b1d1cb882f03 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:18:50 -0500 Subject: [PATCH 10/46] Pad buzzes when the guide can't do something The dashboard never asks for rumble, so the guide is the only place it fits. A on something that does nothing, or an import that can't find anything, gives a short buzz on the pad you're using. There's a Rumble setting on a new Controller page, on by default. Needs a feel test on real pads. --- theseus/desktop/desktop_settings.cpp | 7 +++++++ theseus/desktop/guide.cpp | 28 ++++++++++++++++++++-------- theseus/desktop/pads.cpp | 11 +++++++++++ theseus/desktop/pads.h | 4 ++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index eb5efca..b7bf66d 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -10,6 +10,7 @@ #include "audio_sdl.h" #include "media_player.h" #include "virtual_games.h" +#include "pads.h" extern char s_xemuPath[512]; extern char g_qcowPath[512]; @@ -68,6 +69,9 @@ static const int kStartupVals[] = { 0, 1, 2 }; static const char* kStartupLbl[] = { "Ask on launch", "Dashboard", "Development" }; static const char* kStartupTok[] = { "", "dashboard", "development" }; +// Turning it on buzzes once, so you know it works. +static void ApplyRumble() { if (g_padRumble) Pads_Rumble(0.5f, 150); } + static const int kMsaaVals[] = { 0, 2, 4, 8 }; static const char* kMsaaLbl[] = { "Off", "2x", "4x", "8x" }; @@ -151,6 +155,9 @@ static const SettingDef kDefs[] = { { "GuideTheme", "Desktop", "Display", "Guide Color", SK_ENUM, &g_guideTheme, 0, "green", SF_STRICT, ENUM(kThemeVals, kThemeLbl, kThemeTok), 0, 0, 0, NULL, NULL }, + { "Rumble", "Controller", "Controller", "Rumble", SK_BOOL, &g_padRumble, 0, "1", 0, + NOENUM, 0, 0, 0, NULL, ApplyRumble }, + S_BOOL("CRT_Enabled", "CRT", "Display", "CRT Effect", g_crt.enabled, "0", 0), S_CRT("CRT_Scanlines", "Scanlines", scanlineIntensity, "0.500", 0.0f, 1.0f), S_CRT("CRT_Curvature", "Curvature", curvature, "0.400", 0.0f, 2.0f), diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 662ef8c..f56a8eb 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -28,6 +28,7 @@ #include "xcloud_client.h" #include "guide.h" #include "ui_overlay.h" +#include "pads.h" #include #include #include @@ -230,6 +231,7 @@ static const char* SettingHelp(const SettingDef& d) { "GuideTheme", "The guide's colors." }, { "FetchGameArt", "Box art for games without an icon. Icons you picked are never replaced." }, { "HideDuplicateGames", "A game in Steam and ES-DE shows once: Steam first, then yours, then ES-DE." }, + { "Rumble", "A short buzz when the guide can't do what you asked." }, }; for (size_t i = 0; i < sizeof(kHelp) / sizeof(kHelp[0]); i++) if (strcmp(kHelp[i].key, d.key) == 0) return kHelp[i].help; @@ -240,7 +242,7 @@ static const char* SettingHelp(const SettingDef& d) return "Left and right change it."; } -static const char* kPages[] = { "General", "Display", "Audio", "Media", "Games" }; +static const char* kPages[] = { "General", "Display", "Audio", "Media", "Games", "Controller" }; static const int kPageCount = (int)(sizeof(kPages) / sizeof(kPages[0])); enum Section { SEC_SETTINGS, SEC_ACCOUNTS, SEC_LIBRARY, SEC_LOGS, SEC_SHORTCUTS, SEC_ABOUT, SEC_TOOLS, SEC_EXIT, @@ -1013,11 +1015,20 @@ static bool Adjust(int dir) return true; } +// The pad buzzes when A can't do anything; the keyboard just doesn't. +static void Refuse() +{ + if (g.device == 1) Pads_Rumble(0.35f, 90); +} + static void Select() { if (g.cursor < 0 || g.cursor >= (int)g.rows.size()) return; const Row r = g.rows[g.cursor]; switch (r.act) { + case GA_NONE: + Refuse(); + break; case GA_VIEW: Push((View)r.arg); break; @@ -1068,7 +1079,7 @@ static void Select() int skipped = 0; int added = r.act == GA_STEAM ? TitleMaker_ImportSteam(&skipped) : TitleMaker_ImportRetroArch(&skipped); char msg[64]; - if (added < 0) snprintf(msg, sizeof(msg), "Not found"); + if (added < 0) { snprintf(msg, sizeof(msg), "Not found"); Refuse(); } else snprintf(msg, sizeof(msg), "%d new, %d already in", added, skipped); g.result[r.act] = msg; Build(); @@ -1077,6 +1088,7 @@ static void Select() case GA_ESDE: if (!s_esdePath[0]) { g.result[GA_ESDE] = "Set its folder first"; + Refuse(); } else { EsdeVGames_Sync(s_esdePath); g.result[GA_ESDE] = "Refreshed"; @@ -1117,8 +1129,8 @@ static void Select() break; } case GA_ADDGAME: { - if (g.pickedPath.empty() || g.pickedName.empty()) break; - if (VGames_FindByName(g.pickedName.c_str()) >= 0) { g.added = "Already there"; Build(); break; } + if (g.pickedPath.empty() || g.pickedName.empty()) { Refuse(); break; } + if (VGames_FindByName(g.pickedName.c_str()) >= 0) { g.added = "Already there"; Refuse(); Build(); break; } char genID[16]; snprintf(genID, sizeof(genID), "%08x", (unsigned)time(NULL)); std::string launch = "\"" + g.pickedPath + "\""; @@ -1168,7 +1180,7 @@ static void Select() case GA_FAVORITE: case GA_HIDE: { VirtualGame* vg = PickedGame(); - if (!vg) break; + if (!vg) { Refuse(); break; } if (r.act == GA_FAVORITE) VGames_SetFavorite(g.game, !vg->favorite); else VGames_SetHidden(g.game, !vg->hidden); Build(); @@ -1176,7 +1188,7 @@ static void Select() } case GA_LAUNCH: { VirtualGame* vg = PickedGame(); - if (!vg) break; + if (!vg) { Refuse(); break; } // The same Xbox-style path the launcher hands over. char devicePath[512]; snprintf(devicePath, sizeof(devicePath), "\\Device\\Harddisk0\\Partition1\\%s\\%s", @@ -1190,11 +1202,11 @@ static void Select() Host_OpenFolder(Plat_UserDataDir()); break; case GA_COPYVERSION: - if (SDL_SetClipboardText(VersionLine().c_str()) == 0) g.copied = GA_COPYVERSION; + if (SDL_SetClipboardText(VersionLine().c_str()) == 0) g.copied = GA_COPYVERSION; else Refuse(); Build(); break; case GA_COPYLOG: - if (CopyLog()) g.copied = GA_COPYLOG; + if (CopyLog()) g.copied = GA_COPYLOG; else Refuse(); Build(); break; case GA_QUIT: { diff --git a/theseus/desktop/pads.cpp b/theseus/desktop/pads.cpp index 4f18d56..483f723 100644 --- a/theseus/desktop/pads.cpp +++ b/theseus/desktop/pads.cpp @@ -16,6 +16,8 @@ struct Pad { Uint32 held; // its buttons and directions last frame }; +bool g_padRumble = true; + static std::vector s_pads; static SDL_JoystickID s_active = -1; static Uint32 s_clock = 0; @@ -142,6 +144,15 @@ bool Pads_Button(SDL_GameControllerButton button) return false; } +void Pads_Rumble(float strength, Uint32 ms) +{ + SDL_GameController* gc = Pads_Active(); + if (!g_padRumble || !gc) return; + float s = strength < 0.0f ? 0.0f : strength > 1.0f ? 1.0f : strength; + // The low motor is the heavy one; a touch less of it keeps short ones crisp. + SDL_GameControllerRumble(gc, (Uint16)(s * 0.6f * 65535.0f), (Uint16)(s * 65535.0f), ms); +} + Sint16 Pads_Axis(SDL_GameControllerAxis axis) { int best = 0; diff --git a/theseus/desktop/pads.h b/theseus/desktop/pads.h index 07488f5..0ba9e88 100644 --- a/theseus/desktop/pads.h +++ b/theseus/desktop/pads.h @@ -17,3 +17,7 @@ SDL_GameController* Pads_Active(); // stick or trigger reads off whichever pad pushes it furthest. bool Pads_Button(SDL_GameControllerButton button); Sint16 Pads_Axis(SDL_GameControllerAxis axis); + +// A short buzz on the active pad, strength 0 to 1. Nothing with Rumble off. +void Pads_Rumble(float strength, Uint32 ms); +extern bool g_padRumble; // desktop.ini Rumble From 5d0261f6cc60c728f0dda5a9506bd4421e7bf510 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:21:14 -0500 Subject: [PATCH 11/46] Import Linux .desktop shortcuts Games set up as .desktop files had no way in. The guide on Linux now lists what the app menu, Flatpak, snap and the Desktop hold, adds one or every game with its icon, and Add a Game takes a .desktop file too. Needs a real Linux test. --- build/Makefile | 1 + theseus/desktop/guide.cpp | 67 ++++++++- theseus/desktop/xdg_apps.cpp | 278 +++++++++++++++++++++++++++++++++++ theseus/desktop/xdg_apps.h | 35 +++++ 4 files changed, 379 insertions(+), 2 deletions(-) create mode 100644 theseus/desktop/xdg_apps.cpp create mode 100644 theseus/desktop/xdg_apps.h diff --git a/build/Makefile b/build/Makefile index 8e20dfb..2c5a7f7 100644 --- a/build/Makefile +++ b/build/Makefile @@ -893,6 +893,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/esde_vgames.cpp \ $(THESEUS_SRC)/desktop/icon_compress.cpp \ $(THESEUS_SRC)/desktop/exe_icon.cpp \ + $(THESEUS_SRC)/desktop/xdg_apps.cpp \ $(THESEUS_SRC)/desktop/game_art.cpp \ $(THESEUS_SRC)/desktop/playlist.cpp \ $(THESEUS_SRC)/desktop/playlist_maker.cpp \ diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 0120caa..805487b 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -30,6 +30,7 @@ #include "launchers/pcsx2.h" #include "xiso.h" #include "exe_icon.h" +#include "xdg_apps.h" #include "guide.h" #include "ui_overlay.h" #include @@ -258,7 +259,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_SHORTCUTS, GV_ABOUT, GV_TOOLS, GV_EXIT, GV_WELCOME, GV_GAMES, GV_GAME, GV_LETTERS, GV_APPS }; // What a game list shows. enum GameList { GL_FAVORITES, GL_RECENT, GL_HIDDEN, GL_ALL, GL_LETTER, GL_SEARCH }; @@ -276,7 +277,7 @@ enum Act { GA_PLEX, GA_PLEXOUT, GA_JELLYFIN, GA_JELLYFINOUT, GA_XBOX, GA_XBOXOUT, GA_TEXT, GA_NAME, GA_JELLYFINURL, GA_GAMELIST, GA_GAME, GA_LAUNCH, GA_FAVORITE, GA_HIDE, GA_LETTER, GA_SEARCH, - GA_FINDEMU, GA_RUNNER, + GA_FINDEMU, GA_RUNNER, GA_APPS, GA_APP, GA_APPGAMES, GA_COUNT }; @@ -348,6 +349,7 @@ static struct Guide { std::string result[GA_COUNT]; std::string browseDir, pickedPath, pickedName, added; std::string found[4]; // what each Find row turned up + std::vector apps; // the Linux app menu, read when its list opens std::vector entries; bool browseStale; int category, playlist, runner; @@ -505,6 +507,8 @@ static void Build() Add("Import Steam Library", g.result[GA_STEAM].c_str(), "Adds installed Steam games with their icons.", GA_STEAM); Add("Import RetroArch Recent", g.result[GA_RETROARCH].c_str(), "Adds what RetroArch's playlists list.", GA_RETROARCH); Add("Refresh ES-DE", g.result[GA_ESDE].c_str(), "Reads your ES-DE game lists again.", GA_ESDE); + if (strcmp(Host_Name(), "Linux") == 0) + Add("Import Linux Apps", "", "Games and apps from your app menu, Flatpak and your Desktop.", GA_APPS); char n[32]; std::vector list; static const char* kListHelp[] = { @@ -589,6 +593,17 @@ static void Build() Add("Category", where.c_str(), NULL); break; } + case GV_APPS: { + Add("Add All Games", g.result[GA_APPGAMES].c_str(), "Everything marked as a game, with its icon.", GA_APPGAMES); + for (size_t i = 0; i < g.apps.size(); i++) { + char clean[128]; + Title_SanitizeName(g.apps[i].name.c_str(), clean, sizeof(clean)); + const char* state = VGames_FindByName(clean) >= 0 ? "In Library" : g.apps[i].game ? "Game" : "App"; + Add(g.apps[i].name.c_str(), state, g.apps[i].exec.c_str(), GA_APP, (int)i); + } + if (g.apps.empty()) Add("Nothing found", "", "No .desktop entries in the app menu folders or on the Desktop."); + break; + } case GV_PLAYLISTS: for (int i = 0; i < Playlist_Count(); i++) { const Playlist* pl = Playlist_Get(i); @@ -704,6 +719,7 @@ static const char* ViewTitle() case GV_BROWSE: return "Choose a File"; case GV_PLAYLISTS: return "Playlists"; case GV_LETTERS: return "Find a Game"; + case GV_APPS: return "Linux Apps"; case GV_GAMES: { static char title[32]; if (g.gameList == GL_SEARCH) snprintf(title, sizeof(title), "Search: %.20s", g.search.c_str()); @@ -1162,6 +1178,13 @@ static void Select() g.pickedPath = full; g.pickedName = NameFromPath(full); g.runner = RUN_SELF; + XdgApp entry; + if (e.name.size() > 8 && strcasecmp(e.name.c_str() + e.name.size() - 8, ".desktop") == 0 && + XdgApps_Parse(full.c_str(), &entry)) { + char clean[128]; + Title_SanitizeName(entry.name.c_str(), clean, sizeof(clean)); + if (clean[0]) g.pickedName = clean; + } if (Pcsx2_IsDisc(full.c_str())) { // An Xbox disc names itself; anything else is a PS2 guess. XisoTitleInfo xiso = XisoGetTitleInfo(full.c_str()); @@ -1175,9 +1198,49 @@ static void Select() Back(); break; } + case GA_APPS: { + std::vector dirs; + XdgApps_Dirs(dirs); + XdgApps_Scan(dirs, g.apps); + g.result[GA_APPGAMES].clear(); + Push(GV_APPS); + break; + } + case GA_APP: + case GA_APPGAMES: { + int added = 0, had = 0; + for (size_t i = 0; i < g.apps.size(); i++) { + const XdgApp& app = g.apps[i]; + if (r.act == GA_APP ? (int)i != r.arg : !app.game) continue; + if (XdgApps_Add(app, app.game ? "Games" : "Applications")) added++; else had++; + } + if (added) { VGames_Save(); UDataSynth_RebuildAll(); } + if (r.act == GA_APPGAMES) { + char msg[64]; + snprintf(msg, sizeof(msg), "%d new, %d already in", added, had); + g.result[GA_APPGAMES] = msg; + } + Build(); + break; + } case GA_ADDGAME: { if (g.pickedPath.empty() || g.pickedName.empty()) break; if (VGames_FindByName(g.pickedName.c_str()) >= 0) { g.added = "Already there"; Build(); break; } + // A .desktop shortcut runs its Exec line, not the file. + XdgApp entry; + if (g.runner == RUN_SELF && XdgApps_Parse(g.pickedPath.c_str(), &entry) && + g.pickedPath.size() > 8 && strcasecmp(g.pickedPath.c_str() + g.pickedPath.size() - 8, ".desktop") == 0) { + entry.name = g.pickedName; + g.added = XdgApps_Add(entry, kCategories[g.category]) ? "Added" : "Already there"; + if (g.added == "Added") { + VGames_Save(); + UDataSynth_RebuildAll(); + g.pickedPath.clear(); + g.pickedName.clear(); + } + Build(); + break; + } char genID[16]; snprintf(genID, sizeof(genID), "%08x", (unsigned)time(NULL)); char launch[sizeof(VirtualGame::launch)]; diff --git a/theseus/desktop/xdg_apps.cpp b/theseus/desktop/xdg_apps.cpp new file mode 100644 index 0000000..71f799c --- /dev/null +++ b/theseus/desktop/xdg_apps.cpp @@ -0,0 +1,278 @@ +// xdg_apps.cpp: .desktop entries, read the way the freedesktop Desktop +// Entry spec lays them out. + +#include "xdg_apps.h" +#include "virtual_games.h" +#include "icon_compress.h" +#include "exe_icon.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "host.h" +#include "platform_env.h" + +namespace { + +bool Exists(const std::string& p) { + HostFileInfo info; + return Host_Stat(p.c_str(), &info); +} + +bool HasExt(const std::string& s, const char* ext) { + size_t e = strlen(ext); + return s.size() > e && strcasecmp(s.c_str() + s.size() - e, ext) == 0; +} + +std::string Env(const char* name, const std::string& fallback) { + const char* v = getenv(name); + return v && *v ? std::string(v) : fallback; +} + +void AddUnique(std::vector& v, const std::string& s) { + if (!s.empty() && std::find(v.begin(), v.end(), s) == v.end()) v.push_back(s); +} + +// The data folders: XDG_DATA_HOME, then XDG_DATA_DIRS, then the Flatpak +// exports, which a session started outside Flatpak's profile script misses. +void DataDirs(std::vector& out) { + std::string home = PlatformHomeDir(); + AddUnique(out, Env("XDG_DATA_HOME", home.empty() ? "" : home + "/.local/share")); + std::string dirs = Env("XDG_DATA_DIRS", "/usr/local/share:/usr/share"); + size_t at = 0; + while (at <= dirs.size()) { + size_t end = dirs.find(':', at); + if (end == std::string::npos) end = dirs.size(); + std::string d = dirs.substr(at, end - at); + while (d.size() > 1 && d[d.size() - 1] == '/') d.erase(d.size() - 1); + AddUnique(out, d); + at = end + 1; + } + if (!home.empty()) AddUnique(out, home + "/.local/share/flatpak/exports/share"); + AddUnique(out, "/var/lib/flatpak/exports/share"); +} + +// A value with the spec's escapes undone: \s \n \t \r \\. +std::string Unescape(const std::string& v) { + std::string o; + for (size_t i = 0; i < v.size(); i++) { + if (v[i] != '\\' || i + 1 >= v.size()) { o += v[i]; continue; } + char c = v[++i]; + o += c == 's' ? ' ' : c == 'n' ? '\n' : c == 't' ? '\t' : c == 'r' ? '\r' : c; + } + return o; +} + +// Exec split into arguments. Inside quotes a backslash keeps the next ", `, $ or \. +std::vector SplitExec(const std::string& exec) { + std::vector args; + std::string cur; + bool in = false, quoted = false; + for (size_t i = 0; i < exec.size(); i++) { + char c = exec[i]; + if (quoted) { + if (c == '\\' && i + 1 < exec.size()) cur += exec[++i]; + else if (c == '"') quoted = false; + else cur += c; + } else if (c == '"') { + quoted = in = true; + } else if (c == ' ' || c == '\t') { + if (in) { args.push_back(cur); cur.clear(); in = false; } + } else { + cur += c; + in = true; + } + } + if (in) args.push_back(cur); + return args; +} + +// Double quotes, like every other Launch line, with what sh still reads in them escaped. +std::string ShellQuote(const std::string& a) { + bool plain = !a.empty(); + for (size_t i = 0; i < a.size() && plain; i++) { + char c = a[i]; + plain = isalnum((unsigned char)c) || strchr("_./:=+,@%-", c); + } + if (plain) return a; + std::string o = "\""; + for (size_t i = 0; i < a.size(); i++) { + if (strchr("\"\\$`", a[i])) o += '\\'; + o += a[i]; + } + return o + "\""; +} + +void ScanDir(const std::string& dir, int depth, std::vector& seenIds, + const std::string& idPrefix, std::vector& out) { + HostDir* d = Host_OpenDir(dir.c_str()); + if (!d) return; + char name[512]; + bool isDir = false; + std::vector > entries; + while (entries.size() < 20000 && Host_ReadDirType(d, name, sizeof(name), &isDir)) + if (name[0] != '.') entries.push_back(std::make_pair(std::string(name), isDir)); + Host_CloseDir(d); + for (size_t i = 0; i < entries.size(); i++) { + std::string full = dir + "/" + entries[i].first; + if (entries[i].second) { + if (depth < 3) ScanDir(full, depth + 1, seenIds, idPrefix + entries[i].first + "-", out); + continue; + } + if (!HasExt(entries[i].first, ".desktop")) continue; + // The same id further down the list is hidden by the first one. + std::string id = idPrefix + entries[i].first; + if (std::find(seenIds.begin(), seenIds.end(), id) != seenIds.end()) continue; + seenIds.push_back(id); + XdgApp app; + if (XdgApps_Parse(full.c_str(), &app)) out.push_back(app); + } +} + +} // namespace + +void XdgApps_Dirs(std::vector& out) { + out.clear(); + std::vector data; + DataDirs(data); + for (size_t i = 0; i < data.size(); i++) AddUnique(out, data[i] + "/applications"); + AddUnique(out, "/var/lib/snapd/desktop/applications"); + // Shortcuts people keep on the Desktop. + std::string home = PlatformHomeDir(); + if (!home.empty()) AddUnique(out, Env("XDG_DESKTOP_DIR", home + "/Desktop")); +} + +bool XdgApps_Parse(const char* file, XdgApp* out) { + FILE* f = fopen(file, "r"); + if (!f) return false; + *out = XdgApp(); + out->path = file; + std::string type, categories; + bool inEntry = false, hidden = false, terminal = false; + char line[4096]; + while (fgets(line, sizeof(line), f)) { + std::string l = line; + while (!l.empty() && (l[l.size() - 1] == '\n' || l[l.size() - 1] == '\r')) l.erase(l.size() - 1); + if (l.empty() || l[0] == '#') continue; + if (l[0] == '[') { inEntry = l == "[Desktop Entry]"; continue; } + if (!inEntry) continue; + size_t eq = l.find('='); + if (eq == std::string::npos) continue; + std::string key = l.substr(0, eq), val = l.substr(eq + 1); + while (!key.empty() && key[key.size() - 1] == ' ') key.erase(key.size() - 1); + while (!val.empty() && val[0] == ' ') val.erase(0, 1); + val = Unescape(val); + // Keys are case sensitive in the spec; hand written files aren't always. + const char* k = key.c_str(); + if (!strcasecmp(k, "Type")) type = val; + else if (!strcasecmp(k, "Name")) out->name = val; + else if (!strcasecmp(k, "Exec")) out->exec = val; + else if (!strcasecmp(k, "Icon")) out->icon = val; + else if (!strcasecmp(k, "Categories")) categories = val; + else if (!strcasecmp(k, "Hidden")) hidden = !strcasecmp(val.c_str(), "true"); + else if (!strcasecmp(k, "NoDisplay")) hidden = hidden || !strcasecmp(val.c_str(), "true"); + else if (!strcasecmp(k, "Terminal")) terminal = !strcasecmp(val.c_str(), "true"); + } + fclose(f); + std::string cats = ";" + categories + ";"; + out->game = cats.find(";Game;") != std::string::npos; + if (!type.empty() && type != "Application") return false; + return !hidden && !terminal && !out->name.empty() && !out->exec.empty(); +} + +void XdgApps_Scan(const std::vector& dirs, std::vector& out) { + out.clear(); + std::vector seen; + for (size_t i = 0; i < dirs.size(); i++) ScanDir(dirs[i], 0, seen, "", out); + std::stable_sort(out.begin(), out.end(), [](const XdgApp& a, const XdgApp& b) { + if (a.game != b.game) return a.game; + return strcasecmp(a.name.c_str(), b.name.c_str()) < 0; + }); +} + +std::string XdgApps_Command(const XdgApp& app) { + std::vector args = SplitExec(app.exec); + // Steam's own shortcuts: the URL alone lets the launcher watch the game. + if (args.size() == 2 && args[0] == "steam" && args[1].compare(0, 8, "steam://") == 0) return args[1]; + std::string cmd; + for (size_t i = 0; i < args.size(); i++) { + const std::string& a = args[i]; + // Flatpak wraps the file arguments in @@ markers; there are no files. + if (a == "@@" || a == "@@u" || a == "@@f") continue; + std::string o; + bool dropped = false; + for (size_t j = 0; j < a.size(); j++) { + if (a[j] != '%' || j + 1 >= a.size()) { o += a[j]; continue; } + char c = a[++j]; + if (c == '%') o += '%'; + else if (c == 'c') o += app.name; + else if (c == 'k') o += app.path; + else dropped = true; // %f %u %i and the old ones: nothing to hand over + } + if (dropped && o.empty()) continue; + if (!cmd.empty()) cmd += ' '; + cmd += ShellQuote(o); + } + return cmd; +} + +std::string XdgApps_IconFile(const std::string& icon) { + if (icon.empty()) return ""; + static const char* const kDrawable[] = { ".png", ".jpg", ".jpeg", ".bmp", ".ico", NULL }; + if (icon[0] == '/') { + for (int i = 0; kDrawable[i]; i++) + if (HasExt(icon, kDrawable[i])) return Exists(icon) ? icon : ""; + return ""; + } + std::string name = HasExt(icon, ".png") ? icon.substr(0, icon.size() - 4) : icon; + std::vector bases; + std::string home = PlatformHomeDir(); + if (!home.empty()) AddUnique(bases, home + "/.icons"); + std::vector data; + DataDirs(data); + for (size_t i = 0; i < data.size(); i++) AddUnique(bases, data[i] + "/icons"); + static const char* const kSizes[] = { + "512x512", "256x256", "192x192", "128x128", "96x96", "72x72", "64x64", "48x48", "32x32", NULL + }; + // Biggest first, across every folder, so a 256 in /usr/share beats a 48 in yours. + for (int s = 0; kSizes[s]; s++) + for (size_t b = 0; b < bases.size(); b++) { + std::string p = bases[b] + "/hicolor/" + kSizes[s] + "/apps/" + name + ".png"; + if (Exists(p)) return p; + } + for (size_t i = 0; i < data.size(); i++) { + std::string p = data[i] + "/pixmaps/" + name + ".png"; + if (Exists(p)) return p; + } + return ""; +} + +bool XdgApps_Add(const XdgApp& app, const char* category) { + extern int Title_SanitizeName(const char*, char*, size_t); + char clean[128]; + Title_SanitizeName(app.name.c_str(), clean, sizeof(clean)); + std::string cmd = XdgApps_Command(app); + if (!clean[0] || cmd.empty() || cmd.size() >= sizeof(VirtualGame::launch)) return false; + if (VGames_FindByName(clean) >= 0) return false; + for (int i = 0; i < g_vgames.count; i++) + if (g_vgames.games[i].valid && cmd == g_vgames.games[i].launch) return false; + // Several added in the same second still need their own ids. + static unsigned s_bump = 0; + char id[16]; + snprintf(id, sizeof(id), "%08x", (unsigned)time(NULL) + s_bump++); + VGames_Add(clean, id, cmd.c_str(), "E", category); + std::string icon = XdgApps_IconFile(app.icon); + if (!icon.empty()) { + char dst[1024]; + Host_MakeDir(VGAMES_ICONS); + snprintf(dst, sizeof(dst), "%s/%s.jpg", VGAMES_ICONS, id); + if (ExeIcon_IsIconSource(icon.c_str())) ExeIcon_Save(icon.c_str(), dst); + else Icons_FitFile(icon.c_str(), dst, 256, 90); + } + return true; +} diff --git a/theseus/desktop/xdg_apps.h b/theseus/desktop/xdg_apps.h new file mode 100644 index 0000000..6ba2242 --- /dev/null +++ b/theseus/desktop/xdg_apps.h @@ -0,0 +1,35 @@ +// xdg_apps.h: Linux .desktop entries as launcher games. Reads the same +// folders an app menu does (yours, the system's, Flatpak and snap exports) +// plus the Desktop, and finds each one's icon in the icon themes. + +#pragma once + +#include +#include + +struct XdgApp { + std::string name, exec, icon, path; // path is the .desktop file + bool game; // Categories has Game +}; + +// The folders to read, yours first, so your copy of an entry wins. +void XdgApps_Dirs(std::vector& out); + +// One .desktop file. False when it isn't something you can launch: not an +// Application, hidden, terminal only, or no Exec. +bool XdgApps_Parse(const char* file, XdgApp* out); + +// Every launchable entry under the folders, games first, then A to Z. +void XdgApps_Scan(const std::vector& dirs, std::vector& out); + +// Exec as a shell command: field codes filled in or dropped, every +// argument quoted the way sh wants it. +std::string XdgApps_Command(const XdgApp& app); + +// A picture file for the entry's Icon, from the hicolor theme or pixmaps. +// Empty when there's none we can draw (SVG only, say). +std::string XdgApps_IconFile(const std::string& icon); + +// Into the library under category, with its icon. False when a game of that +// name or command is already there. The caller saves. +bool XdgApps_Add(const XdgApp& app, const char* category); From 40baaf4be0bd1dbc861d098217a2e7cf5bf5d9eb Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:22:10 -0500 Subject: [PATCH 12/46] Guide shows PlayStation and Nintendo buttons The prompts always drew Xbox buttons. Now they match the pad you used last: PlayStation symbols drawn from shapes, Nintendo letters where they actually sit. Button Prompts on the Controller page can force a style. Buttons now go by position on every pad, so the bottom one is always A. Needs a test with a real DualSense and Switch Pro. --- theseus/desktop/desktop_settings.cpp | 6 +++ theseus/desktop/guide.cpp | 2 + theseus/desktop/pads.cpp | 31 +++++++++++ theseus/desktop/pads.h | 6 +++ theseus/desktop/sdl_main.cpp | 4 ++ theseus/desktop/ui_overlay.cpp | 79 +++++++++++++++++++++++++--- theseus/desktop/ui_overlay.h | 4 ++ 7 files changed, 124 insertions(+), 8 deletions(-) diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index b7bf66d..7365a7d 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -72,6 +72,10 @@ static const char* kStartupTok[] = { "", "dashboard", "development" }; // Turning it on buzzes once, so you know it works. static void ApplyRumble() { if (g_padRumble) Pads_Rumble(0.5f, 150); } +static const int kPadStyleVals[] = { 0, 1, 2, 3 }; +static const char* kPadStyleLbl[] = { "Match the Pad", "Xbox", "PlayStation", "Nintendo" }; +static const char* kPadStyleTok[] = { "auto", "xbox", "playstation", "nintendo" }; + static const int kMsaaVals[] = { 0, 2, 4, 8 }; static const char* kMsaaLbl[] = { "Off", "2x", "4x", "8x" }; @@ -157,6 +161,8 @@ static const SettingDef kDefs[] = { { "Rumble", "Controller", "Controller", "Rumble", SK_BOOL, &g_padRumble, 0, "1", 0, NOENUM, 0, 0, 0, NULL, ApplyRumble }, + { "ButtonStyle", "Controller", "Controller", "Button Prompts", SK_ENUM, &g_padStyle, 0, "auto", SF_STRICT, + ENUM(kPadStyleVals, kPadStyleLbl, kPadStyleTok), 0, 0, 0, NULL, NULL }, S_BOOL("CRT_Enabled", "CRT", "Display", "CRT Effect", g_crt.enabled, "0", 0), S_CRT("CRT_Scanlines", "Scanlines", scanlineIntensity, "0.500", 0.0f, 1.0f), diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index f56a8eb..700a0dd 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -232,6 +232,7 @@ static const char* SettingHelp(const SettingDef& d) { "FetchGameArt", "Box art for games without an icon. Icons you picked are never replaced." }, { "HideDuplicateGames", "A game in Steam and ES-DE shows once: Steam first, then yours, then ES-DE." }, { "Rumble", "A short buzz when the guide can't do what you asked." }, + { "ButtonStyle", "The buttons the guide shows. Match the Pad follows the pad you used last." }, }; for (size_t i = 0; i < sizeof(kHelp) / sizeof(kHelp[0]); i++) if (strcmp(kHelp[i].key, d.key) == 0) return kHelp[i].help; @@ -1708,6 +1709,7 @@ void Guide_Render(int width, int height) Hover(); g.targets.clear(); ui_overlay_set_device(g.device); + ui_overlay_set_pad_style(Pads_Style()); ui_style_theme(g_guideTheme); ui_style_clock(SDL_GetTicks()); ui_overlay_layer(0); diff --git a/theseus/desktop/pads.cpp b/theseus/desktop/pads.cpp index 483f723..c816a93 100644 --- a/theseus/desktop/pads.cpp +++ b/theseus/desktop/pads.cpp @@ -17,6 +17,7 @@ struct Pad { }; bool g_padRumble = true; +int g_padStyle = 0; static std::vector s_pads; static SDL_JoystickID s_active = -1; @@ -144,6 +145,36 @@ bool Pads_Button(SDL_GameControllerButton button) return false; } +int Pads_Style() +{ + if (g_padStyle > 0) return g_padStyle - 1; + SDL_GameController* gc = Pads_Active(); + if (!gc) return PAD_STYLE_XBOX; + switch (SDL_GameControllerGetType(gc)) { + case SDL_CONTROLLER_TYPE_PS3: + case SDL_CONTROLLER_TYPE_PS4: +#if SDL_VERSION_ATLEAST(2, 0, 14) + case SDL_CONTROLLER_TYPE_PS5: +#endif + return PAD_STYLE_PLAYSTATION; + case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO: +#if SDL_VERSION_ATLEAST(2, 24, 0) + case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT: + case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT: + case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: +#endif + return PAD_STYLE_NINTENDO; + default: + break; + } + // Pads SDL can't name (third party, virtual) go by who made them. + switch (SDL_GameControllerGetVendor(gc)) { + case 0x054C: return PAD_STYLE_PLAYSTATION; // Sony + case 0x057E: return PAD_STYLE_NINTENDO; // Nintendo + } + return PAD_STYLE_XBOX; +} + void Pads_Rumble(float strength, Uint32 ms) { SDL_GameController* gc = Pads_Active(); diff --git a/theseus/desktop/pads.h b/theseus/desktop/pads.h index 0ba9e88..a0b6a59 100644 --- a/theseus/desktop/pads.h +++ b/theseus/desktop/pads.h @@ -18,6 +18,12 @@ SDL_GameController* Pads_Active(); bool Pads_Button(SDL_GameControllerButton button); Sint16 Pads_Axis(SDL_GameControllerAxis axis); +// Which labels the buttons get, in ui_overlay's UI_PAD_* order: the +// active pad's own, unless ButtonStyle picks one. +enum { PAD_STYLE_XBOX, PAD_STYLE_PLAYSTATION, PAD_STYLE_NINTENDO }; +int Pads_Style(); +extern int g_padStyle; // desktop.ini ButtonStyle: 0 the pad's own, else style + 1 + // A short buzz on the active pad, strength 0 to 1. Nothing with Rumble off. void Pads_Rumble(float strength, Uint32 ms); extern bool g_padRumble; // desktop.ini Rumble diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index b66c6fd..aee3853 100644 --- a/theseus/desktop/sdl_main.cpp +++ b/theseus/desktop/sdl_main.cpp @@ -980,6 +980,10 @@ int main(int argc, char* argv[]) { #undef ASAN_ACTIVE // Clean up + // Buttons by where they sit, not what's printed on them: the bottom one + // is A on every pad, and the guide draws each pad's own labels. + SDL_SetHint(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, "0"); + // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) < 0) { fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError()); diff --git a/theseus/desktop/ui_overlay.cpp b/theseus/desktop/ui_overlay.cpp index ce66e9e..9242f02 100644 --- a/theseus/desktop/ui_overlay.cpp +++ b/theseus/desktop/ui_overlay.cpp @@ -90,7 +90,7 @@ static struct { float shift[8]; // second map's place and scale, then the threads' color bool plasmaDrawn; - int device; + int device, padStyle; float scale, originX, originY; // last present's layout -> pixels Vertex vertices[MAX_QUADS * 6]; @@ -315,12 +315,26 @@ void ui_overlay_plasma_thread(unsigned int color) void ui_overlay_set_device(int device) { ov.device = device; } int ui_overlay_keyboard() { return ov.device == 0; } +void ui_overlay_set_pad_style(int style) +{ + ov.padStyle = style >= 0 && style < UI_PAD_STYLE_COUNT ? style : UI_PAD_XBOX; +} -static const char* const kPillLabels[2][UI_BUTTON_COUNT] = { - { "ENTER", "ESC", "X", "Y", "F7", "BKSP", "Q", "E", "\xE2\x86\x90", "\xE2\x86\x92" }, +static const char* const kKeyLabels[UI_BUTTON_COUNT] = { + "ENTER", "ESC", "X", "Y", "F7", "BKSP", "Q", "E", "\xE2\x86\x90", "\xE2\x86\x92", +}; +// PlayStation's face buttons are symbols, drawn below. +static const char* const kPadLabels[UI_PAD_STYLE_COUNT][UI_BUTTON_COUNT] = { { "A", "B", "X", "Y", "START", "BACK", "LB", "RB", "\xE2\x80\xB9", "\xE2\x80\xBA" }, + { "", "", "", "", "OPTIONS", "SHARE", "L1", "R1", "\xE2\x80\xB9", "\xE2\x80\xBA" }, + { "B", "A", "Y", "X", "+", "\xE2\x88\x92", "L", "R", "\xE2\x80\xB9", "\xE2\x80\xBA" }, }; +static const char* Label(int button) +{ + return ov.device == 1 ? kPadLabels[ov.padStyle][button] : kKeyLabels[button]; +} + // The pad's face buttons, lit at the top and deep at the bottom. static const unsigned int kFaceColors[4][2] = { { 0x9BE57AFF, 0x2C8A1CFF }, // A green @@ -329,6 +343,9 @@ static const unsigned int kFaceColors[4][2] = { { 0xFFE680FF, 0xC48A0CFF }, // Y yellow }; +// Cross, circle, square and triangle. +static const unsigned int kSymbolColors[4] = { 0x9CC8FFFF, 0xFF8A8AFF, 0xF3A5E4FF, 0x6FE8C2FF }; + static float PillTextSize(float size) { return size * 0.52f; } static float PillWidth(const char* label, float size) @@ -357,25 +374,71 @@ float ui_overlay_button_width(int button, float size) { if (button < 0 || button >= UI_BUTTON_COUNT) return 0.0f; if (ov.device == 1 && button <= UI_BUTTON_Y) return size; - return PillWidth(kPillLabels[ov.device == 1][button], size); + return PillWidth(Label(button), size); +} + +// A line of round dots close enough to read as one stroke. +static void Stroke(float x0, float y0, float x1, float y1, float width, unsigned int color) +{ + float dx = x1 - x0, dy = y1 - y0; + int steps = (int)ceilf(sqrtf(dx * dx + dy * dy) / (width * 0.25f)); + if (steps < 1) steps = 1; + for (int i = 0; i <= steps; i++) { + float t = (float)i / (float)steps; + ui_overlay_rect(x0 + dx * t - width * 0.5f, y0 + dy * t - width * 0.5f, width, width, width * 0.5f, color); + } +} + +// PlayStation's symbols, centered on cx, cy in a ball d across. +static void Symbol(int button, float cx, float cy, float d, unsigned int color) +{ + float r = d * 0.24f, w = d * 0.1f; + switch (button) { + case UI_BUTTON_A: + Stroke(cx - r, cy - r, cx + r, cy + r, w, color); + Stroke(cx - r, cy + r, cx + r, cy - r, w, color); + break; + case UI_BUTTON_B: + ui_overlay_outline(cx - r, cy - r, r * 2.0f, r * 2.0f, r, w, color); + break; + case UI_BUTTON_X: + r *= 0.9f; + ui_overlay_outline(cx - r, cy - r, r * 2.0f, r * 2.0f, w * 0.6f, w, color); + break; + case UI_BUTTON_Y: { + // Equilateral, sitting a touch low so it looks centered. + float side = r * 2.3f, h = side * 0.866f, top = cy - h * 0.6f, base = cy + h * 0.4f; + Stroke(cx, top, cx - side * 0.5f, base, w, color); + Stroke(cx - side * 0.5f, base, cx + side * 0.5f, base, w, color); + Stroke(cx + side * 0.5f, base, cx, top, w, color); + break; + } + } } float ui_overlay_button(int button, float size, float x, float y, unsigned int color) { if (button < 0 || button >= UI_BUTTON_COUNT) return 0.0f; if (ov.device != 1 || button > UI_BUTTON_Y) - return Pill(kPillLabels[ov.device == 1][button], size, x, y, color, ov.device != 1); + return Pill(Label(button), size, x, y, color, ov.device != 1); - // A glossy ball: lit to deep, a sheen on its upper half, its letter in white. + // A glossy ball: lit to deep, a sheen on its upper half, its letter in + // white. Xbox balls wear their colors; the others are dark. float share = (float)(color & 0xFF) / 255.0f; float d = size * 0.96f, inset = (size - d) * 0.5f, letter = size * 0.66f; - const char* label = kPillLabels[1][button]; + const char* label = kPadLabels[ov.padStyle][button]; + const bool xbox = ov.padStyle == UI_PAD_XBOX; ui_overlay_rect(x + inset, y + inset + size * 0.05f, d, d, d * 0.5f, Fade(0x00000060, share)); ui_overlay_gradient(x + inset, y + inset, d, d, d * 0.5f, - Fade(kFaceColors[button][0], share), Fade(kFaceColors[button][1], share)); + Fade(xbox ? kFaceColors[button][0] : 0x5A606BFF, share), + Fade(xbox ? kFaceColors[button][1] : 0x16191FFF, share)); ui_overlay_gradient(x + inset + d * 0.16f, y + inset + d * 0.06f, d * 0.68f, d * 0.42f, d * 0.21f, Fade(0xFFFFFF70, share), Fade(0xFFFFFF08, share)); ui_overlay_outline(x + inset, y + inset, d, d, d * 0.5f, 0.75f, Fade(0x00000070, share)); + if (ov.padStyle == UI_PAD_PLAYSTATION) { + Symbol(button, x + size * 0.5f, y + size * 0.5f, d, Fade(kSymbolColors[button], share)); + return size; + } AddText(UI_FONT_BOLD, letter, x + size * 0.5f + 0.4f, y + (size - letter) * 0.5f + 0.9f, UI_ALIGN_CENTER, Fade(0x00000080, share), label); AddText(UI_FONT_BOLD, letter, x + size * 0.5f, y + (size - letter) * 0.5f + 0.3f, UI_ALIGN_CENTER, diff --git a/theseus/desktop/ui_overlay.h b/theseus/desktop/ui_overlay.h index 78cd2ff..33d22e0 100644 --- a/theseus/desktop/ui_overlay.h +++ b/theseus/desktop/ui_overlay.h @@ -44,6 +44,10 @@ void ui_overlay_layer(int layer); // Which device the prompts show: 0 keyboard (and mouse), 1 pad. void ui_overlay_set_device(int device); +// How a pad's buttons look. They're named by where they sit: A is the +// bottom face button, so on a Nintendo pad it reads B. +enum { UI_PAD_XBOX, UI_PAD_PLAYSTATION, UI_PAD_NINTENDO, UI_PAD_STYLE_COUNT }; +void ui_overlay_set_pad_style(int style); int ui_overlay_keyboard(); float ui_overlay_button(int button, float size, float x, float y, unsigned int color); float ui_overlay_button_width(int button, float size); From 24ed3ce465f9bb851dee3409a235030f089393e1 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:23:44 -0500 Subject: [PATCH 13/46] Setting to confirm with the right face button Nintendo players expect the right button to select and the bottom one to go back. Confirm With the Right Button swaps them for the dashboard and the guide, and the prompts follow. Games and streams still get the pad as it is. --- theseus/desktop/desktop_settings.cpp | 1 + theseus/desktop/guide.cpp | 4 ++++ theseus/desktop/joystick.cpp | 2 +- theseus/desktop/pads.cpp | 10 ++++++++++ theseus/desktop/pads.h | 6 +++++- theseus/desktop/ui_overlay.cpp | 13 +++++++++++-- theseus/desktop/ui_overlay.h | 2 ++ 7 files changed, 34 insertions(+), 4 deletions(-) diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index 7365a7d..3669f88 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -163,6 +163,7 @@ static const SettingDef kDefs[] = { NOENUM, 0, 0, 0, NULL, ApplyRumble }, { "ButtonStyle", "Controller", "Controller", "Button Prompts", SK_ENUM, &g_padStyle, 0, "auto", SF_STRICT, ENUM(kPadStyleVals, kPadStyleLbl, kPadStyleTok), 0, 0, 0, NULL, NULL }, + S_BOOL("SwapConfirm", "Controller", "Controller", "Confirm With the Right Button", g_padSwapConfirm, "0", 0), S_BOOL("CRT_Enabled", "CRT", "Display", "CRT Effect", g_crt.enabled, "0", 0), S_CRT("CRT_Scanlines", "Scanlines", scanlineIntensity, "0.500", 0.0f, 1.0f), diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 700a0dd..23b3fea 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -233,6 +233,7 @@ static const char* SettingHelp(const SettingDef& d) { "HideDuplicateGames", "A game in Steam and ES-DE shows once: Steam first, then yours, then ES-DE." }, { "Rumble", "A short buzz when the guide can't do what you asked." }, { "ButtonStyle", "The buttons the guide shows. Match the Pad follows the pad you used last." }, + { "SwapConfirm", "Nintendo style: the right face button selects and the bottom one goes back." }, }; for (size_t i = 0; i < sizeof(kHelp) / sizeof(kHelp[0]); i++) if (strcmp(kHelp[i].key, d.key) == 0) return kHelp[i].help; @@ -1013,6 +1014,8 @@ static bool Adjust(int dir) if (d.apply) d.apply(); SaveDesktopSettings(); Build(); + // The button still held can mean something else now (SwapConfirm). + g.settle = true; return true; } @@ -1710,6 +1713,7 @@ void Guide_Render(int width, int height) g.targets.clear(); ui_overlay_set_device(g.device); ui_overlay_set_pad_style(Pads_Style()); + ui_overlay_set_pad_swap(g_padSwapConfirm); ui_style_theme(g_guideTheme); ui_style_clock(SDL_GetTicks()); ui_overlay_layer(0); diff --git a/theseus/desktop/joystick.cpp b/theseus/desktop/joystick.cpp index c83088a..1dff266 100755 --- a/theseus/desktop/joystick.cpp +++ b/theseus/desktop/joystick.cpp @@ -485,7 +485,7 @@ static bool GuideChord() const bool b = Pads_Button(SDL_CONTROLLER_BUTTON_B); for (int i = 0; i < Pads_Count(); i++) { SDL_GameController* gc = Pads_Get(i); - if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B) && + if (SDL_GameControllerGetButton(gc, Pads_Map(SDL_CONTROLLER_BUTTON_B)) && SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERLEFT) > 8000) chord = true; } extern bool ImGui_WantsKeyboard(); diff --git a/theseus/desktop/pads.cpp b/theseus/desktop/pads.cpp index c816a93..69676e1 100644 --- a/theseus/desktop/pads.cpp +++ b/theseus/desktop/pads.cpp @@ -18,6 +18,7 @@ struct Pad { bool g_padRumble = true; int g_padStyle = 0; +bool g_padSwapConfirm = false; static std::vector s_pads; static SDL_JoystickID s_active = -1; @@ -138,8 +139,17 @@ SDL_GameController* Pads_Get(int i) return i < 0 || i >= (int)s_pads.size() ? NULL : s_pads[i].gc; } +SDL_GameControllerButton Pads_Map(SDL_GameControllerButton button) +{ + if (!g_padSwapConfirm) return button; + if (button == SDL_CONTROLLER_BUTTON_A) return SDL_CONTROLLER_BUTTON_B; + if (button == SDL_CONTROLLER_BUTTON_B) return SDL_CONTROLLER_BUTTON_A; + return button; +} + bool Pads_Button(SDL_GameControllerButton button) { + button = Pads_Map(button); for (size_t i = 0; i < s_pads.size(); i++) if (SDL_GameControllerGetButton(s_pads[i].gc, button)) return true; return false; diff --git a/theseus/desktop/pads.h b/theseus/desktop/pads.h index a0b6a59..d34d877 100644 --- a/theseus/desktop/pads.h +++ b/theseus/desktop/pads.h @@ -14,8 +14,12 @@ SDL_GameController* Pads_Get(int i); SDL_GameController* Pads_Active(); // Every pad drives the dashboard: a button counts held on any pad, and a -// stick or trigger reads off whichever pad pushes it furthest. +// stick or trigger reads off whichever pad pushes it furthest. A and B +// here are confirm and back, so they follow SwapConfirm. bool Pads_Button(SDL_GameControllerButton button); +// The button a pad really has to hold for one of Pads_Button's. +SDL_GameControllerButton Pads_Map(SDL_GameControllerButton button); +extern bool g_padSwapConfirm; // desktop.ini SwapConfirm: right face button confirms Sint16 Pads_Axis(SDL_GameControllerAxis axis); // Which labels the buttons get, in ui_overlay's UI_PAD_* order: the diff --git a/theseus/desktop/ui_overlay.cpp b/theseus/desktop/ui_overlay.cpp index 9242f02..7c20b90 100644 --- a/theseus/desktop/ui_overlay.cpp +++ b/theseus/desktop/ui_overlay.cpp @@ -90,7 +90,7 @@ static struct { float shift[8]; // second map's place and scale, then the threads' color bool plasmaDrawn; - int device, padStyle; + int device, padStyle, padSwap; float scale, originX, originY; // last present's layout -> pixels Vertex vertices[MAX_QUADS * 6]; @@ -320,6 +320,8 @@ void ui_overlay_set_pad_style(int style) ov.padStyle = style >= 0 && style < UI_PAD_STYLE_COUNT ? style : UI_PAD_XBOX; } +void ui_overlay_set_pad_swap(int swap) { ov.padSwap = swap != 0; } + static const char* const kKeyLabels[UI_BUTTON_COUNT] = { "ENTER", "ESC", "X", "Y", "F7", "BKSP", "Q", "E", "\xE2\x86\x90", "\xE2\x86\x92", }; @@ -330,9 +332,15 @@ static const char* const kPadLabels[UI_PAD_STYLE_COUNT][UI_BUTTON_COUNT] = { { "B", "A", "Y", "X", "+", "\xE2\x88\x92", "L", "R", "\xE2\x80\xB9", "\xE2\x80\xBA" }, }; +// Where on the pad a button is, with confirm and back swapped or not. +static int Position(int button) +{ + return ov.padSwap && (button == UI_BUTTON_A || button == UI_BUTTON_B) ? button ^ 1 : button; +} + static const char* Label(int button) { - return ov.device == 1 ? kPadLabels[ov.padStyle][button] : kKeyLabels[button]; + return ov.device == 1 ? kPadLabels[ov.padStyle][Position(button)] : kKeyLabels[button]; } // The pad's face buttons, lit at the top and deep at the bottom. @@ -424,6 +432,7 @@ float ui_overlay_button(int button, float size, float x, float y, unsigned int c // A glossy ball: lit to deep, a sheen on its upper half, its letter in // white. Xbox balls wear their colors; the others are dark. + button = Position(button); float share = (float)(color & 0xFF) / 255.0f; float d = size * 0.96f, inset = (size - d) * 0.5f, letter = size * 0.66f; const char* label = kPadLabels[ov.padStyle][button]; diff --git a/theseus/desktop/ui_overlay.h b/theseus/desktop/ui_overlay.h index 33d22e0..8f83fac 100644 --- a/theseus/desktop/ui_overlay.h +++ b/theseus/desktop/ui_overlay.h @@ -48,6 +48,8 @@ void ui_overlay_set_device(int device); // bottom face button, so on a Nintendo pad it reads B. enum { UI_PAD_XBOX, UI_PAD_PLAYSTATION, UI_PAD_NINTENDO, UI_PAD_STYLE_COUNT }; void ui_overlay_set_pad_style(int style); +// With confirm and back swapped, UI_BUTTON_A draws the right face button. +void ui_overlay_set_pad_swap(int swap); int ui_overlay_keyboard(); float ui_overlay_button(int button, float size, float x, float y, unsigned int color); float ui_overlay_button_width(int button, float size); From a3fdceca94fb8ab237c053e511f8b954436c1643 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:25:18 -0500 Subject: [PATCH 14/46] Per-game launch options There was nowhere to give one game extra arguments, a working folder or environment variables short of rewriting its launch line. The guide's game page now has all three, kept in games.ini, and a .desktop entry's Path fills in the working folder. Env is NAME=value pairs split by ';'. --- theseus/desktop/guide.cpp | 28 ++++++++- theseus/desktop/host.h | 2 + theseus/desktop/host_posix_app.cpp | 5 ++ theseus/desktop/host_win_app.cpp | 6 ++ theseus/desktop/launch.cpp | 97 ++++++++++++++++++++++++++---- theseus/desktop/virtual_games.h | 14 +++++ theseus/desktop/xdg_apps.cpp | 4 +- theseus/desktop/xdg_apps.h | 1 + 8 files changed, 142 insertions(+), 15 deletions(-) diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 805487b..44b0b9a 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -277,7 +277,7 @@ enum Act { GA_PLEX, GA_PLEXOUT, GA_JELLYFIN, GA_JELLYFINOUT, GA_XBOX, GA_XBOXOUT, GA_TEXT, GA_NAME, GA_JELLYFINURL, GA_GAMELIST, GA_GAME, GA_LAUNCH, GA_FAVORITE, GA_HIDE, GA_LETTER, GA_SEARCH, - GA_FINDEMU, GA_RUNNER, GA_APPS, GA_APP, GA_APPGAMES, + GA_FINDEMU, GA_RUNNER, GA_APPS, GA_APP, GA_APPGAMES, GA_GAMEOPT, GA_COUNT }; @@ -321,7 +321,7 @@ static const float kWideKeys[KEY_COUNT - KEY_CHARS][2] = { { 0, 1.5f }, { 1.5f, 1.5f }, { 3, 3 }, { 6, 1.5f }, { 7.5f, 1.25f }, { 8.75f, 1.25f }, }; -enum EditTarget { ED_SETTING, ED_NAME, ED_JELLYFIN, ED_SEARCH }; +enum EditTarget { ED_SETTING, ED_NAME, ED_JELLYFIN, ED_SEARCH, ED_GAMEOPT }; struct Editor { bool on, secret, shift, symbols; @@ -591,6 +591,15 @@ static void Build() "Counted when the game closes. Games another launcher starts for us can't be timed."); std::string where = vg->group[0] ? std::string(vg->category) + "/" + vg->group : std::string(vg->category); Add("Category", where.c_str(), NULL); + // Rows from someone else's library aren't saved, so neither would these be. + if (!VGames_IsLive(*vg)) { + Add("Arguments", vg->args[0] ? vg->args : "None", "Added after the launch line, like -windowed.", + GA_GAMEOPT, 0); + Add("Working Folder", vg->workdir[0] ? vg->workdir : "Its own", + "Where the game starts. Empty starts it in the program's own folder.", GA_GAMEOPT, 1); + Add("Environment", vg->env[0] ? vg->env : "None", + "NAME=value, more than one split by ;. Like DXVK_HUD=1;MANGOHUD=1", GA_GAMEOPT, 2); + } break; } case GV_APPS: { @@ -908,6 +917,14 @@ static void EditDone() case ED_SEARCH: g.search = Tidy(e.text, false); break; + case ED_GAMEOPT: { + VirtualGame* vg = PickedGame(); + if (!vg) break; + char* field = e.arg == 0 ? vg->args : e.arg == 1 ? vg->workdir : vg->env; + snprintf(field, sizeof(vg->args), "%s", Tidy(e.text, e.arg == 1).c_str()); + VGames_Save(); + break; + } } bool search = e.what == ED_SEARCH && !g.search.empty(); EditClose(); @@ -1095,6 +1112,13 @@ static void Select() Build(); break; } + case GA_GAMEOPT: { + VirtualGame* vg = PickedGame(); + if (!vg) break; + const char* text = r.arg == 0 ? vg->args : r.arg == 1 ? vg->workdir : vg->env; + EditOpen(ED_GAMEOPT, r.arg, r.label.c_str(), text, sizeof(vg->args) - 1, false); + break; + } case GA_NAME: EditOpen(ED_NAME, 0, "Name", g.pickedName, 100, false); break; diff --git a/theseus/desktop/host.h b/theseus/desktop/host.h index e3f4039..ca1b9f1 100644 --- a/theseus/desktop/host.h +++ b/theseus/desktop/host.h @@ -91,6 +91,8 @@ bool Host_PickFile(const char* title, char* out, size_t outSize); bool Host_ExePath(char* out, size_t outSize); // Show a folder in the OS file manager. Doesn't wait. void Host_OpenFolder(const char* dir); +// Set an environment variable for this process and what it starts. NULL removes it. +void Host_SetEnv(const char* name, const char* value); // A value under HKEY_CURRENT_USER as text (numbers in decimal). Always false off Windows. bool Host_RegistryString(const char* subKey, const char* value, char* out, size_t outSize); // Audio CD in the first optical drive: track count and per-track lengths diff --git a/theseus/desktop/host_posix_app.cpp b/theseus/desktop/host_posix_app.cpp index a8cdbbe..a697293 100644 --- a/theseus/desktop/host_posix_app.cpp +++ b/theseus/desktop/host_posix_app.cpp @@ -585,6 +585,11 @@ void Host_OpenFolder(const char* dir) { bool Host_RegistryString(const char*, const char*, char*, size_t) { return false; } +void Host_SetEnv(const char* name, const char* value) { + if (value) setenv(name, value, 1); + else unsetenv(name); +} + // Linux reads its TOC in cdaudio.cpp. int Host_CdReadToc(int*, int, bool*) { return -1; } diff --git a/theseus/desktop/host_win_app.cpp b/theseus/desktop/host_win_app.cpp index e9ad014..9fc24fa 100644 --- a/theseus/desktop/host_win_app.cpp +++ b/theseus/desktop/host_win_app.cpp @@ -554,6 +554,12 @@ int Host_CdReadToc(int* durations, int maxTracks, bool* allAudio) { return count; } +// The C runtime's copy and the one CreateProcess hands down, kept the same. +void Host_SetEnv(const char* name, const char* value) { + _putenv_s(name, value ? value : ""); + SetEnvironmentVariableA(name, value); +} + const char* Host_Name() { return "Windows"; } const char* Host_DefaultShaderDir() { return "dx11"; } diff --git a/theseus/desktop/launch.cpp b/theseus/desktop/launch.cpp index 5a49320..3206cce 100644 --- a/theseus/desktop/launch.cpp +++ b/theseus/desktop/launch.cpp @@ -19,6 +19,7 @@ #include "launchers/launcher.h" #include "launchers/steam.h" +#include #include extern "C" void DashAudio_MuteAll(void); @@ -136,7 +137,45 @@ static bool DeriveWorkDir(const char* cmd, char* out, size_t outSize) // e.g. Title Maker Test Launch) and SpawnLaunchSpec (overlay-driven game // launch) call this. Returns true if the OS handed us back a process / // shell-exec handle; the parent doesn't wait on the child either way. -static bool Launch_DoSpawn(const char* expanded, HostProc** proc) +// A game's own launch options from games.ini, all empty for anything else. +struct LaunchOpts { + char args[256]; + char workdir[256]; + char env[256]; +}; + +// Each NAME=value from a ';' list, set now and put back by EnvRestore. +struct EnvSaved { std::string name, old; bool had; }; + +static void EnvApply(const char* list, std::vector& saved) +{ + std::string all = list ? list : ""; + size_t at = 0; + while (at < all.size()) { + size_t end = all.find(';', at); + if (end == std::string::npos) end = all.size(); + std::string pair = all.substr(at, end - at); + at = end + 1; + size_t eq = pair.find('='); + size_t start = pair.find_first_not_of(" \t"); + if (eq == std::string::npos || start == std::string::npos || start >= eq) continue; + std::string name = pair.substr(start, eq - start); + while (!name.empty() && (name[name.size() - 1] == ' ' || name[name.size() - 1] == '\t')) + name.erase(name.size() - 1); + const char* old = getenv(name.c_str()); + EnvSaved e = { name, old ? old : "", old != NULL }; + saved.push_back(e); + Host_SetEnv(name.c_str(), pair.c_str() + eq + 1); + } +} + +static void EnvRestore(const std::vector& saved) +{ + for (size_t i = saved.size(); i-- > 0;) + Host_SetEnv(saved[i].name.c_str(), saved[i].had ? saved[i].old.c_str() : NULL); +} + +static bool Launch_DoSpawn(const char* expanded, const LaunchOpts* opts, HostProc** proc) { if (!expanded || !*expanded) return false; @@ -148,12 +187,30 @@ static bool Launch_DoSpawn(const char* expanded, HostProc** proc) char workdir[1024]; bool haveWorkdir = DeriveWorkDir(spec, workdir, sizeof(workdir)); + if (opts && opts->workdir[0]) { + PathTemplate_Expand(opts->workdir, workdir, sizeof(workdir)); + haveWorkdir = true; + } + // A URL goes to whatever handles it, so there's nothing to add arguments to. + if (opts && opts->args[0] && !IsUrl(spec)) { + char args[1024]; + PathTemplate_Expand(opts->args, args, sizeof(args)); + size_t n = strlen(spec); + snprintf(spec + n, sizeof(spec) - n, " %s", args); + } + std::vector env; + if (opts) EnvApply(opts->env, env); - if (!Host_Spawn(spec, IsUrl(spec), IsSteamUrl(spec), haveWorkdir ? workdir : NULL, - g_launchLastResult, sizeof(g_launchLastResult), proc)) { + bool spawned = Host_Spawn(spec, IsUrl(spec), IsSteamUrl(spec), haveWorkdir ? workdir : NULL, + g_launchLastResult, sizeof(g_launchLastResult), proc); + EnvRestore(env); + if (!spawned) { fprintf(stderr, "[launch] %s\n", g_launchLastResult); return false; } + if (opts && (opts->args[0] || opts->workdir[0] || opts->env[0])) + fprintf(stderr, "[launch] with options: %s%s%s%s\n", spec, + haveWorkdir ? " (in " : "", haveWorkdir ? workdir : "", haveWorkdir ? ")" : ""); snprintf(g_launchLastResult, sizeof(g_launchLastResult), "Launched: %s", spec); @@ -164,7 +221,7 @@ static bool Launch_DoSpawn(const char* expanded, HostProc** proc) // (Build()), log the trace, then spawn. Both public dispatchers funnel // through this so the trace, error reporting, and command-form rules // live in one place. -static bool Launch_ExpandAndSpawn(const char* spec, +static bool Launch_ExpandAndSpawn(const char* spec, const LaunchOpts* opts, char* finalOut, size_t finalSize, HostProc** proc) { if (!spec || !spec[0]) return false; @@ -176,7 +233,7 @@ static bool Launch_ExpandAndSpawn(const char* spec, fprintf(stderr, "[launch] var: %s\n", expanded); if (strcmp(expanded, finalOut) != 0) fprintf(stderr, "[launch] cmd: %s\n", finalOut); - return Launch_DoSpawn(finalOut, proc); + return Launch_DoSpawn(finalOut, opts, proc); } // ============================================================================ @@ -319,18 +376,18 @@ void DesktopLaunch(const char* spec) { char finalCmd[2048]; HostProc* proc = NULL; - Launch_ExpandAndSpawn(spec, finalCmd, sizeof(finalCmd), &proc); + Launch_ExpandAndSpawn(spec, NULL, finalCmd, sizeof(finalCmd), &proc); Stray(proc); } // Spawn called by the launch overlay tick once the fade-in completes. // Identical to DesktopLaunch except we minimize the dashboard window // after a successful spawn so the game gets focus. -static void SpawnLaunchSpec(const char* spec) +static void SpawnLaunchSpec(const char* spec, const LaunchOpts* opts) { char finalCmd[2048]; HostProc* proc = NULL; - if (!Launch_ExpandAndSpawn(spec, finalCmd, sizeof(finalCmd), &proc)) return; + if (!Launch_ExpandAndSpawn(spec, opts, finalCmd, sizeof(finalCmd), &proc)) return; VGames_MarkPlayed(spec); SessionBegin(spec, finalCmd, proc); @@ -352,6 +409,7 @@ static bool s_overlayActive = false; static double s_overlayStart = 0.0; static bool s_overlaySpawned = false; static char s_pendingSpec[2048]; +static LaunchOpts s_pendingOpts; // Total fade duration (seconds). The first kFadeIn portion is the alpha ramp, // after which we hold full black for the remaining time and fire the spawn at @@ -385,6 +443,7 @@ void LaunchOverlay_Reset() s_overlaySpawned = false; s_overlayStart = 0.0; s_pendingSpec[0] = 0; + memset(&s_pendingOpts, 0, sizeof(s_pendingOpts)); } // Lazy-load the Xbox logo PNG (Configs/xboxlogo.png) into an ImGui @@ -432,7 +491,7 @@ void LaunchOverlay_Tick() if (!s_overlaySpawned && t >= (double)kSpawnAt) { s_overlaySpawned = true; - SpawnLaunchSpec(s_pendingSpec); + SpawnLaunchSpec(s_pendingSpec, &s_pendingOpts); } if (t >= (double)kHoldEnd) @@ -444,7 +503,14 @@ void LaunchOverlay_Tick() } } +static void QueueGame(const char* spec, const LaunchOpts* opts); + void DesktopLaunchGame(const char* spec) +{ + QueueGame(spec, NULL); +} + +static void QueueGame(const char* spec, const LaunchOpts* opts) { if (!spec || !spec[0]) return; @@ -472,11 +538,13 @@ void DesktopLaunchGame(const char* spec) if (s_overlayActive && !s_overlaySpawned && s_pendingSpec[0]) { s_overlaySpawned = true; - SpawnLaunchSpec(s_pendingSpec); + SpawnLaunchSpec(s_pendingSpec, &s_pendingOpts); } strncpy(s_pendingSpec, spec, sizeof(s_pendingSpec) - 1); s_pendingSpec[sizeof(s_pendingSpec) - 1] = 0; + if (opts) s_pendingOpts = *opts; + else memset(&s_pendingOpts, 0, sizeof(s_pendingOpts)); s_overlayStart = LaunchOverlay_Now(); s_overlaySpawned = false; s_overlayActive = true; @@ -541,8 +609,13 @@ void DesktopLaunchTitle(const char* devicePath) // Primary: virtualized games.ini lookup. int vgIdx = VGames_MatchFolder(localPath); if (vgIdx >= 0 && g_vgames.games[vgIdx].launch[0]) { - fprintf(stderr, "[launch] VGames match: %s -> %s\n", devicePath, g_vgames.games[vgIdx].launch); - DesktopLaunchGame(g_vgames.games[vgIdx].launch); + const VirtualGame& vg = g_vgames.games[vgIdx]; + fprintf(stderr, "[launch] VGames match: %s -> %s\n", devicePath, vg.launch); + LaunchOpts opts; + snprintf(opts.args, sizeof(opts.args), "%s", vg.args); + snprintf(opts.workdir, sizeof(opts.workdir), "%s", vg.workdir); + snprintf(opts.env, sizeof(opts.env), "%s", vg.env); + QueueGame(vg.launch, &opts); return; } diff --git a/theseus/desktop/virtual_games.h b/theseus/desktop/virtual_games.h index 642e9dd..1b3f2c8 100644 --- a/theseus/desktop/virtual_games.h +++ b/theseus/desktop/virtual_games.h @@ -46,6 +46,11 @@ struct VirtualGame { long long playTime; // seconds, counted only when the launcher saw the game close // Another source has the same game and wins (VGames_FindDuplicates). bool duplicate; + // Launch options from the guide's game page. args go after the Launch + // line, env is NAME=value pairs split by ';'. Empty means as before. + char args[256]; + char workdir[256]; + char env[256]; }; struct VirtualGameDB { @@ -127,6 +132,12 @@ inline void VGames_Load() { cur->lastPlayed = atoll(val); else if (strcmp(key, "PlayTime") == 0) cur->playTime = atoll(val); + else if (strcmp(key, "Args") == 0) + strncpy(cur->args, val, sizeof(cur->args) - 1); + else if (strcmp(key, "WorkDir") == 0) + strncpy(cur->workdir, val, sizeof(cur->workdir) - 1); + else if (strcmp(key, "Env") == 0) + strncpy(cur->env, val, sizeof(cur->env) - 1); } fclose(fp); g_vgames.generation++; @@ -196,6 +207,9 @@ inline void VGames_Save() { if (g.hidden) fprintf(fp, "Hidden=1\n"); if (g.lastPlayed) fprintf(fp, "LastPlayed=%lld\n", g.lastPlayed); if (g.playTime) fprintf(fp, "PlayTime=%lld\n", g.playTime); + if (g.args[0]) fprintf(fp, "Args=%s\n", g.args); + if (g.workdir[0]) fprintf(fp, "WorkDir=%s\n", g.workdir); + if (g.env[0]) fprintf(fp, "Env=%s\n", g.env); fprintf(fp, "\n"); } save.Commit(); diff --git a/theseus/desktop/xdg_apps.cpp b/theseus/desktop/xdg_apps.cpp index 71f799c..7fe0de3 100644 --- a/theseus/desktop/xdg_apps.cpp +++ b/theseus/desktop/xdg_apps.cpp @@ -174,6 +174,7 @@ bool XdgApps_Parse(const char* file, XdgApp* out) { else if (!strcasecmp(k, "Exec")) out->exec = val; else if (!strcasecmp(k, "Icon")) out->icon = val; else if (!strcasecmp(k, "Categories")) categories = val; + else if (!strcasecmp(k, "Path")) out->workdir = val; else if (!strcasecmp(k, "Hidden")) hidden = !strcasecmp(val.c_str(), "true"); else if (!strcasecmp(k, "NoDisplay")) hidden = hidden || !strcasecmp(val.c_str(), "true"); else if (!strcasecmp(k, "Terminal")) terminal = !strcasecmp(val.c_str(), "true"); @@ -265,7 +266,8 @@ bool XdgApps_Add(const XdgApp& app, const char* category) { static unsigned s_bump = 0; char id[16]; snprintf(id, sizeof(id), "%08x", (unsigned)time(NULL) + s_bump++); - VGames_Add(clean, id, cmd.c_str(), "E", category); + int row = VGames_Add(clean, id, cmd.c_str(), "E", category); + if (row >= 0) snprintf(g_vgames.games[row].workdir, sizeof(g_vgames.games[row].workdir), "%s", app.workdir.c_str()); std::string icon = XdgApps_IconFile(app.icon); if (!icon.empty()) { char dst[1024]; diff --git a/theseus/desktop/xdg_apps.h b/theseus/desktop/xdg_apps.h index 6ba2242..5d51ffa 100644 --- a/theseus/desktop/xdg_apps.h +++ b/theseus/desktop/xdg_apps.h @@ -9,6 +9,7 @@ struct XdgApp { std::string name, exec, icon, path; // path is the .desktop file + std::string workdir; // its Path, where it wants to start bool game; // Categories has Game }; From 75ac56b4a6c25af1f7e7e437bc43d35887fcccd8 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:32:47 -0500 Subject: [PATCH 15/46] Fixed Jellyfin and Plex posters that never showed The scene asked for the poster before it finished downloading, and the texture cache remembers a miss for the whole session. The library now hands back the logo until the file is on disk and the scene swaps the poster in when it lands. Seasons and episodes without art fall back to the show's poster. Plex got the same change but needs a test against a real server. --- Data/Xips/default.xip | Bin 1688042 -> 1688892 bytes theseus/desktop/desktop_nodes.cpp | 61 ++++++++++++++++++++--- theseus/desktop/jellyfin_client.cpp | 16 +++++- theseus/desktop/jellyfin_client.h | 3 ++ theseus/desktop/plex_client.cpp | 16 +++++- theseus/desktop/plex_client.h | 3 ++ xips-source/default-desktop/Jellyfin.xap | 41 +++++++++------ xips-source/default-desktop/Plex.xap | 41 +++++++++------ xips-source/jellyfin/jellyfin.xap | 41 +++++++++------ xips-source/plex/plex.xap | 41 +++++++++------ 10 files changed, 197 insertions(+), 66 deletions(-) diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index 74b5d402f2aebdb2ac4f86864ca047dc515bbff6..b0f59a4fe380bdd1beabc03ce1428bb2682c9f0c 100644 GIT binary patch delta 1558 zcmc(fOK1~O6ow~lO`NgDrakGyKDaGb60x;f@IiO{P!x zJi5^1-n+fCZKy~Py!1Ifa>f01*EyeHuYE5;xRduR{siIt89OapJ>?aIg(U(N$gHd9 zYlQu^x%{VFr@I_yyBwB^NX4WQ(gKo`~g@x zJ16>Njp-fHPE|L!7GU;TwTks-Vl1g8n5r-%#@UvwOi@z-7UD6vFRs$gl-#ScxWQ5} zt}t0MSVC4Jx@1)ibwqcla)d_;t6Fu!F-<+hnI7iL70%*RL0QRkHFJhtJ1ohb$scvU6Z-P*kdSyPkw^d9(J4Y{Nh3`nBg1q-s(c=8EsKs8+A#I@t#Ha88z zWhXu#f>u0yAE0QBAIFBE7H z$tj&~B+N70G%j2BL#N0}eME1SqDdue#OcNgTa=FB^#`yH4^D!J-NR7oibt7G>4@T& zG)=pH04i{!2~I2@0dGY%w%thnyxOkS)&ICX5 zFDSL@{+ZJi7N~#6sY#qV9W|n!>$Z^67jKBtru_6Ar@21nNUg)xk5Gm?kCuoTX3h5Z z@X(1jCc%r2NxHM4x5VnrNocXYRTdGe*R3$IT8jNs;BF{9r_gyD*<7pt1KK+4otO_= z9Qy!EaWD-H7PeJ*I}INE{Eo(3Fag!rJe7?(+VMx4{vg`Y;Iar6ahk@T!*tU$)R~0o ueNTNT-{s#J^~^v+^E`~^T=HA*0{aFvt}LZz-7`S)k}646rhBG(;_)v#Ui!KK delta 546 zcmYk%KS*0q6bA77^3OzTG|87ln??!&p`D5%f*=S^R*VulNF6#fm{CzWbV#Y#D%zn0 zhXW!)_6|j*7eXNZNzl0z5v(}4C3&QR2(3{2nP}?0{NUYp&OPsY+2urWKH(l88hf^F zQOeK#G?#K;MoXQlzOvt;uI`=nZ>XgY^|Bgx=U2*UQyfrT0}JiyW$1r>H9a3Q7GuT@ z3t7oVc5+YyImtzh)I<-cncUPut>hsu`E<;{r>`rotRY$7z>)sEiOvQ&GtsUq8RQ)D ztAL=4?ZPhmJMhbJ3H|b73lC+Y443oyNtY3> zb+*aKIh^vb!ay8n7hj2)tG~mUUNOt)xEI%JBE-1DxDh>SBIQ|(UxWMempty() && Plex_ArtReady(*k)) + return new CStrObject(_T(Plex_ArtCachePath(*k).c_str())); + return new CStrObject(_T("E:\\Plex\\plex_logo.png")); + } + + void QueueShowArt() + { + std::vector items = CurrentItems(); + if (m_currentShow < 0 || m_currentShow >= (int)items.size()) return; + const PlexItem& sh = items[m_currentShow]; + if (!sh.thumbUrl.empty()) Plex_QueueArtDownload(sh.ratingKey, sh.thumbUrl); + } + CStrObject* GetItemArtPath(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; - return new CStrObject(_T(Plex_ArtCachePath(items[i].ratingKey).c_str())); + return ArtOrLogo(items[i].ratingKey); } void QueueSeasonArt(int i) @@ -3599,6 +3619,7 @@ class CPlexLibrary : public CNode Plex_Cache_GetSeasons(showKey, seasons); if (i < 0 || i >= (int)seasons.size()) return; const PlexSeason& s = seasons[i]; + QueueShowArt(); if (!s.thumbUrl.empty()) Plex_QueueArtDownload(s.ratingKey, s.thumbUrl); } @@ -3609,7 +3630,7 @@ class CPlexLibrary : public CNode if (showKey.empty()) return new CStrObject; Plex_Cache_GetSeasons(showKey, seasons); if (i < 0 || i >= (int)seasons.size()) return new CStrObject; - return new CStrObject(_T(Plex_ArtCachePath(seasons[i].ratingKey).c_str())); + return ArtOrLogo(seasons[i].ratingKey, showKey); } void QueueEpisodeArt(int i) @@ -3620,6 +3641,7 @@ class CPlexLibrary : public CNode Plex_Cache_GetEpisodes(seasonKey, eps); if (i < 0 || i >= (int)eps.size()) return; const PlexEpisode& e = eps[i]; + QueueShowArt(); if (!e.thumbUrl.empty()) Plex_QueueArtDownload(e.ratingKey, e.thumbUrl); } @@ -3630,7 +3652,7 @@ class CPlexLibrary : public CNode if (seasonKey.empty()) return new CStrObject; Plex_Cache_GetEpisodes(seasonKey, eps); if (i < 0 || i >= (int)eps.size()) return new CStrObject; - return new CStrObject(_T(Plex_ArtCachePath(eps[i].ratingKey).c_str())); + return ArtOrLogo(eps[i].ratingKey, seasonKey, CurrentShowKey()); } void PlayRatingKey(const std::string& ratingKey, @@ -3930,11 +3952,30 @@ class CJellyfinLibrary : public CNode Jellyfin_QueueArtDownload(items[i].id, items[i].primaryTag); } + // First poster in the list that's on disk, else the logo. A missing file + // would stick as a miss in the texture cache, so it's never asked for. + static CStrObject* ArtOrLogo(const std::string& a, const std::string& b = "", + const std::string& c = "") + { + const std::string* ids[3] = { &a, &b, &c }; + for (const std::string* id : ids) + if (!id->empty() && Jellyfin_ArtReady(*id)) + return new CStrObject(_T(Jellyfin_ArtCachePath(*id).c_str())); + return new CStrObject(_T("E:\\Jellyfin\\jellyfin_logo.png")); + } + + void QueueShowArt() + { + std::vector items = CurrentItems(); + if (m_currentShow < 0 || m_currentShow >= (int)items.size()) return; + Jellyfin_QueueArtDownload(items[m_currentShow].id, items[m_currentShow].primaryTag); + } + CStrObject* GetItemArtPath(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; - return new CStrObject(_T(Jellyfin_ArtCachePath(items[i].id).c_str())); + return ArtOrLogo(items[i].id); } std::string CurrentShowId() @@ -4041,7 +4082,9 @@ class CJellyfinLibrary : public CNode if (showId.empty()) return; Jellyfin_Cache_GetSeasons(showId, seasons); if (i < 0 || i >= (int)seasons.size()) return; - Jellyfin_QueueArtDownload(seasons[i].id, seasons[i].primaryTag); + QueueShowArt(); + if (!seasons[i].primaryTag.empty()) + Jellyfin_QueueArtDownload(seasons[i].id, seasons[i].primaryTag); } CStrObject* GetSeasonArtPath(int i) @@ -4051,7 +4094,7 @@ class CJellyfinLibrary : public CNode if (showId.empty()) return new CStrObject; Jellyfin_Cache_GetSeasons(showId, seasons); if (i < 0 || i >= (int)seasons.size()) return new CStrObject; - return new CStrObject(_T(Jellyfin_ArtCachePath(seasons[i].id).c_str())); + return ArtOrLogo(seasons[i].id, showId); } int GetEpisodeCount() @@ -4107,7 +4150,9 @@ class CJellyfinLibrary : public CNode if (seasonId.empty()) return; Jellyfin_Cache_GetEpisodes(seasonId, eps); if (i < 0 || i >= (int)eps.size()) return; - Jellyfin_QueueArtDownload(eps[i].id, eps[i].primaryTag); + QueueShowArt(); + if (!eps[i].primaryTag.empty()) + Jellyfin_QueueArtDownload(eps[i].id, eps[i].primaryTag); } CStrObject* GetEpisodeArtPath(int i) @@ -4117,7 +4162,7 @@ class CJellyfinLibrary : public CNode if (seasonId.empty()) return new CStrObject; Jellyfin_Cache_GetEpisodes(seasonId, eps); if (i < 0 || i >= (int)eps.size()) return new CStrObject; - return new CStrObject(_T(Jellyfin_ArtCachePath(eps[i].id).c_str())); + return ArtOrLogo(eps[i].id, seasonId, CurrentShowId()); } CStrObject* GetSubtitle(int view, int i) diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index 87743e6..0783f58 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -97,6 +97,7 @@ static std::map> s_cacheEpisodes; // ---------- Art download queue ---------- static std::mutex s_artMtx; static std::map*> s_artInFlight; +static std::map s_artFailed; // ============================================================================ @@ -610,6 +611,8 @@ static void ArtWorker(std::string itemId, std::string tag, } if (!Http_GetToFile(url, path)) { fprintf(stderr, "[Jellyfin] art fetch failed for %s\n", itemId.c_str()); + std::lock_guard lk(s_artMtx); + s_artFailed[itemId] = true; } } { @@ -627,9 +630,20 @@ void Jellyfin_QueueArtDownload(const std::string& itemId, const std::string& tag std::atomic* flag; { std::lock_guard lk(s_artMtx); - if (s_artInFlight.count(itemId)) return; + if (s_artInFlight.count(itemId) || s_artFailed.count(itemId)) return; flag = new std::atomic(false); s_artInFlight[itemId] = flag; } std::thread(ArtWorker, itemId, tag, flag).detach(); } + +bool Jellyfin_ArtReady(const std::string& itemId) +{ + if (!Http_IsSafeFileId(itemId)) return false; + { + std::lock_guard lk(s_artMtx); + if (s_artInFlight.count(itemId)) return false; + } + struct stat st; + return stat(ArtHostPath(itemId).c_str(), &st) == 0 && st.st_size > 0; +} diff --git a/theseus/desktop/jellyfin_client.h b/theseus/desktop/jellyfin_client.h index 02a15e8..aa38cd9 100644 --- a/theseus/desktop/jellyfin_client.h +++ b/theseus/desktop/jellyfin_client.h @@ -75,3 +75,6 @@ std::string Jellyfin_StreamUrl(const std::string& itemId); std::string Jellyfin_ArtCachePath(const std::string& itemId); void Jellyfin_QueueArtDownload(const std::string& itemId, const std::string& primaryTag); +// The poster is on disk. Only hand the scene a path once this is true: the +// texture cache remembers a miss for the rest of the session. +bool Jellyfin_ArtReady(const std::string& itemId); diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index 3416c52..a25f588 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -74,6 +74,7 @@ static std::atomic s_episodesBusy{false}; // Art download queue static std::mutex s_artMtx; static std::map*> s_artInFlight; +static std::map s_artFailed; // ---------- Pre-stage cache ---------- static std::atomic s_syncReady{false}; @@ -691,6 +692,8 @@ static void ArtWorker(std::string ratingKey, std::string url, if (stat(path.c_str(), &st) != 0 || st.st_size == 0) { if (!Http_GetToFile(url, path)) { fprintf(stderr, "[Plex] art fetch failed for %s\n", ratingKey.c_str()); + std::lock_guard lk(s_artMtx); + s_artFailed[ratingKey] = true; } } { @@ -708,9 +711,20 @@ void Plex_QueueArtDownload(const std::string& ratingKey, const std::string& url) std::atomic* flag; { std::lock_guard lk(s_artMtx); - if (s_artInFlight.count(ratingKey)) return; + if (s_artInFlight.count(ratingKey) || s_artFailed.count(ratingKey)) return; flag = new std::atomic(false); s_artInFlight[ratingKey] = flag; } std::thread(ArtWorker, ratingKey, url, flag).detach(); } + +bool Plex_ArtReady(const std::string& ratingKey) +{ + if (!Http_IsSafeFileId(ratingKey)) return false; + { + std::lock_guard lk(s_artMtx); + if (s_artInFlight.count(ratingKey)) return false; + } + struct stat st; + return stat(Plex_ArtCacheHostPath(ratingKey).c_str(), &st) == 0 && st.st_size > 0; +} diff --git a/theseus/desktop/plex_client.h b/theseus/desktop/plex_client.h index e3be6e0..b17a019 100644 --- a/theseus/desktop/plex_client.h +++ b/theseus/desktop/plex_client.h @@ -92,3 +92,6 @@ bool Plex_Cache_GetEpisodes(const std::string& seasonRatingKey, std::string Plex_ArtCachePath(const std::string& ratingKey); void Plex_QueueArtDownload(const std::string& ratingKey, const std::string& url); +// The poster is on disk. Only hand the scene a path once this is true: the +// texture cache remembers a miss for the rest of the session. +bool Plex_ArtReady(const std::string& ratingKey); diff --git a/xips-source/default-desktop/Jellyfin.xap b/xips-source/default-desktop/Jellyfin.xap index a447aac..de0775b 100644 --- a/xips-source/default-desktop/Jellyfin.xap +++ b/xips-source/default-desktop/Jellyfin.xap @@ -14,6 +14,8 @@ var nJfLastCount; // last count we actually drew; behavior re-renders on m var nJfCursorBackup0; // saved cursor when drilling lib -> items var nJfCursorBackup1; // saved cursor when drilling item -> seasons var nJfCursorBackup2; // saved cursor when drilling season -> episodes +var sJfPoster; // poster url on the CD now; behavior swaps it when art lands +var bJfLoaded; // the chrome scene is in, so the behavior can touch it function initialize() @@ -27,6 +29,7 @@ function initialize() nJfCursorBackup0 = 0; nJfCursorBackup1 = 0; nJfCursorBackup2 = 0; + sJfPoster = ""; } @@ -104,6 +107,8 @@ function StartJellyfinLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sJfPoster = ""; + bJfLoaded = 1; BindActiveList(); UpdateJellyfinList(); } @@ -165,24 +170,27 @@ function UpdateJellyfinList() function UpdatePoster(c) { if (nJfView == 1) - { theJellyfinLibrary.QueueItemArt(nJfCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = theJellyfinLibrary.GetItemArtPath(nJfCursor); - } else if (nJfView == 2) - { theJellyfinLibrary.QueueSeasonArt(nJfCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = theJellyfinLibrary.GetSeasonArtPath(nJfCursor); - } else if (nJfView == 3) - { theJellyfinLibrary.QueueEpisodeArt(nJfCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = theJellyfinLibrary.GetEpisodeArtPath(nJfCursor); - } - else - { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Jellyfin\\jellyfin_logo.png"; - } + sJfPoster = GetPosterArt(); + c.MU_cd_01.children[0].children[0].appearance.texture.url = sJfPoster; +} + + +// The library hands back the logo until the poster is downloaded; the +// behavior redraws once the real one lands. +function GetPosterArt() +{ + if (nJfView == 1) + return theJellyfinLibrary.GetItemArtPath(nJfCursor); + if (nJfView == 2) + return theJellyfinLibrary.GetSeasonArtPath(nJfCursor); + if (nJfView == 3) + return theJellyfinLibrary.GetEpisodeArtPath(nJfCursor); + return "E:\\Jellyfin\\jellyfin_logo.png"; } @@ -437,7 +445,12 @@ DEF theJellyfinMenu Level { sleep .4; BindActiveList(); - if (nJfCount != nJfLastCount) + if (bJfLoaded == 1) + { + if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster)) + UpdateJellyfinList(); + } + else if (nJfCount != nJfLastCount) { UpdateJellyfinList(); } diff --git a/xips-source/default-desktop/Plex.xap b/xips-source/default-desktop/Plex.xap index 4d61250..02cdef7 100644 --- a/xips-source/default-desktop/Plex.xap +++ b/xips-source/default-desktop/Plex.xap @@ -14,6 +14,8 @@ var nPlexLastCount; // last count we actually drew; behavior re-renders on var nPlexCursorBackup0; // saved cursor when drilling lib -> items var nPlexCursorBackup1; // saved cursor when drilling item -> seasons var nPlexCursorBackup2; // saved cursor when drilling season -> episodes +var sPlexPoster; // poster url on the CD now; behavior swaps it when art lands +var bPlexLoaded; // the chrome scene is in, so the behavior can touch it function initialize() @@ -27,6 +29,7 @@ function initialize() nPlexCursorBackup0 = 0; nPlexCursorBackup1 = 0; nPlexCursorBackup2 = 0; + sPlexPoster = ""; } @@ -104,6 +107,8 @@ function StartPlexLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sPlexPoster = ""; + bPlexLoaded = 1; BindActiveList(); UpdatePlexList(); } @@ -165,24 +170,27 @@ function UpdatePlexList() function UpdatePoster(c) { if (nPlexView == 1) - { thePlexLibrary.QueueItemArt(nPlexCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = thePlexLibrary.GetItemArtPath(nPlexCursor); - } else if (nPlexView == 2) - { thePlexLibrary.QueueSeasonArt(nPlexCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = thePlexLibrary.GetSeasonArtPath(nPlexCursor); - } else if (nPlexView == 3) - { thePlexLibrary.QueueEpisodeArt(nPlexCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = thePlexLibrary.GetEpisodeArtPath(nPlexCursor); - } - else - { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Plex\\plex_logo.png"; - } + sPlexPoster = GetPosterArt(); + c.MU_cd_01.children[0].children[0].appearance.texture.url = sPlexPoster; +} + + +// The library hands back the logo until the poster is downloaded; the +// behavior redraws once the real one lands. +function GetPosterArt() +{ + if (nPlexView == 1) + return thePlexLibrary.GetItemArtPath(nPlexCursor); + if (nPlexView == 2) + return thePlexLibrary.GetSeasonArtPath(nPlexCursor); + if (nPlexView == 3) + return thePlexLibrary.GetEpisodeArtPath(nPlexCursor); + return "E:\\Plex\\plex_logo.png"; } @@ -437,7 +445,12 @@ DEF thePlexMenu Level { sleep .4; BindActiveList(); - if (nPlexCount != nPlexLastCount) + if (bPlexLoaded == 1) + { + if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster)) + UpdatePlexList(); + } + else if (nPlexCount != nPlexLastCount) { UpdatePlexList(); } diff --git a/xips-source/jellyfin/jellyfin.xap b/xips-source/jellyfin/jellyfin.xap index a447aac..de0775b 100644 --- a/xips-source/jellyfin/jellyfin.xap +++ b/xips-source/jellyfin/jellyfin.xap @@ -14,6 +14,8 @@ var nJfLastCount; // last count we actually drew; behavior re-renders on m var nJfCursorBackup0; // saved cursor when drilling lib -> items var nJfCursorBackup1; // saved cursor when drilling item -> seasons var nJfCursorBackup2; // saved cursor when drilling season -> episodes +var sJfPoster; // poster url on the CD now; behavior swaps it when art lands +var bJfLoaded; // the chrome scene is in, so the behavior can touch it function initialize() @@ -27,6 +29,7 @@ function initialize() nJfCursorBackup0 = 0; nJfCursorBackup1 = 0; nJfCursorBackup2 = 0; + sJfPoster = ""; } @@ -104,6 +107,8 @@ function StartJellyfinLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sJfPoster = ""; + bJfLoaded = 1; BindActiveList(); UpdateJellyfinList(); } @@ -165,24 +170,27 @@ function UpdateJellyfinList() function UpdatePoster(c) { if (nJfView == 1) - { theJellyfinLibrary.QueueItemArt(nJfCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = theJellyfinLibrary.GetItemArtPath(nJfCursor); - } else if (nJfView == 2) - { theJellyfinLibrary.QueueSeasonArt(nJfCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = theJellyfinLibrary.GetSeasonArtPath(nJfCursor); - } else if (nJfView == 3) - { theJellyfinLibrary.QueueEpisodeArt(nJfCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = theJellyfinLibrary.GetEpisodeArtPath(nJfCursor); - } - else - { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Jellyfin\\jellyfin_logo.png"; - } + sJfPoster = GetPosterArt(); + c.MU_cd_01.children[0].children[0].appearance.texture.url = sJfPoster; +} + + +// The library hands back the logo until the poster is downloaded; the +// behavior redraws once the real one lands. +function GetPosterArt() +{ + if (nJfView == 1) + return theJellyfinLibrary.GetItemArtPath(nJfCursor); + if (nJfView == 2) + return theJellyfinLibrary.GetSeasonArtPath(nJfCursor); + if (nJfView == 3) + return theJellyfinLibrary.GetEpisodeArtPath(nJfCursor); + return "E:\\Jellyfin\\jellyfin_logo.png"; } @@ -437,7 +445,12 @@ DEF theJellyfinMenu Level { sleep .4; BindActiveList(); - if (nJfCount != nJfLastCount) + if (bJfLoaded == 1) + { + if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster)) + UpdateJellyfinList(); + } + else if (nJfCount != nJfLastCount) { UpdateJellyfinList(); } diff --git a/xips-source/plex/plex.xap b/xips-source/plex/plex.xap index 4d61250..02cdef7 100644 --- a/xips-source/plex/plex.xap +++ b/xips-source/plex/plex.xap @@ -14,6 +14,8 @@ var nPlexLastCount; // last count we actually drew; behavior re-renders on var nPlexCursorBackup0; // saved cursor when drilling lib -> items var nPlexCursorBackup1; // saved cursor when drilling item -> seasons var nPlexCursorBackup2; // saved cursor when drilling season -> episodes +var sPlexPoster; // poster url on the CD now; behavior swaps it when art lands +var bPlexLoaded; // the chrome scene is in, so the behavior can touch it function initialize() @@ -27,6 +29,7 @@ function initialize() nPlexCursorBackup0 = 0; nPlexCursorBackup1 = 0; nPlexCursorBackup2 = 0; + sPlexPoster = ""; } @@ -104,6 +107,8 @@ function StartPlexLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sPlexPoster = ""; + bPlexLoaded = 1; BindActiveList(); UpdatePlexList(); } @@ -165,24 +170,27 @@ function UpdatePlexList() function UpdatePoster(c) { if (nPlexView == 1) - { thePlexLibrary.QueueItemArt(nPlexCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = thePlexLibrary.GetItemArtPath(nPlexCursor); - } else if (nPlexView == 2) - { thePlexLibrary.QueueSeasonArt(nPlexCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = thePlexLibrary.GetSeasonArtPath(nPlexCursor); - } else if (nPlexView == 3) - { thePlexLibrary.QueueEpisodeArt(nPlexCursor); - c.MU_cd_01.children[0].children[0].appearance.texture.url = thePlexLibrary.GetEpisodeArtPath(nPlexCursor); - } - else - { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Plex\\plex_logo.png"; - } + sPlexPoster = GetPosterArt(); + c.MU_cd_01.children[0].children[0].appearance.texture.url = sPlexPoster; +} + + +// The library hands back the logo until the poster is downloaded; the +// behavior redraws once the real one lands. +function GetPosterArt() +{ + if (nPlexView == 1) + return thePlexLibrary.GetItemArtPath(nPlexCursor); + if (nPlexView == 2) + return thePlexLibrary.GetSeasonArtPath(nPlexCursor); + if (nPlexView == 3) + return thePlexLibrary.GetEpisodeArtPath(nPlexCursor); + return "E:\\Plex\\plex_logo.png"; } @@ -437,7 +445,12 @@ DEF thePlexMenu Level { sleep .4; BindActiveList(); - if (nPlexCount != nPlexLastCount) + if (bPlexLoaded == 1) + { + if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster)) + UpdatePlexList(); + } + else if (nPlexCount != nPlexLastCount) { UpdatePlexList(); } From 9a65b8876c7e57e9db9a847e71a4997c70b55e2c Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:36:29 -0500 Subject: [PATCH 16/46] Stopped long Jellyfin and Plex headers running into the count A header like DEMO / MOVIES ran under the item count. The header now stays in its own box and scrolls when it's too long, the same way a highlighted row does. --- Data/Xips/jellyfin.xip | Bin 2205004 -> 2205064 bytes Data/Xips/plex.xip | Bin 2205004 -> 2205064 bytes xips-source/jellyfin/jellyfin/default.xap | 2 +- xips-source/plex/plex/default.xap | 2 +- 4 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Data/Xips/jellyfin.xip b/Data/Xips/jellyfin.xip index f7dd808ac779d30d0bd019e19e0d6f5a2f7fc019..20dcffcfdbeaa3269fb054e790b21ad9ed2da14e 100644 GIT binary patch delta 255 zcmX}gO%B0O00iLos(y<4|EIhQkg~9`wW!#L4cmq$B#k!pMA$VFdL64CKqP`IxQmfA zX7Vj&-p@1jUS}%LM-#P@Bt%2)t2`5x-ktnoO9~+#AwuxjCs(|o3RIy6b>9^m?rpGNFZqhK`)s>#EYs91XMMCbTsIka gc1G|{b#5@V(+%d(F!clLUg)C%3N)eR(+3-WzFO!>R{#J2 delta 195 zcmX}gI}Uek@Xmc)!P-|E%<1og8&9y^w7ru gLyR!S1XIiqVvYrtrPGnS=4lln#tKQ9R_p!i1Kyc6CIA2c diff --git a/Data/Xips/plex.xip b/Data/Xips/plex.xip index f7dd808ac779d30d0bd019e19e0d6f5a2f7fc019..20dcffcfdbeaa3269fb054e790b21ad9ed2da14e 100644 GIT binary patch delta 255 zcmX}gO%B0O00iLos(y<4|EIhQkg~9`wW!#L4cmq$B#k!pMA$VFdL64CKqP`IxQmfA zX7Vj&-p@1jUS}%LM-#P@Bt%2)t2`5x-ktnoO9~+#AwuxjCs(|o3RIy6b>9^m?rpGNFZqhK`)s>#EYs91XMMCbTsIka gc1G|{b#5@V(+%d(F!clLUg)C%3N)eR(+3-WzFO!>R{#J2 delta 195 zcmX}gI}Uek@Xmc)!P-|E%<1og8&9y^w7ru gLyR!S1XIiqVvYrtrPGnS=4lln#tKQ9R_p!i1Kyc6CIA2c diff --git a/xips-source/jellyfin/jellyfin/default.xap b/xips-source/jellyfin/jellyfin/default.xap index 73634aa..d3fbd61 100644 --- a/xips-source/jellyfin/jellyfin/default.xap +++ b/xips-source/jellyfin/jellyfin/default.xap @@ -1302,7 +1302,7 @@ DEF MU_text_musicCollection Transform name "NavType" } } - geometry DEF MediaHeaderText Text { font "Heading" text "MEDIA" } + geometry DEF MediaHeaderText Text { font "Heading" text "MEDIA" width -6 scrollHorizontal true scrollRate 0.1 scrollDelay 1 } } ] //rotation -0.999200 -0.027600 0.027600 -1.572000 diff --git a/xips-source/plex/plex/default.xap b/xips-source/plex/plex/default.xap index 73634aa..d3fbd61 100644 --- a/xips-source/plex/plex/default.xap +++ b/xips-source/plex/plex/default.xap @@ -1302,7 +1302,7 @@ DEF MU_text_musicCollection Transform name "NavType" } } - geometry DEF MediaHeaderText Text { font "Heading" text "MEDIA" } + geometry DEF MediaHeaderText Text { font "Heading" text "MEDIA" width -6 scrollHorizontal true scrollRate 0.1 scrollDelay 1 } } ] //rotation -0.999200 -0.027600 0.027600 -1.572000 From 3e9373eb6a33bf5c8a67cc50d0b39bb8b7d3e4f2 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:39:04 -0500 Subject: [PATCH 17/46] Guide help names the buttons the way your pad does Help lines said LB and RB and LT+B on every pad. They read L1 and R1 and PS button, L2+Circle on a PlayStation pad, and L and R and Home, ZL+A on a Nintendo one. --- theseus/desktop/guide.cpp | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index f638310..38d1015 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -439,6 +439,25 @@ static VirtualGame* PickedGame() return vg->valid ? vg : NULL; } +// Button names in help text, as this pad prints them. +static const char* Shoulders() +{ + switch (Pads_Style()) { + case UI_PAD_PLAYSTATION: return "L1 and R1"; + case UI_PAD_NINTENDO: return "L and R"; + default: return "LB and RB"; + } +} + +static const char* GuideCombo() +{ + switch (Pads_Style()) { + case UI_PAD_PLAYSTATION: return "PS button, L2+Circle or F7"; + case UI_PAD_NINTENDO: return "Home button, ZL+A or F7"; + default: return "Guide button, LT+B or F7"; + } +} + static const char* kGameListNames[] = { "Favorites", "Recently Played", "Hidden Games", "All Games", "", "" }; // Emulators the guide can look for, each under its path setting. @@ -488,7 +507,8 @@ static void Build() Add("And everyone who contributed", "", NULL); break; case GV_WELCOME: { - const char* intro = g_welcomeDone ? "A or B starts the dashboard." + const char* intro = g_welcomeDone + ? (Pads_Style() == UI_PAD_PLAYSTATION ? "Cross or Circle starts the dashboard." : "A or B starts the dashboard.") : "Nothing here is required. It's all in the guide later too."; Add("Start the Dashboard", "", intro, GA_RESUME); Add("Development Mode", "", "Edit the scenes live. Restarts UIX Desktop.", GA_DEVMODE); @@ -519,12 +539,14 @@ static void Build() "Games you starred. They get their own spot in the launcher too.", "The last games you started, newest first.", "Games kept out of the launcher. Pick one to bring it back.", - "Everything in the launcher, A to Z. LB and RB jump a letter.", + "Everything in the launcher, A to Z.", }; for (int l = GL_FAVORITES; l <= GL_ALL; l++) { GameListRows(l, list); snprintf(n, sizeof(n), "%d", (int)list.size()); - Add(kGameListNames[l], n, kListHelp[l], GA_GAMELIST, l); + std::string help = kListHelp[l]; + if (l == GL_ALL) help = help + " " + Shoulders() + " jump a letter."; + Add(kGameListNames[l], n, help.c_str(), GA_GAMELIST, l); } snprintf(n, sizeof(n), "%d", Playlist_Count()); Add("Playlists", n, "Made in the Playlist Maker.", GA_VIEW, GV_PLAYLISTS); @@ -688,7 +710,7 @@ static void Build() Add("Report a Problem", "", "Paste the version and the log into an issue on GitHub."); break; case GV_SHORTCUTS: - Add("Guide button, LT+B or F7", "Guide", "Opens and closes this guide."); + Add(GuideCombo(), "Guide", "Opens and closes this guide."); Add("F3", "Title Maker", NULL); Add("F4", "Settings Window", NULL); Add("F5", "HDD Browser", NULL); @@ -1830,7 +1852,7 @@ static void DrawEditor() ui_style_text(UI_TEXT_LINE, left, BODY_B + 8, UI_ALIGN_LEFT, ui_overlay_keyboard() ? "Type away. Enter saves, Esc cancels." - : "LB and RB move the cursor."); + : (std::string(Shoulders()) + " move the cursor.").c_str()); } static void Prompt(ui_style_prompt* p, int* n, int button, const char* key, const char* word, unsigned bits) From 21c9f6a4b7306607523172625c8687e884765d6f Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:39:27 -0500 Subject: [PATCH 18/46] Moved the Y INFO button beside BACK in Jellyfin and Plex It sat in a second row under BACK and got cut off at the bottom of a 1280x720 window. It now sits next to B with its label on the right. --- Data/Xips/jellyfin.xip | Bin 2205064 -> 2204927 bytes Data/Xips/plex.xip | Bin 2205064 -> 2204927 bytes xips-source/jellyfin/jellyfin/default.xap | 24 ++++++++++------------ xips-source/plex/plex/default.xap | 24 ++++++++++------------ 4 files changed, 22 insertions(+), 26 deletions(-) diff --git a/Data/Xips/jellyfin.xip b/Data/Xips/jellyfin.xip index 20dcffcfdbeaa3269fb054e790b21ad9ed2da14e..2c9f5e6393b62d5db70e8683663445093fad31e1 100644 GIT binary patch delta 502 zcmZ9`%S#(k6bIlLXN-@giO)8+C*~+fHagBsY(iXSA-btum2SF7GNTS?CS*p`l@K9u z>F&Dm4{%kwD6`F?U5M+hiqr>fXrUnl3SHIyLZt=I<-7Nu!?};c^O}5nR+A&IR$l0_ zup}*GG>_j#UaFI)@1=jy?2k**p(OR(RhmZ!RkdDKW#|C~x_K{zpbz?C00!X!gyA7X zAPPe;3?ncKV=xYn;4#Et0-nIrpsLcrr~O6FbI~pDvAf2(q{rooTd?z$t=YdjEUv}* zlEwaZ!JcK$_PJntj%5$>UChsOj&~e?gIAs}t+HEU$M?A6tZ(@2xwt-K>SZ*PEO&=3 z*Y-+DpNpGL8GTxCdr7}##nem@{YaRus4vLg(4`zT4K0<`b=_cNK{E`IP~*v9^$We} zwx>m-Ln(nY6f8FB^nNYzjZXg8g3fpPDl59SAgVuctkI(0VDty=%1R2g=?lt;4=ws7 rlu$e^UVo-3(Y~f|1n-*NFR-Z@&(dP(AMO4I`ym-;Ku~nSqGqZ2r+b{d;<(l4mwWb$t zU%6pSsAZwP)hEBZv|3Na9B%P%MsiYP=gCl!v8Z(ntUDiK9HZf%D*MK^gLaN zAATegDfMPR#?vNUR9gdbMm_#a#^TLw@=RCDo1;cG-uOfY|4M}=Rn;HlL0tYqCjW1o zjiaw*TQ8W@m^Tcg0wwc2HR8M9$WvX-Y>{lbLMt)(PEPCjJE4$nBZ5=RbJUYm(NO-7 aRMqSEIAzeq_5P5cBAP}saeoNcpZ^9LgvJp7 diff --git a/Data/Xips/plex.xip b/Data/Xips/plex.xip index 20dcffcfdbeaa3269fb054e790b21ad9ed2da14e..2c9f5e6393b62d5db70e8683663445093fad31e1 100644 GIT binary patch delta 502 zcmZ9`%S#(k6bIlLXN-@giO)8+C*~+fHagBsY(iXSA-btum2SF7GNTS?CS*p`l@K9u z>F&Dm4{%kwD6`F?U5M+hiqr>fXrUnl3SHIyLZt=I<-7Nu!?};c^O}5nR+A&IR$l0_ zup}*GG>_j#UaFI)@1=jy?2k**p(OR(RhmZ!RkdDKW#|C~x_K{zpbz?C00!X!gyA7X zAPPe;3?ncKV=xYn;4#Et0-nIrpsLcrr~O6FbI~pDvAf2(q{rooTd?z$t=YdjEUv}* zlEwaZ!JcK$_PJntj%5$>UChsOj&~e?gIAs}t+HEU$M?A6tZ(@2xwt-K>SZ*PEO&=3 z*Y-+DpNpGL8GTxCdr7}##nem@{YaRus4vLg(4`zT4K0<`b=_cNK{E`IP~*v9^$We} zwx>m-Ln(nY6f8FB^nNYzjZXg8g3fpPDl59SAgVuctkI(0VDty=%1R2g=?lt;4=ws7 rlu$e^UVo-3(Y~f|1n-*NFR-Z@&(dP(AMO4I`ym-;Ku~nSqGqZ2r+b{d;<(l4mwWb$t zU%6pSsAZwP)hEBZv|3Na9B%P%MsiYP=gCl!v8Z(ntUDiK9HZf%D*MK^gLaN zAATegDfMPR#?vNUR9gdbMm_#a#^TLw@=RCDo1;cG-uOfY|4M}=Rn;HlL0tYqCjW1o zjiaw*TQ8W@m^Tcg0wwc2HR8M9$WvX-Y>{lbLMt)(PEPCjJE4$nBZ5=RbJUYm(NO-7 aRMqSEIAzeq_5P5cBAP}saeoNcpZ^9LgvJp7 diff --git a/xips-source/jellyfin/jellyfin/default.xap b/xips-source/jellyfin/jellyfin/default.xap index d3fbd61..2a15d01 100644 --- a/xips-source/jellyfin/jellyfin/default.xap +++ b/xips-source/jellyfin/jellyfin/default.xap @@ -1512,10 +1512,8 @@ DEF Group06 Transform //scaleOrientation 0.000000 0.000000 1.000000 -0.005973 translation 1.183300 2.156 -0.409200 } - // Y cluster -- mirror of B's probearm + probe + pod + tube + - // label, shifted down by ~1.6 units so it forms a second row - // below B/BACK. Reuses the same mesh URLs since they're the - // same physical button parts. delta_y vs B = -1.622. + // Y cluster: a copy of B's probearm, probe, pod and tube, set beside + // B with INFO on its right so a 720p window doesn't clip it. DEF MU_y_probearm Transform { children @@ -1529,7 +1527,7 @@ DEF Group06 Transform rotation 0.753300 0.386200 -0.532400 -1.747000 scale 0.465000 0.465000 0.465000 scaleOrientation 0.981300 0.180300 0.067500 -0.715500 - translation 20.680000 13.660000 6.071000 + translation 22.280000 14.960000 6.071000 } DEF MU_y_probe Transform { @@ -1544,7 +1542,7 @@ DEF Group06 Transform rotation 0.753300 0.386200 -0.532400 -1.747000 scale 0.465000 0.465000 0.465000 scaleOrientation 0.981300 0.180300 0.067500 -0.715500 - translation 19.790001 12.810000 6.235000 + translation 21.390001 14.110000 6.235000 } DEF MU_y_pod_inner Transform { @@ -1558,7 +1556,7 @@ DEF Group06 Transform ] rotation -1.000000 0.000000 0.000000 -3.142000 scale 0.465000 0.465000 0.465000 - translation 11.010000 -12.590000 3.150000 + translation 12.610000 -11.290000 3.150000 } DEF MU_y_pod_outer Transform { @@ -1572,7 +1570,7 @@ DEF Group06 Transform ] rotation -1.000000 0.000000 0.000000 -3.142000 scale 0.465000 0.465000 0.465000 - translation 11.010000 -12.590000 3.150000 + translation 12.610000 -11.290000 3.150000 } DEF MU_y_pod_HL Transform { @@ -1586,7 +1584,7 @@ DEF Group06 Transform ] rotation -1.000000 0.000000 0.000000 -3.142000 scale 0.465000 0.465000 0.465000 - translation 11.010000 -12.590000 3.150000 + translation 12.610000 -11.290000 3.150000 } DEF MU_y_tube Transform { @@ -1601,7 +1599,7 @@ DEF Group06 Transform rotation 0.990900 -0.095410 -0.095410 -1.580000 scale 0.465000 0.465000 0.465000 scaleOrientation 0.010380 -0.285600 0.958300 -0.080610 - translation -22.030001 -29.050000 9.817000 + translation -20.430001 -27.750000 9.817000 } DEF MU_Text_y Transform { @@ -1614,7 +1612,7 @@ DEF Group06 Transform } ] scale 0.605000 0.605000 0.000 - translation 1.889000 1.122000 -0.409200 + translation 3.489000 2.422000 -0.409200 } DEF MU_Text_info Transform { @@ -1623,11 +1621,11 @@ DEF Group06 Transform Shape { appearance Appearance { material MaxMaterial { name "XBOXgreen" } } - geometry Text { font "Body" text "INFO" justify "end" } + geometry Text { font "Body" text "INFO" } } ] scale 0.375000 0.475000 0.00 - translation 1.183300 0.856000 -0.409200 + translation 4.129000 2.156000 -0.409200 } DEF MU_back_pod_outer Transform { diff --git a/xips-source/plex/plex/default.xap b/xips-source/plex/plex/default.xap index d3fbd61..2a15d01 100644 --- a/xips-source/plex/plex/default.xap +++ b/xips-source/plex/plex/default.xap @@ -1512,10 +1512,8 @@ DEF Group06 Transform //scaleOrientation 0.000000 0.000000 1.000000 -0.005973 translation 1.183300 2.156 -0.409200 } - // Y cluster -- mirror of B's probearm + probe + pod + tube + - // label, shifted down by ~1.6 units so it forms a second row - // below B/BACK. Reuses the same mesh URLs since they're the - // same physical button parts. delta_y vs B = -1.622. + // Y cluster: a copy of B's probearm, probe, pod and tube, set beside + // B with INFO on its right so a 720p window doesn't clip it. DEF MU_y_probearm Transform { children @@ -1529,7 +1527,7 @@ DEF Group06 Transform rotation 0.753300 0.386200 -0.532400 -1.747000 scale 0.465000 0.465000 0.465000 scaleOrientation 0.981300 0.180300 0.067500 -0.715500 - translation 20.680000 13.660000 6.071000 + translation 22.280000 14.960000 6.071000 } DEF MU_y_probe Transform { @@ -1544,7 +1542,7 @@ DEF Group06 Transform rotation 0.753300 0.386200 -0.532400 -1.747000 scale 0.465000 0.465000 0.465000 scaleOrientation 0.981300 0.180300 0.067500 -0.715500 - translation 19.790001 12.810000 6.235000 + translation 21.390001 14.110000 6.235000 } DEF MU_y_pod_inner Transform { @@ -1558,7 +1556,7 @@ DEF Group06 Transform ] rotation -1.000000 0.000000 0.000000 -3.142000 scale 0.465000 0.465000 0.465000 - translation 11.010000 -12.590000 3.150000 + translation 12.610000 -11.290000 3.150000 } DEF MU_y_pod_outer Transform { @@ -1572,7 +1570,7 @@ DEF Group06 Transform ] rotation -1.000000 0.000000 0.000000 -3.142000 scale 0.465000 0.465000 0.465000 - translation 11.010000 -12.590000 3.150000 + translation 12.610000 -11.290000 3.150000 } DEF MU_y_pod_HL Transform { @@ -1586,7 +1584,7 @@ DEF Group06 Transform ] rotation -1.000000 0.000000 0.000000 -3.142000 scale 0.465000 0.465000 0.465000 - translation 11.010000 -12.590000 3.150000 + translation 12.610000 -11.290000 3.150000 } DEF MU_y_tube Transform { @@ -1601,7 +1599,7 @@ DEF Group06 Transform rotation 0.990900 -0.095410 -0.095410 -1.580000 scale 0.465000 0.465000 0.465000 scaleOrientation 0.010380 -0.285600 0.958300 -0.080610 - translation -22.030001 -29.050000 9.817000 + translation -20.430001 -27.750000 9.817000 } DEF MU_Text_y Transform { @@ -1614,7 +1612,7 @@ DEF Group06 Transform } ] scale 0.605000 0.605000 0.000 - translation 1.889000 1.122000 -0.409200 + translation 3.489000 2.422000 -0.409200 } DEF MU_Text_info Transform { @@ -1623,11 +1621,11 @@ DEF Group06 Transform Shape { appearance Appearance { material MaxMaterial { name "XBOXgreen" } } - geometry Text { font "Body" text "INFO" justify "end" } + geometry Text { font "Body" text "INFO" } } ] scale 0.375000 0.475000 0.00 - translation 1.183300 0.856000 -0.409200 + translation 4.129000 2.156000 -0.409200 } DEF MU_back_pod_outer Transform { From 76cd5e34ad55351b8df7159e018fdd3146b57720 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:41:13 -0500 Subject: [PATCH 19/46] First run offers your Steam games and emulators The Welcome screen only made folders, so a new install opened on an empty launcher. On first run it now has Import My Steam Games when Steam is installed, and Find xemu and Find PCSX2. --- theseus/desktop/guide.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 38d1015..6f1b4c2 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -34,6 +34,7 @@ #include "guide.h" #include "ui_overlay.h" #include "pads.h" +#include "launchers/steam.h" #include #include #include @@ -515,6 +516,15 @@ static void Build() if (!g_welcomeDone || g.foldersDone) Add("Set Up My Folders", g.foldersDone ? "Done" : "", "Makes Music, Movies, TV Shows and ROMs folders. Fill them when you like.", GA_FOLDERS); + // First run: fill the launcher from what's already on this machine. + if (!g_welcomeDone) { + char roots[4][512]; + if (Steam_DiscoverInstallRoots(s_steamPath, roots, 4) > 0) + Add("Import My Steam Games", g.result[GA_STEAM].c_str(), "Adds installed Steam games with their icons.", + GA_STEAM); + for (int e = 0; e < kEmuCount; e++) + Add(kEmus[e].findLabel, g.found[e].c_str(), kEmus[e].findHelp, GA_FINDEMU, e); + } Add("Open My Folders", "", "Shows them in your file manager.", GA_OPENFOLDERS); if (const SettingDef* mode = DesktopSettings_Find("StartupMode")) { char val[64]; From 3fe3e0bbabb8ef44ab636b7199a1476aec21293a Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:42:02 -0500 Subject: [PATCH 20/46] README catches up with the guide and the new launcher bits Adding games starts in the guide now, with Runs With, imports, search and per-game options. Covers PCSX2, program icons, Linux apps, time played and coming back after a game, and the Controller settings. LT+B opens the guide, so the tool windows' pad mode is under Desktop Tools. --- README.md | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index bf93417..c5b2040 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,15 @@ On macOS, Linux and Windows it goes by **UIX Desktop**: a launcher and media cen ## What's in it -- **Games grid** for anything you can launch: native PC games, scripts, Steam, RetroArch, [ES-DE](https://es-de.org/) collections, Xbox ISOs through [xemu](https://xemu.app), and your Xbox Cloud Gaming library +- **Games grid** for anything you can launch: native PC games, scripts, Steam, RetroArch, [ES-DE](https://es-de.org/) collections, Xbox ISOs through [xemu](https://xemu.app), PS2 discs through [PCSX2](https://pcsx2.net), Linux app shortcuts, and your Xbox Cloud Gaming library. Box art, favorites, recently played, time played, and the dashboard comes back when a game closes +- **The guide**: press the Guide button, LT+B or F7 anywhere for settings, accounts, adding and finding games, logs and help, all from a controller with its own on screen keyboard - **Title Maker** (F3) for adding and editing entries by hand, with import tabs for Steam, RetroArch and ES-DE - **Media library** for your Movies and TV folders, with posters from [TMDB](https://www.themoviedb.org/), plus [Plex](https://www.plex.tv/) and [Jellyfin](https://jellyfin.org/) servers. Playback runs through libmpv - **Music** from your own folders, with a [projectM](https://github.com/projectM-visualizer/projectm) (MilkDrop) visualizer - **Xbox Cloud Gaming and remote play**: sign in with your Xbox account and your cloud games and consoles show up in the grid - **Skins**: UIX Lite community skins drop in as is, and the Skin Editor helps you make your own - **CRT effect** for that living room TV look: scanlines, curvature, phosphor mask, bloom, all tunable -- **Controllers**: Xbox, PlayStation and other SDL2 gamepads, plus full keyboard control +- **Controllers**: Xbox, PlayStation, Nintendo and other SDL2 gamepads, any number of them, plugged in or out while it runs, with matching button prompts, rumble, and full keyboard control - **Xbox HDD browser** (F5) for xemu qcow2 images and their FATX partitions ## Get it @@ -77,16 +78,22 @@ When an update ships new Data (scene archives, fonts, skins), it reaches your co ### Adding games and apps -Open **Title Maker** with F3 (or Tools > Title Maker). +The quickest way is the guide (Guide button, LT+B or F7) > **Games & Playlists**: -- **Main** lists every entry, whatever added it. Create one by hand with a name and a launch line: a path to an executable, a script, a `steam://` link, or any shell command. Quote paths with spaces. **Test Launch** tries it without leaving the dashboard. **Add ISO** turns an Xbox ISO into an xemu entry once the xemu path is set (Find checks the usual install spots). +- **Add a Game** picks a program, shortcut, ROM or disc image. **Runs With** sends Xbox ISOs to xemu and PS2 discs to PCSX2 (Settings > Games has Find rows for both), and a Windows program brings its own icon along. +- **Import Steam Library**, **Import RetroArch Recent** and **Refresh ES-DE** fill the launcher in one go. On Linux, **Import Linux Apps** reads your app menu, Flatpak and snap shortcuts. +- **Search by Name**, **Find a Game** by letter, **Favorites**, **Recently Played** and **Hidden Games** get you to anything. Each game's page has favorite and hide toggles, its time played, and **Arguments**, **Working Folder** and **Environment** for that game alone. + +For hand editing, **Title Maker** (F3) has every entry and the import tabs: + +- **Main** lists every entry, whatever added it. Create one by hand with a name and a launch line: a path to an executable, a script, a `steam://` link, or any shell command. Quote paths with spaces. **Test Launch** tries it without leaving the dashboard. **Add ISO** turns an Xbox ISO into an xemu entry and **Add PS2 Disc** a disc into a PCSX2 one (Find checks the usual install spots, RetroBat, scoop, Flatpak and AppImages). Icons can come from images, `.ico` files or straight out of an `.exe` or `.dll`. - **Steam** finds your Steam install, and **Import Steam Library** brings in every installed game with its icon. Add by App ID covers betas and demos. - **RetroArch** finds your install, and **Import Recent Titles** pulls in what you've played lately with the core and box art already sorted. Or pick a ROM and a core by hand. - **ES-DE** points at your ES-DE data folder (the one holding `gamelists/`). Your systems and games show up under an ES-DE category, read live on every launch. Entries from Main, Steam and RetroArch are stored in **`Configs/games.ini`** inside your user data folder, with their icons in `Configs/icons/` and the icon mapping in `Configs/Icons.ini`. Back those up and you've backed up your launcher. ES-DE and Xbox Cloud Gaming entries are never written there; they're rebuilt each launch from their source. -The Steam, RetroArch and ES-DE tabs can be hidden under Optional Tabs at the top of Main. Hiding a tab keeps its entries. When you launch something, the dashboard fades to black and minimizes so the game gets the screen; switch back to it when you're done. Cloud and remote play streams run inside the dashboard window instead. +The Steam, RetroArch and ES-DE tabs can be hidden under Optional Tabs at the top of Main. Hiding a tab keeps its entries. When you launch something, the dashboard fades to black and minimizes so the game gets the screen, and idles while it plays. When the game closes, its time played is added and the dashboard comes back (Settings > Games > Back to UIX When a Game Closes turns that off). Steam games count from when Steam says they're running. A launcher that starts the real game and quits right away isn't followed. Cloud and remote play streams run inside the dashboard window instead. ### Xbox Cloud Gaming @@ -113,6 +120,9 @@ Skins live in `Data/Skins//` in your user data folder. Pick one from t - **Display**: fullscreen (F11), borderless (F12), resolution, vsync, FPS cap, MSAA, renderer, hardware video decode, and Emulate Xbox Resolution, which frames scenes in the original 720x480 design space - **CRT Effect**: Settings > Display, or View > CRT Effect. Four presets or eight sliders - **Audio**: master volume, mute (Ctrl+M), and the projectM visualizer. With it on, X + Y (keys or pad) opens and closes the visualizer window +- **Controller**: rumble, which buttons the prompts show (follow the pad, or force Xbox, PlayStation or Nintendo), and Confirm With the Right Button for Nintendo style A and B + +Every setting lives in the guide's Settings pages, and in the Settings window (F4) for mouse and keyboard. Command line flags: `--fullscreen`, `--4k` (fullscreen plus 2x UI scale), `--scale N`, `--no-toolbar`, `--muted`, `--minimized`, `--dashboard`, `--development`. @@ -173,7 +183,7 @@ On a Mac, Cmd works in place of Ctrl.
Controller in the tool windows -**LT + B** (the same chord as the Xbox overlay) hands the pad to the tool windows. A prompt bar along the bottom shows what each button does right now. +Guide > Desktop Tools > **Use the Tools with the Pad** hands the pad to the tool windows. A prompt bar along the bottom shows what each button does right now. | Input | Action | |---|---| @@ -183,7 +193,7 @@ On a Mac, Cmd works in place of Ctrl. | Y | Open a text field with the on screen keyboard | | Hold X | Move and resize windows | -Turn it off with `PadMode=0` in `Configs/desktop.ini`. The Skin Editor stays mouse and keyboard only. +The Skin Editor stays mouse and keyboard only.
From 9e7e766db12ed1eff3b0fdc05cbe49a9c3a7e30d Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:52:14 -0500 Subject: [PATCH 21/46] Fixed posters still going missing after a few screens AppPath_Tree only kept 8 folders and cut names at 15 characters, so Library/Jellyfin never matched its own slot and once the table filled every later folder came back as a bare relative path. Posters then went next to the binary instead of the user folder. It keeps 32 now, works out the full path even when it can't keep one, and takes a lock since art downloads call it from their threads. Also stopped queueing a poster that's already on disk, which kept marking it in flight forever. --- theseus/desktop/app_paths.cpp | 15 ++++++++++++--- theseus/desktop/jellyfin_client.cpp | 3 +++ theseus/desktop/plex_client.cpp | 3 +++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/theseus/desktop/app_paths.cpp b/theseus/desktop/app_paths.cpp index 4e826ec..e429137 100644 --- a/theseus/desktop/app_paths.cpp +++ b/theseus/desktop/app_paths.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include "host.h" @@ -282,16 +283,24 @@ const char* AppPathf(const char* fmt, ...) { } const char* AppPath_Tree(const char* tree) { - // One slot per tree; only the drive letter roots land here. - static struct { char name[16]; char path[1024]; } s_cache[8]; + // One slot per tree, kept for the whole run. Art downloads ask from their + // own threads, hence the lock. + static std::mutex s_mtx; + static struct { char name[64]; char path[1024]; } s_cache[32]; static int s_count = 0; if (!tree || !*tree) return ""; + std::lock_guard lk(s_mtx); for (int i = 0; i < s_count; i++) if (strcasecmp(s_cache[i].name, tree) == 0) return s_cache[i].path; - if (s_count >= 8) return tree; const char* root = IsUserOwned(tree) ? Plat_UserDataDir() : Plat_ShippedDir(); + // Out of slots or too long a name: still the right folder, just not kept. + if (s_count >= 32 || strlen(tree) >= sizeof(s_cache[0].name)) { + static thread_local char t_path[1024]; + snprintf(t_path, sizeof(t_path), "%s/%s", root, tree); + return t_path; + } snprintf(s_cache[s_count].name, sizeof(s_cache[0].name), "%s", tree); snprintf(s_cache[s_count].path, sizeof(s_cache[0].path), "%s/%s", root, tree); return s_cache[s_count++].path; diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index 0783f58..39e7447 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -626,6 +626,9 @@ void Jellyfin_QueueArtDownload(const std::string& itemId, const std::string& tag { // The id comes off the server and ends up in a file path. if (!Http_IsSafeFileId(itemId)) return; + // Already here: queueing would only mark it in flight again. + struct stat st; + if (stat(ArtHostPath(itemId).c_str(), &st) == 0 && st.st_size > 0) return; // Workers erase from the map on other threads, so it is only touched under the lock. std::atomic* flag; { diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index a25f588..5baa0ad 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -707,6 +707,9 @@ void Plex_QueueArtDownload(const std::string& ratingKey, const std::string& url) { // The key comes off the server and ends up in a file path. if (!Http_IsSafeFileId(ratingKey) || url.empty()) return; + // Already here: queueing would only mark it in flight again. + struct stat st; + if (stat(Plex_ArtCacheHostPath(ratingKey).c_str(), &st) == 0 && st.st_size > 0) return; // Workers erase from the map on other threads, so it is only touched under the lock. std::atomic* flag; { From 09eb99eb4c7b4f7bd90982fb82ae74e27c03feb3 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:55:29 -0500 Subject: [PATCH 22/46] Gave fullscreen video the pad and fixed backing out one level too far The pad did nothing while video played, so Esc was the only way out, and the Esc (or B) still held as the menu woke up backed out another level, landing on seasons instead of the episode list. The pad now stops, pauses and seeks, the menu ignores whatever is still held when video closes, and a stream that won't open closes the player instead of sitting on a frozen frame. Couldn't get the player to open twice by hand. --- theseus/desktop/guide.h | 5 ++++ theseus/desktop/joystick.cpp | 27 +++++++++++++++++++++ theseus/desktop/media_player.cpp | 6 +++++ theseus/desktop/media_ui.cpp | 40 +++++++++++++++++++++++++++----- theseus/desktop/sdl_main.cpp | 2 ++ 5 files changed, 74 insertions(+), 6 deletions(-) diff --git a/theseus/desktop/guide.h b/theseus/desktop/guide.h index bf6c4c9..d244d6d 100644 --- a/theseus/desktop/guide.h +++ b/theseus/desktop/guide.h @@ -15,6 +15,11 @@ enum { // Pad and keyboard as guide buttons. device becomes 1 for the pad, 0 for // the keyboard, and is left alone when nothing is held. unsigned Joy_GuideButtons(int* device); +// The pad alone (and the dev script) as guide buttons, for fullscreen video. +unsigned Joy_PadButtons(); +// The scene's next poll only records what's held, so a button or key still +// down when fullscreen video closes doesn't land in the menu underneath. +void Joy_Rebaseline(); extern bool g_guideRequested; // set by the Guide button, LT+B or F7 extern bool g_welcomeDone; // desktop.ini WelcomeDone diff --git a/theseus/desktop/joystick.cpp b/theseus/desktop/joystick.cpp index 3ad42ef..f496a2b 100755 --- a/theseus/desktop/joystick.cpp +++ b/theseus/desktop/joystick.cpp @@ -714,6 +714,33 @@ unsigned Joy_GuideButtons(int* device) return bits | keys; } +unsigned Joy_PadButtons() +{ + JoySnapshot pad; + memset(&pad, 0, sizeof(pad)); + ReadPad(CJoystick::c_controller, false, &pad); + DevPadScript(&pad); + unsigned bits = 0; + if (pad.analogDown[0]) bits |= GUIDE_A; + if (pad.analogDown[1]) bits |= GUIDE_B; + if (pad.analogDown[2]) bits |= GUIDE_X; + if (pad.analogDown[3]) bits |= GUIDE_Y; + if (pad.analogDown[5]) bits |= GUIDE_LB; + if (pad.analogDown[4]) bits |= GUIDE_RB; + if (pad.digitalDown[0] || pad.thumbLY > 0.5f) bits |= GUIDE_UP; + if (pad.digitalDown[1] || pad.thumbLY < -0.5f) bits |= GUIDE_DOWN; + if (pad.digitalDown[2] || pad.thumbLX < -0.5f) bits |= GUIDE_LEFT; + if (pad.digitalDown[3] || pad.thumbLX > 0.5f) bits |= GUIDE_RIGHT; + if (pad.digitalDown[4]) bits |= GUIDE_START; + if (pad.digitalDown[5]) bits |= GUIDE_BACK; + return bits; +} + +void Joy_Rebaseline() +{ + if (CJoystick::c_pActivePad) CJoystick::c_pActivePad->m_bFirstPoll = true; +} + // ============================================================================ // Media Keys (DVD player controls mapped to keyboard) // ============================================================================ diff --git a/theseus/desktop/media_player.cpp b/theseus/desktop/media_player.cpp index 587f7ab..c108b8d 100644 --- a/theseus/desktop/media_player.cpp +++ b/theseus/desktop/media_player.cpp @@ -407,6 +407,12 @@ void MediaPlayer_Update() { if (ef && ef->reason == MPV_END_FILE_REASON_EOF) { s_state = MP_STOPPED; } + // A stream that won't open would otherwise sit on a black + // screen forever. + if (ef && ef->reason == MPV_END_FILE_REASON_ERROR) { + fprintf(stderr, "[MediaPlayer] couldn't play it: %s\n", mpv_error_string(ef->error)); + s_state = MP_STOPPED; + } break; } case MPV_EVENT_FILE_LOADED: diff --git a/theseus/desktop/media_ui.cpp b/theseus/desktop/media_ui.cpp index e751315..1a2773a 100644 --- a/theseus/desktop/media_ui.cpp +++ b/theseus/desktop/media_ui.cpp @@ -10,6 +10,7 @@ #include "audio_sdl.h" #include "imgui.h" #include "playlist.h" +#include "guide.h" #include "d3d8_sdl.h" // for g_bgfxProgBlit / g_bgfxSamplerBlit on bgfx path #include @@ -106,6 +107,29 @@ void MediaUI_PlaylistPrev() { bool MediaUI_PlaylistActive() { return s_queueIdx >= 0 && !s_queue.empty(); } +// The scene is frozen while video is up, so the pad is read here: B or Back +// stops, A or Start pauses, left and right seek, LB and RB step a playlist. +void MediaUI_PadFrame() +{ + static unsigned s_prev = ~0u; + if (!g_mediaFullscreen) { s_prev = ~0u; return; } + // Show the title for a moment as playback starts. + if (s_prev == ~0u) MediaUI_NoteActivity(); + unsigned pad = Joy_PadButtons(); + // The A that started playback is usually still held on the first frame. + unsigned pressed = (s_prev == ~0u) ? 0 : (pad & ~s_prev); + s_prev = pad; + if (!pressed) return; + MediaUI_NoteActivity(); + extern void MediaUI_StopFullscreen(); + if (pressed & (GUIDE_B | GUIDE_BACK)) { MediaUI_StopFullscreen(); return; } + if (pressed & (GUIDE_A | GUIDE_START)) MediaPlayer_TogglePause(); + if (pressed & GUIDE_LEFT) MediaPlayer_SeekRelative(-10.0); + if (pressed & GUIDE_RIGHT) MediaPlayer_SeekRelative(10.0); + if (pressed & GUIDE_LB) MediaUI_PlaylistPrev(); + if (pressed & GUIDE_RB) MediaUI_PlaylistNext(); +} + // 0.0 = hidden, 1.0 = fully visible. Smoothly fades. static float OsdAlpha() { @@ -153,12 +177,6 @@ void MediaUI_DrawFullscreenVideo() // through outside the aspect-fit rect. (void)boundFBO; - int vw = 0, vh = 0; - unsigned int texIdx = MediaPlayer_GetVideoTexture(&vw, &vh); - if (!bgfx::isValid(g_bgfxProgBlit) || texIdx == 0 || vw <= 0 || vh <= 0) return; - bgfx::TextureHandle vidTex; vidTex.idx = (uint16_t)texIdx; - if (!bgfx::isValid(vidTex)) return; - int dw = (ww > 0) ? ww : 1; int dh = (wh > 0) ? wh : 1; @@ -169,6 +187,14 @@ void MediaUI_DrawFullscreenVideo() if (pw <= 0 || ph <= 0) { pw = dw; ph = dh; } bgfx::setViewRect(0, 0, 0, (uint16_t)pw, (uint16_t)ph); bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x000000ff, 1.0f, 0); + // Black until the first frame decodes, not the menu frozen underneath. + bgfx::touch(0); + + int vw = 0, vh = 0; + unsigned int texIdx = MediaPlayer_GetVideoTexture(&vw, &vh); + if (!bgfx::isValid(g_bgfxProgBlit) || texIdx == 0 || vw <= 0 || vh <= 0) return; + bgfx::TextureHandle vidTex; vidTex.idx = (uint16_t)texIdx; + if (!bgfx::isValid(vidTex)) return; float qw, qh; Bgfx_AspectFitNDC(vw, vh, dw, dh, qw, qh); @@ -434,4 +460,6 @@ void MediaUI_StopFullscreen() SDL_ShowCursor(SDL_ENABLE); s_cursorVisible = true; } + // Whatever closed the video (Esc, B) is still held as the menu wakes up. + Joy_Rebaseline(); } diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index 98959a4..075ed7c 100644 --- a/theseus/desktop/sdl_main.cpp +++ b/theseus/desktop/sdl_main.cpp @@ -1729,6 +1729,8 @@ int main(int argc, char* argv[]) { } Guide_Frame(); + extern void MediaUI_PadFrame(); + MediaUI_PadFrame(); if (!g_mediaFullscreen && !g_xcloudFullscreen) { FramePhaseScope advance(FP_ADVANCE); From 39a8450157d438d19be391e70b519561a8823945 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:00:17 -0500 Subject: [PATCH 23/46] Let Jellyfin and Plex open folders instead of trying to play them A library made of folders (the Jellyfin demo's Movies is two) tried to stream the folder itself, so nothing in it could be reached. Folders, box sets, albums and playlists now open in place, B steps back out to the row you came from, and the header names the folder. Music plays through Jellyfin's audio stream. The Plex side (artists, albums, collections) needs a test on a real server. --- Data/Xips/default.xip | Bin 1688892 -> 1689674 bytes theseus/desktop/desktop_nodes.cpp | 124 +++++++++++++++++++++-- theseus/desktop/jellyfin_client.cpp | 34 ++++++- theseus/desktop/jellyfin_client.h | 7 +- theseus/desktop/plex_client.cpp | 79 +++++++++++---- theseus/desktop/plex_client.h | 4 + xips-source/default-desktop/Jellyfin.xap | 24 ++++- xips-source/default-desktop/Plex.xap | 24 ++++- xips-source/jellyfin/jellyfin.xap | 24 ++++- xips-source/plex/plex.xap | 24 ++++- 10 files changed, 294 insertions(+), 50 deletions(-) diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index b0f59a4fe380bdd1beabc03ce1428bb2682c9f0c..5db99a0ca220ff26373974af15b2b83316656742 100644 GIT binary patch delta 736 zcmdnfm40eMI$wlmfWZMK1_n_e>^eG;@0*{P76TkSzbe9DfW#LEs_JZkOEWBJ5oKWD zU||3n00s+sBpITl5%Ry5HwQ7c2Qh*$6A&{4F$)m00x=s9vjZ^)5OV@C7Z7s;F%J;) z0x=&D^8>K}5DNma5D*J*4`LMQ*vjFRnv+wRmYFyG-ZqgeE}zWel90@joK%hNvD-y- z`K%QZ^HLPj@^eyBi;B7Q^%XRd@+%aIQ%j0<6cTfiN^^m9K~7?24p3jQrb2!}YMw%7 z9!MxTb$ZuPkvKMp-sx|Sil`{Lfz8p#^Gb6rEh^40(zNE{iylv;F>2 zk?qVvAa!AxspSf`whD%t3Tg@((+_SH5rdlIl3Gxbp`oc@r(mF|$;DZXY|`|=Eh1vP zKBGkhLM5o_=FT%+NaozND??hynf!?3K`jd#; z^!QIAtkZ!(AThn;y$BCTA=mcP??h%Ydurqb0G*8*CM6lEAVHtZq@u*4N#A$?C*I$wlmfWZMK1_n_etT{B1@0(wT1_K;KUJ+r~fW+tgE5gv(0+(i()F{fp zz`?=*Gyn`HbxJZsNh9RnENKp6Y!6}tVJ0AE24WTJLTurt@zXu@&`8%uUtE z^Gb6rEh^40a!O3jE-f(F9=2UXmv8#MqatzJ_Z|~j$2|T1NfGYp1zSZ}wi}-oxgg34 zF-!5Wi12jjha#ck5Mu&zQY%mms(L6A2sTJ#y50v7lj%Uy__qsu6j{$aUH6L!Z+rb$ T5g--?Vlf~V-(LS!;`Ai|jVfx6 diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index a65af21..543a115 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3396,6 +3396,15 @@ class CPlexLibrary : public CNode int m_currentShow; int m_currentSeason; std::string m_serverUri; + // Artists, albums and collections opened inside the library, innermost + // last, with the row to put the cursor back on when B leaves each one. + struct Folder { std::string key, name; int cursor; }; + std::vector m_folders; + + static bool IsFolderType(const std::string& t) + { + return t == "artist" || t == "album" || t == "collection" || t == "playlist"; + } void EnsureLibrariesPending() { @@ -3428,6 +3437,7 @@ class CPlexLibrary : public CNode void SetCurrent(int i) { + m_folders.clear(); if (i == m_currentLib) return; m_currentLib = i; m_currentShow = -1; @@ -3448,13 +3458,50 @@ class CPlexLibrary : public CNode { std::vector libs = Plex_Cache_GetLibraries(); if (m_currentLib < 0 || m_currentLib >= (int)libs.size()) return {}; + if (!m_folders.empty()) { + std::vector kids; + Plex_Cache_GetChildren(m_folders.back().key, kids); + return kids; + } return Plex_Cache_GetItems(libs[m_currentLib].sectionKey); } + void DrillIntoFolder(int i) + { + std::vector items = CurrentItems(); + if (i < 0 || i >= (int)items.size() || !IsFolderType(items[i].type)) return; + m_folders.push_back({ items[i].ratingKey, items[i].title, i }); + m_currentShow = -1; + m_currentSeason = -1; + std::vector dummy; + (void)Plex_Cache_GetChildren(items[i].ratingKey, dummy); + } + + int GetFolderDepth() { return (int)m_folders.size(); } + + // Steps out of the innermost folder; the row it was opened from. + int LeaveFolder() + { + if (m_folders.empty()) return 0; + int cursor = m_folders.back().cursor; + m_folders.pop_back(); + m_currentShow = -1; + m_currentSeason = -1; + return cursor; + } + + // The library's name, or the folder's once one is open. + CStrObject* GetListTitle() + { + if (!m_folders.empty()) return new CStrObject(_T(m_folders.back().name.c_str())); + return GetName(m_currentLib); + } + CStrObject* GetItemType(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; + if (IsFolderType(items[i].type)) return new CStrObject(_T("folder")); return new CStrObject(_T(items[i].type.c_str())); } @@ -3607,7 +3654,7 @@ class CPlexLibrary : public CNode CStrObject* GetItemArtPath(int i) { std::vector items = CurrentItems(); - if (i < 0 || i >= (int)items.size()) return new CStrObject; + if (i < 0 || i >= (int)items.size()) return ArtOrLogo(""); return ArtOrLogo(items[i].ratingKey); } @@ -3627,9 +3674,9 @@ class CPlexLibrary : public CNode { std::vector seasons; std::string showKey = CurrentShowKey(); - if (showKey.empty()) return new CStrObject; + if (showKey.empty()) return ArtOrLogo(""); Plex_Cache_GetSeasons(showKey, seasons); - if (i < 0 || i >= (int)seasons.size()) return new CStrObject; + if (i < 0 || i >= (int)seasons.size()) return ArtOrLogo(""); return ArtOrLogo(seasons[i].ratingKey, showKey); } @@ -3649,9 +3696,9 @@ class CPlexLibrary : public CNode { std::vector eps; std::string seasonKey = CurrentSeasonKey(); - if (seasonKey.empty()) return new CStrObject; + if (seasonKey.empty()) return ArtOrLogo(""); Plex_Cache_GetEpisodes(seasonKey, eps); - if (i < 0 || i >= (int)eps.size()) return new CStrObject; + if (i < 0 || i >= (int)eps.size()) return ArtOrLogo(""); return ArtOrLogo(eps[i].ratingKey, seasonKey, CurrentShowKey()); } @@ -3844,6 +3891,10 @@ START_NODE_FUN(CPlexLibrary, CNode) NODE_FUN_VI(QueueEpisodeArt) NODE_FUN_SI(GetEpisodeArtPath) NODE_FUN_IV(IsSignedIn) + NODE_FUN_VI(DrillIntoFolder) + NODE_FUN_IV(GetFolderDepth) + NODE_FUN_IV(LeaveFolder) + NODE_FUN_SV(GetListTitle) END_NODE_FUN() @@ -3866,6 +3917,10 @@ class CJellyfinLibrary : public CNode int m_currentLib; int m_currentShow; int m_currentSeason; + // Folders opened inside the library, innermost last, with the row to + // put the cursor back on when B leaves each one. + struct Folder { std::string id, name; int cursor; }; + std::vector m_folders; void EnsureLibrariesPending() { @@ -3895,6 +3950,7 @@ class CJellyfinLibrary : public CNode void SetCurrent(int i) { + m_folders.clear(); if (i == m_currentLib) return; m_currentLib = i; m_currentShow = -1; @@ -3917,9 +3973,45 @@ class CJellyfinLibrary : public CNode { std::vector libs = Jellyfin_Cache_GetLibraries(); if (m_currentLib < 0 || m_currentLib >= (int)libs.size()) return {}; + if (!m_folders.empty()) { + std::vector kids; + Jellyfin_Cache_GetChildren(m_folders.back().id, kids); + return kids; + } return Jellyfin_Cache_GetItems(libs[m_currentLib].id); } + void DrillIntoFolder(int i) + { + std::vector items = CurrentItems(); + if (i < 0 || i >= (int)items.size() || !items[i].isFolder) return; + m_folders.push_back({ items[i].id, items[i].name, i }); + m_currentShow = -1; + m_currentSeason = -1; + std::vector dummy; + (void)Jellyfin_Cache_GetChildren(items[i].id, dummy); + } + + int GetFolderDepth() { return (int)m_folders.size(); } + + // Steps out of the innermost folder; the row it was opened from. + int LeaveFolder() + { + if (m_folders.empty()) return 0; + int cursor = m_folders.back().cursor; + m_folders.pop_back(); + m_currentShow = -1; + m_currentSeason = -1; + return cursor; + } + + // The library's name, or the folder's once one is open. + CStrObject* GetListTitle() + { + if (!m_folders.empty()) return new CStrObject(_T(m_folders.back().name.c_str())); + return GetName(m_currentLib); + } + int GetItemCount() { return (int)CurrentItems().size(); } CStrObject* GetItemTitle(int i) @@ -3940,6 +4032,7 @@ class CJellyfinLibrary : public CNode std::string t = items[i].type; if (t == "Series") return new CStrObject(_T("show")); if (t == "Movie") return new CStrObject(_T("movie")); + if (items[i].isFolder) return new CStrObject(_T("folder")); std::string lc = t; for (auto& c : lc) c = (char)tolower((unsigned char)c); return new CStrObject(_T(lc.c_str())); @@ -3974,7 +4067,7 @@ class CJellyfinLibrary : public CNode CStrObject* GetItemArtPath(int i) { std::vector items = CurrentItems(); - if (i < 0 || i >= (int)items.size()) return new CStrObject; + if (i < 0 || i >= (int)items.size()) return ArtOrLogo(""); return ArtOrLogo(items[i].id); } @@ -3999,7 +4092,7 @@ class CJellyfinLibrary : public CNode const std::string& title, const std::string& subtitle) { - std::string url = Jellyfin_StreamUrl(itemId); + std::string url = Jellyfin_StreamUrl(itemId, m_playAudio); if (url.empty()) { fprintf(stderr, "[Jellyfin] stream URL build failed for %s\n", itemId.c_str()); return; @@ -4022,11 +4115,15 @@ class CJellyfinLibrary : public CNode g_mediaFullscreenSubtitle[sizeof(g_mediaFullscreenSubtitle) - 1] = 0; } + bool m_playAudio = false; + void PlayItem(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return; const JellyfinItem& it = items[i]; + if (it.isFolder) return; + m_playAudio = (it.type == "Audio"); std::string sub = "Jellyfin"; if (!it.year.empty()) { sub += " \xE2\x80\xA2 "; sub += it.year; } PlayRatingKey(it.id, it.name, sub); @@ -4091,9 +4188,9 @@ class CJellyfinLibrary : public CNode { std::vector seasons; std::string showId = CurrentShowId(); - if (showId.empty()) return new CStrObject; + if (showId.empty()) return ArtOrLogo(""); Jellyfin_Cache_GetSeasons(showId, seasons); - if (i < 0 || i >= (int)seasons.size()) return new CStrObject; + if (i < 0 || i >= (int)seasons.size()) return ArtOrLogo(""); return ArtOrLogo(seasons[i].id, showId); } @@ -4128,6 +4225,7 @@ class CJellyfinLibrary : public CNode Jellyfin_Cache_GetEpisodes(seasonId, eps); if (i < 0 || i >= (int)eps.size()) return; const JellyfinEpisode& e = eps[i]; + m_playAudio = false; std::vector items = CurrentItems(); std::vector seasons; std::string showId = CurrentShowId(); @@ -4159,9 +4257,9 @@ class CJellyfinLibrary : public CNode { std::vector eps; std::string seasonId = CurrentSeasonId(); - if (seasonId.empty()) return new CStrObject; + if (seasonId.empty()) return ArtOrLogo(""); Jellyfin_Cache_GetEpisodes(seasonId, eps); - if (i < 0 || i >= (int)eps.size()) return new CStrObject; + if (i < 0 || i >= (int)eps.size()) return ArtOrLogo(""); return ArtOrLogo(eps[i].id, seasonId, CurrentShowId()); } @@ -4315,6 +4413,10 @@ START_NODE_FUN(CJellyfinLibrary, CNode) NODE_FUN_VI(QueueEpisodeArt) NODE_FUN_SI(GetEpisodeArtPath) NODE_FUN_IV(IsSignedIn) + NODE_FUN_VI(DrillIntoFolder) + NODE_FUN_IV(GetFolderDepth) + NODE_FUN_IV(LeaveFolder) + NODE_FUN_SV(GetListTitle) END_NODE_FUN() diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index 39e7447..dd8077e 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -93,6 +93,8 @@ static std::vector s_cacheLibs; static std::map> s_cacheItems; static std::map> s_cacheSeasons; static std::map> s_cacheEpisodes; +static std::map> s_cacheChildren; +static std::map s_childrenBusy; // ---------- Art download queue ---------- static std::mutex s_artMtx; @@ -141,6 +143,7 @@ void Jellyfin_SignOut() s_cacheItems.clear(); s_cacheSeasons.clear(); s_cacheEpisodes.clear(); + s_cacheChildren.clear(); s_syncGen++; s_syncReady = false; s_syncProgress = 0; @@ -318,6 +321,7 @@ static JellyfinItem ParseItem(const std::string& obj) it.overview = Json_GetString(obj, "Overview"); it.type = Json_GetString(obj, "Type"); it.primaryTag = ParsePrimaryTag(obj); + it.isFolder = Json_GetBool(obj, "IsFolder"); int y = Json_GetInt(obj, "ProductionYear"); if (y > 0) { char buf[8]; snprintf(buf, sizeof(buf), "%d", y); @@ -553,6 +557,32 @@ bool Jellyfin_Cache_GetEpisodes(const std::string& seasonId, } +// ============================================================================ +// Folder contents (lazy, in the background) +// ============================================================================ + +static void ChildrenWorker(unsigned gen, std::string parentId) +{ + std::vector items = FetchItemsForLibrary(parentId); + std::lock_guard lk(g_mtx); + if (gen == s_syncGen) s_cacheChildren[parentId] = std::move(items); + s_childrenBusy.erase(parentId); +} + +bool Jellyfin_Cache_GetChildren(const std::string& parentId, std::vector& out) +{ + if (parentId.empty()) return false; + std::lock_guard lk(g_mtx); + auto it = s_cacheChildren.find(parentId); + if (it != s_cacheChildren.end()) { out = it->second; return true; } + if (!s_childrenBusy.count(parentId)) { + s_childrenBusy[parentId] = true; + std::thread(ChildrenWorker, (unsigned)s_syncGen, parentId).detach(); + } + return false; +} + + // ============================================================================ // Stream URL // ============================================================================ @@ -564,11 +594,11 @@ static std::string Base() return u; } -std::string Jellyfin_StreamUrl(const std::string& itemId) +std::string Jellyfin_StreamUrl(const std::string& itemId, bool audio) { if (itemId.empty() || g_jellyfinUrl[0] == 0 || g_jellyfinToken[0] == 0) return ""; std::string out = Base(); - out += "/Videos/"; + out += audio ? "/Audio/" : "/Videos/"; out += itemId; out += "/stream?Static=true&api_key="; out += g_jellyfinToken; diff --git a/theseus/desktop/jellyfin_client.h b/theseus/desktop/jellyfin_client.h index aa38cd9..d4b15a5 100644 --- a/theseus/desktop/jellyfin_client.h +++ b/theseus/desktop/jellyfin_client.h @@ -18,6 +18,7 @@ struct JellyfinItem { std::string overview; // plot std::string type; // "Movie" | "Series" | "Audio" | ... std::string primaryTag; // image tag for Primary image URL + bool isFolder = false; // opens to more items (folders, box sets, albums) }; struct JellyfinSeason { @@ -68,8 +69,12 @@ std::vector Jellyfin_Cache_GetItems(const std::string& libraryI bool Jellyfin_Cache_GetSeasons (const std::string& showId, std::vector& out); bool Jellyfin_Cache_GetEpisodes(const std::string& seasonId, std::vector& out); +// Items inside a folder, box set, album or playlist. Fetched in the +// background on first ask: false until they land. +bool Jellyfin_Cache_GetChildren(const std::string& parentId, std::vector& out); + // Direct-play URL with api_key. Empty on failure. -std::string Jellyfin_StreamUrl(const std::string& itemId); +std::string Jellyfin_StreamUrl(const std::string& itemId, bool audio = false); // Cover art. Same E:\Jellyfin\.jpg trick as Plex. std::string Jellyfin_ArtCachePath(const std::string& itemId); diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index 5baa0ad..6756539 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -89,6 +89,8 @@ static std::vector s_cacheLibs; static std::map> s_cacheItems; // sectionKey -> items static std::map> s_cacheSeasons; // showRk -> seasons static std::map> s_cacheEpisodes; // seasonRk -> episodes +static std::map> s_cacheChildren; // rk -> items inside it +static std::map s_childrenBusy; // ============================================================================ @@ -133,6 +135,7 @@ void Plex_SignOut() s_cacheItems.clear(); s_cacheSeasons.clear(); s_cacheEpisodes.clear(); + s_cacheChildren.clear(); s_syncGen++; s_syncReady = false; s_syncProgress = 0; @@ -326,6 +329,61 @@ static std::string BuildAssetUrl(const std::string& serverUri, return out; } +static PlexItem ParseItem(const std::string& obj, const std::string& serverUri) +{ + PlexItem it; + it.ratingKey = Json_GetString(obj, "ratingKey"); + it.title = Json_GetString(obj, "title"); + int y = Json_GetInt(obj, "year"); + if (y > 0) { + char ybuf[8]; snprintf(ybuf, sizeof(ybuf), "%d", y); + it.year = ybuf; + } + it.summary = Json_GetString(obj, "summary"); + it.thumbUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "thumb")); + it.artUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "art")); + it.type = Json_GetString(obj, "type"); + return it; +} + +static std::vector ParseItems(const std::string& body, const std::string& serverUri) +{ + std::vector items; + size_t mArr = Json_FindArray(body, "Metadata"); + if (mArr == std::string::npos) return items; + for (const auto& obj : Json_SplitArray(body, mArr)) { + PlexItem it = ParseItem(obj, serverUri); + if (!it.ratingKey.empty()) items.push_back(it); + } + return items; +} + +static void ChildrenWorker(unsigned gen, std::string serverUri, std::string rk) +{ + HttpResponse r = Http_Get(serverUri + "/library/metadata/" + rk + "/children", + PlexHeaders(true, true)); + std::vector items; + if (r.ok()) items = ParseItems(r.body, serverUri); + else fprintf(stderr, "[Plex] children fetch failed for %s (status %ld)\n", rk.c_str(), r.status); + std::lock_guard lk(g_mtx); + if (gen == s_syncGen) s_cacheChildren[rk] = std::move(items); + s_childrenBusy.erase(rk); +} + +bool Plex_Cache_GetChildren(const std::string& ratingKey, std::vector& out) +{ + if (ratingKey.empty()) return false; + std::string uri = Plex_GetActiveServerUri(); + std::lock_guard lk(g_mtx); + auto it = s_cacheChildren.find(ratingKey); + if (it != s_cacheChildren.end()) { out = it->second; return true; } + if (!uri.empty() && !s_childrenBusy.count(ratingKey)) { + s_childrenBusy[ratingKey] = true; + std::thread(ChildrenWorker, (unsigned)s_syncGen, uri, ratingKey).detach(); + } + return false; +} + // ============================================================================ // TV drill: /library/metadata/{rk}/children returns seasons or episodes. // ============================================================================ @@ -559,26 +617,7 @@ static void SyncWorker() std::string url = serverUri + "/library/sections/" + lib.sectionKey + "/all"; HttpResponse ir = Http_Get(url, PlexHeaders(true, true)); std::vector items; - if (ir.ok()) { - size_t mArr = Json_FindArray(ir.body, "Metadata"); - if (mArr != std::string::npos) { - for (const auto& obj : Json_SplitArray(ir.body, mArr)) { - PlexItem it; - it.ratingKey = Json_GetString(obj, "ratingKey"); - it.title = Json_GetString(obj, "title"); - int y = Json_GetInt(obj, "year"); - if (y > 0) { - char ybuf[8]; snprintf(ybuf, sizeof(ybuf), "%d", y); - it.year = ybuf; - } - it.summary = Json_GetString(obj, "summary"); - it.thumbUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "thumb")); - it.artUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "art")); - it.type = Json_GetString(obj, "type"); - if (!it.ratingKey.empty()) items.push_back(it); - } - } - } + if (ir.ok()) items = ParseItems(ir.body, serverUri); itemsByKey[lib.sectionKey] = std::move(items); } diff --git a/theseus/desktop/plex_client.h b/theseus/desktop/plex_client.h index b17a019..b06d581 100644 --- a/theseus/desktop/plex_client.h +++ b/theseus/desktop/plex_client.h @@ -86,6 +86,10 @@ bool Plex_Cache_GetSeasons(const std::string& showRatingKey, std::vector& out); bool Plex_Cache_GetEpisodes(const std::string& seasonRatingKey, std::vector& out); +// What's inside an artist, album or collection. Fetched in the background +// on first ask: false until it lands. +bool Plex_Cache_GetChildren(const std::string& ratingKey, + std::vector& out); // Cover art. Cache path is Xbox-style (E:\Plex\.jpg); xboxfs routes // it to Library/Plex/ for the texture loader. diff --git a/xips-source/default-desktop/Jellyfin.xap b/xips-source/default-desktop/Jellyfin.xap index de0775b..1f32625 100644 --- a/xips-source/default-desktop/Jellyfin.xap +++ b/xips-source/default-desktop/Jellyfin.xap @@ -64,11 +64,11 @@ function GetHeaderText() { var server = theJellyfinLibrary.GetServerName(); if (server == "") - server = "PLEX"; + server = "Jellyfin"; if (nJfView == 0) return server; if (nJfView == 1) - return server + " / " + theJellyfinLibrary.GetName(nJfCursorBackup0); + return server + " / " + theJellyfinLibrary.GetListTitle(); var showTitle = theJellyfinLibrary.GetItemTitle(nJfCursorBackup1); if (nJfView == 2) return showTitle; @@ -206,11 +206,20 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +// Movies/tracks play immediately; TV shows drill into seasons and folders +// (box sets, albums, playlists) open in place. function EnterItem() { var type = theJellyfinLibrary.GetItemType(nJfCursor); - if (type == "show") + if (type == "folder") + { + theJellyfinLibrary.DrillIntoFolder(nJfCursor); + nJfCursor = 0; + nJfScroll = 0; + BindActiveList(); + UpdateJellyfinList(); + } + else if (type == "show") { theJellyfinLibrary.DrillIntoShow(nJfCursor); nJfCursorBackup1 = nJfCursor; @@ -264,6 +273,13 @@ function GoBackOne() BindActiveList(); UpdateJellyfinList(); } + else if ((nJfView == 1) & (theJellyfinLibrary.GetFolderDepth() > 0)) + { + nJfCursor = theJellyfinLibrary.LeaveFolder(); + nJfScroll = 0; + BindActiveList(); + UpdateJellyfinList(); + } else if (nJfView == 1) { nJfView = 0; diff --git a/xips-source/default-desktop/Plex.xap b/xips-source/default-desktop/Plex.xap index 02cdef7..7c10b5e 100644 --- a/xips-source/default-desktop/Plex.xap +++ b/xips-source/default-desktop/Plex.xap @@ -64,11 +64,11 @@ function GetHeaderText() { var server = thePlexLibrary.GetServerName(); if (server == "") - server = "PLEX"; + server = "Plex"; if (nPlexView == 0) return server; if (nPlexView == 1) - return server + " / " + thePlexLibrary.GetName(nPlexCursorBackup0); + return server + " / " + thePlexLibrary.GetListTitle(); var showTitle = thePlexLibrary.GetItemTitle(nPlexCursorBackup1); if (nPlexView == 2) return showTitle; @@ -206,11 +206,20 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +// Movies/tracks play immediately; TV shows drill into seasons and folders +// (box sets, albums, playlists) open in place. function EnterItem() { var type = thePlexLibrary.GetItemType(nPlexCursor); - if (type == "show") + if (type == "folder") + { + thePlexLibrary.DrillIntoFolder(nPlexCursor); + nPlexCursor = 0; + nPlexScroll = 0; + BindActiveList(); + UpdatePlexList(); + } + else if (type == "show") { thePlexLibrary.DrillIntoShow(nPlexCursor); nPlexCursorBackup1 = nPlexCursor; @@ -264,6 +273,13 @@ function GoBackOne() BindActiveList(); UpdatePlexList(); } + else if ((nPlexView == 1) & (thePlexLibrary.GetFolderDepth() > 0)) + { + nPlexCursor = thePlexLibrary.LeaveFolder(); + nPlexScroll = 0; + BindActiveList(); + UpdatePlexList(); + } else if (nPlexView == 1) { nPlexView = 0; diff --git a/xips-source/jellyfin/jellyfin.xap b/xips-source/jellyfin/jellyfin.xap index de0775b..1f32625 100644 --- a/xips-source/jellyfin/jellyfin.xap +++ b/xips-source/jellyfin/jellyfin.xap @@ -64,11 +64,11 @@ function GetHeaderText() { var server = theJellyfinLibrary.GetServerName(); if (server == "") - server = "PLEX"; + server = "Jellyfin"; if (nJfView == 0) return server; if (nJfView == 1) - return server + " / " + theJellyfinLibrary.GetName(nJfCursorBackup0); + return server + " / " + theJellyfinLibrary.GetListTitle(); var showTitle = theJellyfinLibrary.GetItemTitle(nJfCursorBackup1); if (nJfView == 2) return showTitle; @@ -206,11 +206,20 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +// Movies/tracks play immediately; TV shows drill into seasons and folders +// (box sets, albums, playlists) open in place. function EnterItem() { var type = theJellyfinLibrary.GetItemType(nJfCursor); - if (type == "show") + if (type == "folder") + { + theJellyfinLibrary.DrillIntoFolder(nJfCursor); + nJfCursor = 0; + nJfScroll = 0; + BindActiveList(); + UpdateJellyfinList(); + } + else if (type == "show") { theJellyfinLibrary.DrillIntoShow(nJfCursor); nJfCursorBackup1 = nJfCursor; @@ -264,6 +273,13 @@ function GoBackOne() BindActiveList(); UpdateJellyfinList(); } + else if ((nJfView == 1) & (theJellyfinLibrary.GetFolderDepth() > 0)) + { + nJfCursor = theJellyfinLibrary.LeaveFolder(); + nJfScroll = 0; + BindActiveList(); + UpdateJellyfinList(); + } else if (nJfView == 1) { nJfView = 0; diff --git a/xips-source/plex/plex.xap b/xips-source/plex/plex.xap index 02cdef7..7c10b5e 100644 --- a/xips-source/plex/plex.xap +++ b/xips-source/plex/plex.xap @@ -64,11 +64,11 @@ function GetHeaderText() { var server = thePlexLibrary.GetServerName(); if (server == "") - server = "PLEX"; + server = "Plex"; if (nPlexView == 0) return server; if (nPlexView == 1) - return server + " / " + thePlexLibrary.GetName(nPlexCursorBackup0); + return server + " / " + thePlexLibrary.GetListTitle(); var showTitle = thePlexLibrary.GetItemTitle(nPlexCursorBackup1); if (nPlexView == 2) return showTitle; @@ -206,11 +206,20 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +// Movies/tracks play immediately; TV shows drill into seasons and folders +// (box sets, albums, playlists) open in place. function EnterItem() { var type = thePlexLibrary.GetItemType(nPlexCursor); - if (type == "show") + if (type == "folder") + { + thePlexLibrary.DrillIntoFolder(nPlexCursor); + nPlexCursor = 0; + nPlexScroll = 0; + BindActiveList(); + UpdatePlexList(); + } + else if (type == "show") { thePlexLibrary.DrillIntoShow(nPlexCursor); nPlexCursorBackup1 = nPlexCursor; @@ -264,6 +273,13 @@ function GoBackOne() BindActiveList(); UpdatePlexList(); } + else if ((nPlexView == 1) & (thePlexLibrary.GetFolderDepth() > 0)) + { + nPlexCursor = thePlexLibrary.LeaveFolder(); + nPlexScroll = 0; + BindActiveList(); + UpdatePlexList(); + } else if (nPlexView == 1) { nPlexView = 0; From caa2b64fdeb6b409142cc5b316c4fea23bc1eda4 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:02:06 -0500 Subject: [PATCH 24/46] =?UTF-8?q?Episode=20rows=20read=20S1E05=20=C2=B7=20?= =?UTF-8?q?Title=20in=20Jellyfin=20and=20Plex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit They were a bare 5. Title. The player's subtitle uses the same code now, and the separators there are a middle dot because the player's font has no bullet and showed a question mark. --- theseus/desktop/desktop_nodes.cpp | 62 +++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index 543a115..7f7b3e8 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3382,6 +3382,15 @@ END_NODE_FUN() #include "plex_client.h" +// "S2E05 ยท Title" for an episode row. No number, just the title. +static std::string EpisodeCode(const std::string& season, const std::string& episode) +{ + if (episode.empty()) return ""; + char buf[32]; + snprintf(buf, sizeof(buf), "S%sE%02d", season.empty() ? "?" : season.c_str(), atoi(episode.c_str())); + return buf; +} + class CPlexLibrary : public CNode { public: @@ -3517,7 +3526,7 @@ class CPlexLibrary : public CNode const PlexItem& it = items[i]; s = it.type; for (auto& c : s) c = (char)toupper((unsigned char)c); - if (!it.year.empty()) { s += " \xE2\x80\xA2 "; s += it.year; } + if (!it.year.empty()) { s += " \xC2\xB7 "; s += it.year; } return new CStrObject(_T(s.c_str())); } if (view == 2) { @@ -3739,7 +3748,7 @@ class CPlexLibrary : public CNode if (i < 0 || i >= (int)items.size()) return; const PlexItem& it = items[i]; std::string sub = "Plex"; - if (!it.year.empty()) { sub += " โ€ข "; sub += it.year; } + if (!it.year.empty()) { sub += " \xC2\xB7 "; sub += it.year; } PlayRatingKey(it.ratingKey, it.title, sub); } @@ -3805,6 +3814,17 @@ class CPlexLibrary : public CNode (void)Plex_Cache_GetEpisodes(seasons[i].ratingKey, dummy); } + std::string EpisodeLabel(const std::string& index, const std::string& title) + { + std::vector seasons; + Plex_Cache_GetSeasons(CurrentShowKey(), seasons); + std::string season; + if (m_currentSeason >= 0 && m_currentSeason < (int)seasons.size()) + season = seasons[m_currentSeason].index; + std::string code = EpisodeCode(season, index); + return code.empty() ? title : code + " \xC2\xB7 " + title; + } + int GetEpisodeCount() { std::vector eps; @@ -3821,11 +3841,7 @@ class CPlexLibrary : public CNode if (seasonKey.empty()) return new CStrObject; Plex_Cache_GetEpisodes(seasonKey, eps); if (i < 0 || i >= (int)eps.size()) return new CStrObject; - const PlexEpisode& e = eps[i]; - std::string s; - if (!e.index.empty()) { s += e.index; s += ". "; } - s += e.title; - return new CStrObject(_T(s.c_str())); + return new CStrObject(_T(EpisodeLabel(eps[i].index, eps[i].title).c_str())); } void PlayEpisode(int i) @@ -3844,9 +3860,8 @@ class CPlexLibrary : public CNode if (m_currentShow >= 0 && m_currentShow < (int)items.size()) sub = items[m_currentShow].title; if (m_currentSeason >= 0 && m_currentSeason < (int)seasons.size()) { - sub += " โ€ข S"; - sub += seasons[m_currentSeason].index; - if (!e.index.empty()) { sub += "E"; sub += e.index; } + std::string code = EpisodeCode(seasons[m_currentSeason].index, e.index); + if (!code.empty()) { sub += " \xC2\xB7 "; sub += code; } } PlayRatingKey(e.ratingKey, e.title, sub); } @@ -4125,7 +4140,7 @@ class CJellyfinLibrary : public CNode if (it.isFolder) return; m_playAudio = (it.type == "Audio"); std::string sub = "Jellyfin"; - if (!it.year.empty()) { sub += " \xE2\x80\xA2 "; sub += it.year; } + if (!it.year.empty()) { sub += " \xC2\xB7 "; sub += it.year; } PlayRatingKey(it.id, it.name, sub); } @@ -4194,6 +4209,18 @@ class CJellyfinLibrary : public CNode return ArtOrLogo(seasons[i].id, showId); } + std::string EpisodeLabel(const std::string& index, const std::string& title) + { + std::vector seasons; + std::string showId = CurrentShowId(); + if (!showId.empty()) Jellyfin_Cache_GetSeasons(showId, seasons); + std::string season; + if (m_currentSeason >= 0 && m_currentSeason < (int)seasons.size()) + season = seasons[m_currentSeason].index; + std::string code = EpisodeCode(season, index); + return code.empty() ? title : code + " \xC2\xB7 " + title; + } + int GetEpisodeCount() { std::vector eps; @@ -4210,11 +4237,7 @@ class CJellyfinLibrary : public CNode if (seasonId.empty()) return new CStrObject; Jellyfin_Cache_GetEpisodes(seasonId, eps); if (i < 0 || i >= (int)eps.size()) return new CStrObject; - const JellyfinEpisode& e = eps[i]; - std::string s; - if (!e.index.empty()) { s += e.index; s += ". "; } - s += e.name; - return new CStrObject(_T(s.c_str())); + return new CStrObject(_T(EpisodeLabel(eps[i].index, eps[i].name).c_str())); } void PlayEpisode(int i) @@ -4234,9 +4257,8 @@ class CJellyfinLibrary : public CNode if (m_currentShow >= 0 && m_currentShow < (int)items.size()) sub = items[m_currentShow].name; if (m_currentSeason >= 0 && m_currentSeason < (int)seasons.size()) { - sub += " \xE2\x80\xA2 S"; - sub += seasons[m_currentSeason].index; - if (!e.index.empty()) { sub += "E"; sub += e.index; } + std::string code = EpisodeCode(seasons[m_currentSeason].index, e.index); + if (!code.empty()) { sub += " \xC2\xB7 "; sub += code; } } PlayRatingKey(e.id, e.name, sub); } @@ -4274,7 +4296,7 @@ class CJellyfinLibrary : public CNode std::string t = it.type; for (auto& c : t) c = (char)toupper((unsigned char)c); s = t; - if (!it.year.empty()) { s += " \xE2\x80\xA2 "; s += it.year; } + if (!it.year.empty()) { s += " \xC2\xB7 "; s += it.year; } return new CStrObject(_T(s.c_str())); } if (view == 2) { From 5ade1b41f90383b4c926d713c6e5a17cab37c603 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:07:58 -0500 Subject: [PATCH 25/46] Filled out the Y info card in Jellyfin and Plex It only had the title, year and plot. It now shows runtime, rating, score, genres and where you left off (or how many episodes are left), then the plot. Plex reads the same facts off its own fields but hasn't been tried against a server. --- theseus/desktop/desktop_nodes.cpp | 148 +++++++++++++++++++++++----- theseus/desktop/jellyfin_client.cpp | 50 +++++++++- theseus/desktop/jellyfin_client.h | 17 +++- theseus/desktop/plex_client.cpp | 24 +++++ theseus/desktop/plex_client.h | 22 ++++- 5 files changed, 228 insertions(+), 33 deletions(-) diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index 7f7b3e8..06922d8 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3391,6 +3391,78 @@ static std::string EpisodeCode(const std::string& season, const std::string& epi return buf; } +// "1h 13m", "47m". +static std::string RunLength(long long seconds) +{ + if (seconds <= 0) return ""; + char buf[32]; + long long m = (seconds + 30) / 60; + if (m >= 60) snprintf(buf, sizeof(buf), "%lldh %02lldm", m / 60, m % 60); + else snprintf(buf, sizeof(buf), "%lldm", m < 1 ? 1 : m); + return buf; +} + +// "47:41", "1:02:03". +static std::string ClockTime(long long seconds) +{ + char buf[32]; + if (seconds >= 3600) snprintf(buf, sizeof(buf), "%lld:%02lld:%02lld", seconds / 3600, (seconds / 60) % 60, seconds % 60); + else snprintf(buf, sizeof(buf), "%lld:%02lld", seconds / 60, seconds % 60); + return buf; +} + +static void JoinDot(std::string& out, const std::string& part) +{ + if (part.empty()) return; + if (!out.empty()) out += " \xC2\xB7 "; + out += part; +} + +// "1931 ยท 1h 13m ยท NR ยท 7.2/10" for the info card. +static std::string FactsLine(const std::string& year, long long runSeconds, + const std::string& rating, float stars) +{ + std::string out; + JoinDot(out, year); + JoinDot(out, RunLength(runSeconds)); + JoinDot(out, rating); + if (stars > 0.0f) { + char buf[16]; snprintf(buf, sizeof(buf), "%.1f/10", stars); + JoinDot(out, buf); + } + return out; +} + +// "Watched", "Resume from 47:41 of 1:14:26", or nothing. +static std::string WatchLine(bool played, long long posSeconds, long long runSeconds) +{ + if (posSeconds > 0) { + std::string s = "Resume from " + ClockTime(posSeconds); + if (runSeconds > 0) s += " of " + ClockTime(runSeconds); + return s; + } + return played ? "Watched" : ""; +} + +static void AppendLine(std::string& body, const std::string& line) +{ + if (line.empty()) return; + if (!body.empty()) body += "\n"; + body += line; +} + +static std::string ClipInfo(std::string body) +{ + const size_t kMax = 1200; + if (body.size() > kMax) { + size_t n = kMax - 1; + while (n > 0 && ((unsigned char)body[n] & 0xC0) == 0x80) n--; + body.resize(n); + body += "\xE2\x80\xA6"; + } + return body; +} + class CPlexLibrary : public CNode { public: @@ -3552,7 +3624,8 @@ class CPlexLibrary : public CNode return new CStrObject; } - // Y-button modal text: title + full plot. Seasons inherit the show plot. + // Y: the info card. Title, the facts line, genres, where you left off, + // then the plot. Seasons show the show's plot. CStrObject* GetInfoText(int view, int i) { if (i < 0) return new CStrObject; @@ -3563,18 +3636,23 @@ class CPlexLibrary : public CNode if (i >= (int)items.size()) return new CStrObject; const PlexItem& it = items[i]; body = it.title; - if (!it.year.empty()) { body += " ("; body += it.year; body += ")"; } + AppendLine(body, FactsLine(it.year, it.durationMs / 1000, it.rating, it.stars)); + AppendLine(body, it.genres); + if (it.leafCount > 0) AppendLine(body, LeftLine(it)); + else AppendLine(body, WatchLine(it.Played(), it.offsetMs / 1000, it.durationMs / 1000)); if (!it.summary.empty()) { body += "\n\n"; body += it.summary; } } else if (view == 2) { - // Seasons have no summary. Surface the show's plot. std::vector items = CurrentItems(); if (m_currentShow < 0 || m_currentShow >= (int)items.size()) return new CStrObject; const PlexItem& sh = items[m_currentShow]; std::vector seasons; Plex_Cache_GetSeasons(CurrentShowKey(), seasons); body = sh.title; - if (i < (int)seasons.size()) { body += " - "; body += seasons[i].title; } + if (i < (int)seasons.size()) { body += " \xC2\xB7 "; body += seasons[i].title; } + AppendLine(body, FactsLine(sh.year, 0, sh.rating, sh.stars)); + AppendLine(body, sh.genres); + if (i < (int)seasons.size()) AppendLine(body, LeftLine(seasons[i])); if (!sh.summary.empty()) { body += "\n\n"; body += sh.summary; } } else if (view == 3) { @@ -3582,17 +3660,15 @@ class CPlexLibrary : public CNode Plex_Cache_GetEpisodes(CurrentSeasonKey(), eps); if (i >= (int)eps.size()) return new CStrObject; const PlexEpisode& e = eps[i]; - body = ""; - if (!e.index.empty()) { body += e.index; body += ". "; } - body += e.title; + body = EpisodeLabel(e.index, e.title); + std::vector items = CurrentItems(); + if (m_currentShow >= 0 && m_currentShow < (int)items.size()) + AppendLine(body, items[m_currentShow].title); + AppendLine(body, FactsLine("", e.durationMs / 1000, e.rating, e.stars)); + AppendLine(body, WatchLine(e.Played(), e.offsetMs / 1000, e.durationMs / 1000)); if (!e.summary.empty()) { body += "\n\n"; body += e.summary; } } - const size_t kMax = 1200; - if (body.size() > kMax) { - body.resize(kMax - 1); - body += "\xE2\x80\xA6"; - } - return new CStrObject(_T(body.c_str())); + return new CStrObject(_T(ClipInfo(body).c_str())); } // Truncated plot blurb for inline display. Items + episodes only. @@ -3814,6 +3890,13 @@ class CPlexLibrary : public CNode (void)Plex_Cache_GetEpisodes(seasons[i].ratingKey, dummy); } + static std::string LeftLine(const PlexDetails& d) + { + if (d.Played() || d.Unplayed() <= 0) return d.Played() ? "Watched" : ""; + char buf[48]; snprintf(buf, sizeof(buf), "%d episode%s left", d.Unplayed(), d.Unplayed() == 1 ? "" : "s"); + return buf; + } + std::string EpisodeLabel(const std::string& index, const std::string& title) { std::vector seasons; @@ -4209,6 +4292,8 @@ class CJellyfinLibrary : public CNode return ArtOrLogo(seasons[i].id, showId); } + static long long Secs(long long ticks) { return ticks / 10000000; } + std::string EpisodeLabel(const std::string& index, const std::string& title) { std::vector seasons; @@ -4353,6 +4438,8 @@ class CJellyfinLibrary : public CNode return new CStrObject(_T(s.c_str())); } + // Y: the info card. Title, the facts line, genres, where you left off, + // then the plot. Seasons show the show's plot. CStrObject* GetInfoText(int view, int i) { if (i < 0) return new CStrObject; @@ -4362,7 +4449,14 @@ class CJellyfinLibrary : public CNode if (i >= (int)items.size()) return new CStrObject; const JellyfinItem& it = items[i]; body = it.name; - if (!it.year.empty()) { body += " ("; body += it.year; body += ")"; } + AppendLine(body, FactsLine(it.year, Secs(it.runTicks), it.rating, it.stars)); + AppendLine(body, it.genres); + if (it.type == "Series" && it.unplayed > 0 && !it.played) { + char buf[48]; snprintf(buf, sizeof(buf), "%d episode%s left", it.unplayed, it.unplayed == 1 ? "" : "s"); + AppendLine(body, buf); + } else { + AppendLine(body, WatchLine(it.played, Secs(it.posTicks), Secs(it.runTicks))); + } if (!it.overview.empty()) { body += "\n\n"; body += it.overview; } } else if (view == 2) { @@ -4372,7 +4466,15 @@ class CJellyfinLibrary : public CNode std::vector seasons; Jellyfin_Cache_GetSeasons(sh.id, seasons); body = sh.name; - if (i < (int)seasons.size()) { body += " - "; body += seasons[i].name; } + if (i < (int)seasons.size()) { body += " \xC2\xB7 "; body += seasons[i].name; } + AppendLine(body, FactsLine(sh.year, 0, sh.rating, sh.stars)); + AppendLine(body, sh.genres); + if (i < (int)seasons.size() && seasons[i].unplayed > 0 && !seasons[i].played) { + char buf[48]; snprintf(buf, sizeof(buf), "%d episode%s left", seasons[i].unplayed, seasons[i].unplayed == 1 ? "" : "s"); + AppendLine(body, buf); + } else if (i < (int)seasons.size() && seasons[i].played) { + AppendLine(body, "Watched"); + } if (!sh.overview.empty()) { body += "\n\n"; body += sh.overview; } } else if (view == 3) { @@ -4382,17 +4484,15 @@ class CJellyfinLibrary : public CNode Jellyfin_Cache_GetEpisodes(seasonId, eps); if (i >= (int)eps.size()) return new CStrObject; const JellyfinEpisode& e = eps[i]; - body = ""; - if (!e.index.empty()) { body += e.index; body += ". "; } - body += e.name; + body = EpisodeLabel(e.index, e.name); + std::vector items = CurrentItems(); + if (m_currentShow >= 0 && m_currentShow < (int)items.size()) + AppendLine(body, items[m_currentShow].name); + AppendLine(body, FactsLine("", Secs(e.runTicks), e.rating, e.stars)); + AppendLine(body, WatchLine(e.played, Secs(e.posTicks), Secs(e.runTicks))); if (!e.overview.empty()) { body += "\n\n"; body += e.overview; } } - const size_t kMax = 1200; - if (body.size() > kMax) { - body.resize(kMax - 1); - body += "\xE2\x80\xA6"; - } - return new CStrObject(_T(body.c_str())); + return new CStrObject(_T(ClipInfo(body).c_str())); } int IsSignedIn() { return Jellyfin_HasToken() ? 1 : 0; } diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index dd8077e..63ac5b9 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -68,6 +68,47 @@ static std::string ParsePrimaryTag(const std::string& obj) } +static long long GetInt64(const std::string& obj, const char* key, size_t from = 0) +{ + size_t v = Json_FindKey(obj, key, from); + if (v == std::string::npos) return 0; + return strtoll(obj.c_str() + v, NULL, 10); +} + +// "Genres": ["Horror", "Thriller"] as "Horror, Thriller". +static std::string ParseGenres(const std::string& obj) +{ + size_t v = Json_FindKey(obj, "Genres"); + if (v == std::string::npos || v >= obj.size() || obj[v] != '[') return ""; + size_t end = obj.find(']', v); + if (end == std::string::npos) return ""; + std::string out; + int n = 0; + for (size_t p = obj.find('"', v); p < end && n < 3; p = obj.find('"', p + 1), n++) { + size_t q = obj.find('"', p + 1); + if (q == std::string::npos || q > end) break; + if (!out.empty()) out += ", "; + out.append(obj, p + 1, q - p - 1); + p = q; + } + return out; +} + +static void ParseDetails(const std::string& obj, JellyfinDetails& d) +{ + d.runTicks = GetInt64(obj, "RunTimeTicks"); + d.rating = Json_GetString(obj, "OfficialRating"); + d.stars = Json_GetFloat(obj, "CommunityRating"); + d.genres = ParseGenres(obj); + size_t ud = Json_FindKey(obj, "UserData"); + if (ud != std::string::npos) { + d.posTicks = GetInt64(obj, "PlaybackPositionTicks", ud); + d.played = Json_GetBool(obj, "Played", ud); + d.unplayed = Json_GetInt(obj, "UnplayedItemCount", ud); + } +} + + // ============================================================================ // State // ============================================================================ @@ -322,6 +363,7 @@ static JellyfinItem ParseItem(const std::string& obj) it.type = Json_GetString(obj, "Type"); it.primaryTag = ParsePrimaryTag(obj); it.isFolder = Json_GetBool(obj, "IsFolder"); + ParseDetails(obj, it); int y = Json_GetInt(obj, "ProductionYear"); if (y > 0) { char buf[8]; snprintf(buf, sizeof(buf), "%d", y); @@ -334,7 +376,7 @@ static std::vector FetchItemsForLibrary(const std::string& library { char url[1024]; snprintf(url, sizeof(url), - "%s/Users/%s/Items?ParentId=%s&Recursive=false&Fields=Overview,ProductionYear", + "%s/Users/%s/Items?ParentId=%s&Recursive=false&Fields=Overview,ProductionYear,Genres&EnableUserData=true", g_jellyfinUrl, g_jellyfinUserId, libraryId.c_str()); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); std::vector out; @@ -454,7 +496,7 @@ std::vector Jellyfin_Cache_GetItems(const std::string& libraryId) static std::vector FetchSeasonsForShow(const std::string& showId) { char url[1024]; - snprintf(url, sizeof(url), "%s/Shows/%s/Seasons?UserId=%s", + snprintf(url, sizeof(url), "%s/Shows/%s/Seasons?UserId=%s&EnableUserData=true", g_jellyfinUrl, showId.c_str(), g_jellyfinUserId); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); std::vector out; @@ -470,6 +512,7 @@ static std::vector FetchSeasonsForShow(const std::string& showId char buf[8]; snprintf(buf, sizeof(buf), "%d", idx); s.index = buf; s.primaryTag = ParsePrimaryTag(obj); + ParseDetails(obj, s); if (!s.id.empty()) out.push_back(s); } return out; @@ -480,7 +523,7 @@ static std::vector FetchEpisodesForSeason(const std::string& se { char url[1024]; snprintf(url, sizeof(url), - "%s/Shows/%s/Episodes?seasonId=%s&UserId=%s&Fields=Overview", + "%s/Shows/%s/Episodes?seasonId=%s&UserId=%s&Fields=Overview&EnableUserData=true", g_jellyfinUrl, showId.c_str(), seasonId.c_str(), g_jellyfinUserId); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); std::vector out; @@ -498,6 +541,7 @@ static std::vector FetchEpisodesForSeason(const std::string& se e.index = buf; } e.primaryTag = ParsePrimaryTag(obj); + ParseDetails(obj, e); if (!e.id.empty()) out.push_back(e); } return out; diff --git a/theseus/desktop/jellyfin_client.h b/theseus/desktop/jellyfin_client.h index d4b15a5..9186617 100644 --- a/theseus/desktop/jellyfin_client.h +++ b/theseus/desktop/jellyfin_client.h @@ -11,7 +11,18 @@ struct JellyfinLibrary { std::string type; // "movies" | "tvshows" | "music" | ... }; -struct JellyfinItem { +// Watch state and the facts the info card shows, common to items and episodes. +struct JellyfinDetails { + long long runTicks = 0; // length, 10,000,000 ticks a second + long long posTicks = 0; // resume point, 0 when not started + bool played = false; + int unplayed = 0; // episodes left, for a series + std::string rating; // "PG-13" + float stars = 0.0f; // community rating out of 10 + std::string genres; // "Horror, Thriller" +}; + +struct JellyfinItem : JellyfinDetails { std::string id; std::string name; std::string year; // optional, as string @@ -21,14 +32,14 @@ struct JellyfinItem { bool isFolder = false; // opens to more items (folders, box sets, albums) }; -struct JellyfinSeason { +struct JellyfinSeason : JellyfinDetails { std::string id; std::string name; // "Season 1" std::string index; // season number as string std::string primaryTag; }; -struct JellyfinEpisode { +struct JellyfinEpisode : JellyfinDetails { std::string id; std::string name; std::string index; // episode number as string diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index 6756539..9cd7f4a 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -329,9 +329,31 @@ static std::string BuildAssetUrl(const std::string& serverUri, return out; } +static void ParseDetails(const std::string& obj, PlexDetails& d) +{ + d.durationMs = Json_GetInt(obj, "duration"); + d.offsetMs = Json_GetInt(obj, "viewOffset"); + d.viewCount = Json_GetInt(obj, "viewCount"); + d.leafCount = Json_GetInt(obj, "leafCount"); + d.viewedLeafCount = Json_GetInt(obj, "viewedLeafCount"); + d.rating = Json_GetString(obj, "contentRating"); + d.stars = Json_GetFloat(obj, "audienceRating"); + if (d.stars <= 0.0f) d.stars = Json_GetFloat(obj, "rating"); + size_t g = Json_FindArray(obj, "Genre"); + if (g != std::string::npos) { + int n = 0; + for (const auto& tag : Json_SplitArray(obj, g)) { + if (n++ == 3) break; + if (!d.genres.empty()) d.genres += ", "; + d.genres += Json_GetString(tag, "tag"); + } + } +} + static PlexItem ParseItem(const std::string& obj, const std::string& serverUri) { PlexItem it; + ParseDetails(obj, it); it.ratingKey = Json_GetString(obj, "ratingKey"); it.title = Json_GetString(obj, "title"); int y = Json_GetInt(obj, "year"); @@ -406,6 +428,7 @@ static void SeasonsWorker(std::string serverUri, std::string showRk) char ibuf[8]; snprintf(ibuf, sizeof(ibuf), "%d", idx); s.index = ibuf; s.thumbUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "thumb")); + ParseDetails(obj, s); if (!s.ratingKey.empty()) seasons.push_back(s); } } @@ -449,6 +472,7 @@ static void EpisodesWorker(std::string serverUri, std::string seasonRk) } e.summary = Json_GetString(obj, "summary"); e.thumbUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "thumb")); + ParseDetails(obj, e); if (!e.ratingKey.empty()) episodes.push_back(e); } } diff --git a/theseus/desktop/plex_client.h b/theseus/desktop/plex_client.h index b06d581..966e275 100644 --- a/theseus/desktop/plex_client.h +++ b/theseus/desktop/plex_client.h @@ -17,7 +17,23 @@ struct PlexLibrary { std::string type; // "movie" | "show" | "artist" | "photo" }; -struct PlexItem { +// Watch state and the facts the info card shows, common to items, seasons +// and episodes. +struct PlexDetails { + int durationMs = 0; + int offsetMs = 0; // resume point, 0 when not started + int viewCount = 0; + int leafCount = 0; // episodes, for a show or season + int viewedLeafCount = 0; + std::string rating; // contentRating, "PG-13" + float stars = 0.0f; // out of 10 + std::string genres; // "Horror, Thriller" + + bool Played() const { return leafCount > 0 ? viewedLeafCount >= leafCount : viewCount > 0; } + int Unplayed() const { return leafCount > viewedLeafCount ? leafCount - viewedLeafCount : 0; } +}; + +struct PlexItem : PlexDetails { std::string ratingKey; // numeric id, identifies the item std::string title; std::string year; // optional, as string @@ -27,14 +43,14 @@ struct PlexItem { std::string type; // "movie" | "show" | "track" | "artist" | ... }; -struct PlexSeason { +struct PlexSeason : PlexDetails { std::string ratingKey; std::string title; // "Season 1" std::string index; // season number as string std::string thumbUrl; }; -struct PlexEpisode { +struct PlexEpisode : PlexDetails { std::string ratingKey; std::string title; std::string index; // episode number as string From f67482baa31e8cb7c048b857ba88909f83c5ba1f Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:10:48 -0500 Subject: [PATCH 26/46] Marked watched and half watched rows in Jellyfin and Plex Rows now start with a check once watched and a chevron when there's a resume point, for movies, shows, seasons and episodes. Plex reads viewCount and viewOffset for the same marks, untested on a real server. --- theseus/desktop/desktop_nodes.cpp | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index 06922d8..7d75eba 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3444,6 +3444,14 @@ static std::string WatchLine(bool played, long long posSeconds, long long runSec return played ? "Watched" : ""; } +// Row prefix: a check once watched, a chevron while part watched. +static std::string WatchMark(bool played, long long posSeconds, long long runSeconds) +{ + (void)runSeconds; + if (posSeconds > 0) return "\xC2\xBB "; + return played ? "\xE2\x88\x9A " : ""; +} + static void AppendLine(std::string& body, const std::string& line) { if (line.empty()) return; @@ -3705,6 +3713,7 @@ class CPlexLibrary : public CNode const PlexItem& it = items[i]; std::string s = it.title; if (!it.year.empty()) { s += " ("; s += it.year; s += ")"; } + if (!IsFolderType(it.type)) s = Mark(it) + s; return new CStrObject(_T(s.c_str())); } @@ -3875,7 +3884,7 @@ class CPlexLibrary : public CNode if (showKey.empty()) return new CStrObject; Plex_Cache_GetSeasons(showKey, seasons); if (i < 0 || i >= (int)seasons.size()) return new CStrObject; - return new CStrObject(_T(seasons[i].title.c_str())); + return new CStrObject(_T((Mark(seasons[i]) + seasons[i].title).c_str())); } void DrillIntoSeason(int i) @@ -3890,6 +3899,8 @@ class CPlexLibrary : public CNode (void)Plex_Cache_GetEpisodes(seasons[i].ratingKey, dummy); } + static std::string Mark(const PlexDetails& d) { return WatchMark(d.Played(), d.offsetMs / 1000, d.durationMs / 1000); } + static std::string LeftLine(const PlexDetails& d) { if (d.Played() || d.Unplayed() <= 0) return d.Played() ? "Watched" : ""; @@ -3924,7 +3935,7 @@ class CPlexLibrary : public CNode if (seasonKey.empty()) return new CStrObject; Plex_Cache_GetEpisodes(seasonKey, eps); if (i < 0 || i >= (int)eps.size()) return new CStrObject; - return new CStrObject(_T(EpisodeLabel(eps[i].index, eps[i].title).c_str())); + return new CStrObject(_T((Mark(eps[i]) + EpisodeLabel(eps[i].index, eps[i].title)).c_str())); } void PlayEpisode(int i) @@ -4119,6 +4130,7 @@ class CJellyfinLibrary : public CNode const JellyfinItem& it = items[i]; std::string s = it.name; if (!it.year.empty()) { s += " ("; s += it.year; s += ")"; } + if (!it.isFolder || it.type == "Series") s = Mark(it) + s; return new CStrObject(_T(s.c_str())); } @@ -4255,7 +4267,7 @@ class CJellyfinLibrary : public CNode if (showId.empty()) return new CStrObject; Jellyfin_Cache_GetSeasons(showId, seasons); if (i < 0 || i >= (int)seasons.size()) return new CStrObject; - return new CStrObject(_T(seasons[i].name.c_str())); + return new CStrObject(_T((Mark(seasons[i]) + seasons[i].name).c_str())); } void DrillIntoSeason(int i) @@ -4293,6 +4305,7 @@ class CJellyfinLibrary : public CNode } static long long Secs(long long ticks) { return ticks / 10000000; } + static std::string Mark(const JellyfinDetails& d) { return WatchMark(d.played, Secs(d.posTicks), Secs(d.runTicks)); } std::string EpisodeLabel(const std::string& index, const std::string& title) { @@ -4322,7 +4335,7 @@ class CJellyfinLibrary : public CNode if (seasonId.empty()) return new CStrObject; Jellyfin_Cache_GetEpisodes(seasonId, eps); if (i < 0 || i >= (int)eps.size()) return new CStrObject; - return new CStrObject(_T(EpisodeLabel(eps[i].index, eps[i].name).c_str())); + return new CStrObject(_T((Mark(eps[i]) + EpisodeLabel(eps[i].index, eps[i].name)).c_str())); } void PlayEpisode(int i) From 8facaacdb5e35b11671191d500207d3e487b5776 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:12:44 -0500 Subject: [PATCH 27/46] Library rows show how many items each holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Jellyfin and Plex library lists read Movies ยท 12 instead of a bare name. The count is the top level of the library, so a folder counts once. --- Data/Xips/default.xip | Bin 1689674 -> 1689686 bytes theseus/desktop/desktop_nodes.cpp | 22 ++++++++++++++++++++++ xips-source/default-desktop/Jellyfin.xap | 2 +- xips-source/default-desktop/Plex.xap | 2 +- xips-source/jellyfin/jellyfin.xap | 2 +- xips-source/plex/plex.xap | 2 +- 6 files changed, 26 insertions(+), 4 deletions(-) diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index 5db99a0ca220ff26373974af15b2b83316656742..49cf1b29dbd69c6e31b50f1ce0c1d3ac484c62e4 100644 GIT binary patch delta 251 zcmX>#A^qBfblwQh0D}We3=E<`IBg>DcRv{|1~_8ftUk`If0l9h`E872Z(ur zm=B2gfmi^D1%X%yh=rF2F^X*A^2tmpN-U}j$}gWjd#i}l_JXYTH2aGc0HkWnkc7 zVF2m}g9Sa33{lbu`CrSMgBaU`7(ti`h?#+y1&CRJm<@>8ftUk`If0l9h`E872Z(ur zm=B2gfmi^D1%X%yh=rF2F^X(q_Djs2zF@0}^mO^{B0SUU4vR=l-|$d`ZF;pk3)l8F mTSXpdf|cC3FCshL_n`<+`@Z`kKr9NxVn8guecyeF87}~yl0)AB diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index 7d75eba..7ee85da 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3516,6 +3516,16 @@ class CPlexLibrary : public CNode return new CStrObject(_T(libs[i].title.c_str())); } + // Library row: "Movies \xC2\xB7 12". + CStrObject* GetLibraryRow(int i) + { + std::vector libs = Plex_Cache_GetLibraries(); + if (i < 0 || i >= (int)libs.size()) return new CStrObject; + char buf[32]; + snprintf(buf, sizeof(buf), " \xC2\xB7 %d", (int)Plex_Cache_GetItems(libs[i].sectionKey).size()); + return new CStrObject(_T((libs[i].title + buf).c_str())); + } + CStrObject* GetMeta(int i) { std::vector libs = Plex_Cache_GetLibraries(); @@ -4004,6 +4014,7 @@ START_NODE_FUN(CPlexLibrary, CNode) NODE_FUN_IV(GetFolderDepth) NODE_FUN_IV(LeaveFolder) NODE_FUN_SV(GetListTitle) + NODE_FUN_SI(GetLibraryRow) END_NODE_FUN() @@ -4050,6 +4061,16 @@ class CJellyfinLibrary : public CNode return new CStrObject(_T(libs[i].name.c_str())); } + // Library row: "Movies \xC2\xB7 12". + CStrObject* GetLibraryRow(int i) + { + std::vector libs = Jellyfin_Cache_GetLibraries(); + if (i < 0 || i >= (int)libs.size()) return new CStrObject; + char buf[32]; + snprintf(buf, sizeof(buf), " \xC2\xB7 %d", (int)Jellyfin_Cache_GetItems(libs[i].id).size()); + return new CStrObject(_T((libs[i].name + buf).c_str())); + } + CStrObject* GetMeta(int i) { std::vector libs = Jellyfin_Cache_GetLibraries(); @@ -4552,6 +4573,7 @@ START_NODE_FUN(CJellyfinLibrary, CNode) NODE_FUN_IV(GetFolderDepth) NODE_FUN_IV(LeaveFolder) NODE_FUN_SV(GetListTitle) + NODE_FUN_SI(GetLibraryRow) END_NODE_FUN() diff --git a/xips-source/default-desktop/Jellyfin.xap b/xips-source/default-desktop/Jellyfin.xap index 1f32625..572bea8 100644 --- a/xips-source/default-desktop/Jellyfin.xap +++ b/xips-source/default-desktop/Jellyfin.xap @@ -50,7 +50,7 @@ function BindActiveList() function GetActiveTitle(absIdx) { if (nJfView == 0) - return theJellyfinLibrary.GetName(absIdx); + return theJellyfinLibrary.GetLibraryRow(absIdx); if (nJfView == 1) return theJellyfinLibrary.GetItemTitle(absIdx); if (nJfView == 2) diff --git a/xips-source/default-desktop/Plex.xap b/xips-source/default-desktop/Plex.xap index 7c10b5e..e89c601 100644 --- a/xips-source/default-desktop/Plex.xap +++ b/xips-source/default-desktop/Plex.xap @@ -50,7 +50,7 @@ function BindActiveList() function GetActiveTitle(absIdx) { if (nPlexView == 0) - return thePlexLibrary.GetName(absIdx); + return thePlexLibrary.GetLibraryRow(absIdx); if (nPlexView == 1) return thePlexLibrary.GetItemTitle(absIdx); if (nPlexView == 2) diff --git a/xips-source/jellyfin/jellyfin.xap b/xips-source/jellyfin/jellyfin.xap index 1f32625..572bea8 100644 --- a/xips-source/jellyfin/jellyfin.xap +++ b/xips-source/jellyfin/jellyfin.xap @@ -50,7 +50,7 @@ function BindActiveList() function GetActiveTitle(absIdx) { if (nJfView == 0) - return theJellyfinLibrary.GetName(absIdx); + return theJellyfinLibrary.GetLibraryRow(absIdx); if (nJfView == 1) return theJellyfinLibrary.GetItemTitle(absIdx); if (nJfView == 2) diff --git a/xips-source/plex/plex.xap b/xips-source/plex/plex.xap index 7c10b5e..e89c601 100644 --- a/xips-source/plex/plex.xap +++ b/xips-source/plex/plex.xap @@ -50,7 +50,7 @@ function BindActiveList() function GetActiveTitle(absIdx) { if (nPlexView == 0) - return thePlexLibrary.GetName(absIdx); + return thePlexLibrary.GetLibraryRow(absIdx); if (nPlexView == 1) return thePlexLibrary.GetItemTitle(absIdx); if (nPlexView == 2) From 4087dd3b7b5f17b60556c33133c41b7609493d20 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:17:44 -0500 Subject: [PATCH 28/46] Jellyfin and Plex say Loading or Can't reach instead of an empty list An empty list now tells you why: still loading, the server didn't answer, nothing there, or not signed in. Jellyfin seasons and episodes load in the background like Plex's instead of stalling the menu, and a failed fetch is tried again when you go back in. Also kept the watched mark out of the show name in the header. --- Data/Xips/default.xip | Bin 1689686 -> 1691564 bytes theseus/desktop/desktop_nodes.cpp | 127 ++++++++++++++++++ theseus/desktop/jellyfin_client.cpp | 156 ++++++++++++++--------- theseus/desktop/jellyfin_client.h | 8 +- theseus/desktop/plex_client.cpp | 30 ++++- theseus/desktop/plex_client.h | 4 + xips-source/default-desktop/Jellyfin.xap | 21 ++- xips-source/default-desktop/Plex.xap | 21 ++- xips-source/jellyfin/jellyfin.xap | 21 ++- xips-source/plex/plex.xap | 21 ++- 10 files changed, 334 insertions(+), 75 deletions(-) diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index 49cf1b29dbd69c6e31b50f1ce0c1d3ac484c62e4..1e2be157d55453a2ab97e9c62fab0db127e382c7 100644 GIT binary patch delta 1244 zcmeH`O-vI}5XZOMZDC7kyD+5`P#-nQZlZ$mU?QoWC9x?rF)AF~Kugz@R=caEkpl)3 zLSl?YOUtb-% zGc^=AemL1R%X3_qzHcwD1%4&wc5}|UxdhzD4f}FUn47%hTyy;8Fvryj93`+8e^pArTEkqnUES-iIg7t3{^w zWR4oDaZc}M&g$%BrL1Z&Bb#RF;WI{=k)kSiB17?>@oNRcS0RDub43J#s^*C@#HSJqfO&bkz~lgV}nYmZY=Me&K^1wtgziGq+ zfYn4sE0TVaX7^CamiJ)$DzxJ5gjA2Ym{-KHXArqw=kep(XV|u`imgH$9R_j512QJZ z8#=7rp|7wX-%Lt=4D|?g>rp{W9uXMsSgj^%#_2B*#6M}Q+}4p7r%ns?xOi3yVPL$W z1w%E^h^JKI`d|x%7w~^3NaNoO=simtWMYHIUxF-CSOV1-E5_nfLH&vk9aX2utfd zR03@qjD3Qi|7}pQLDaTEb*7FHkc^<3gKO}kNnoQ)M%O!N+;06_a^4xGWr%8Y<>$d^ VKHM^4@L{5fh!D-D!AC#L{RWhug}DF# delta 336 zcmZ28KmFQ-biN4B0D}We3=E<`IPK^}zHfdqS`2XT_NoYj84_O^sH(FCF3qr}MU;Vo zgM|TT02r+4kz|OHM#!_RXbxg*4`KviCLm@8Viq7~1!6WJW(Q&pAm#*OE+FOxVjdvo z1!6uR<_BT{AQl8-As`ms9>geOxN-XW2O=`le{2%@F#Xj-5uxqETSQ(mPv_ev!nU1p zhsY7;>HADY*tYEvxyUko0w){i^n}AA?b~&ah(w7qYEIv9O+ items = CurrentItems(); if (i < 0 || i >= (int)items.size() || !IsFolderType(items[i].type)) return; m_folders.push_back({ items[i].ratingKey, items[i].title, i }); + Plex_RetryFetch(items[i].ratingKey); m_currentShow = -1; m_currentSeason = -1; std::vector dummy; @@ -3716,6 +3717,16 @@ class CPlexLibrary : public CNode int GetItemCount() { return (int)CurrentItems().size(); } + // Title and year without the watch mark, for the header. + CStrObject* GetItemName(int i) + { + std::vector items = CurrentItems(); + if (i < 0 || i >= (int)items.size()) return new CStrObject; + std::string s = items[i].title; + if (!items[i].year.empty()) { s += " ("; s += items[i].year; s += ")"; } + return new CStrObject(_T(s.c_str())); + } + CStrObject* GetItemTitle(int i) { std::vector items = CurrentItems(); @@ -3872,6 +3883,7 @@ class CPlexLibrary : public CNode if (i < 0 || i >= (int)items.size()) return; const PlexItem& it = items[i]; if (it.type != "show") return; + Plex_RetryFetch(it.ratingKey); m_currentShow = i; m_currentSeason = -1; std::vector dummy; @@ -3905,6 +3917,7 @@ class CPlexLibrary : public CNode Plex_Cache_GetSeasons(showKey, seasons); if (i < 0 || i >= (int)seasons.size()) return; m_currentSeason = i; + Plex_RetryFetch(seasons[i].ratingKey); std::vector dummy; (void)Plex_Cache_GetEpisodes(seasons[i].ratingKey, dummy); } @@ -3971,6 +3984,54 @@ class CPlexLibrary : public CNode } int IsSignedIn() { return Plex_HasToken() ? 1 : 0; } + + // What an empty list says instead: still loading, the server didn't + // answer, or there's nothing there. Empty while there are rows. + CStrObject* GetStatus(int view) + { + return new CStrObject(_T(StatusFor(view).c_str())); + } + + static std::string Unreachable() + { + std::string name = Plex_GetActiveServerName(); + return "Can't reach " + (name.empty() ? std::string("your Plex server") : name); + } + + template + static std::string Pending(bool cached, const std::vector& rows, const std::string& key, const char* none) + { + if (cached) return rows.empty() ? none : ""; + return Plex_FetchFailed(key) ? Unreachable() : "Loading..."; + } + + std::string StatusFor(int view) + { + if (!Plex_HasToken()) return "Sign in to Plex in Settings"; + if (!Plex_SyncReady()) return "Loading..."; + if (view == 0) { + if (Plex_GetActiveServerUri().empty()) return Unreachable(); + return Plex_Cache_GetLibraries().empty() ? "No libraries" : ""; + } + if (view == 1) { + if (m_folders.empty()) return CurrentItems().empty() ? "Nothing here" : ""; + std::vector kids; + bool cached = Plex_Cache_GetChildren(m_folders.back().key, kids); + return Pending(cached, kids, m_folders.back().key, "Nothing here"); + } + if (view == 2) { + std::string showKey = CurrentShowKey(); + if (showKey.empty()) return ""; + std::vector seasons; + bool cached = Plex_Cache_GetSeasons(showKey, seasons); + return Pending(cached, seasons, showKey, "No seasons"); + } + std::string seasonKey = CurrentSeasonKey(); + if (seasonKey.empty()) return "Loading..."; + std::vector eps; + bool cached = Plex_Cache_GetEpisodes(seasonKey, eps); + return Pending(cached, eps, seasonKey, "No episodes"); + } }; IMPLEMENT_NODE("PlexLibrary", CPlexLibrary, CNode) @@ -4015,6 +4076,8 @@ START_NODE_FUN(CPlexLibrary, CNode) NODE_FUN_IV(LeaveFolder) NODE_FUN_SV(GetListTitle) NODE_FUN_SI(GetLibraryRow) + NODE_FUN_SI(GetStatus) + NODE_FUN_SI(GetItemName) END_NODE_FUN() @@ -4116,6 +4179,7 @@ class CJellyfinLibrary : public CNode std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size() || !items[i].isFolder) return; m_folders.push_back({ items[i].id, items[i].name, i }); + Jellyfin_RetryFetch(items[i].id); m_currentShow = -1; m_currentSeason = -1; std::vector dummy; @@ -4144,6 +4208,16 @@ class CJellyfinLibrary : public CNode int GetItemCount() { return (int)CurrentItems().size(); } + // Title and year without the watch mark, for the header. + CStrObject* GetItemName(int i) + { + std::vector items = CurrentItems(); + if (i < 0 || i >= (int)items.size()) return new CStrObject; + std::string s = items[i].name; + if (!items[i].year.empty()) { s += " ("; s += items[i].year; s += ")"; } + return new CStrObject(_T(s.c_str())); + } + CStrObject* GetItemTitle(int i) { std::vector items = CurrentItems(); @@ -4266,6 +4340,7 @@ class CJellyfinLibrary : public CNode if (i < 0 || i >= (int)items.size()) return; const JellyfinItem& it = items[i]; if (it.type != "Series") return; + Jellyfin_RetryFetch(it.id); m_currentShow = i; m_currentSeason = -1; std::vector dummy; @@ -4299,6 +4374,7 @@ class CJellyfinLibrary : public CNode Jellyfin_Cache_GetSeasons(showId, seasons); if (i < 0 || i >= (int)seasons.size()) return; m_currentSeason = i; + Jellyfin_RetryFetch(seasons[i].id); std::vector dummy; (void)Jellyfin_Cache_GetEpisodes(seasons[i].id, dummy); } @@ -4530,6 +4606,55 @@ class CJellyfinLibrary : public CNode } int IsSignedIn() { return Jellyfin_HasToken() ? 1 : 0; } + + // What an empty list says instead: still loading, the server didn't + // answer, or there's nothing there. Empty while there are rows. + CStrObject* GetStatus(int view) + { + return new CStrObject(_T(StatusFor(view).c_str())); + } + + static std::string Unreachable() + { + std::string host = Jellyfin_GetServerUrl(); + size_t scheme = host.find("://"); + if (scheme != std::string::npos) host = host.substr(scheme + 3); + host = host.substr(0, host.find('/')); + return "Can't reach " + (host.empty() ? std::string("the server") : host); + } + + template + static std::string Pending(bool cached, const std::vector& rows, const std::string& id, const char* none) + { + if (cached) return rows.empty() ? none : ""; + return Jellyfin_FetchFailed(id) ? Unreachable() : "Loading..."; + } + + std::string StatusFor(int view) + { + if (!Jellyfin_HasToken()) return "Sign in to Jellyfin in Settings"; + if (!Jellyfin_SyncReady()) return "Loading..."; + if (view == 0) { + if (Jellyfin_SyncFailed()) return Unreachable(); + return Jellyfin_Cache_GetLibraries().empty() ? "No libraries" : ""; + } + if (view == 1) { + if (m_folders.empty()) return CurrentItems().empty() ? "Nothing here" : ""; + std::vector kids; + bool cached = Jellyfin_Cache_GetChildren(m_folders.back().id, kids); + return Pending(cached, kids, m_folders.back().id, "Nothing here"); + } + if (view == 2) { + std::string showId = CurrentShowId(); + std::vector seasons; + bool cached = Jellyfin_Cache_GetSeasons(showId, seasons); + return Pending(cached, seasons, showId, "No seasons"); + } + std::string seasonId = CurrentSeasonId(); + std::vector eps; + bool cached = Jellyfin_Cache_GetEpisodes(seasonId, eps); + return Pending(cached, eps, seasonId, "No episodes"); + } }; IMPLEMENT_NODE("JellyfinLibrary", CJellyfinLibrary, CNode) @@ -4574,6 +4699,8 @@ START_NODE_FUN(CJellyfinLibrary, CNode) NODE_FUN_IV(LeaveFolder) NODE_FUN_SV(GetListTitle) NODE_FUN_SI(GetLibraryRow) + NODE_FUN_SI(GetStatus) + NODE_FUN_SI(GetItemName) END_NODE_FUN() diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index 63ac5b9..1a48024 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -130,12 +130,15 @@ static std::thread s_syncThread; // Bumped by sign out. A worker from an older generation finishes on its own // but publishes nothing, and owns s_syncRunning until it does. static std::atomic s_syncGen{0}; +static std::atomic s_syncFailed{false}; +// Seasons, episodes and folder contents whose last fetch failed. Asking +// again doesn't refetch until the scene drills in again. +static std::map s_fetchFailed; static std::vector s_cacheLibs; static std::map> s_cacheItems; static std::map> s_cacheSeasons; static std::map> s_cacheEpisodes; static std::map> s_cacheChildren; -static std::map s_childrenBusy; // ---------- Art download queue ---------- static std::mutex s_artMtx; @@ -185,6 +188,8 @@ void Jellyfin_SignOut() s_cacheSeasons.clear(); s_cacheEpisodes.clear(); s_cacheChildren.clear(); + s_fetchFailed.clear(); + s_syncFailed = false; s_syncGen++; s_syncReady = false; s_syncProgress = 0; @@ -372,26 +377,26 @@ static JellyfinItem ParseItem(const std::string& obj) return it; } -static std::vector FetchItemsForLibrary(const std::string& libraryId) +static bool FetchItemsForLibrary(const std::string& libraryId, std::vector& out) { char url[1024]; snprintf(url, sizeof(url), "%s/Users/%s/Items?ParentId=%s&Recursive=false&Fields=Overview,ProductionYear,Genres&EnableUserData=true", g_jellyfinUrl, g_jellyfinUserId, libraryId.c_str()); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); - std::vector out; + out.clear(); if (!r.ok()) { fprintf(stderr, "[Jellyfin] items fetch failed for %s (status %ld)\n", libraryId.c_str(), r.status); - return out; + return false; } size_t arr = Json_FindArray(r.body, "Items"); - if (arr == std::string::npos) return out; + if (arr == std::string::npos) return true; for (const auto& obj : Json_SplitArray(r.body, arr)) { JellyfinItem it = ParseItem(obj); if (!it.id.empty()) out.push_back(it); } - return out; + return true; } @@ -417,6 +422,9 @@ static void SyncWorker() snprintf(url, sizeof(url), "%s/Users/%s/Views", g_jellyfinUrl, g_jellyfinUserId); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); std::vector libs; + s_syncFailed = !r.ok(); + if (!r.ok()) + fprintf(stderr, "[Jellyfin] library list failed (status %ld)\n", r.status); if (r.ok()) { size_t arr = Json_FindArray(r.body, "Items"); if (arr != std::string::npos) { @@ -438,7 +446,7 @@ static void SyncWorker() snprintf(phaseBuf, sizeof(phaseBuf), "Loading %s (%d/%d)", lib.name.c_str(), i + 1, libCount); SetSyncPhase(gen, phaseBuf, 100 + (i * 900) / (libCount > 0 ? libCount : 1)); - itemsById[lib.id] = FetchItemsForLibrary(lib.id); + FetchItemsForLibrary(lib.id, itemsById[lib.id]); } size_t nLibs = libs.size(); @@ -467,6 +475,19 @@ void Jellyfin_StartSync() } bool Jellyfin_SyncReady() { return s_syncReady; } +bool Jellyfin_SyncFailed() { return s_syncReady && s_syncFailed; } + +bool Jellyfin_FetchFailed(const std::string& id) +{ + std::lock_guard lk(g_mtx); + return s_fetchFailed.count(id) != 0; +} + +void Jellyfin_RetryFetch(const std::string& id) +{ + std::lock_guard lk(g_mtx); + s_fetchFailed.erase(id); +} int Jellyfin_SyncProgress() { return s_syncProgress; } std::string Jellyfin_SyncPhase() { @@ -493,16 +514,15 @@ std::vector Jellyfin_Cache_GetItems(const std::string& libraryId) // Seasons + episodes (lazy, fetched on first drill) // ============================================================================ -static std::vector FetchSeasonsForShow(const std::string& showId) +static bool FetchSeasonsForShow(const std::string& showId, std::vector& out) { char url[1024]; snprintf(url, sizeof(url), "%s/Shows/%s/Seasons?UserId=%s&EnableUserData=true", g_jellyfinUrl, showId.c_str(), g_jellyfinUserId); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); - std::vector out; - if (!r.ok()) return out; + if (!r.ok()) return false; size_t arr = Json_FindArray(r.body, "Items"); - if (arr == std::string::npos) return out; + if (arr == std::string::npos) return true; for (const auto& obj : Json_SplitArray(r.body, arr)) { JellyfinSeason s; s.id = Json_GetString(obj, "Id"); @@ -515,21 +535,20 @@ static std::vector FetchSeasonsForShow(const std::string& showId ParseDetails(obj, s); if (!s.id.empty()) out.push_back(s); } - return out; + return true; } -static std::vector FetchEpisodesForSeason(const std::string& seasonId, - const std::string& showId) +static bool FetchEpisodesForSeason(const std::string& seasonId, const std::string& showId, + std::vector& out) { char url[1024]; snprintf(url, sizeof(url), "%s/Shows/%s/Episodes?seasonId=%s&UserId=%s&Fields=Overview&EnableUserData=true", g_jellyfinUrl, showId.c_str(), seasonId.c_str(), g_jellyfinUserId); HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); - std::vector out; - if (!r.ok()) return out; + if (!r.ok()) return false; size_t arr = Json_FindArray(r.body, "Items"); - if (arr == std::string::npos) return out; + if (arr == std::string::npos) return true; for (const auto& obj : Json_SplitArray(r.body, arr)) { JellyfinEpisode e; e.id = Json_GetString(obj, "Id"); @@ -544,7 +563,7 @@ static std::vector FetchEpisodesForSeason(const std::string& se ParseDetails(obj, e); if (!e.id.empty()) out.push_back(e); } - return out; + return true; } // Map from seasonId -> parent showId, populated as we fetch seasons. Lets @@ -552,52 +571,64 @@ static std::vector FetchEpisodesForSeason(const std::string& se // with the right show id; we never have to plumb it from the caller. static std::map s_seasonToShow; +// One background fetch per id at a time; the scene polls the getters. +static std::map s_fetchBusy; + +// True when this id needs a fetch started: not cached, not running, not failed. +static bool ClaimFetch(const std::string& id) +{ + if (s_fetchBusy.count(id) || s_fetchFailed.count(id)) return false; + s_fetchBusy[id] = true; + return true; +} + +static void SeasonsWorker(unsigned gen, std::string showId) +{ + std::vector seasons; + bool ok = FetchSeasonsForShow(showId, seasons); + std::lock_guard lk(g_mtx); + s_fetchBusy.erase(showId); + if (gen != s_syncGen) return; + if (!ok) { s_fetchFailed[showId] = true; return; } + for (const auto& se : seasons) s_seasonToShow[se.id] = showId; + s_cacheSeasons[showId] = std::move(seasons); +} + bool Jellyfin_Cache_GetSeasons(const std::string& showId, std::vector& out) { - { - std::lock_guard lk(g_mtx); - auto it = s_cacheSeasons.find(showId); - if (it != s_cacheSeasons.end()) { - out = it->second; - return true; - } - } - std::vector fetched = FetchSeasonsForShow(showId); - { - std::lock_guard lk(g_mtx); - s_cacheSeasons[showId] = fetched; - for (const auto& s : fetched) s_seasonToShow[s.id] = showId; - out = fetched; - } - return true; + if (showId.empty()) return false; + std::lock_guard lk(g_mtx); + auto it = s_cacheSeasons.find(showId); + if (it != s_cacheSeasons.end()) { out = it->second; return true; } + if (ClaimFetch(showId)) + std::thread(SeasonsWorker, (unsigned)s_syncGen, showId).detach(); + return false; +} + +static void EpisodesWorker(unsigned gen, std::string seasonId, std::string showId) +{ + std::vector eps; + bool ok = FetchEpisodesForSeason(seasonId, showId, eps); + std::lock_guard lk(g_mtx); + s_fetchBusy.erase(seasonId); + if (gen != s_syncGen) return; + if (!ok) { s_fetchFailed[seasonId] = true; return; } + s_cacheEpisodes[seasonId] = std::move(eps); } bool Jellyfin_Cache_GetEpisodes(const std::string& seasonId, std::vector& out) { - { - std::lock_guard lk(g_mtx); - auto it = s_cacheEpisodes.find(seasonId); - if (it != s_cacheEpisodes.end()) { - out = it->second; - return true; - } - } - std::string showId; - { - std::lock_guard lk(g_mtx); - auto it = s_seasonToShow.find(seasonId); - if (it != s_seasonToShow.end()) showId = it->second; - } - if (showId.empty()) return false; - std::vector fetched = FetchEpisodesForSeason(seasonId, showId); - { - std::lock_guard lk(g_mtx); - s_cacheEpisodes[seasonId] = fetched; - out = fetched; - } - return true; + if (seasonId.empty()) return false; + std::lock_guard lk(g_mtx); + auto it = s_cacheEpisodes.find(seasonId); + if (it != s_cacheEpisodes.end()) { out = it->second; return true; } + auto show = s_seasonToShow.find(seasonId); + if (show == s_seasonToShow.end()) return false; + if (ClaimFetch(seasonId)) + std::thread(EpisodesWorker, (unsigned)s_syncGen, seasonId, show->second).detach(); + return false; } @@ -607,10 +638,13 @@ bool Jellyfin_Cache_GetEpisodes(const std::string& seasonId, static void ChildrenWorker(unsigned gen, std::string parentId) { - std::vector items = FetchItemsForLibrary(parentId); + std::vector items; + bool ok = FetchItemsForLibrary(parentId, items); std::lock_guard lk(g_mtx); - if (gen == s_syncGen) s_cacheChildren[parentId] = std::move(items); - s_childrenBusy.erase(parentId); + s_fetchBusy.erase(parentId); + if (gen != s_syncGen) return; + if (!ok) { s_fetchFailed[parentId] = true; return; } + s_cacheChildren[parentId] = std::move(items); } bool Jellyfin_Cache_GetChildren(const std::string& parentId, std::vector& out) @@ -619,10 +653,8 @@ bool Jellyfin_Cache_GetChildren(const std::string& parentId, std::vector lk(g_mtx); auto it = s_cacheChildren.find(parentId); if (it != s_cacheChildren.end()) { out = it->second; return true; } - if (!s_childrenBusy.count(parentId)) { - s_childrenBusy[parentId] = true; + if (ClaimFetch(parentId)) std::thread(ChildrenWorker, (unsigned)s_syncGen, parentId).detach(); - } return false; } diff --git a/theseus/desktop/jellyfin_client.h b/theseus/desktop/jellyfin_client.h index 9186617..94be59b 100644 --- a/theseus/desktop/jellyfin_client.h +++ b/theseus/desktop/jellyfin_client.h @@ -69,9 +69,15 @@ void Jellyfin_SetServerUrl(const std::string& url); std::string Jellyfin_GetUserName(); // empty until token acquired // Pre-stage cache. Walks libraries + items on sign-in; seasons + episodes -// stay lazy with permanent in-session caching (same shape as Plex). +// load in the background on first ask (false until they land) and stay +// cached for the session, same shape as Plex. void Jellyfin_StartSync(); bool Jellyfin_SyncReady(); +bool Jellyfin_SyncFailed(); // done, but the server never answered +// Seasons, episodes or folder contents for this id failed to load. A failed +// id isn't fetched again until RetryFetch. +bool Jellyfin_FetchFailed(const std::string& id); +void Jellyfin_RetryFetch(const std::string& id); std::string Jellyfin_SyncPhase(); int Jellyfin_SyncProgress(); // 0..1000 per-mille diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index 9cd7f4a..f2f84c7 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -91,6 +91,9 @@ static std::map> s_cacheSeasons; // sh static std::map> s_cacheEpisodes; // seasonRk -> episodes static std::map> s_cacheChildren; // rk -> items inside it static std::map s_childrenBusy; +// Seasons, episodes and children whose last fetch failed. Asking again +// doesn't refetch until the scene drills in again. +static std::map s_fetchFailed; // ============================================================================ @@ -136,6 +139,7 @@ void Plex_SignOut() s_cacheSeasons.clear(); s_cacheEpisodes.clear(); s_cacheChildren.clear(); + s_fetchFailed.clear(); s_syncGen++; s_syncReady = false; s_syncProgress = 0; @@ -388,8 +392,10 @@ static void ChildrenWorker(unsigned gen, std::string serverUri, std::string rk) if (r.ok()) items = ParseItems(r.body, serverUri); else fprintf(stderr, "[Plex] children fetch failed for %s (status %ld)\n", rk.c_str(), r.status); std::lock_guard lk(g_mtx); - if (gen == s_syncGen) s_cacheChildren[rk] = std::move(items); s_childrenBusy.erase(rk); + if (gen != s_syncGen) return; + if (r.ok()) s_cacheChildren[rk] = std::move(items); + else s_fetchFailed[rk] = true; } bool Plex_Cache_GetChildren(const std::string& ratingKey, std::vector& out) @@ -399,7 +405,7 @@ bool Plex_Cache_GetChildren(const std::string& ratingKey, std::vector& std::lock_guard lk(g_mtx); auto it = s_cacheChildren.find(ratingKey); if (it != s_cacheChildren.end()) { out = it->second; return true; } - if (!uri.empty() && !s_childrenBusy.count(ratingKey)) { + if (!uri.empty() && !s_childrenBusy.count(ratingKey) && !s_fetchFailed.count(ratingKey)) { s_childrenBusy[ratingKey] = true; std::thread(ChildrenWorker, (unsigned)s_syncGen, uri, ratingKey).detach(); } @@ -439,7 +445,8 @@ static void SeasonsWorker(std::string serverUri, std::string showRk) size_t n = seasons.size(); { std::lock_guard lk(g_mtx); - s_cacheSeasons[showRk] = std::move(seasons); + if (r.ok()) s_cacheSeasons[showRk] = std::move(seasons); + else s_fetchFailed[showRk] = true; } fprintf(stderr, "[Plex] %zu season(s) under show %s\n", n, showRk.c_str()); s_seasonsBusy = false; @@ -483,7 +490,8 @@ static void EpisodesWorker(std::string serverUri, std::string seasonRk) size_t n = episodes.size(); { std::lock_guard lk(g_mtx); - s_cacheEpisodes[seasonRk] = std::move(episodes); + if (r.ok()) s_cacheEpisodes[seasonRk] = std::move(episodes); + else s_fetchFailed[seasonRk] = true; } fprintf(stderr, "[Plex] %zu episode(s) under season %s\n", n, seasonRk.c_str()); s_episodesBusy = false; @@ -671,6 +679,18 @@ void Plex_StartSync() } bool Plex_SyncReady() { return s_syncReady; } + +bool Plex_FetchFailed(const std::string& rk) +{ + std::lock_guard lk(g_mtx); + return s_fetchFailed.count(rk) != 0; +} + +void Plex_RetryFetch(const std::string& rk) +{ + std::lock_guard lk(g_mtx); + s_fetchFailed.erase(rk); +} int Plex_SyncProgress() { return s_syncProgress; } std::string Plex_SyncPhase() { @@ -702,6 +722,7 @@ bool Plex_Cache_GetSeasons(const std::string& showRatingKey, out = it->second; return true; } + if (s_fetchFailed.count(showRatingKey)) return false; } // Not cached, fire a fetch; SeasonsWorker promotes the result. // Same server the library came from, not just the first one listed. @@ -720,6 +741,7 @@ bool Plex_Cache_GetEpisodes(const std::string& seasonRatingKey, out = it->second; return true; } + if (s_fetchFailed.count(seasonRatingKey)) return false; } std::string uri = Plex_GetActiveServerUri(); if (!uri.empty()) Plex_FetchEpisodes(uri, seasonRatingKey); diff --git a/theseus/desktop/plex_client.h b/theseus/desktop/plex_client.h index 966e275..fb71be6 100644 --- a/theseus/desktop/plex_client.h +++ b/theseus/desktop/plex_client.h @@ -93,6 +93,10 @@ std::string Plex_ResolveStreamUrl(const std::string& serverUri, // Seasons + episodes stay lazy with permanent in-session caching. void Plex_StartSync(); bool Plex_SyncReady(); +// Seasons, episodes or children for this key failed to load. A failed key +// isn't fetched again until RetryFetch. +bool Plex_FetchFailed(const std::string& ratingKey); +void Plex_RetryFetch(const std::string& ratingKey); std::string Plex_SyncPhase(); int Plex_SyncProgress(); // 0..1000 per-mille diff --git a/xips-source/default-desktop/Jellyfin.xap b/xips-source/default-desktop/Jellyfin.xap index 572bea8..74aa938 100644 --- a/xips-source/default-desktop/Jellyfin.xap +++ b/xips-source/default-desktop/Jellyfin.xap @@ -16,6 +16,7 @@ var nJfCursorBackup1; // saved cursor when drilling item -> seasons var nJfCursorBackup2; // saved cursor when drilling season -> episodes var sJfPoster; // poster url on the CD now; behavior swaps it when art lands var bJfLoaded; // the chrome scene is in, so the behavior can touch it +var sJfStatus; // what the empty list says (loading, can't reach); "" with rows function initialize() @@ -30,6 +31,7 @@ function initialize() nJfCursorBackup1 = 0; nJfCursorBackup2 = 0; sJfPoster = ""; + sJfStatus = ""; } @@ -69,7 +71,7 @@ function GetHeaderText() return server; if (nJfView == 1) return server + " / " + theJellyfinLibrary.GetListTitle(); - var showTitle = theJellyfinLibrary.GetItemTitle(nJfCursorBackup1); + var showTitle = theJellyfinLibrary.GetItemName(nJfCursorBackup1); if (nJfView == 2) return showTitle; return showTitle + " / " + theJellyfinLibrary.GetSeasonTitle(nJfCursorBackup2); @@ -117,6 +119,7 @@ function StartJellyfinLevel() function UpdateJellyfinList() { var c = theJellyfinMenu.children[0].children[0]; + var status = theJellyfinLibrary.GetStatus(nJfView); if (nJfCursor < nJfScroll) nJfScroll = nJfCursor; @@ -147,6 +150,17 @@ function UpdateJellyfinList() c.MenuButtons.children[i].children[1].children[0].geometry.scrollDelay = 0; } } + else if ((i == 0) & (status != "")) + { + // Nothing to list yet: the first row says why. + c.MenuButtons.children[0].visible = true; + c.MenuButtons.children[0].children[1].children[0].geometry.text = status; + c.MenuButtons.children[0].children[0].children[0].appearance.material.name = "GameHilite"; + c.MenuButtons.children[0].children[0].children[0].appearance.texture.url = "outline.tga"; + c.MenuButtons.children[0].children[1].children[0].appearance.name = "NavType"; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollRate = 0; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollDelay = 0; + } else { c.MenuButtons.children[i].visible = false; @@ -155,6 +169,9 @@ function UpdateJellyfinList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sJfStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -463,7 +480,7 @@ DEF theJellyfinMenu Level BindActiveList(); if (bJfLoaded == 1) { - if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster)) + if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster) | (theJellyfinLibrary.GetStatus(nJfView) != sJfStatus)) UpdateJellyfinList(); } else if (nJfCount != nJfLastCount) diff --git a/xips-source/default-desktop/Plex.xap b/xips-source/default-desktop/Plex.xap index e89c601..0a2bd3e 100644 --- a/xips-source/default-desktop/Plex.xap +++ b/xips-source/default-desktop/Plex.xap @@ -16,6 +16,7 @@ var nPlexCursorBackup1; // saved cursor when drilling item -> seasons var nPlexCursorBackup2; // saved cursor when drilling season -> episodes var sPlexPoster; // poster url on the CD now; behavior swaps it when art lands var bPlexLoaded; // the chrome scene is in, so the behavior can touch it +var sPlexStatus; // what the empty list says (loading, can't reach); "" with rows function initialize() @@ -30,6 +31,7 @@ function initialize() nPlexCursorBackup1 = 0; nPlexCursorBackup2 = 0; sPlexPoster = ""; + sPlexStatus = ""; } @@ -69,7 +71,7 @@ function GetHeaderText() return server; if (nPlexView == 1) return server + " / " + thePlexLibrary.GetListTitle(); - var showTitle = thePlexLibrary.GetItemTitle(nPlexCursorBackup1); + var showTitle = thePlexLibrary.GetItemName(nPlexCursorBackup1); if (nPlexView == 2) return showTitle; return showTitle + " / " + thePlexLibrary.GetSeasonTitle(nPlexCursorBackup2); @@ -117,6 +119,7 @@ function StartPlexLevel() function UpdatePlexList() { var c = thePlexMenu.children[0].children[0]; + var status = thePlexLibrary.GetStatus(nPlexView); if (nPlexCursor < nPlexScroll) nPlexScroll = nPlexCursor; @@ -147,6 +150,17 @@ function UpdatePlexList() c.MenuButtons.children[i].children[1].children[0].geometry.scrollDelay = 0; } } + else if ((i == 0) & (status != "")) + { + // Nothing to list yet: the first row says why. + c.MenuButtons.children[0].visible = true; + c.MenuButtons.children[0].children[1].children[0].geometry.text = status; + c.MenuButtons.children[0].children[0].children[0].appearance.material.name = "GameHilite"; + c.MenuButtons.children[0].children[0].children[0].appearance.texture.url = "outline.tga"; + c.MenuButtons.children[0].children[1].children[0].appearance.name = "NavType"; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollRate = 0; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollDelay = 0; + } else { c.MenuButtons.children[i].visible = false; @@ -155,6 +169,9 @@ function UpdatePlexList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sPlexStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -463,7 +480,7 @@ DEF thePlexMenu Level BindActiveList(); if (bPlexLoaded == 1) { - if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster)) + if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster) | (thePlexLibrary.GetStatus(nPlexView) != sPlexStatus)) UpdatePlexList(); } else if (nPlexCount != nPlexLastCount) diff --git a/xips-source/jellyfin/jellyfin.xap b/xips-source/jellyfin/jellyfin.xap index 572bea8..74aa938 100644 --- a/xips-source/jellyfin/jellyfin.xap +++ b/xips-source/jellyfin/jellyfin.xap @@ -16,6 +16,7 @@ var nJfCursorBackup1; // saved cursor when drilling item -> seasons var nJfCursorBackup2; // saved cursor when drilling season -> episodes var sJfPoster; // poster url on the CD now; behavior swaps it when art lands var bJfLoaded; // the chrome scene is in, so the behavior can touch it +var sJfStatus; // what the empty list says (loading, can't reach); "" with rows function initialize() @@ -30,6 +31,7 @@ function initialize() nJfCursorBackup1 = 0; nJfCursorBackup2 = 0; sJfPoster = ""; + sJfStatus = ""; } @@ -69,7 +71,7 @@ function GetHeaderText() return server; if (nJfView == 1) return server + " / " + theJellyfinLibrary.GetListTitle(); - var showTitle = theJellyfinLibrary.GetItemTitle(nJfCursorBackup1); + var showTitle = theJellyfinLibrary.GetItemName(nJfCursorBackup1); if (nJfView == 2) return showTitle; return showTitle + " / " + theJellyfinLibrary.GetSeasonTitle(nJfCursorBackup2); @@ -117,6 +119,7 @@ function StartJellyfinLevel() function UpdateJellyfinList() { var c = theJellyfinMenu.children[0].children[0]; + var status = theJellyfinLibrary.GetStatus(nJfView); if (nJfCursor < nJfScroll) nJfScroll = nJfCursor; @@ -147,6 +150,17 @@ function UpdateJellyfinList() c.MenuButtons.children[i].children[1].children[0].geometry.scrollDelay = 0; } } + else if ((i == 0) & (status != "")) + { + // Nothing to list yet: the first row says why. + c.MenuButtons.children[0].visible = true; + c.MenuButtons.children[0].children[1].children[0].geometry.text = status; + c.MenuButtons.children[0].children[0].children[0].appearance.material.name = "GameHilite"; + c.MenuButtons.children[0].children[0].children[0].appearance.texture.url = "outline.tga"; + c.MenuButtons.children[0].children[1].children[0].appearance.name = "NavType"; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollRate = 0; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollDelay = 0; + } else { c.MenuButtons.children[i].visible = false; @@ -155,6 +169,9 @@ function UpdateJellyfinList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sJfStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -463,7 +480,7 @@ DEF theJellyfinMenu Level BindActiveList(); if (bJfLoaded == 1) { - if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster)) + if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster) | (theJellyfinLibrary.GetStatus(nJfView) != sJfStatus)) UpdateJellyfinList(); } else if (nJfCount != nJfLastCount) diff --git a/xips-source/plex/plex.xap b/xips-source/plex/plex.xap index e89c601..0a2bd3e 100644 --- a/xips-source/plex/plex.xap +++ b/xips-source/plex/plex.xap @@ -16,6 +16,7 @@ var nPlexCursorBackup1; // saved cursor when drilling item -> seasons var nPlexCursorBackup2; // saved cursor when drilling season -> episodes var sPlexPoster; // poster url on the CD now; behavior swaps it when art lands var bPlexLoaded; // the chrome scene is in, so the behavior can touch it +var sPlexStatus; // what the empty list says (loading, can't reach); "" with rows function initialize() @@ -30,6 +31,7 @@ function initialize() nPlexCursorBackup1 = 0; nPlexCursorBackup2 = 0; sPlexPoster = ""; + sPlexStatus = ""; } @@ -69,7 +71,7 @@ function GetHeaderText() return server; if (nPlexView == 1) return server + " / " + thePlexLibrary.GetListTitle(); - var showTitle = thePlexLibrary.GetItemTitle(nPlexCursorBackup1); + var showTitle = thePlexLibrary.GetItemName(nPlexCursorBackup1); if (nPlexView == 2) return showTitle; return showTitle + " / " + thePlexLibrary.GetSeasonTitle(nPlexCursorBackup2); @@ -117,6 +119,7 @@ function StartPlexLevel() function UpdatePlexList() { var c = thePlexMenu.children[0].children[0]; + var status = thePlexLibrary.GetStatus(nPlexView); if (nPlexCursor < nPlexScroll) nPlexScroll = nPlexCursor; @@ -147,6 +150,17 @@ function UpdatePlexList() c.MenuButtons.children[i].children[1].children[0].geometry.scrollDelay = 0; } } + else if ((i == 0) & (status != "")) + { + // Nothing to list yet: the first row says why. + c.MenuButtons.children[0].visible = true; + c.MenuButtons.children[0].children[1].children[0].geometry.text = status; + c.MenuButtons.children[0].children[0].children[0].appearance.material.name = "GameHilite"; + c.MenuButtons.children[0].children[0].children[0].appearance.texture.url = "outline.tga"; + c.MenuButtons.children[0].children[1].children[0].appearance.name = "NavType"; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollRate = 0; + c.MenuButtons.children[0].children[1].children[0].geometry.scrollDelay = 0; + } else { c.MenuButtons.children[i].visible = false; @@ -155,6 +169,9 @@ function UpdatePlexList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sPlexStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -463,7 +480,7 @@ DEF thePlexMenu Level BindActiveList(); if (bPlexLoaded == 1) { - if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster)) + if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster) | (thePlexLibrary.GetStatus(nPlexView) != sPlexStatus)) UpdatePlexList(); } else if (nPlexCount != nPlexLastCount) From f6a669b67e7ac2914d3de2df7529ec45a656fff3 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:20:50 -0500 Subject: [PATCH 29/46] Added Continue Watching and Next Up above the Jellyfin libraries They show at the top of the library list when they have anything, episodes labeled with the show and S1E02. Playing something with a resume point now picks up there, and X plays it from the start. Plex gets its On Deck list the same way, untested without a server. --- Data/Xips/default.xip | Bin 1691564 -> 1692946 bytes theseus/desktop/desktop_nodes.cpp | 87 +++++++++++++++++------ theseus/desktop/jellyfin_client.cpp | 39 ++++++++++ theseus/desktop/jellyfin_client.h | 3 + theseus/desktop/media_player.cpp | 11 +++ theseus/desktop/media_player.h | 1 + theseus/desktop/plex_client.cpp | 21 ++++++ theseus/desktop/plex_client.h | 3 + xips-source/default-desktop/Jellyfin.xap | 34 ++++++++- xips-source/default-desktop/Plex.xap | 34 ++++++++- xips-source/jellyfin/jellyfin.xap | 34 ++++++++- xips-source/plex/plex.xap | 34 ++++++++- 12 files changed, 277 insertions(+), 24 deletions(-) diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index 1e2be157d55453a2ab97e9c62fab0db127e382c7..65113d02de28c26bf7775d8f9047d064f18ca4f9 100644 GIT binary patch delta 931 zcmZ28KYh}wbiN4B0D}We3=E<`7<6eO-#5P|0|qz_)l|n&IVx>Y_QGTvMNk*zdQfhi;US4Ki zxE5?Rc-U=h6$~^LYNk6}5z&}# zq%0&d{myj}+38K&MMT&*tGPHiIj8%d6tU0&GBVQ?G&D*o3sMzqZ55Q#@^eyBiY;=nG?+PmifAeTV-lEBa4Llc_FE=V y9(Z6Y;8YDUm~*=MFA*(8pveS`#ufC_fkE%kzKm5Ah{b?d9Ec^hFJqNtI|Tqf2pqWp delta 269 zcmbQVDt*oTbiN4B0D}We3=E<`_~y(+zHfdGJQ*dD|P!c0KS48$xz%nHP8K+F!r96-zo#9Tnk4a7V^ z%nQVPK+F%s0zfPX#6mzUygi6f~S#1^B0*;SzP& dUUf?(Q5TnzcAyd<76W2&AePvEhD*}z6aX5|J?sDg diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index 75d03b5..c1cc06e 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3717,23 +3717,39 @@ class CPlexLibrary : public CNode int GetItemCount() { return (int)CurrentItems().size(); } + // "Dracula (1931)", or "Show ยท S1E02 ยท Title" for an episode out on the + // On Deck shelf. + static std::string ItemLabel(const PlexItem& it) + { + if (it.type == "episode" && !it.showTitle.empty()) { + std::string s = it.showTitle; + std::string code = EpisodeCode(it.seasonIndex, it.episodeIndex); + if (!code.empty()) { s += " \xC2\xB7 "; s += code; } + return s + " \xC2\xB7 " + it.title; + } + std::string s = it.title; + if (!it.year.empty()) { s += " ("; s += it.year; s += ")"; } + return s; + } + // Title and year without the watch mark, for the header. CStrObject* GetItemName(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; - std::string s = items[i].title; - if (!items[i].year.empty()) { s += " ("; s += items[i].year; s += ")"; } - return new CStrObject(_T(s.c_str())); + return new CStrObject(_T(ItemLabel(items[i]).c_str())); } + // X plays from the top instead of the resume point. + bool m_startOver = false; + void SetStartOver(int on) { m_startOver = on != 0; } + CStrObject* GetItemTitle(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; const PlexItem& it = items[i]; - std::string s = it.title; - if (!it.year.empty()) { s += " ("; s += it.year; s += ")"; } + std::string s = ItemLabel(it); if (!IsFolderType(it.type)) s = Mark(it) + s; return new CStrObject(_T(s.c_str())); } @@ -3819,7 +3835,8 @@ class CPlexLibrary : public CNode void PlayRatingKey(const std::string& ratingKey, const std::string& title, - const std::string& subtitle) + const std::string& subtitle, + int offsetMs = 0) { if (m_serverUri.empty()) m_serverUri = Plex_GetActiveServerUri(); if (m_serverUri.empty() || ratingKey.empty()) return; @@ -3829,7 +3846,8 @@ class CPlexLibrary : public CNode ratingKey.c_str()); return; } - if (!MediaPlayer_Open(url.c_str())) { + double start = m_startOver ? 0.0 : offsetMs / 1000.0; + if (!MediaPlayer_OpenAt(url.c_str(), start)) { fprintf(stderr, "[Plex] MediaPlayer_Open failed for %s\n", ratingKey.c_str()); return; @@ -3853,9 +3871,14 @@ class CPlexLibrary : public CNode std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return; const PlexItem& it = items[i]; + if (IsFolderType(it.type)) return; std::string sub = "Plex"; - if (!it.year.empty()) { sub += " \xC2\xB7 "; sub += it.year; } - PlayRatingKey(it.ratingKey, it.title, sub); + if (it.type == "episode" && !it.showTitle.empty()) { + sub = it.showTitle; + std::string code = EpisodeCode(it.seasonIndex, it.episodeIndex); + if (!code.empty()) { sub += " \xC2\xB7 "; sub += code; } + } else if (!it.year.empty()) { sub += " \xC2\xB7 "; sub += it.year; } + PlayRatingKey(it.ratingKey, it.title, sub, it.offsetMs); } // ----- TV drill: show -> seasons -> episodes ----- @@ -3980,7 +4003,7 @@ class CPlexLibrary : public CNode std::string code = EpisodeCode(seasons[m_currentSeason].index, e.index); if (!code.empty()) { sub += " \xC2\xB7 "; sub += code; } } - PlayRatingKey(e.ratingKey, e.title, sub); + PlayRatingKey(e.ratingKey, e.title, sub, e.offsetMs); } int IsSignedIn() { return Plex_HasToken() ? 1 : 0; } @@ -4078,6 +4101,7 @@ START_NODE_FUN(CPlexLibrary, CNode) NODE_FUN_SI(GetLibraryRow) NODE_FUN_SI(GetStatus) NODE_FUN_SI(GetItemName) + NODE_FUN_VI(SetStartOver) END_NODE_FUN() @@ -4208,23 +4232,39 @@ class CJellyfinLibrary : public CNode int GetItemCount() { return (int)CurrentItems().size(); } + // "Dracula (1931)", or "Pioneer One ยท S1E02 ยท The Man From Mars" for an + // episode out on the Continue Watching or Next Up shelf. + static std::string ItemLabel(const JellyfinItem& it) + { + if (it.type == "Episode" && !it.seriesName.empty()) { + std::string s = it.seriesName; + std::string code = EpisodeCode(it.seasonIndex, it.episodeIndex); + if (!code.empty()) { s += " \xC2\xB7 "; s += code; } + return s + " \xC2\xB7 " + it.name; + } + std::string s = it.name; + if (!it.year.empty()) { s += " ("; s += it.year; s += ")"; } + return s; + } + // Title and year without the watch mark, for the header. CStrObject* GetItemName(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; - std::string s = items[i].name; - if (!items[i].year.empty()) { s += " ("; s += items[i].year; s += ")"; } - return new CStrObject(_T(s.c_str())); + return new CStrObject(_T(ItemLabel(items[i]).c_str())); } + // X plays from the top instead of the resume point. + bool m_startOver = false; + void SetStartOver(int on) { m_startOver = on != 0; } + CStrObject* GetItemTitle(int i) { std::vector items = CurrentItems(); if (i < 0 || i >= (int)items.size()) return new CStrObject; const JellyfinItem& it = items[i]; - std::string s = it.name; - if (!it.year.empty()) { s += " ("; s += it.year; s += ")"; } + std::string s = ItemLabel(it); if (!it.isFolder || it.type == "Series") s = Mark(it) + s; return new CStrObject(_T(s.c_str())); } @@ -4295,14 +4335,16 @@ class CJellyfinLibrary : public CNode void PlayRatingKey(const std::string& itemId, const std::string& title, - const std::string& subtitle) + const std::string& subtitle, + long long posTicks = 0) { std::string url = Jellyfin_StreamUrl(itemId, m_playAudio); if (url.empty()) { fprintf(stderr, "[Jellyfin] stream URL build failed for %s\n", itemId.c_str()); return; } - if (!MediaPlayer_Open(url.c_str())) { + double start = m_startOver ? 0.0 : (double)Secs(posTicks); + if (!MediaPlayer_OpenAt(url.c_str(), start)) { fprintf(stderr, "[Jellyfin] MediaPlayer_Open failed\n"); return; } @@ -4330,8 +4372,12 @@ class CJellyfinLibrary : public CNode if (it.isFolder) return; m_playAudio = (it.type == "Audio"); std::string sub = "Jellyfin"; - if (!it.year.empty()) { sub += " \xC2\xB7 "; sub += it.year; } - PlayRatingKey(it.id, it.name, sub); + if (it.type == "Episode" && !it.seriesName.empty()) { + sub = it.seriesName; + std::string code = EpisodeCode(it.seasonIndex, it.episodeIndex); + if (!code.empty()) { sub += " \xC2\xB7 "; sub += code; } + } else if (!it.year.empty()) { sub += " \xC2\xB7 "; sub += it.year; } + PlayRatingKey(it.id, it.name, sub, it.posTicks); } void DrillIntoShow(int i) @@ -4455,7 +4501,7 @@ class CJellyfinLibrary : public CNode std::string code = EpisodeCode(seasons[m_currentSeason].index, e.index); if (!code.empty()) { sub += " \xC2\xB7 "; sub += code; } } - PlayRatingKey(e.id, e.name, sub); + PlayRatingKey(e.id, e.name, sub, e.posTicks); } void QueueEpisodeArt(int i) @@ -4701,6 +4747,7 @@ START_NODE_FUN(CJellyfinLibrary, CNode) NODE_FUN_SI(GetLibraryRow) NODE_FUN_SI(GetStatus) NODE_FUN_SI(GetItemName) + NODE_FUN_VI(SetStartOver) END_NODE_FUN() diff --git a/theseus/desktop/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index 1a48024..eb3bdf7 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -369,6 +369,12 @@ static JellyfinItem ParseItem(const std::string& obj) it.primaryTag = ParsePrimaryTag(obj); it.isFolder = Json_GetBool(obj, "IsFolder"); ParseDetails(obj, it); + if (it.type == "Episode") { + it.seriesName = Json_GetString(obj, "SeriesName"); + int sn = Json_GetInt(obj, "ParentIndexNumber"), en = Json_GetInt(obj, "IndexNumber"); + if (sn > 0) it.seasonIndex = std::to_string(sn); + if (en > 0) it.episodeIndex = std::to_string(en); + } int y = Json_GetInt(obj, "ProductionYear"); if (y > 0) { char buf[8]; snprintf(buf, sizeof(buf), "%d", y); @@ -377,6 +383,20 @@ static JellyfinItem ParseItem(const std::string& obj) return it; } +static bool FetchItemList(const std::string& url, std::vector& out) +{ + HttpResponse r = Http_Get(url, JellyfinHeaders(g_jellyfinToken)); + out.clear(); + if (!r.ok()) return false; + size_t arr = Json_FindArray(r.body, "Items"); + if (arr == std::string::npos) return true; + for (const auto& obj : Json_SplitArray(r.body, arr)) { + JellyfinItem it = ParseItem(obj); + if (!it.id.empty()) out.push_back(it); + } + return true; +} + static bool FetchItemsForLibrary(const std::string& libraryId, std::vector& out) { char url[1024]; @@ -449,6 +469,25 @@ static void SyncWorker() FetchItemsForLibrary(lib.id, itemsById[lib.id]); } + // Continue Watching and Next Up go above the libraries, when there's + // anything in them. + SetSyncPhase(gen, "Loading Continue Watching", 950); + std::string base = std::string(g_jellyfinUrl); + const char* fields = "Fields=Overview,ProductionYear,Genres&EnableUserData=true"; + std::vector resume, nextUp; + FetchItemList(base + "/Users/" + g_jellyfinUserId + "/Items/Resume?Limit=24&MediaTypes=Video&" + fields, resume); + FetchItemList(base + "/Shows/NextUp?UserId=" + g_jellyfinUserId + "&Limit=24&" + fields, nextUp); + std::vector shelves; + if (!resume.empty()) { + shelves.push_back({ "uix-resume", "Continue Watching", "resume" }); + itemsById["uix-resume"] = std::move(resume); + } + if (!nextUp.empty()) { + shelves.push_back({ "uix-nextup", "Next Up", "nextup" }); + itemsById["uix-nextup"] = std::move(nextUp); + } + if (!libs.empty()) libs.insert(libs.begin(), shelves.begin(), shelves.end()); + size_t nLibs = libs.size(); SetSyncPhase(gen, "Jellyfin library ready", 1000); { diff --git a/theseus/desktop/jellyfin_client.h b/theseus/desktop/jellyfin_client.h index 94be59b..cbccf73 100644 --- a/theseus/desktop/jellyfin_client.h +++ b/theseus/desktop/jellyfin_client.h @@ -30,6 +30,9 @@ struct JellyfinItem : JellyfinDetails { std::string type; // "Movie" | "Series" | "Audio" | ... std::string primaryTag; // image tag for Primary image URL bool isFolder = false; // opens to more items (folders, box sets, albums) + std::string seriesName; // episodes in Continue Watching / Next Up + std::string seasonIndex; + std::string episodeIndex; }; struct JellyfinSeason : JellyfinDetails { diff --git a/theseus/desktop/media_player.cpp b/theseus/desktop/media_player.cpp index c108b8d..882ff58 100644 --- a/theseus/desktop/media_player.cpp +++ b/theseus/desktop/media_player.cpp @@ -170,12 +170,22 @@ void MediaPlayer_Shutdown() { // ============================================================================ bool MediaPlayer_Open(const char* path) { + return MediaPlayer_OpenAt(path, 0.0); +} + +bool MediaPlayer_OpenAt(const char* path, double startSeconds) { // Re-init if a previous Stop tore mpv down. This is the normal path // for any playback after the first one in the session. if (!s_mpv) { if (!MediaPlayer_Init()) return false; } + // start is a global option, so it's put back once the file loads. + if (startSeconds > 0.0) { + char start[32]; + snprintf(start, sizeof(start), "%.0f", startSeconds); + mpv_set_property_string(s_mpv, "start", start); + } const char* cmd[] = { "loadfile", path, NULL }; mpv_command(s_mpv, cmd); @@ -417,6 +427,7 @@ void MediaPlayer_Update() { } case MPV_EVENT_FILE_LOADED: s_state = MP_PLAYING; + mpv_set_property_string(s_mpv, "start", "none"); break; default: break; diff --git a/theseus/desktop/media_player.h b/theseus/desktop/media_player.h index 82f4d93..8aaf6d1 100644 --- a/theseus/desktop/media_player.h +++ b/theseus/desktop/media_player.h @@ -22,6 +22,7 @@ void MediaPlayer_Shutdown(); // Open a media file for playback bool MediaPlayer_Open(const char* path); +bool MediaPlayer_OpenAt(const char* path, double startSeconds); // resume partway in // Transport controls void MediaPlayer_Play(); diff --git a/theseus/desktop/plex_client.cpp b/theseus/desktop/plex_client.cpp index f2f84c7..5a9a629 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -369,6 +369,12 @@ static PlexItem ParseItem(const std::string& obj, const std::string& serverUri) it.thumbUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "thumb")); it.artUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "art")); it.type = Json_GetString(obj, "type"); + if (it.type == "episode") { + it.showTitle = Json_GetString(obj, "grandparentTitle"); + int sn = Json_GetInt(obj, "parentIndex"), en = Json_GetInt(obj, "index"); + if (sn > 0) it.seasonIndex = std::to_string(sn); + if (en > 0) it.episodeIndex = std::to_string(en); + } return it; } @@ -653,6 +659,21 @@ static void SyncWorker() itemsByKey[lib.sectionKey] = std::move(items); } + // On Deck (what you're partway through and the next episodes) goes above + // the libraries when there's anything on it. + HttpResponse dr = Http_Get(serverUri + "/library/onDeck", PlexHeaders(true, true)); + if (dr.ok()) { + std::vector deck = ParseItems(dr.body, serverUri); + if (!deck.empty() && !libs.empty()) { + PlexLibrary shelf; + shelf.sectionKey = "uix-ondeck"; + shelf.title = "On Deck"; + shelf.type = "ondeck"; + libs.insert(libs.begin(), shelf); + itemsByKey[shelf.sectionKey] = std::move(deck); + } + } + // Publish atomically. Readers see old snapshot or whole new one. size_t nLibs = libs.size(); { diff --git a/theseus/desktop/plex_client.h b/theseus/desktop/plex_client.h index fb71be6..25d0a9f 100644 --- a/theseus/desktop/plex_client.h +++ b/theseus/desktop/plex_client.h @@ -41,6 +41,9 @@ struct PlexItem : PlexDetails { std::string artUrl; // absolute URL (hero/fanart) std::string summary; // plot synopsis std::string type; // "movie" | "show" | "track" | "artist" | ... + std::string showTitle; // episodes on the On Deck shelf + std::string seasonIndex; + std::string episodeIndex; }; struct PlexSeason : PlexDetails { diff --git a/xips-source/default-desktop/Jellyfin.xap b/xips-source/default-desktop/Jellyfin.xap index 74aa938..8900a77 100644 --- a/xips-source/default-desktop/Jellyfin.xap +++ b/xips-source/default-desktop/Jellyfin.xap @@ -437,7 +437,39 @@ DEF theJellyfinMenu Level UpdateJellyfinList(); } - function OnXDown() { PlaySoundError(); } + // X: play from the beginning instead of the resume point. + function OnXDown() + { + if ((nJfCount <= 0) | (theJellyfinLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (nJfView == 1) + { + var type = theJellyfinLibrary.GetItemType(nJfCursor); + if ((type == "folder") | (type == "show")) + { + PlaySoundError(); + return; + } + PlaySoundA(); + theJellyfinLibrary.SetStartOver(1); + theJellyfinLibrary.PlayItem(nJfCursor); + theJellyfinLibrary.SetStartOver(0); + } + else if (nJfView == 3) + { + PlaySoundA(); + theJellyfinLibrary.SetStartOver(1); + theJellyfinLibrary.PlayEpisode(nJfCursor); + theJellyfinLibrary.SetStartOver(0); + } + else + { + PlaySoundError(); + } + } function OnYDown() { // Y: modal info with full plot. No-op at library view. diff --git a/xips-source/default-desktop/Plex.xap b/xips-source/default-desktop/Plex.xap index 0a2bd3e..28a62b0 100644 --- a/xips-source/default-desktop/Plex.xap +++ b/xips-source/default-desktop/Plex.xap @@ -437,7 +437,39 @@ DEF thePlexMenu Level UpdatePlexList(); } - function OnXDown() { PlaySoundError(); } + // X: play from the beginning instead of the resume point. + function OnXDown() + { + if ((nPlexCount <= 0) | (thePlexLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (nPlexView == 1) + { + var type = thePlexLibrary.GetItemType(nPlexCursor); + if ((type == "folder") | (type == "show")) + { + PlaySoundError(); + return; + } + PlaySoundA(); + thePlexLibrary.SetStartOver(1); + thePlexLibrary.PlayItem(nPlexCursor); + thePlexLibrary.SetStartOver(0); + } + else if (nPlexView == 3) + { + PlaySoundA(); + thePlexLibrary.SetStartOver(1); + thePlexLibrary.PlayEpisode(nPlexCursor); + thePlexLibrary.SetStartOver(0); + } + else + { + PlaySoundError(); + } + } function OnYDown() { // Y: modal info with full plot. No-op at library view. diff --git a/xips-source/jellyfin/jellyfin.xap b/xips-source/jellyfin/jellyfin.xap index 74aa938..8900a77 100644 --- a/xips-source/jellyfin/jellyfin.xap +++ b/xips-source/jellyfin/jellyfin.xap @@ -437,7 +437,39 @@ DEF theJellyfinMenu Level UpdateJellyfinList(); } - function OnXDown() { PlaySoundError(); } + // X: play from the beginning instead of the resume point. + function OnXDown() + { + if ((nJfCount <= 0) | (theJellyfinLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (nJfView == 1) + { + var type = theJellyfinLibrary.GetItemType(nJfCursor); + if ((type == "folder") | (type == "show")) + { + PlaySoundError(); + return; + } + PlaySoundA(); + theJellyfinLibrary.SetStartOver(1); + theJellyfinLibrary.PlayItem(nJfCursor); + theJellyfinLibrary.SetStartOver(0); + } + else if (nJfView == 3) + { + PlaySoundA(); + theJellyfinLibrary.SetStartOver(1); + theJellyfinLibrary.PlayEpisode(nJfCursor); + theJellyfinLibrary.SetStartOver(0); + } + else + { + PlaySoundError(); + } + } function OnYDown() { // Y: modal info with full plot. No-op at library view. diff --git a/xips-source/plex/plex.xap b/xips-source/plex/plex.xap index 0a2bd3e..28a62b0 100644 --- a/xips-source/plex/plex.xap +++ b/xips-source/plex/plex.xap @@ -437,7 +437,39 @@ DEF thePlexMenu Level UpdatePlexList(); } - function OnXDown() { PlaySoundError(); } + // X: play from the beginning instead of the resume point. + function OnXDown() + { + if ((nPlexCount <= 0) | (thePlexLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (nPlexView == 1) + { + var type = thePlexLibrary.GetItemType(nPlexCursor); + if ((type == "folder") | (type == "show")) + { + PlaySoundError(); + return; + } + PlaySoundA(); + thePlexLibrary.SetStartOver(1); + thePlexLibrary.PlayItem(nPlexCursor); + thePlexLibrary.SetStartOver(0); + } + else if (nPlexView == 3) + { + PlaySoundA(); + thePlexLibrary.SetStartOver(1); + thePlexLibrary.PlayEpisode(nPlexCursor); + thePlexLibrary.SetStartOver(0); + } + else + { + PlaySoundError(); + } + } function OnYDown() { // Y: modal info with full plot. No-op at library view. From dbaaadf1f0c190d88b3f02ef3cb9a95a3fd20fa4 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:35:27 -0500 Subject: [PATCH 30/46] Added Import Epic Games to the guide The Games & Playlists page now reads the Epic launcher's install manifests and Heroic's Epic list when either is on disk, and adds those games under Games. Heroic's cover art gets fetched when the game has no icon of its own. Needs a test on a real Windows Epic install. --- build/Makefile | 3 + theseus/desktop/game_art.cpp | 32 ++++-- theseus/desktop/game_art.h | 3 + theseus/desktop/guide.cpp | 30 +++++- theseus/desktop/launchers/epic.cpp | 132 +++++++++++++++++++++++++ theseus/desktop/launchers/stores.cpp | 141 +++++++++++++++++++++++++++ theseus/desktop/launchers/stores.h | 49 ++++++++++ theseus/desktop/store_import.cpp | 70 +++++++++++++ 8 files changed, 453 insertions(+), 7 deletions(-) create mode 100644 theseus/desktop/launchers/epic.cpp create mode 100644 theseus/desktop/launchers/stores.cpp create mode 100644 theseus/desktop/launchers/stores.h create mode 100644 theseus/desktop/store_import.cpp diff --git a/build/Makefile b/build/Makefile index 7c8b023..4359115 100644 --- a/build/Makefile +++ b/build/Makefile @@ -875,6 +875,8 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/launchers/xemu.cpp \ $(THESEUS_SRC)/desktop/launchers/pcsx2.cpp \ $(THESEUS_SRC)/desktop/launchers/emu_find.cpp \ + $(THESEUS_SRC)/desktop/launchers/stores.cpp \ + $(THESEUS_SRC)/desktop/launchers/epic.cpp \ $(THESEUS_SRC)/desktop/title_sanitize.cpp \ $(THESEUS_SRC)/desktop/udata_synth.cpp \ $(THESEUS_SRC)/desktop/desktop_stubs.cpp \ @@ -895,6 +897,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/icon_compress.cpp \ $(THESEUS_SRC)/desktop/exe_icon.cpp \ $(THESEUS_SRC)/desktop/xdg_apps.cpp \ + $(THESEUS_SRC)/desktop/store_import.cpp \ $(THESEUS_SRC)/desktop/game_art.cpp \ $(THESEUS_SRC)/desktop/playlist.cpp \ $(THESEUS_SRC)/desktop/playlist_maker.cpp \ diff --git a/theseus/desktop/game_art.cpp b/theseus/desktop/game_art.cpp index 6cc9b50..e55087f 100644 --- a/theseus/desktop/game_art.cpp +++ b/theseus/desktop/game_art.cpp @@ -1,8 +1,9 @@ // game_art.cpp: box art for games that came in without an icon. // -// Three places to look, no key needed for the first two: +// Four places to look, no key needed for the first three: // Steam's public CDN by appid, for steam:// launches. Also keeps the bigger // capsule and header art in Configs/art for whatever wants it. +// The cover a store importer handed over (GameArt_HintArt). // libretro-thumbnails by system and exact rom name, for RetroArch and ES-DE. // SteamGridDB, only when the user typed their own API key into Settings. // @@ -221,6 +222,7 @@ struct ArtJob { int appid = 0; std::string system; // libretro name, empty when it isn't an emulated game std::string romStem; + std::string artUrl; // a store's cover bool wantIcon = false, wantBig = false, trySgdb = false; std::string iconDir, artDir, sgdbKey; }; @@ -235,7 +237,7 @@ static struct { } s_q; // Main thread only from here down to the workers. -struct Hint { std::string system, rom; }; +struct Hint { std::string system, rom, art; }; static std::map s_hints; static std::set s_seen; // queued this run static std::map s_misses; // titleID -> KeyTag of the SteamGridDB key tried, 0 for none @@ -255,10 +257,15 @@ static std::string MissFile() { return ArtDir() + "/misses.txt"; } void GameArt_Hint(const char* titleID, const char* system, const char* romPath) { if (!titleID || !*titleID) return; - Hint h; + Hint& h = s_hints[titleID]; h.system = system ? system : ""; h.rom = romPath ? romPath : ""; - s_hints[titleID] = h; +} + +void GameArt_HintArt(const char* titleID, const char* url) +{ + if (!titleID || !*titleID || !url || strncmp(url, "https://", 8) != 0) return; + s_hints[titleID].art = url; } const char* GameArt_CachedPath(const char* titleID, const char* kind) @@ -337,6 +344,17 @@ static bool FromLibretro(const ArtJob& j) return false; } +static bool FromStore(const ArtJob& j) +{ + std::string tmp = j.artDir + "/" + j.titleID + ".store"; + if (!FetchTo(j.artUrl, tmp)) return false; + std::string cover = j.artDir + "/" + j.titleID + ".cover.jpg"; + Icons_FitFile(tmp.c_str(), cover.c_str(), 600, 90); + bool placed = PlaceIcon(j, tmp); + remove(tmp.c_str()); + return placed; +} + // SteamGridDB: square grids first, they suit the orb. Never webp, stb can't read it. static bool FromSteamGridDb(const ArtJob& j) { @@ -381,6 +399,7 @@ static void Worker() Plat_MkdirP(j.artDir.c_str()); bool got = false; if (j.appid > 0) got = FromSteam(j); + if (!got && j.wantIcon && !j.artUrl.empty()) got = FromStore(j); if (!got && j.wantIcon && !j.system.empty()) got = FromLibretro(j); if (!got && j.wantIcon && j.trySgdb) got = FromSteamGridDb(j); if (got) fprintf(stderr, "[art] %s: got art\n", j.name.c_str()); @@ -509,7 +528,8 @@ static void Scan() std::string sys, rom, core, stem, ext; std::map::iterator h = s_hints.find(j.titleID); if (h != s_hints.end()) { sys = h->second.system; rom = h->second.rom; } - else RomFromLaunch(g.launch, rom, core); + if (h == s_hints.end() || (sys.empty() && rom.empty())) RomFromLaunch(g.launch, rom, core); + if (h != s_hints.end() && !missed) j.artUrl = h->second.art; SplitRom(rom, stem, ext); if (sys.empty() && !ext.empty() && SystemForExt(ext.c_str())) sys = SystemForExt(ext.c_str()); if (sys.empty() && !core.empty() && SystemForCore(core.c_str())) sys = SystemForCore(core.c_str()); @@ -517,7 +537,7 @@ static void Scan() if (lr && !missed) { j.system = lr; j.romStem = stem; } } j.trySgdb = haveKey && j.wantIcon; - if (!j.wantBig && j.system.empty() && !j.trySgdb) continue; + if (!j.wantBig && j.system.empty() && j.artUrl.empty() && !j.trySgdb) continue; j.iconDir = iconDir; j.artDir = artDir; diff --git a/theseus/desktop/game_art.h b/theseus/desktop/game_art.h index 72be37e..fcf3118 100644 --- a/theseus/desktop/game_art.h +++ b/theseus/desktop/game_art.h @@ -5,6 +5,9 @@ // ("snes") and the rom path. Main thread only. void GameArt_Hint(const char* titleID, const char* system, const char* romPath); +// A public cover picture a store lists for the game. Main thread only. +void GameArt_HintArt(const char* titleID, const char* url); + // Once a frame on the main thread. Notices library changes, queues whatever // is missing and lets the grid pick up art as it lands. void GameArt_Tick(); diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index 6f1b4c2..4f365b5 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -35,6 +35,7 @@ #include "ui_overlay.h" #include "pads.h" #include "launchers/steam.h" +#include "launchers/stores.h" #include #include #include @@ -146,6 +147,17 @@ int TitleMaker_ImportRetroArch(int* outSkipped); extern int Title_SanitizeName(const char*, char*, size_t); extern char s_esdePath[512]; +// PC stores with an Import row of their own, shown only when the store is here. +static const struct Store { + const char* label; + const char* help; + bool (*found)(); + void (*scan)(std::vector&); +} kStores[] = { + { "Import Epic Games", "Installed games from the Epic launcher and Heroic.", Epic_Found, Epic_Scan }, +}; +static const int kStoreCount = (int)(sizeof(kStores) / sizeof(kStores[0])); + static const char* kCategories[] = { "Games", "Applications", "Homebrew", "Emulators", "Dashboards" }; static const int kCategoryCount = (int)(sizeof(kCategories) / sizeof(kCategories[0])); @@ -282,7 +294,7 @@ enum Act { GA_PLEX, GA_PLEXOUT, GA_JELLYFIN, GA_JELLYFINOUT, GA_XBOX, GA_XBOXOUT, GA_TEXT, GA_NAME, GA_JELLYFINURL, GA_GAMELIST, GA_GAME, GA_LAUNCH, GA_FAVORITE, GA_HIDE, GA_LETTER, GA_SEARCH, - GA_FINDEMU, GA_RUNNER, GA_APPS, GA_APP, GA_APPGAMES, GA_GAMEOPT, + GA_FINDEMU, GA_RUNNER, GA_APPS, GA_APP, GA_APPGAMES, GA_GAMEOPT, GA_STORE, GA_COUNT }; @@ -352,6 +364,7 @@ static struct Guide { int copied; std::string result[GA_COUNT]; + std::string storeResult[kStoreCount]; std::string browseDir, pickedPath, pickedName, added; std::string found[4]; // what each Find row turned up std::vector apps; // the Linux app menu, read when its list opens @@ -541,6 +554,9 @@ static void Build() Add("Import Steam Library", g.result[GA_STEAM].c_str(), "Adds installed Steam games with their icons.", GA_STEAM); Add("Import RetroArch Recent", g.result[GA_RETROARCH].c_str(), "Adds what RetroArch's playlists list.", GA_RETROARCH); Add("Refresh ES-DE", g.result[GA_ESDE].c_str(), "Reads your ES-DE game lists again.", GA_ESDE); + for (int s = 0; s < kStoreCount; s++) + if (kStores[s].found()) + Add(kStores[s].label, g.storeResult[s].c_str(), kStores[s].help, GA_STORE, s); if (strcmp(Host_Name(), "Linux") == 0) Add("Import Linux Apps", "", "Games and apps from your app menu, Flatpak and your Desktop.", GA_APPS); char n[32]; @@ -1210,6 +1226,18 @@ static void Select() Build(); break; } + case GA_STORE: { + if (r.arg < 0 || r.arg >= kStoreCount) break; + std::vector list; + kStores[r.arg].scan(list); + int added = 0, had = 0; + StoreGames_Add(list, &added, &had); + char msg[64]; + snprintf(msg, sizeof(msg), "%d new, %d already in", added, had); + g.storeResult[r.arg] = msg; + Build(); + break; + } case GA_ESDE: if (!s_esdePath[0]) { g.result[GA_ESDE] = "Set its folder first"; diff --git a/theseus/desktop/launchers/epic.cpp b/theseus/desktop/launchers/epic.cpp new file mode 100644 index 0000000..6b8c599 --- /dev/null +++ b/theseus/desktop/launchers/epic.cpp @@ -0,0 +1,132 @@ +// epic.cpp: Epic Games Store installs. The launcher writes a JSON .item per +// install into its Manifests folder (ProgramData on Windows, Application +// Support on a Mac); a game launches through the launcher's own URL so +// sign-in and cloud saves still happen. Heroic keeps its Epic installs in +// legendary's installed.json and launches them through heroic://. + +#include "stores.h" + +#include +#include +#include + +#include "host.h" +#include "../json_util.h" + +static void ManifestDirs(std::vector& out) +{ + out.clear(); + if (strcmp(Host_Name(), "Windows") == 0) { + const char* pd = getenv("ProgramData"); + out.push_back(std::string(pd && *pd ? pd : "C:\\ProgramData") + + "\\Epic\\EpicGamesLauncher\\Data\\Manifests"); + } + std::string home = Store_Home(); + if (!home.empty()) + out.push_back(home + "/Library/Application Support/Epic/EpicGamesLauncher/Data/Manifests"); + for (size_t i = out.size(); i-- > 0;) + if (!Store_IsDir(out[i])) out.erase(out.begin() + i); +} + +static void LegendaryFiles(std::vector& out) +{ + out.clear(); + std::vector heroic; + Store_HeroicDirs(heroic); + for (size_t i = 0; i < heroic.size(); i++) { + std::string f = heroic[i] + "/legendaryConfig/legendary/installed.json"; + if (Store_IsFile(f)) out.push_back(f); + } +} + +bool Epic_Found() +{ + std::vector a, b; + ManifestDirs(a); + LegendaryFiles(b); + return !a.empty() || !b.empty(); +} + +// AppCategories lists "games" for a game; add-ons and engines leave it out. +static bool IsGame(const std::string& item) +{ + size_t at = Store_JsonKey(item, "AppCategories"); + if (at == std::string::npos) return true; + size_t open = item.find('[', at), close = item.find(']', at); + if (open == std::string::npos || close == std::string::npos) return true; + return item.substr(open, close - open).find("\"games\"") != std::string::npos; +} + +static void ScanManifests(const std::string& dir, std::vector& out) +{ + std::vector names; + Store_ListDir(dir, names); + for (size_t i = 0; i < names.size(); i++) { + const std::string& n = names[i]; + if (n.size() < 5 || strcasecmp(n.c_str() + n.size() - 5, ".item") != 0) continue; + std::string item; + if (!Store_ReadFile(Store_Join(dir, n), item)) continue; + std::string app = Store_JsonString(item, "AppName"); + std::string ns = Store_JsonString(item, "CatalogNamespace"); + std::string id = Store_JsonString(item, "CatalogItemId"); + std::string mainApp = Store_JsonString(item, "MainGameAppName"); + if (app.empty() || ns.empty() || id.empty()) continue; + if (Store_JsonBool(item, "bIsIncompleteInstall")) continue; + if (!mainApp.empty() && mainApp != app) continue; // DLC + if (!IsGame(item)) continue; + + StoreGame g; + g.name = Store_JsonString(item, "DisplayName"); + if (g.name.empty()) g.name = app; + g.launch = "com.epicgames.launcher://apps/" + ns + "%3A" + id + "%3A" + app + + "?action=launch&silent=true"; + std::string loc = Store_JsonString(item, "InstallLocation"); + std::string exe = Store_JsonString(item, "LaunchExecutable"); + if (!loc.empty() && !exe.empty()) g.icon = Store_Join(loc, exe); + out.push_back(g); + } +} + +static void ScanLegendary(const std::string& file, const std::string& heroicDir, + std::vector& out) +{ + std::string text; + if (!Store_ReadFile(file, text)) return; + size_t obj = text.find('{'); + if (obj == std::string::npos) return; + std::map lib; + Store_HeroicLibrary(heroicDir, "legendary_library.json", lib); + std::vector games = Json_SplitObjectValues(text, obj); + for (size_t i = 0; i < games.size(); i++) { + const std::string& e = games[i]; + std::string app = Store_JsonString(e, "app_name"); + if (app.empty() || Store_JsonBool(e, "is_dlc")) continue; + StoreGame g; + g.name = Store_JsonString(e, "title"); + std::map::iterator it = lib.find(app); + if (it != lib.end()) { + if (g.name.empty()) g.name = it->second.title; + g.artUrl = it->second.art; + } + if (g.name.empty()) g.name = app; + g.launch = "heroic://launch/legendary/" + app; + std::string path = Store_JsonString(e, "install_path"); + std::string exe = Store_JsonString(e, "executable"); + if (!path.empty() && !exe.empty()) g.icon = Store_Join(path, exe); + out.push_back(g); + } +} + +void Epic_Scan(std::vector& out) +{ + out.clear(); + std::vector dirs; + ManifestDirs(dirs); + for (size_t i = 0; i < dirs.size(); i++) ScanManifests(dirs[i], out); + std::vector heroic; + Store_HeroicDirs(heroic); + for (size_t i = 0; i < heroic.size(); i++) { + std::string f = heroic[i] + "/legendaryConfig/legendary/installed.json"; + if (Store_IsFile(f)) ScanLegendary(f, heroic[i], out); + } +} diff --git a/theseus/desktop/launchers/stores.cpp b/theseus/desktop/launchers/stores.cpp new file mode 100644 index 0000000..17a4df8 --- /dev/null +++ b/theseus/desktop/launchers/stores.cpp @@ -0,0 +1,141 @@ +// stores.cpp: the file and JSON bits every store reader shares, and where +// Heroic keeps its config. + +#include "stores.h" + +#include +#include +#include + +#include "host.h" +#include "../json_util.h" + +std::string Store_Home() +{ + const char* h = getenv("HOME"); + if (!h || !*h) h = getenv("USERPROFILE"); + return h ? h : ""; +} + +std::string Store_Join(const std::string& dir, const std::string& name) +{ + if (dir.empty()) return name; + char last = dir[dir.size() - 1]; + if (last == '/' || last == '\\') return dir + name; + // Keep a Windows path looking like one. + return dir + (dir.find('\\') != std::string::npos ? "\\" : "/") + name; +} + +bool Store_IsDir(const std::string& path) +{ + HostFileInfo info; + return !path.empty() && Host_Stat(path.c_str(), &info) && (info.attrs & HOST_ATTR_DIR); +} + +bool Store_IsFile(const std::string& path) +{ + HostFileInfo info; + return !path.empty() && Host_Stat(path.c_str(), &info) && !(info.attrs & HOST_ATTR_DIR); +} + +bool Store_ReadFile(const std::string& path, std::string& out) +{ + out.clear(); + FILE* f = fopen(path.c_str(), "rb"); + if (!f) return false; + char buf[65536]; + size_t n; + // A store cache past 64 MB isn't one we want to walk. + while ((n = fread(buf, 1, sizeof(buf), f)) > 0 && out.size() < (64u << 20)) + out.append(buf, n); + fclose(f); + return true; +} + +void Store_ListDir(const std::string& dir, std::vector& names) +{ + names.clear(); + HostDir* d = Host_OpenDir(dir.c_str()); + if (!d) return; + char name[512]; + bool isDir = false; + while (Host_ReadDirType(d, name, sizeof(name), &isDir)) + if (name[0] != '.') names.push_back(name); + Host_CloseDir(d); +} + +size_t Store_JsonKey(const std::string& obj, const char* key) +{ + size_t klen = strlen(key); + int depth = 0; + for (size_t i = 0; i < obj.size(); i++) { + char c = obj[i]; + if (c == '{' || c == '[') { depth++; continue; } + if (c == '}' || c == ']') { depth--; continue; } + if (c != '"') continue; + size_t start = i; + for (i++; i < obj.size() && obj[i] != '"'; i++) + if (obj[i] == '\\') i++; + if (depth != 1) continue; + size_t j = i + 1; + while (j < obj.size() && (obj[j] == ' ' || obj[j] == '\t' || obj[j] == '\r' || obj[j] == '\n')) j++; + if (j >= obj.size() || obj[j] != ':') continue; + if (i - start - 1 == klen && obj.compare(start + 1, klen, key) == 0) return start; + } + return std::string::npos; +} + +std::string Store_JsonString(const std::string& obj, const char* key) +{ + size_t at = Store_JsonKey(obj, key); + return at == std::string::npos ? "" : Json_GetString(obj, key, at); +} + +bool Store_JsonBool(const std::string& obj, const char* key) +{ + size_t at = Store_JsonKey(obj, key); + return at != std::string::npos && Json_GetBool(obj, key, at); +} + +void Store_HeroicDirs(std::vector& out) +{ + out.clear(); + std::vector tries; + std::string home = Store_Home(); + const char* xdg = getenv("XDG_CONFIG_HOME"); + if (xdg && *xdg) tries.push_back(std::string(xdg) + "/heroic"); + if (!home.empty()) { + tries.push_back(home + "/.config/heroic"); + tries.push_back(home + "/.var/app/com.heroicgameslauncher.hgl/config/heroic"); + tries.push_back(home + "/Library/Application Support/heroic"); + } + const char* appData = getenv("APPDATA"); + if (appData && *appData) tries.push_back(std::string(appData) + "\\heroic"); + for (size_t i = 0; i < tries.size(); i++) { + bool dup = false; + for (size_t k = 0; k < out.size(); k++) dup |= out[k] == tries[i]; + if (!dup && Store_IsDir(tries[i])) out.push_back(tries[i]); + } +} + +void Store_HeroicLibrary(const std::string& heroicDir, const char* file, + std::map& out) +{ + std::string text; + if (!Store_ReadFile(heroicDir + "/store_cache/" + file, text)) return; + // Epic's list sits under "library", GOG's under "games". + size_t arr = Json_FindArray(text, "library"); + if (arr == std::string::npos) arr = Json_FindArray(text, "games"); + if (arr == std::string::npos) return; + std::vector games = Json_SplitArray(text, arr); + for (size_t i = 0; i < games.size(); i++) { + std::string id = Store_JsonString(games[i], "app_name"); + if (id.empty()) continue; + HeroicInfo info; + info.title = Store_JsonString(games[i], "title"); + info.art = Store_JsonString(games[i], "art_square"); + if (info.art.empty()) info.art = Store_JsonString(games[i], "art_cover"); + if (info.art.compare(0, 8, "https://") != 0) info.art.clear(); + out[id] = info; + } +} diff --git a/theseus/desktop/launchers/stores.h b/theseus/desktop/launchers/stores.h new file mode 100644 index 0000000..37eeaba --- /dev/null +++ b/theseus/desktop/launchers/stores.h @@ -0,0 +1,49 @@ +// stores.h: installed games from the PC stores, read off the files each +// store leaves on disk. No logins, no accounts. The guide's Games & Playlists +// page shows an Import row for each store that's here. + +#pragma once + +#include +#include +#include + +struct StoreGame { + std::string name; // as the store spells it, UTF-8 + std::string launch; // the games.ini Launch line + std::string workdir; // empty lets the launcher work it out + std::string icon; // picture, .ico or .exe on disk to take the icon from + std::string artUrl; // public cover art to fetch when there's no icon + std::string category; // empty means Games +}; + +// Into the library, skipping anything already there by name or launch line. +// Saves when something was added. store_import.cpp. +void StoreGames_Add(const std::vector& games, int* added, int* had); + +// Epic Games Store: the launcher's manifests, and Heroic's Epic installs. +bool Epic_Found(); +void Epic_Scan(std::vector& out); + +// Shared by the readers (stores.cpp). +std::string Store_Home(); +std::string Store_Join(const std::string& dir, const std::string& name); +bool Store_IsDir(const std::string& path); +bool Store_IsFile(const std::string& path); +bool Store_ReadFile(const std::string& path, std::string& out); +void Store_ListDir(const std::string& dir, std::vector& names); +// JSON keys of the object itself, never one nested inside it. Store_JsonKey +// is the offset of the key's opening quote, or npos. +size_t Store_JsonKey(const std::string& obj, const char* key); +std::string Store_JsonString(const std::string& obj, const char* key); +bool Store_JsonBool(const std::string& obj, const char* key); + +// Heroic's config folders that exist: native and Flatpak on Linux, macOS, +// Windows. +void Store_HeroicDirs(std::vector& out); + +// What Heroic's store cache knows about a game it lists. +struct HeroicInfo { std::string title, art; }; +// file is under store_cache, like "legendary_library.json". Keyed by app_name. +void Store_HeroicLibrary(const std::string& heroicDir, const char* file, + std::map& out); diff --git a/theseus/desktop/store_import.cpp b/theseus/desktop/store_import.cpp new file mode 100644 index 0000000..6316805 --- /dev/null +++ b/theseus/desktop/store_import.cpp @@ -0,0 +1,70 @@ +// store_import.cpp: store games into games.ini, with an icon from the disk +// when the game has one and the store's cover art queued when it doesn't. + +#include "launchers/stores.h" +#include "virtual_games.h" +#include "udata_synth.h" +#include "icon_compress.h" +#include "exe_icon.h" +#include "game_art.h" +#include "title_sanitize.h" +#include "host.h" + +#include +#include + +// The same game gets the same id every time it comes in. +static void TitleIdFor(const std::string& launch, char* out, size_t size) +{ + unsigned h = 2166136261u; + for (size_t i = 0; i < launch.size(); i++) { h ^= (unsigned char)launch[i]; h *= 16777619u; } + for (;;) { + snprintf(out, size, "%08x", h); + bool used = false; + for (int i = 0; i < g_vgames.count && !used; i++) + used = g_vgames.games[i].valid && strcmp(g_vgames.games[i].titleID, out) == 0; + if (!used) return; + h++; + } +} + +static bool PlaceIcon(const std::string& src, const char* titleID) +{ + HostFileInfo info; + if (src.empty() || !Host_Stat(src.c_str(), &info) || (info.attrs & HOST_ATTR_DIR)) return false; + char dst[1024]; + Host_MakeDir(VGAMES_ICONS); + snprintf(dst, sizeof(dst), "%s/%s.jpg", VGAMES_ICONS, titleID); + if (ExeIcon_IsIconSource(src.c_str())) return ExeIcon_Save(src.c_str(), dst); + return Icons_FitFile(src.c_str(), dst, 256, 90); +} + +void StoreGames_Add(const std::vector& games, int* added, int* had) +{ + *added = *had = 0; + VGames_Load(); + for (size_t i = 0; i < games.size(); i++) { + const StoreGame& sg = games[i]; + char clean[128]; + Title_SanitizeName(sg.name.c_str(), clean, sizeof(clean)); + if (!clean[0] || sg.launch.empty() || sg.launch.size() >= sizeof(VirtualGame::launch)) continue; + bool there = VGames_FindByName(clean) >= 0; + for (int k = 0; k < g_vgames.count && !there; k++) + there = g_vgames.games[k].valid && sg.launch == g_vgames.games[k].launch; + if (there) { (*had)++; continue; } + + char id[16]; + TitleIdFor(sg.launch, id, sizeof(id)); + int row = VGames_Add(clean, id, sg.launch.c_str(), "E", + sg.category.empty() ? "Games" : sg.category.c_str()); + if (row < 0) break; + if (!sg.workdir.empty() && sg.workdir.size() < sizeof(g_vgames.games[row].workdir)) + snprintf(g_vgames.games[row].workdir, sizeof(g_vgames.games[row].workdir), "%s", sg.workdir.c_str()); + if (!PlaceIcon(sg.icon, id) && !sg.artUrl.empty()) GameArt_HintArt(id, sg.artUrl.c_str()); + (*added)++; + } + if (*added) { + VGames_Save(); + UDataSynth_RebuildAll(); + } +} From af1df4df7798e6f5a5f7075851d9dcad7baf333f Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:35:44 -0500 Subject: [PATCH 31/46] Added collections for games Added named lists of your own. A game's page has Collections to put it in one or start a new one, Games & Playlists lists them with counts, and any with games in it shows up in the launcher next to Favorites. --- Data/Xips/default.xip | Bin 1692946 -> 1693523 bytes theseus/desktop/desktop_nodes.cpp | 30 +++++- theseus/desktop/guide.cpp | 110 +++++++++++++++++++-- theseus/desktop/virtual_games.h | 115 ++++++++++++++++++++-- xips-source/default-desktop/harddrive.xap | 20 +++- 5 files changed, 258 insertions(+), 17 deletions(-) diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index 65113d02de28c26bf7775d8f9047d064f18ca4f9..5b174927ed31fa9d3a4a3957a803b132fafddf0b 100644 GIT binary patch delta 727 zcmZ|K&1(}u6aetqHfnb@$>d|JX)dpdn5AOUgC1I=m53r}&_F>2!8O?=L$Hz zkRqWEfp^a^)6U@lOp%i!Fs>i0U(RwjdN_ zOcVuLzyh}*W2PiSlr%#A(3a*P#`Yja5M}~mW*}w(Vpbq#17da{<^W<&Am##MZXo6X zVqPHT17iN|L5u=rQ?^@97g(Y>{rY7Af$4Pz1$fzW^Gf{^b5p0!J;