diff --git a/Configs/version b/Configs/version index 90a7e7c..900b669 100644 --- a/Configs/version +++ b/Configs/version @@ -1,2 +1,2 @@ [default] -version=0.4.1 +version=0.4.2 diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index 74b5d40..ef5d185 100644 Binary files a/Data/Xips/default.xip and b/Data/Xips/default.xip differ diff --git a/Data/Xips/jellyfin.xip b/Data/Xips/jellyfin.xip index f7dd808..4f78e73 100644 Binary files a/Data/Xips/jellyfin.xip and b/Data/Xips/jellyfin.xip differ diff --git a/Data/Xips/plex.xip b/Data/Xips/plex.xip index f7dd808..4f78e73 100644 Binary files a/Data/Xips/plex.xip and b/Data/Xips/plex.xip differ diff --git a/README.md b/README.md index 7df248c..f336b58 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 @@ -58,6 +59,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 | @@ -75,16 +78,23 @@ 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**: + +- **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, and so do **Import Epic Games**, **Import GOG Games**, **Import Lutris Games** and **Import itch.io Games** when those are installed (Heroic's Epic and GOG games count too). 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. In a game list, X filters by where games come from (or Most Played, Never Played) and Y sorts All Games by name, time played or last played. +- **Collections** are your own groups: add a game from its page and the collection shows up in the dashboard's launcher next to Favorites. Each game's page also has favorite and hide toggles, its time played, and **Arguments**, **Working Folder** and **Environment** for that game alone. -- **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). +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. +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`. Guide > Logs & Help > **Back Up My Settings** copies those and your settings into a dated folder under `Backups`, and **Restore a Backup** puts one back. 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 @@ -111,6 +121,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`. @@ -171,7 +184,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 | |---|---| @@ -181,7 +194,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.
diff --git a/build/Makefile b/build/Makefile index b1263cf..635a9fc 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 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: @@ -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 \ @@ -872,6 +873,13 @@ 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/launchers/stores.cpp \ + $(THESEUS_SRC)/desktop/launchers/epic.cpp \ + $(THESEUS_SRC)/desktop/launchers/gog.cpp \ + $(THESEUS_SRC)/desktop/launchers/lutris.cpp \ + $(THESEUS_SRC)/desktop/launchers/itch.cpp \ $(THESEUS_SRC)/desktop/title_sanitize.cpp \ $(THESEUS_SRC)/desktop/udata_synth.cpp \ $(THESEUS_SRC)/desktop/desktop_stubs.cpp \ @@ -890,6 +898,10 @@ 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/xdg_apps.cpp \ + $(THESEUS_SRC)/desktop/store_import.cpp \ + $(THESEUS_SRC)/desktop/sqlite_read.cpp \ $(THESEUS_SRC)/desktop/game_art.cpp \ $(THESEUS_SRC)/desktop/playlist.cpp \ $(THESEUS_SRC)/desktop/playlist_maker.cpp \ diff --git a/release-notes/0.4.2-testing.md b/release-notes/0.4.2-testing.md new file mode 100644 index 0000000..38aa554 --- /dev/null +++ b/release-notes/0.4.2-testing.md @@ -0,0 +1,39 @@ +A testing build with a lot in it. Please kick the tires and tell us what breaks, especially on Windows, the Steam Deck and anything with a Plex server. + +## Downloads +| OS | File | +|---|---| +| macOS (Apple Silicon) | `Theseus-v0.4.2-testing-macos-app.zip` (the app), or `Theseus-v0.4.2-testing-macos.zip` (bare binary, needs Homebrew libs) | +| Windows x64 | `Theseus-v0.4.2-testing-windows-x64.zip`. Unzip anywhere, run `theseus.exe` | +| Linux x64 | `UIX-Desktop-v0.4.2-testing-x86_64.AppImage` (Steam Deck too), or the tarball | +| Linux ARM64 | `UIX-Desktop-v0.4.2-testing-aarch64.AppImage`, or the tarball | + +`SHA256SUMS.txt` lists a checksum for every file. + +## Games +- **Time played and back to the dashboard.** Games started from the dashboard are timed, and the dashboard comes back when they close (Settings > Games to turn it off). Steam games count from when Steam says they're running. +- **More places to bring games in from:** Epic, GOG, Lutris and itch.io (Heroic's Epic and GOG games too), PS2 discs through PCSX2, Linux app shortcuts, and icons straight out of .exe, .dll and .ico files. xemu and PCSX2 get found in a lot more places, RetroBat and Flatpak included. +- **Your own collections,** shown in the launcher next to Favorites. Filter a list by where games come from (X), sort All Games by time or last played (Y), and search by name. +- **Per-game options:** arguments, working folder and environment for any game. +- First launch offers to import your Steam games and find your emulators. + +## Controllers +- Any number of pads, plugged in or out while it runs. +- PlayStation and Nintendo pads get their own button prompts, and there's a setting to confirm with the right button. +- Rumble when the guide can't do something (Settings > Controller turns it off). + +## Jellyfin and Plex +- Continue Watching and Next Up, resume where you stopped (X starts from the beginning), and your progress goes back to the server. +- An info card on Y with year, runtime, rating, genres and the plot. Watched marks in lists, RB to mark watched, and search. +- Folders and box sets open, episodes read "S1E05 · Title", and you see Loading or Can't reach the server instead of an empty list. +- Fixed posters that never showed up, the header running into the item count, the pad doing nothing during a video, and B backing out of the menu as well as the video. +- Sign-in tokens no longer end up in theseus.log. + +## Everything else +- The guide reads better: only things you can do are buttons, information is plain text, and pages are split into sections. +- **Back Up My Settings** and **Restore a Backup** in Logs & Help. +- **Portable mode:** put a `portable.txt` next to the app and everything stays in a `UserData` folder beside it. +- Music keeps track order when files aren't tagged, and .m3u playlists keep their order (#27). +- Copy Log hides sign-ins along with your home folder and IP addresses. + +Plex support is written but hasn't been tried against a real server yet. Same for the store imports on real installs. If something's off, the issue form on GitHub plus `theseus.log` (Guide > Logs & Help > Copy Log) is the fastest way to get it fixed. diff --git a/theseus/desktop/app_paths.cpp b/theseus/desktop/app_paths.cpp index 4e826ec..2d7df38 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" @@ -42,6 +43,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; } @@ -282,16 +298,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/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); }; diff --git a/theseus/desktop/client_util.h b/theseus/desktop/client_util.h index 2d5097e..2252bb5 100644 --- a/theseus/desktop/client_util.h +++ b/theseus/desktop/client_util.h @@ -4,6 +4,10 @@ #pragma once #include +#include +#include +#include +#include #include #include #include @@ -26,3 +30,46 @@ inline void GenerateUUID(char out[37]) { b[0],b[1],b[2],b[3], b[4],b[5], b[6],b[7], b[8],b[9], b[10],b[11],b[12],b[13],b[14],b[15]); } + +// One background thread running jobs in the order they were posted, so a +// stop report never overtakes the start it belongs to. +class SerialWorker { +public: + ~SerialWorker() { Stop(); } + void Post(std::function job) { + std::lock_guard lk(m_mtx); + if (m_quit) return; + m_jobs.push_back(std::move(job)); + if (!m_thread.joinable()) m_thread = std::thread(&SerialWorker::Run, this); + m_cv.notify_one(); + } + // Drops what hasn't started and waits out the job that has. + void Stop() { + { + std::lock_guard lk(m_mtx); + m_quit = true; + m_jobs.clear(); + m_cv.notify_one(); + } + JoinIf(m_thread); + } +private: + void Run() { + for (;;) { + std::function job; + { + std::unique_lock lk(m_mtx); + m_cv.wait(lk, [this] { return m_quit || !m_jobs.empty(); }); + if (m_quit) return; + job = std::move(m_jobs.front()); + m_jobs.pop_front(); + } + job(); + } + } + std::mutex m_mtx; + std::condition_variable m_cv; + std::deque> m_jobs; + std::thread m_thread; + bool m_quit = false; +}; diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index c2db6b1..d45d8fc 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -3381,21 +3381,137 @@ END_NODE_FUN() // ============================================================================ #include "plex_client.h" +#include "guide.h" +#include "pads.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; +} + +// "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" : ""; +} + +// 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; + 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; +} + +// The info card's last line: which button flips the watched mark, named for +// the pad or the keyboard used last. +static std::string MarkHint(bool played) +{ + const char* key = "`"; + if (Joy_LastDevice() == 1) { + switch (Pads_Style()) { + case PAD_STYLE_PLAYSTATION: key = "R1"; break; + case PAD_STYLE_NINTENDO: key = "R"; break; + default: key = "RB"; break; + } + } + return std::string("Press ") + key + (played ? " to mark unwatched" : " to mark watched"); +} class CPlexLibrary : public CNode { public: CPlexLibrary() - : m_currentLib(-1), m_currentShow(-1), m_currentSeason(-1) {} + : m_currentShow(-1), m_currentSeason(-1) {} DECLARE_NODE(CPlexLibrary, CNode) DECLARE_NODE_PROPS() DECLARE_NODE_FUNCTIONS() - int m_currentLib; + // The library open, by key: the shelves above the libraries come and go. + std::string m_libKey, m_libName; 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() { @@ -3418,6 +3534,20 @@ 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]; + if (libs[i].type == "search") { + std::string term = Plex_SearchTerm(); + return new CStrObject(_T((term.empty() ? libs[i].title : libs[i].title + " \xC2\xB7 " + term).c_str())); + } + 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(); @@ -3428,8 +3558,12 @@ class CPlexLibrary : public CNode void SetCurrent(int i) { - if (i == m_currentLib) return; - m_currentLib = i; + m_folders.clear(); + std::vector libs = Plex_Cache_GetLibraries(); + if (i < 0 || i >= (int)libs.size()) return; + m_libName = libs[i].title; + if (libs[i].sectionKey == m_libKey) return; + m_libKey = libs[i].sectionKey; m_currentShow = -1; m_currentSeason = -1; } @@ -3446,15 +3580,53 @@ class CPlexLibrary : public CNode std::vector CurrentItems() { - std::vector libs = Plex_Cache_GetLibraries(); - if (m_currentLib < 0 || m_currentLib >= (int)libs.size()) return {}; - return Plex_Cache_GetItems(libs[m_currentLib].sectionKey); + if (m_libKey.empty()) return {}; + if (!m_folders.empty()) { + std::vector kids; + Plex_Cache_GetChildren(m_folders.back().key, kids); + return kids; + } + return Plex_Cache_GetItems(m_libKey); + } + + 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 }); + Plex_RetryFetch(items[i].ratingKey); + 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())); + if (m_libKey == "uix-search") return new CStrObject(_T(("\xE2\x80\x9C" + SearchTerm() + "\xE2\x80\x9D").c_str())); + return new CStrObject(_T(m_libName.c_str())); } 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())); } @@ -3470,7 +3642,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) { @@ -3496,7 +3668,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; @@ -3507,18 +3680,25 @@ 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 (!IsFolderType(it.type)) AppendLine(body, MarkHint(it.Played())); 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 (i < (int)seasons.size()) AppendLine(body, MarkHint(seasons[i].Played())); if (!sh.summary.empty()) { body += "\n\n"; body += sh.summary; } } else if (view == 3) { @@ -3526,17 +3706,16 @@ 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)); + AppendLine(body, MarkHint(e.Played())); 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. @@ -3566,13 +3745,40 @@ 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; + 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())); } @@ -3584,11 +3790,31 @@ class CPlexLibrary : public CNode if (!it.thumbUrl.empty()) Plex_QueueArtDownload(it.ratingKey, it.thumbUrl); } + // 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* keys[3] = { &a, &b, &c }; + for (const std::string* k : keys) + if (!k->empty() && 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())); + if (i < 0 || i >= (int)items.size()) return ArtOrLogo(""); + return ArtOrLogo(items[i].ratingKey); } void QueueSeasonArt(int i) @@ -3599,6 +3825,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); } @@ -3606,10 +3833,10 @@ 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; - return new CStrObject(_T(Plex_ArtCachePath(seasons[i].ratingKey).c_str())); + if (i < 0 || i >= (int)seasons.size()) return ArtOrLogo(""); + return ArtOrLogo(seasons[i].ratingKey, showKey); } void QueueEpisodeArt(int i) @@ -3620,6 +3847,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); } @@ -3627,15 +3855,86 @@ 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; - return new CStrObject(_T(Plex_ArtCachePath(eps[i].ratingKey).c_str())); + if (i < 0 || i >= (int)eps.size()) return ArtOrLogo(""); + return ArtOrLogo(eps[i].ratingKey, seasonKey, CurrentShowKey()); + } + + // What's playing, for the server's playback reports. + static std::string s_playing; + static void Report(int event, double pos, double dur, bool paused) + { + Plex_ReportPlayback(s_playing, event, (int)(pos * 1000.0), (int)(dur * 1000.0), paused); + } + + // Bumps when a playback report or a mark changes watch state. + int GetWatchStamp() { return (int)Plex_WatchStamp(); } + + // The search row at the end of the libraries: the keyboard's text goes + // here, and the results open as that library's items. + static std::string SearchTerm() { return Plex_SearchTerm(); } + void Search(const TCHAR* term) + { + std::string t = term ? term : ""; + while (!t.empty() && t.back() == ' ') t.pop_back(); + while (!t.empty() && t.front() == ' ') t.erase(0, 1); + Plex_Search(t); + } + CStrObject* GetSearchTerm() { return new CStrObject(_T(SearchTerm().c_str())); } + + // RB: watched becomes unwatched and the other way round. The new state, + // or -1 when the row can't be marked. + int ToggleWatched(int view, int i) + { + if (i < 0) return -1; + std::string key; + bool played = false; + if (view == 1) { + std::vector items = CurrentItems(); + if (i >= (int)items.size() || IsFolderType(items[i].type)) return -1; + key = items[i].ratingKey; played = items[i].Played(); + } else if (view == 2) { + std::vector seasons; + Plex_Cache_GetSeasons(CurrentShowKey(), seasons); + if (i >= (int)seasons.size()) return -1; + key = seasons[i].ratingKey; played = seasons[i].Played(); + } else if (view == 3) { + std::vector eps; + std::string seasonKey = CurrentSeasonKey(); + if (seasonKey.empty()) return -1; + Plex_Cache_GetEpisodes(seasonKey, eps); + if (i >= (int)eps.size()) return -1; + key = eps[i].ratingKey; played = eps[i].Played(); + } + if (key.empty()) return -1; + Plex_SetPlayed(key, !played); + return played ? 0 : 1; + } + + // The row has a resume point, so X has a start to go back to. + int CanStartOver(int view, int i) + { + if (i < 0) return 0; + if (view == 1) { + std::vector items = CurrentItems(); + if (i >= (int)items.size() || IsFolderType(items[i].type) || items[i].type == "show") return 0; + return items[i].offsetMs > 0 ? 1 : 0; + } + if (view == 3) { + std::vector eps; + std::string seasonKey = CurrentSeasonKey(); + if (seasonKey.empty()) return 0; + Plex_Cache_GetEpisodes(seasonKey, eps); + return i < (int)eps.size() && eps[i].offsetMs > 0 ? 1 : 0; + } + return 0; } 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; @@ -3645,11 +3944,15 @@ class CPlexLibrary : public CNode ratingKey.c_str()); return; } - if (!MediaPlayer_Open(url.c_str())) { + double start = m_startOver ? 0.0 : offsetMs / 1000.0; + MediaUI_SetReporter(NULL); + if (!MediaPlayer_OpenAt(url.c_str(), start)) { fprintf(stderr, "[Plex] MediaPlayer_Open failed for %s\n", - url.c_str()); + ratingKey.c_str()); return; } + s_playing = ratingKey; + MediaUI_SetReporter(Report); extern bool g_mediaFullscreen; extern char g_mediaFullscreenTitle[256]; extern char g_mediaFullscreenSubtitle[256]; @@ -3669,9 +3972,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 += " • "; 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 ----- @@ -3699,6 +4007,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; @@ -3721,7 +4030,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) @@ -3732,10 +4041,31 @@ 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); } + 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" : ""; + 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; + 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; @@ -3752,11 +4082,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((Mark(eps[i]) + EpisodeLabel(eps[i].index, eps[i].title)).c_str())); } void PlayEpisode(int i) @@ -3775,16 +4101,71 @@ 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); + PlayRatingKey(e.ratingKey, e.title, sub, e.offsetMs); } 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() && m_libKey == "uix-search") { + int state = Plex_SearchState(); + if (state == PLEX_SEARCH_BUSY) return "Searching..."; + if (state == PLEX_SEARCH_FAILED) return Unreachable(); + return CurrentItems().empty() ? "Nothing found" : ""; + } + 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"); + } }; +std::string CPlexLibrary::s_playing; + IMPLEMENT_NODE("PlexLibrary", CPlexLibrary, CNode) START_NODE_PROPS(CPlexLibrary, CNode) @@ -3822,6 +4203,19 @@ 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) + NODE_FUN_SI(GetLibraryRow) + NODE_FUN_SI(GetStatus) + NODE_FUN_SI(GetItemName) + NODE_FUN_VI(SetStartOver) + NODE_FUN_IV(GetWatchStamp) + NODE_FUN_III(CanStartOver) + NODE_FUN_III(ToggleWatched) + NODE_FUN_VS(Search) + NODE_FUN_SV(GetSearchTerm) END_NODE_FUN() @@ -3835,15 +4229,20 @@ class CJellyfinLibrary : public CNode { public: CJellyfinLibrary() - : m_currentLib(-1), m_currentShow(-1), m_currentSeason(-1) {} + : m_currentShow(-1), m_currentSeason(-1) {} DECLARE_NODE(CJellyfinLibrary, CNode) DECLARE_NODE_PROPS() DECLARE_NODE_FUNCTIONS() - int m_currentLib; + // The library open, by key: the shelves above the libraries come and go. + std::string m_libKey, m_libName; 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() { @@ -3864,6 +4263,20 @@ 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]; + if (libs[i].type == "search") { + std::string term = Jellyfin_SearchTerm(); + return new CStrObject(_T((term.empty() ? libs[i].name : libs[i].name + " \xC2\xB7 " + term).c_str())); + } + 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(); @@ -3873,8 +4286,12 @@ class CJellyfinLibrary : public CNode void SetCurrent(int i) { - if (i == m_currentLib) return; - m_currentLib = i; + m_folders.clear(); + std::vector libs = Jellyfin_Cache_GetLibraries(); + if (i < 0 || i >= (int)libs.size()) return; + m_libName = libs[i].name; + if (libs[i].id == m_libKey) return; + m_libKey = libs[i].id; m_currentShow = -1; m_currentSeason = -1; } @@ -3893,20 +4310,84 @@ class CJellyfinLibrary : public CNode std::vector CurrentItems() { - std::vector libs = Jellyfin_Cache_GetLibraries(); - if (m_currentLib < 0 || m_currentLib >= (int)libs.size()) return {}; - return Jellyfin_Cache_GetItems(libs[m_currentLib].id); + if (m_libKey.empty()) return {}; + if (!m_folders.empty()) { + std::vector kids; + Jellyfin_Cache_GetChildren(m_folders.back().id, kids); + return kids; + } + return Jellyfin_Cache_GetItems(m_libKey); + } + + 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 }); + Jellyfin_RetryFetch(items[i].id); + 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())); + if (m_libKey == "uix-search") return new CStrObject(_T(("\xE2\x80\x9C" + SearchTerm() + "\xE2\x80\x9D").c_str())); + return new CStrObject(_T(m_libName.c_str())); } 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; + 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())); } @@ -3918,6 +4399,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())); @@ -3930,11 +4412,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())); + if (i < 0 || i >= (int)items.size()) return ArtOrLogo(""); + return ArtOrLogo(items[i].id); } std::string CurrentShowId() @@ -3954,19 +4455,101 @@ class CJellyfinLibrary : public CNode return seasons[m_currentSeason].id; } + // What's playing, for the server's playback reports. + static std::string s_playing; + static void Report(int event, double pos, double dur, bool paused) + { + (void)dur; + Jellyfin_ReportPlayback(s_playing, event, (long long)(pos * 10000000.0), paused); + } + + // Bumps when a playback report or a mark changes watch state. + int GetWatchStamp() { return (int)Jellyfin_WatchStamp(); } + + // The search row at the end of the libraries: the keyboard's text goes + // here, and the results open as that library's items. + static std::string SearchTerm() { return Jellyfin_SearchTerm(); } + void Search(const TCHAR* term) + { + std::string t = term ? term : ""; + while (!t.empty() && t.back() == ' ') t.pop_back(); + while (!t.empty() && t.front() == ' ') t.erase(0, 1); + Jellyfin_Search(t); + } + CStrObject* GetSearchTerm() { return new CStrObject(_T(SearchTerm().c_str())); } + + // Movies, episodes, tracks and whole series take a watched mark; other + // folders don't. + static bool Markable(const JellyfinItem& it) { return !it.isFolder || it.type == "Series"; } + + // RB: watched becomes unwatched and the other way round. The new state, + // or -1 when the row can't be marked. + int ToggleWatched(int view, int i) + { + if (i < 0) return -1; + std::string id; + bool played = false; + if (view == 1) { + std::vector items = CurrentItems(); + if (i >= (int)items.size() || !Markable(items[i])) return -1; + id = items[i].id; played = items[i].played; + } else if (view == 2) { + std::vector seasons; + std::string showId = CurrentShowId(); + if (showId.empty()) return -1; + Jellyfin_Cache_GetSeasons(showId, seasons); + if (i >= (int)seasons.size()) return -1; + id = seasons[i].id; played = seasons[i].played; + } else if (view == 3) { + std::vector eps; + std::string seasonId = CurrentSeasonId(); + if (seasonId.empty()) return -1; + Jellyfin_Cache_GetEpisodes(seasonId, eps); + if (i >= (int)eps.size()) return -1; + id = eps[i].id; played = eps[i].played; + } + if (id.empty()) return -1; + Jellyfin_SetPlayed(id, !played); + return played ? 0 : 1; + } + + // The row has a resume point, so X has a start to go back to. + int CanStartOver(int view, int i) + { + if (i < 0) return 0; + if (view == 1) { + std::vector items = CurrentItems(); + if (i >= (int)items.size() || items[i].isFolder) return 0; + return items[i].posTicks > 0 ? 1 : 0; + } + if (view == 3) { + std::vector eps; + std::string seasonId = CurrentSeasonId(); + if (seasonId.empty()) return 0; + Jellyfin_Cache_GetEpisodes(seasonId, eps); + return i < (int)eps.size() && eps[i].posTicks > 0 ? 1 : 0; + } + return 0; + } + 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); + 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); + MediaUI_SetReporter(NULL); + if (!MediaPlayer_OpenAt(url.c_str(), start)) { fprintf(stderr, "[Jellyfin] MediaPlayer_Open failed\n"); return; } + s_playing = itemId; + MediaUI_SetReporter(Report); extern bool g_mediaFullscreen; extern char g_mediaFullscreenTitle[256]; extern char g_mediaFullscreenSubtitle[256]; @@ -3981,14 +4564,22 @@ 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); + 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) @@ -3997,6 +4588,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; @@ -4019,7 +4611,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) @@ -4030,6 +4622,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); } @@ -4041,17 +4634,34 @@ 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) { 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; - return new CStrObject(_T(Jellyfin_ArtCachePath(seasons[i].id).c_str())); + if (i < 0 || i >= (int)seasons.size()) return ArtOrLogo(""); + return ArtOrLogo(seasons[i].id, showId); + } + + 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) + { + 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() @@ -4070,11 +4680,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((Mark(eps[i]) + EpisodeLabel(eps[i].index, eps[i].name)).c_str())); } void PlayEpisode(int i) @@ -4085,6 +4691,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(); @@ -4093,11 +4700,10 @@ 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); + PlayRatingKey(e.id, e.name, sub, e.posTicks); } void QueueEpisodeArt(int i) @@ -4107,17 +4713,19 @@ 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) { 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; - return new CStrObject(_T(Jellyfin_ArtCachePath(eps[i].id).c_str())); + if (i < 0 || i >= (int)eps.size()) return ArtOrLogo(""); + return ArtOrLogo(eps[i].id, seasonId, CurrentShowId()); } CStrObject* GetSubtitle(int view, int i) @@ -4131,7 +4739,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) { @@ -4188,6 +4796,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; @@ -4197,7 +4807,15 @@ 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 (Markable(it)) AppendLine(body, MarkHint(it.played)); if (!it.overview.empty()) { body += "\n\n"; body += it.overview; } } else if (view == 2) { @@ -4207,7 +4825,16 @@ 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 (i < (int)seasons.size()) AppendLine(body, MarkHint(seasons[i].played)); if (!sh.overview.empty()) { body += "\n\n"; body += sh.overview; } } else if (view == 3) { @@ -4217,22 +4844,78 @@ 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))); + AppendLine(body, MarkHint(e.played)); 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; } + + // 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() && m_libKey == "uix-search") { + int state = Jellyfin_SearchState(); + if (state == JELLYFIN_SEARCH_BUSY) return "Searching..."; + if (state == JELLYFIN_SEARCH_FAILED) return Unreachable(); + return CurrentItems().empty() ? "Nothing found" : ""; + } + 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"); + } }; +std::string CJellyfinLibrary::s_playing; + IMPLEMENT_NODE("JellyfinLibrary", CJellyfinLibrary, CNode) START_NODE_PROPS(CJellyfinLibrary, CNode) @@ -4270,6 +4953,19 @@ 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) + NODE_FUN_SI(GetLibraryRow) + NODE_FUN_SI(GetStatus) + NODE_FUN_SI(GetItemName) + NODE_FUN_VI(SetStartOver) + NODE_FUN_IV(GetWatchStamp) + NODE_FUN_III(CanStartOver) + NODE_FUN_III(ToggleWatched) + NODE_FUN_VS(Search) + NODE_FUN_SV(GetSearchTerm) END_NODE_FUN() @@ -4300,8 +4996,8 @@ class CGamesCollection : public CNode DECLARE_NODE_PROPS() DECLARE_NODE_FUNCTIONS() - // Current filter - char m_category[32]; + // Current filter. Room for "Collection:" and a collection's name. + char m_category[64]; // Folder we've drilled into, "/" separated, empty at the top of a category char m_group[128]; // Folder rows, the distinct next path segment below m_group @@ -4312,6 +5008,8 @@ class CGamesCollection : public CNode unsigned int m_gen; // Hidden titles come back so a scene can offer to unhide them. bool m_showHidden; + // What GetCollectionCount found, for GetCollectionName. + std::vector m_collections; // Rows are folders first, then titles, so an index below the folder count // addresses m_folders and anything above it addresses m_slice. @@ -4427,6 +5125,27 @@ class CGamesCollection : public CNode return n; } + // Your collections with something showing in them, A to Z, for the + // launcher's category rows. + int GetCollectionCount() + { + VGames_Collections(m_collections, true); + return (int)m_collections.size(); + } + + CStrObject* GetCollectionName(int i) + { + if (i < 0 || i >= (int)m_collections.size()) return new CStrObject; + return new CStrObject(m_collections[i].c_str()); + } + + // 1 for lists that mix categories (Favorites, Recently Played, a + // collection), which launch by row since there's no folder path. + int IsMixedList(const TCHAR* cat) + { + return VGames_IsMarkList(cat) ? 1 : 0; + } + // The DB row behind a list row, or -1 for folders and anything past the end. int Row(int i) { @@ -4593,6 +5312,9 @@ START_NODE_FUN(CGamesCollection, CNode) NODE_FUN_VII(SetHidden) NODE_FUN_VI(ShowHidden) NODE_FUN_SI(GetLastPlayed) + NODE_FUN_IV(GetCollectionCount) + NODE_FUN_SI(GetCollectionName) + NODE_FUN_IS(IsMixedList) END_NODE_FUN() diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index eb5efca..8245087 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -10,8 +10,10 @@ #include "audio_sdl.h" #include "media_player.h" #include "virtual_games.h" +#include "pads.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]; @@ -68,6 +70,13 @@ 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 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" }; @@ -109,7 +118,8 @@ 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("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), @@ -151,6 +161,12 @@ 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 }, + { "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), S_CRT("CRT_Curvature", "Curvature", curvature, "0.400", 0.0f, 2.0f), 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/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 662ef8c..ebabcdd 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -26,8 +26,17 @@ #include "plex_client.h" #include "jellyfin_client.h" #include "xcloud_client.h" +#include "launchers/xemu.h" +#include "launchers/pcsx2.h" +#include "xiso.h" +#include "exe_icon.h" +#include "xdg_apps.h" #include "guide.h" #include "ui_overlay.h" +#include "pads.h" +#include "launchers/steam.h" +#include "settings_backup.h" +#include "launchers/stores.h" #include #include #include @@ -69,6 +78,13 @@ static void RestartWithMode(const char* flag) fprintf(stderr, "[Guide] restart failed: %s\n", strerror(errno)); } +// Starts this program over the way it was started. +static void Restart() +{ + execv(g_argv[0], g_argv); + fprintf(stderr, "[Guide] restart failed: %s\n", strerror(errno)); +} + static const char* ShippedVersion() { static char s_ver[64] = ""; @@ -139,9 +155,27 @@ 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 }, + { "Import GOG Games", "Installed games from GOG Galaxy, GOG installers and Heroic.", Gog_Found, Gog_Scan }, + { "Import Lutris Games", "Installed games from your Lutris library, with its cover art.", Lutris_Found, Lutris_Scan }, + { "Import itch.io Games", "Games installed with the itch.io app.", Itch_Found, Itch_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])); +// 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; }; @@ -230,6 +264,9 @@ 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." }, + { "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; @@ -240,7 +277,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, @@ -250,10 +287,11 @@ 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, + GV_COLLECTIONS, GV_GAMECOLL, GV_BACKUPS, GV_RESTORE }; // What a game list shows. -enum GameList { GL_FAVORITES, GL_RECENT, GL_HIDDEN, GL_ALL, GL_LETTER, GL_SEARCH }; +enum GameList { GL_FAVORITES, GL_RECENT, GL_HIDDEN, GL_ALL, GL_LETTER, GL_SEARCH, GL_COLLECTION }; static const View kSectionViews[SEC_COUNT] = { GV_PAGE, GV_ACCOUNTS, GV_LIBRARY, GV_LOGS, GV_SHORTCUTS, GV_ABOUT, GV_TOOLS, GV_EXIT, @@ -268,15 +306,23 @@ 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_STORE, + GA_COLLECTION, GA_GAMECOLL, GA_INCOLL, GA_NEWCOLL, + GA_BACKUP, GA_BACKUPS, GA_PICKBACKUP, GA_RESTORE, GA_OPENBACKUPS, GA_COUNT }; enum Window { WIN_TITLEMAKER, WIN_HDD, WIN_PLAYLISTS, WIN_SETTINGS, WIN_INSPECTOR, WIN_XAPEDITOR }; +// Actions are the only rows the cursor stops on. Info rows are label and +// value lines, captions head a block, text rows are wrapped paragraphs. +enum RowKind { RK_ACTION, RK_INFO, RK_CAPTION, RK_TEXT }; + struct Row { std::string label, value, help; int act; int arg; // view to open, setting index, window... + int kind; }; // What the pointer can land on. @@ -311,7 +357,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, ED_COLLECTION }; struct Editor { bool on, secret, shift, symbols; @@ -337,13 +383,22 @@ 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 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 + std::string collection; // GL_COLLECTION's name + std::string filter; // the game list's filter, empty for all + int sort; // All Games' order, a SORT_ + std::vector backups; // GV_BACKUPS' rows, newest first + std::string backup; // the one GV_RESTORE offers + std::vector collNames; // the game page's Collections rows, kept while it's open unsigned gameLayout; // g_vgames.layout when game was picked std::vector targets; @@ -356,9 +411,43 @@ static void Add(const char* label, const char* value, const char* help, int act Row r; r.label = label; r.value = value ? value : ""; r.help = help ? help : ""; r.act = act; r.arg = arg; + r.kind = act == GA_NONE ? RK_INFO : RK_ACTION; g.rows.push_back(r); } +static void Caption(const char* text) +{ + Add(text, NULL, NULL); + g.rows.back().kind = RK_CAPTION; +} + +static void Para(const char* text) +{ + Add(text, NULL, NULL); + g.rows.back().kind = RK_TEXT; +} + +static bool Focusable(int i) +{ + return i >= 0 && i < (int)g.rows.size() && g.rows[i].kind == RK_ACTION; +} + +static bool AnyFocusable() +{ + for (size_t i = 0; i < g.rows.size(); i++) + if (g.rows[i].kind == RK_ACTION) return true; + return false; +} + +// The cursor lands on the nearest action, looking the given way first. +static void SnapCursor(int dir) +{ + int n = (int)g.rows.size(); + if (Focusable(g.cursor)) return; + for (int i = g.cursor; i >= 0 && i < n; i += dir) if (Focusable(i)) { g.cursor = i; return; } + for (int i = g.cursor; i >= 0 && i < n; i -= dir) if (Focusable(i)) { g.cursor = i; return; } +} + // What a name files under: A to Z, everything else is '#'. static char Initial(const char* name) { @@ -378,12 +467,134 @@ static bool NameHas(const char* name, const std::string& part) return false; } -// The rows of one game list, as DB indices. +// Where a game comes from, for the game list filter. +static std::string GameSource(const VirtualGame& vg) +{ + if (vg.transient) { + // ES-DE rows sit in a folder per system. + const char* slash = strchr(vg.group, '/'); + std::string sys = slash ? std::string(vg.group, slash - vg.group) : std::string(vg.group); + return sys.empty() ? "ES-DE" : "ES-DE: " + sys; + } + if (strncmp(vg.launch, "xcloud://", 9) == 0) return "xCloud"; + if (strncmp(vg.launch, "xhome://", 8) == 0) return "Remote Play"; + // Heroic launches Epic and GOG games; Lutris runs through its own command. + if (strncasecmp(vg.launch, "heroic://launch/legendary/", 26) == 0) return "Epic"; + if (strncasecmp(vg.launch, "heroic://launch/gog/", 20) == 0) return "GOG"; + if (strstr(vg.launch, "lutris:rungameid/")) return "Lutris"; + static const struct { const char* scheme; const char* name; } kStores[] = { + { "steam://", "Steam" }, { "com.epicgames.launcher://", "Epic" }, { "heroic://", "Heroic" }, + { "goggalaxy://", "GOG" }, { "itch://", "itch.io" }, { "uplay://", "Ubisoft" }, { "origin2://", "EA" }, + { "link2ea://", "EA" }, { "battlenet://", "Battle.net" }, { "amazon-games://", "Amazon" }, + { "lutris:", "Lutris" }, { "retroarch://", "RetroArch" }, + }; + for (size_t i = 0; i < sizeof(kStores) / sizeof(kStores[0]); i++) + if (strncasecmp(vg.launch, kStores[i].scheme, strlen(kStores[i].scheme)) == 0) return kStores[i].name; + // The program's own name, quoted or not, minus its folder. + const char* p = vg.launch; + while (*p == ' ') p++; + std::string exe; + if (*p == '"') { const char* q = strchr(p + 1, '"'); exe = q ? std::string(p + 1, q - p - 1) : std::string(p + 1); } + else { const char* q = strchr(p, ' '); exe = q ? std::string(p, q - p) : std::string(p); } + size_t slash = exe.find_last_of("/\\"); + if (slash != std::string::npos) exe = exe.substr(slash + 1); + if (strncasecmp(exe.c_str(), "xemu", 4) == 0 || strstr(vg.launch, "-dvd_path")) return "xemu"; + if (strncasecmp(exe.c_str(), "pcsx2", 5) == 0) return "PCSX2"; + if (strncasecmp(exe.c_str(), "retroarch", 9) == 0) return "RetroArch"; + if (strstr(vg.launch, "://")) return "Other Launchers"; + return "Programs"; +} + +// All Games' orders. Y steps through them. +enum { SORT_NAME, SORT_TIME, SORT_LAST, SORT_COUNT }; +static const char* const kSorts[SORT_COUNT] = { "A to Z", "Time Played", "Last Played" }; + +// The two filters that aren't a source. +static const char kMostPlayed[] = "Most Played", kNeverPlayed[] = "Never Played"; + +static bool PassesFilter(const VirtualGame& vg) +{ + if (g.filter.empty()) return true; + if (g.filter == kMostPlayed) return vg.playTime > 0; + if (g.filter == kNeverPlayed) return !vg.playTime && !vg.lastPlayed; + return GameSource(vg) == g.filter; +} + +static void GameListRows(int list, std::vector& out); +// The filters worth offering on this list: sources it has, A to Z with +// Programs last, then the play counts. Empty first, for all. +static void FilterChoices(int list, std::vector& out) +{ + std::vector rows; + GameListRows(list, rows); + out.clear(); + bool programs = false, played = false, never = false; + for (size_t i = 0; i < rows.size(); i++) { + const VirtualGame& vg = g_vgames.games[rows[i]]; + std::string src = GameSource(vg); + if (src == "Programs") programs = true; + else if (std::find(out.begin(), out.end(), src) == out.end()) out.push_back(src); + if (vg.playTime > 0) played = true; + if (!vg.playTime && !vg.lastPlayed) never = true; + } + std::sort(out.begin(), out.end(), [](const std::string& a, const std::string& b) { + return strcasecmp(a.c_str(), b.c_str()) < 0; + }); + if (programs) out.push_back("Programs"); + if (played) out.push_back(kMostPlayed); + if (never) out.push_back(kNeverPlayed); + out.insert(out.begin(), std::string()); +} + +// X steps through FilterChoices, back around to all. +static void CycleFilter() +{ + std::vector choices; + FilterChoices(g.gameList, choices); + size_t at = std::find(choices.begin(), choices.end(), g.filter) - choices.begin(); + g.filter = choices[(at + 1) % choices.size()]; + if (choices.size() < 2 && g.device == 1) Pads_Rumble(0.35f, 90); + g.cursor = g.scroll = 0; +} + +// A game list as the list view shows it, filter and all. +static void FilteredRows(int list, std::vector& out) +{ + GameListRows(list, out); + // A to Z already; the others keep it for ties. + if (list == GL_ALL && g.sort == SORT_TIME) + std::stable_sort(out.begin(), out.end(), [](int a, int b) { + return g_vgames.games[a].playTime > g_vgames.games[b].playTime; + }); + else if (list == GL_ALL && g.sort == SORT_LAST) + std::stable_sort(out.begin(), out.end(), [](int a, int b) { + return g_vgames.games[a].lastPlayed > g_vgames.games[b].lastPlayed; + }); + if (g.filter.empty()) return; + std::vector kept; + for (size_t i = 0; i < out.size(); i++) + if (PassesFilter(g_vgames.games[out[i]])) kept.push_back(out[i]); + out.swap(kept); + if (g.filter == kMostPlayed) + std::stable_sort(out.begin(), out.end(), [](int a, int b) { + return g_vgames.games[a].playTime > g_vgames.games[b].playTime; + }); +} + +// Whichever order the list is in now. +static int ListSort() +{ + if (g.view == GV_GAMES && g.gameList == GL_ALL && g.sort) return g.sort; + return g.filter == kMostPlayed ? SORT_TIME : SORT_NAME; +} + +// The rows of one game list, as DB indices, before any filter. static void GameListRows(int list, std::vector& out) { out.clear(); if (list == GL_FAVORITES) { VGames_MarkList(VGAMES_FAVORITES, out); return; } if (list == GL_RECENT) { VGames_MarkList(VGAMES_RECENT, out); return; } + if (list == GL_COLLECTION) { VGames_MarkList((VGAMES_COLLECTION_PREFIX + g.collection).c_str(), out); return; } VGames_Load(); for (int i = 0; i < g_vgames.count; i++) { const VirtualGame& vg = g_vgames.games[i]; @@ -423,7 +634,40 @@ static VirtualGame* PickedGame() return vg->valid ? vg : NULL; } -static const char* kGameListNames[] = { "Favorites", "Recently Played", "Hidden Games", "All Games", "", "" }; +// 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. +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 }, + { "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])); static void Build() { @@ -439,12 +683,24 @@ 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; } case GV_ABOUT: - Add("Version", ShippedVersion(), "The build you're running."); + Caption("This build"); + Add("Version", ShippedVersion(), NULL); Add("Platform", Host_Name(), NULL); + { + VGames_Load(); + long long total = 0; + for (int i = 0; i < g_vgames.count; i++) + if (g_vgames.games[i].valid) total += g_vgames.games[i].playTime; + Add("Time Played", PlayTime(total).c_str(), NULL); + } + Caption("Made by"); Add("Created by", "Milenko", NULL); Add("UIX Lite references", "BigJx, ImOkRuOk", NULL); Add("", "Odb718, Rocky5, TeamUIX", NULL); @@ -452,16 +708,26 @@ static void Build() Add("Original dashboard", "Microsoft", NULL); Add("Community", "Xbox-Scene", NULL); Add("Guide font", "Noto Sans, SIL OFL 1.1", NULL); - Add("And everyone who contributed", "", NULL); + Para("And everyone who contributed, tested and sent in a bug."); 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); 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]; @@ -472,27 +738,76 @@ static void Build() break; } case GV_LIBRARY: { + Caption("Find"); Add("Search by Name", "", "Type part of a name. \"halo\" finds Halo 2.", GA_SEARCH); Add("Find a Game", "", "Pick the first letter, then the game.", GA_VIEW, GV_LETTERS); - Add("Add a Game", "", "Pick a program or file and it shows up in the launcher.", GA_VIEW, GV_ADDGAME); - 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); + Caption("Your lists"); char n[32]; std::vector list; static const char* kListHelp[] = { "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); } + std::vector colls; + VGames_Collections(colls, false); + snprintf(n, sizeof(n), "%d", (int)colls.size()); + Add("Collections", n, "Your own lists. Add a game to one from its page.", GA_VIEW, GV_COLLECTIONS); snprintf(n, sizeof(n), "%d", Playlist_Count()); Add("Playlists", n, "Made in the Playlist Maker.", GA_VIEW, GV_PLAYLISTS); + Caption("Add games"); + Add("Add a Game", "", "Pick a program or file and it shows up in the launcher.", GA_VIEW, GV_ADDGAME); + 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); + break; + } + case GV_COLLECTIONS: { + std::vector colls; + std::vector list; + VGames_Collections(colls, false); + for (size_t i = 0; i < colls.size(); i++) { + VGames_MarkList((VGAMES_COLLECTION_PREFIX + colls[i]).c_str(), list); + char n[16]; + snprintf(n, sizeof(n), "%d", (int)list.size()); + Add(colls[i].c_str(), n, "Shows in the launcher too while it has games in it.", GA_COLLECTION, (int)i); + } + if (g.rows.empty()) + Para("No collections yet. Open a game and pick Collections to start one."); + break; + } + case GV_GAMECOLL: { + VirtualGame* vg = PickedGame(); + if (!vg) { Para("This game moved. Go back and pick it again."); break; } + // A collection emptied here keeps its row until you leave, so it can go back in. + std::vector colls; + VGames_Collections(colls, false); + for (size_t i = 0; i < colls.size(); i++) { + bool have = false; + for (size_t k = 0; k < g.collNames.size() && !have; k++) + have = strcasecmp(g.collNames[k].c_str(), colls[i].c_str()) == 0; + if (!have) g.collNames.push_back(colls[i]); + } + std::sort(g.collNames.begin(), g.collNames.end(), [](const std::string& a, const std::string& b) { + return strcasecmp(a.c_str(), b.c_str()) < 0; + }); + Add("New Collection", g.result[GA_NEWCOLL].c_str(), "Name it and this game goes in.", GA_NEWCOLL); + for (size_t i = 0; i < g.collNames.size(); i++) + Add(g.collNames[i].c_str(), VGames_InCollection(*vg, g.collNames[i].c_str()) ? "Yes" : "No", + "A puts it in or takes it out.", GA_INCOLL, (int)i); break; } case GV_ADDGAME: { @@ -503,6 +818,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; @@ -515,14 +834,17 @@ static void Build() break; case GV_GAMES: { std::vector list; - GameListRows(g.gameList, list); + FilteredRows(g.gameList, list); for (size_t i = 0; i < list.size(); i++) { const VirtualGame& vg = g_vgames.games[list[i]]; - std::string value = g.gameList == GL_RECENT ? PlayedOn(vg.lastPlayed) : std::string(vg.category); + int sort = ListSort(); + std::string value = sort == SORT_TIME ? PlayTime(vg.playTime) + : sort == SORT_LAST || g.gameList == GL_RECENT ? PlayedOn(vg.lastPlayed) + : std::string(vg.category); Add(vg.name, value.c_str(), vg.group[0] ? vg.group : vg.category, GA_GAME, list[i]); } if (g.rows.empty()) - Add(g.gameList == GL_HIDDEN ? "Nothing hidden" : g.gameList == GL_SEARCH ? "No matches" : "Nothing here yet", "", NULL); + Para(g.gameList == GL_HIDDEN ? "Nothing hidden." : g.gameList == GL_SEARCH ? "No matches. Try fewer letters." : "Nothing here yet."); break; } case GV_LETTERS: { @@ -541,21 +863,53 @@ static void Build() snprintf(n, sizeof(n), "%d", counts[k]); Add(label, n, k == 26 ? "Names starting with a number or a symbol." : NULL, GA_LETTER, label[0]); } - if (g.rows.empty()) Add("No games yet", "", "Add some from the Games & Playlists page."); + if (g.rows.empty()) Para("No games yet. Add some from the Games & Playlists page."); break; } case GV_GAME: { VirtualGame* vg = PickedGame(); - if (!vg) { Add("This game moved", "", "Go back and pick it again."); break; } + if (!vg) { Para("This game moved. Go back and pick it again."); break; } Add("Launch", "", vg->launch, GA_LAUNCH); + Caption("Played"); + Add("Last Played", PlayedOn(vg->lastPlayed).c_str(), NULL); + Add("Time Played", PlayTime(vg->playTime).c_str(), NULL); + { + std::string where = vg->group[0] ? std::string(vg->category) + "/" + vg->group : std::string(vg->category); + Add("Category", where.c_str(), NULL); + } + if (!vg->playTime) + Para("Time is counted when a game closes. One that another launcher starts for us can't be timed."); + Caption("Organize"); Add("Favorite", vg->favorite ? "Yes" : "No", "Starred games get their own spot in the launcher.", GA_FAVORITE); Add("Hidden", vg->hidden ? "Yes" : "No", "Hidden games stay out of the launcher until you bring them back.", GA_HIDE); - Add("Last Played", PlayedOn(vg->lastPlayed).c_str(), NULL); - Add("Time Played", PlayTime(vg->playTime).c_str(), - "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); + { + std::string in = vg->collections; + for (size_t i = 0; i < in.size(); i++) if (in[i] == ';') in.replace(i, 1, ", "); + Add("Collections", in.empty() ? "None" : in.c_str(), "Put it in your own lists, or make a new one.", + GA_GAMECOLL); + } + // Rows from someone else's library aren't saved, so neither would these be. + if (!VGames_IsLive(*vg)) { + Caption("Launch options"); + 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: { + 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()) Para("Nothing found. There are no .desktop entries in the app menu folders or on the Desktop."); break; } case GV_PLAYLISTS: @@ -566,7 +920,7 @@ static void Build() snprintf(n, sizeof(n), "%d", (int)pl->items.size()); Add(pl->name.c_str(), n, "Edit playlists in the Playlist Maker (F6).", GA_PLAYLIST, i); } - if (g.rows.empty()) Add("No playlists yet", "", "Make one in the Playlist Maker (F6)."); + if (g.rows.empty()) Para("No playlists yet. Make one in the Playlist Maker (F6)."); break; case GV_PLAYLIST: { const Playlist* pl = Playlist_Get(g.playlist); @@ -574,78 +928,110 @@ static void Build() for (size_t i = 0; i < pl->items.size(); i++) Add(pl->items[i].title.empty() ? NameOnly(pl->items[i].path).c_str() : pl->items[i].title.c_str(), "", NULL); - if (g.rows.empty()) Add("Empty", "", NULL); + if (g.rows.empty()) Para("This playlist is empty."); break; } case GV_ACCOUNTS: { std::string help; + Caption("Plex"); if (Plex_HasToken()) { - Add("Plex", "Signed in", NULL); - Add("Sign Out of Plex", "", NULL, GA_PLEXOUT); + Add("Account", "Signed in", NULL); + Add("Sign Out", "", NULL, GA_PLEXOUT); } else if (Plex_PinAuthInFlight()) { std::string code = Plex_GetPinCode(); - Add("Plex", code.empty() ? "Asking..." : code.c_str(), + Add("Code", code.empty() ? "Asking..." : code.c_str(), "On any device go to plex.tv/link and enter the code. A cancels.", GA_PLEX); } else { - Add("Plex", "Sign In", "Gives you a code to enter at plex.tv/link.", GA_PLEX); + Add("Sign In", "", "Gives you a code to enter at plex.tv/link.", GA_PLEX); } + Caption("Jellyfin"); if (Jellyfin_HasToken()) { - help = "Signed in as " + Jellyfin_GetUserName() + "."; - Add("Jellyfin", "Signed in", help.c_str()); - Add("Sign Out of Jellyfin", "", NULL, GA_JELLYFINOUT); + std::string who = Jellyfin_GetUserName(); + Add("Signed in as", who.empty() ? "Yes" : who.c_str(), NULL); + Add("Server", Jellyfin_GetServerUrl().c_str(), NULL); + Add("Sign Out", "", NULL, GA_JELLYFINOUT); } else { std::string url = Jellyfin_GetServerUrl(); - Add("Jellyfin Server", url.empty() ? "Not set" : url.c_str(), + Add("Server", url.empty() ? "Not set" : url.c_str(), "Your server's address, like 192.168.1.20:8096.", GA_JELLYFINURL); if (!url.empty() && Jellyfin_QuickConnectInFlight()) { std::string code = Jellyfin_GetQuickConnectCode(); - Add("Jellyfin", code.empty() ? "Asking..." : code.c_str(), + Add("Code", code.empty() ? "Asking..." : code.c_str(), "In Jellyfin's web page open your account, then Quick Connect, and enter the code.", GA_JELLYFIN); } else if (!url.empty()) { - Add("Jellyfin", "Sign In", "Quick Connect gives you a code to approve on the server.", GA_JELLYFIN); + Add("Sign In", "", "Quick Connect gives you a code to approve on the server.", GA_JELLYFIN); } } + Caption("Xbox"); if (Xcloud_HasToken()) { std::string gt = Xcloud_GetGamertag(); - Add("Xbox", gt.empty() ? "Signed in" : gt.c_str(), NULL); - Add("Sign Out of Xbox", "", NULL, GA_XBOXOUT); + Add(gt.empty() ? "Account" : "Gamertag", gt.empty() ? "Signed in" : gt.c_str(), NULL); + Add("Sign Out", "", NULL, GA_XBOXOUT); } else if (Xcloud_LoginInFlight()) { std::string code = Xcloud_GetUserCode(); help = "Go to " + Xcloud_GetVerificationUri() + " and enter the code. A cancels."; - Add("Xbox", code.empty() ? "Asking..." : code.c_str(), help.c_str(), GA_XBOX); + Add("Code", code.empty() ? "Asking..." : code.c_str(), help.c_str(), GA_XBOX); } else { - Add("Xbox", "Sign In", "For cloud gaming and your consoles.", GA_XBOX); + Add("Sign In", "", "For cloud gaming and your consoles.", GA_XBOX); } break; } case GV_LOGS: + Para("Something not right? Copy the version and the log, then paste both into an issue on " + "GitHub. The copy hides your home folder, IP addresses and sign-ins."); + Caption("Logs"); Add("Copy Version Info", g.copied == GA_COPYVERSION ? "Copied" : "", "Version, platform and renderer, ready to paste.", GA_COPYVERSION); Add("Copy Log", g.copied == GA_COPYLOG ? "Copied" : "", "This run's log. Your home folder shows as ~ and IP addresses are hidden.", GA_COPYLOG); Add("Open Logs Folder", "", "theseus.log is this run, theseus.prev.log the one before.", GA_OPENLOGS); - Add("Report a Problem", "", "Paste the version and the log into an issue on GitHub."); + Caption("Backups"); + Add("Back Up My Settings", g.result[GA_BACKUP].c_str(), + "Copies your games, settings, icons and playlists into Backups in your user data folder.", GA_BACKUP); + Backup_List(Plat_UserDataDir(), g.backups); + { + char n[16]; + snprintf(n, sizeof(n), "%d", (int)g.backups.size()); + Add("Restore a Backup", n, "Puts an earlier backup back. What you have now is backed up first.", + GA_BACKUPS); + } + break; + case GV_BACKUPS: + for (size_t i = 0; i < g.backups.size(); i++) + Add(g.backups[i].c_str(), "", "Pick it to see what restoring does.", GA_PICKBACKUP, (int)i); + if (g.rows.empty()) Para("No backups yet. Back Up My Settings makes one."); + break; + case GV_RESTORE: + Add("Restore This Backup", g.result[GA_RESTORE].c_str(), + "What you have now is backed up first, then UIX Desktop restarts with this one.", GA_RESTORE); + Add("Open Backups Folder", "", "Each backup is a plain folder you can look through.", GA_OPENBACKUPS); break; case GV_SHORTCUTS: - Add("Guide button, LT+B or F7", "Guide", "Opens and closes this guide."); + Caption("Anywhere"); + Add(GuideCombo(), "Guide", NULL); + Caption("Tool windows"); Add("F3", "Title Maker", NULL); Add("F4", "Settings Window", NULL); Add("F5", "HDD Browser", NULL); Add("F6", "Playlist Maker", NULL); + Caption("Window"); Add("F11", "Fullscreen", NULL); Add("F12", "Borderless Window", NULL); + Caption("App"); Add("Ctrl+M", "Mute", NULL); Add("Ctrl+R", "Restart Dashboard", NULL); Add("Ctrl+Q", "Quit", NULL); if (g_startupMode == 2 || g_extractedMode) { - Add("F1", "Inspector", "Development mode."); - Add("F2", "XAP Editor", "Development mode."); - Add("F10", "Hide Menu Bar", "Development mode."); + Caption("Development mode"); + Add("F1", "Inspector", NULL); + Add("F2", "XAP Editor", NULL); + Add("F10", "Hide Menu Bar", NULL); } break; case GV_TOOLS: + Caption("Tool windows"); Add("Title Maker", "F3", "Names, icons and categories for the launcher.", GA_WINDOW, WIN_TITLEMAKER); Add("Settings Window", "F4", "Every setting, in a desktop window.", GA_WINDOW, WIN_SETTINGS); Add("HDD Browser", "F5", "Look through the dashboard's drives.", GA_WINDOW, WIN_HDD); @@ -653,6 +1039,7 @@ static void Build() if (g_padModeEnabled) Add("Use the Tools with the Pad", "", "The tool windows' own controller menu.", GA_PADTOOLS); if (g_startupMode == 2 || g_extractedMode) { + Caption("Development mode"); Add("Inspector", "F1", "Development mode.", GA_WINDOW, WIN_INSPECTOR); Add("XAP Editor", "F2", "Development mode.", GA_WINDOW, WIN_XAPEDITOR); } @@ -664,6 +1051,7 @@ static void Build() } if (g.cursor >= (int)g.rows.size()) g.cursor = g.rows.empty() ? 0 : (int)g.rows.size() - 1; if (g.cursor < 0) g.cursor = 0; + SnapCursor(1); } static const char* ViewTitle() @@ -673,12 +1061,22 @@ 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_COLLECTIONS: return "Collections"; + case GV_BACKUPS: return "Restore a Backup"; + case GV_RESTORE: return g.backup.c_str(); + case GV_GAMECOLL: return "Collections"; case GV_GAMES: { - static char title[32]; + static char title[32], full[96]; if (g.gameList == GL_SEARCH) snprintf(title, sizeof(title), "Search: %.20s", g.search.c_str()); else if (g.gameList == GL_LETTER) snprintf(title, sizeof(title), "Games: %c", g.letter); - else return kGameListNames[g.gameList]; - return title; + else if (g.gameList == GL_COLLECTION) snprintf(title, sizeof(title), "%.30s", g.collection.c_str()); + else snprintf(title, sizeof(title), "%s", kGameListNames[g.gameList]); + snprintf(full, sizeof(full), "%s", title); + if (!g.filter.empty()) snprintf(full + strlen(full), sizeof(full) - strlen(full), " (%.40s)", g.filter.c_str()); + if (g.gameList == GL_ALL && g.sort) + snprintf(full + strlen(full), sizeof(full) - strlen(full), " by %s", kSorts[g.sort]); + return full; } case GV_GAME: { VirtualGame* vg = PickedGame(); @@ -861,11 +1259,37 @@ static void EditDone() case ED_SEARCH: g.search = Tidy(e.text, false); break; + case ED_COLLECTION: { + std::string name = VGames_CleanCollectionName(Tidy(e.text, false).c_str()); + VirtualGame* vg = PickedGame(); + if (name.empty() || !vg) break; + // Typing an existing name just joins it, spelled the way it already is. + std::vector colls; + VGames_Collections(colls, false); + for (size_t i = 0; i < colls.size(); i++) + if (strcasecmp(colls[i].c_str(), name.c_str()) == 0) name = colls[i]; + if (VGames_SetInCollection(g.game, name.c_str(), true)) { + g.collNames.push_back(name); + g.result[GA_NEWCOLL] = "Added to " + name; + } else { + g.result[GA_NEWCOLL] = "In too many already"; + } + 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(); if (search) { g.gameList = GL_SEARCH; + g.filter.clear(); Push(GV_GAMES); } } @@ -1004,25 +1428,42 @@ 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; if (d.apply) d.apply(); SaveDesktopSettings(); Build(); + // The button still held can mean something else now (SwapConfirm). + g.settle = true; 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; + if (!Focusable(g.cursor)) return; const Row r = g.rows[g.cursor]; switch (r.act) { + case GA_NONE: + Refuse(); + break; case GA_VIEW: Push((View)r.arg); break; case GA_SETTING: case GA_CATEGORY: + case GA_RUNNER: Adjust(1); break; case GA_TEXT: { @@ -1030,6 +1471,25 @@ 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_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; @@ -1039,6 +1499,9 @@ static void Select() case GA_SEARCH: EditOpen(ED_SEARCH, 0, "Search by Name", g.search, 60, false); break; + case GA_NEWCOLL: + EditOpen(ED_COLLECTION, 0, "New Collection", "", VGAMES_COLLECTION_NAME_MAX, false); + break; case GA_PADTOOLS: Close(); g_padModeActive = true; @@ -1068,15 +1531,28 @@ 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(); 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"; + Refuse(); } else { EsdeVGames_Sync(s_esdePath); g.result[GA_ESDE] = "Refreshed"; @@ -1112,17 +1588,97 @@ 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()); + 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; } + 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; } + if (g.pickedPath.empty() || g.pickedName.empty()) { Refuse(); break; } + if (VGames_FindByName(g.pickedName.c_str()) >= 0) { g.added = "Already there"; Refuse(); 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)); - 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]); + char icon[1024]; + snprintf(icon, sizeof(icon), "%s/%s.jpg", VGAMES_ICONS, genID); + if (xiso.titleImageRGBA) { + Host_MakeDir(VGAMES_ICONS); + 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(); UDataSynth_RebuildAll(); g.added = "Added"; @@ -1153,11 +1709,39 @@ static void Select() break; case GA_GAMELIST: g.gameList = r.arg; + g.filter.clear(); + Push(GV_GAMES); + break; + case GA_COLLECTION: { + std::vector colls; + VGames_Collections(colls, false); + if (r.arg < 0 || r.arg >= (int)colls.size()) { Refuse(); break; } + g.collection = colls[r.arg]; + g.gameList = GL_COLLECTION; + g.filter.clear(); Push(GV_GAMES); break; + } + case GA_GAMECOLL: + g.collNames.clear(); + g.result[GA_NEWCOLL].clear(); + Push(GV_GAMECOLL); + break; + case GA_INCOLL: { + VirtualGame* vg = PickedGame(); + if (!vg || r.arg < 0 || r.arg >= (int)g.collNames.size()) { Refuse(); break; } + const char* name = g.collNames[r.arg].c_str(); + if (!VGames_SetInCollection(g.game, name, !VGames_InCollection(*vg, name))) { + g.result[GA_NEWCOLL] = "In too many already"; + Refuse(); + } + Build(); + break; + } case GA_LETTER: g.gameList = GL_LETTER; g.letter = (char)r.arg; + g.filter.clear(); Push(GV_GAMES); break; case GA_GAME: @@ -1168,7 +1752,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 +1760,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", @@ -1189,12 +1773,49 @@ static void Select() case GA_OPENLOGS: Host_OpenFolder(Plat_UserDataDir()); break; + case GA_BACKUP: { + int files = 0; + std::string name = Backup_Make(Plat_UserDataDir(), NULL, &files); + char msg[64]; + if (name.empty()) { snprintf(msg, sizeof(msg), "Couldn't save"); Refuse(); } + else snprintf(msg, sizeof(msg), "Saved %d files", files); + g.result[GA_BACKUP] = msg; + Build(); + break; + } + case GA_BACKUPS: + Push(GV_BACKUPS); + break; + case GA_PICKBACKUP: + if (r.arg < 0 || r.arg >= (int)g.backups.size()) { Refuse(); break; } + g.backup = g.backups[r.arg]; + g.result[GA_RESTORE].clear(); + Push(GV_RESTORE); + break; + case GA_RESTORE: { + std::string saved; + if (!Backup_Restore(Plat_UserDataDir(), g.backup, &saved)) { + g.result[GA_RESTORE] = saved.empty() ? "Couldn't back up first" : "Didn't finish"; + Refuse(); + Build(); + break; + } + fprintf(stderr, "[Guide] restored backup %s, the one before is %s\n", g.backup.c_str(), saved.c_str()); + // Straight over, before anything in memory gets saved on top of it. + Restart(); + break; + } + case GA_OPENBACKUPS: { + std::string dir = std::string(Plat_UserDataDir()) + "/" BACKUP_DIR; + Host_OpenFolder(dir.c_str()); + 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: { @@ -1210,9 +1831,19 @@ static void MoveCursor(int step) { int n = (int)g.rows.size(); if (n == 0) return; - g.cursor += step; - if (g.cursor < 0) g.cursor = 0; - if (g.cursor >= n) g.cursor = n - 1; + if (!AnyFocusable()) { + // Nothing to pick: up and down just read further. DrawRows clamps. + g.scroll += step < 0 ? -1 : 1; + if (g.scroll < 0) g.scroll = 0; + return; + } + int dir = step < 0 ? -1 : 1; + for (int left = step < 0 ? -step : step; left > 0; left--) { + int i = g.cursor + dir; + while (i >= 0 && i < n && !Focusable(i)) i += dir; + if (i < 0 || i >= n) break; + g.cursor = i; + } } // In a long game list LB and RB jump to the previous or next letter. @@ -1237,7 +1868,7 @@ static void LetterStep(int step) static void PageStep(int step) { - if (g.view == GV_GAMES && g.gameList == GL_ALL) { LetterStep(step); return; } + if (g.view == GV_GAMES && g.gameList == GL_ALL && ListSort() == SORT_NAME) { LetterStep(step); return; } if (g.view != GV_PAGE) return; g.page = (g.page + step + kPageCount) % kPageCount; g.cursor = g.scroll = 0; @@ -1268,6 +1899,12 @@ static void Handle(unsigned pressed) } if (pressed & GUIDE_UP) MoveCursor(-1); if (pressed & GUIDE_DOWN) MoveCursor(1); + if ((pressed & GUIDE_X) && g.view == GV_GAMES) { CycleFilter(); Build(); } + if ((pressed & GUIDE_Y) && g.view == GV_GAMES && g.gameList == GL_ALL) { + g.sort = (g.sort + 1) % SORT_COUNT; + g.cursor = g.scroll = 0; + Build(); + } // Left on a row that doesn't change goes back to the sections. if ((pressed & GUIDE_LEFT) && !Adjust(-1) && !g.welcome && g.stack.empty()) g.inPanel = false; if (pressed & GUIDE_RIGHT) Adjust(1); @@ -1503,21 +2140,112 @@ static void DrawSections() } } +// Words that fit width, in as many lines as it takes. +static void Wrap(int font, float size, const std::string& text, float width, std::vector& out) +{ + out.clear(); + std::string line; + size_t i = 0; + while (i <= text.size()) { + size_t j = text.find(' ', i); + if (j == std::string::npos) j = text.size(); + std::string word = text.substr(i, j - i); + std::string tryLine = line.empty() ? word : line + " " + word; + if (!line.empty() && ui_overlay_text_width(font, size, tryLine.c_str()) > width) { + out.push_back(line); + line = word; + } else { + line = tryLine; + } + i = j + 1; + } + if (!line.empty()) out.push_back(line); +} + +static const float TEXT_SIZE = 10.5f, TEXT_LINE = 15.0f, CAPTION_H = 24.0f; + +static float RowHeight(const Row& r, float width) +{ + if (r.kind == RK_CAPTION) return CAPTION_H; + if (r.kind == RK_TEXT) { + std::vector lines; + Wrap(UI_FONT_REGULAR, TEXT_SIZE, r.label, width - 8, lines); + return (float)lines.size() * TEXT_LINE + 10.0f; + } + return ROW_H + ROW_GAP; +} + static void DrawRows(float left, float right, float top) { float width = right - left; - int shown = (int)((BODY_B - top + ROW_GAP) / (ROW_H + ROW_GAP)); - if (shown < 1) shown = 1; + float room = BODY_B - top + ROW_GAP; int n = (int)g.rows.size(); - if (g.cursor < g.scroll) g.scroll = g.cursor; - if (g.cursor >= g.scroll + shown) g.scroll = g.cursor - shown + 1; - if (g.scroll > n - shown) g.scroll = n - shown; + std::vector h(n); + for (int i = 0; i < n; i++) h[i] = RowHeight(g.rows[i], width); + + // The last start that still fills the box, so the end never floats up. + int maxStart = n; + for (float used = 0; maxStart > 0 && used + h[maxStart - 1] <= room; ) used += h[--maxStart]; + if (AnyFocusable()) { + if (g.cursor < g.scroll) g.scroll = g.cursor; + // Keep a block's caption and text with its first action. + while (g.scroll > 0 && g.scroll == g.cursor && g.rows[g.scroll - 1].kind != RK_ACTION && + g.rows[g.scroll - 1].kind != RK_INFO) + g.scroll--; + for (;;) { + float used = 0; + for (int i = g.scroll; i <= g.cursor && i < n; i++) used += h[i]; + if (used <= room || g.scroll >= g.cursor) break; + g.scroll++; + } + } + if (g.scroll > maxStart) g.scroll = maxStart; if (g.scroll < 0) g.scroll = 0; float y = top; - for (int i = g.scroll; i < n && i < g.scroll + shown; i++) { + int i = g.scroll; + for (; i < n && y + h[i] <= top + room + 0.5f; i++) { const Row& r = g.rows[i]; bool on = g.inPanel && i == g.cursor; + if (r.kind == RK_CAPTION) { + // A caption without its first row below it would just dangle. + if (i + 1 < n && y + h[i] + h[i + 1] > top + room + 0.5f) break; + std::string cap = r.label; + for (size_t c = 0; c < cap.size(); c++) cap[c] = (char)toupper((unsigned char)cap[c]); + ui_overlay_text(UI_FONT_BOLD, 8.5f, left + 4, y + (i == g.scroll ? 5.0f : 11.0f), UI_ALIGN_LEFT, + ui_style_color(UI_COLOR_LABEL), cap.c_str()); + y += h[i]; + continue; + } + if (r.kind == RK_TEXT) { + std::vector lines; + Wrap(UI_FONT_REGULAR, TEXT_SIZE, r.label, width - 8, lines); + for (size_t l = 0; l < lines.size(); l++) + ui_overlay_text(UI_FONT_REGULAR, TEXT_SIZE, left + 4, y + 4 + l * TEXT_LINE, UI_ALIGN_LEFT, + ui_style_color(UI_COLOR_TEXT), lines[l].c_str()); + y += h[i]; + continue; + } + if (r.kind == RK_INFO) { + // A line, not a button. A row with no label carries on the one above. + float ty = y + (ROW_H - 11.0f) * 0.5f; + float valueW = ui_overlay_text_width(UI_FONT_BOLD, 11.0f, r.value.c_str()); + if (valueW > width * 0.62f) valueW = width * 0.62f; + std::string label = Fit(UI_FONT_BOLD, 11.0f, r.label, width - 16 - valueW - 8); + ui_overlay_text(UI_FONT_BOLD, 11.0f, left + 4, ty, UI_ALIGN_LEFT, ui_style_color(UI_COLOR_STATUS), + label.c_str()); + if (!r.value.empty()) { + std::string value = Fit(UI_FONT_BOLD, 11.0f, r.value, valueW); + ui_overlay_text(UI_FONT_BOLD, 11.0f, right - 4, ty, UI_ALIGN_RIGHT, 0xFFFFFFFF, value.c_str()); + } + bool nextInfo = i + 1 < n && g.rows[i + 1].kind == RK_INFO && y + h[i] + h[i + 1] <= top + room + 0.5f; + bool joined = nextInfo && g.rows[i + 1].label.empty(); + if (nextInfo && !joined) + ui_overlay_rect(left + 4, y + ROW_H + ROW_GAP * 0.5f, width - 8, 1, 0, + ui_style_color(UI_COLOR_SEPARATOR)); + y += h[i]; + continue; + } if (r.act == GA_SETTING || r.act == GA_CATEGORY) { const SettingDef* d = r.act == GA_SETTING ? &DesktopSettings_Table().defs[r.arg] : NULL; const char* badge = d && (d->flags & SF_RESTART) ? "RESTART" : NULL; @@ -1529,11 +2257,11 @@ static void DrawRows(float left, float right, float top) ui_style_row(left, y, width, ROW_H, on); float ty = y + (ROW_H - 11.0f) * 0.5f; float valueW = r.value.empty() ? 0.0f : ui_overlay_text_width(UI_FONT_BOLD, 11.0f, r.value.c_str()); - float chevron = r.act == GA_VIEW ? 14.0f : 0.0f; + float chevron = r.act == GA_VIEW || r.act == GA_GAMECOLL || r.act == GA_COLLECTION || + r.act == GA_BACKUPS || r.act == GA_PICKBACKUP ? 14.0f : 0.0f; if (valueW > width * 0.45f) valueW = width * 0.45f; std::string label = Fit(UI_FONT_BOLD, 11.0f, r.label, width - 24 - valueW - chevron - 8); - unsigned int labelColor = r.act == GA_NONE ? ui_style_color(UI_COLOR_STATUS) : 0xFFFFFFFF; - ui_overlay_text(UI_FONT_BOLD, 11.0f, left + 12, ty, UI_ALIGN_LEFT, labelColor, label.c_str()); + ui_overlay_text(UI_FONT_BOLD, 11.0f, left + 12, ty, UI_ALIGN_LEFT, 0xFFFFFFFF, label.c_str()); if (!r.value.empty()) { std::string value = Fit(UI_FONT_BOLD, 11.0f, r.value, valueW); ui_overlay_text(UI_FONT_BOLD, 11.0f, right - 12 - chevron, ty, UI_ALIGN_RIGHT, @@ -1544,17 +2272,17 @@ static void DrawRows(float left, float right, float top) "\xE2\x80\xBA"); } AddTarget(left, y, right, y + ROW_H, T_ROW, i); - y += ROW_H + ROW_GAP; + y += h[i]; } // More above or below. if (g.scroll > 0) ui_overlay_text(UI_FONT_BOLD, 9.0f, right - 6, top - 12, UI_ALIGN_RIGHT, ui_style_color(UI_COLOR_LABEL), "MORE"); - if (g.scroll + shown < n) + if (i < n) ui_overlay_text(UI_FONT_BOLD, 9.0f, right - 6, y - ROW_GAP + 1, UI_ALIGN_RIGHT, ui_style_color(UI_COLOR_LABEL), "MORE"); // The chosen row's help along the bottom. - if ((g.inPanel || g.welcome) && g.cursor >= 0 && g.cursor < n && !g.rows[g.cursor].help.empty()) { + if ((g.inPanel || g.welcome) && Focusable(g.cursor) && !g.rows[g.cursor].help.empty()) { std::string help = Fit(UI_FONT_REGULAR, 10.0f, g.rows[g.cursor].help, width); ui_style_text(UI_TEXT_LINE, left, BODY_B + 8, UI_ALIGN_LEFT, help.c_str()); } @@ -1645,7 +2373,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) @@ -1673,12 +2401,18 @@ static void DrawPrompts() int act = g.rows[g.cursor].act; const char* word = act == GA_NONE ? NULL : act == GA_SETTING || act == GA_CATEGORY ? "Change" - : act == GA_VIEW ? "Open" + : act == GA_VIEW || act == GA_GAMECOLL || act == GA_COLLECTION || + act == GA_BACKUPS || act == GA_PICKBACKUP ? "Open" + : act == GA_RESTORE ? "Restore" : act == GA_TEXT || act == GA_NAME || act == GA_JELLYFINURL ? "Edit" : "Select"; if (word) Prompt(p, &n, UI_BUTTON_A, "ENTER", word, GUIDE_A); } else if (!g.inPanel) { Prompt(p, &n, UI_BUTTON_A, "ENTER", "Open", GUIDE_A); } + if (!g.edit.on && g.inPanel && g.view == GV_GAMES) { + Prompt(p, &n, UI_BUTTON_X, "F", "Filter", GUIDE_X); + if (g.gameList == GL_ALL) Prompt(p, &n, UI_BUTTON_Y, "O", "Sort", GUIDE_Y); + } if (!g.edit.on) { bool back = !g.welcome && g.inPanel; Prompt(p, &n, UI_BUTTON_B, "ESC", back ? "Back" : "Close", GUIDE_B); @@ -1696,6 +2430,8 @@ 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_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/guide.h b/theseus/desktop/guide.h index bf6c4c9..ad229e9 100644 --- a/theseus/desktop/guide.h +++ b/theseus/desktop/guide.h @@ -15,6 +15,13 @@ 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(); +// What the scene heard last: 1 the pad, 0 the keyboard. +int Joy_LastDevice(); 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/host.h b/theseus/desktop/host.h index e3f4039..b110ae9 100644 --- a/theseus/desktop/host.h +++ b/theseus/desktop/host.h @@ -91,8 +91,15 @@ 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); +// The same from either hive. HKEY_LOCAL_MACHINE is where installers write for everyone. +enum { HOST_REG_USER, HOST_REG_MACHINE }; +bool Host_RegistryValue(int hive, const char* subKey, const char* value, char* out, size_t outSize); +// Names of the keys right under subKey, up to max. 0 when there are none or off Windows. +int Host_RegistrySubkeys(int hive, const char* subKey, char (*out)[256], int max); // Audio CD in the first optical drive: track count and per-track lengths // in seconds. -1 when there's no readable disc. int Host_CdReadToc(int* durations, int maxTracks, bool* allAudio); diff --git a/theseus/desktop/host_posix_app.cpp b/theseus/desktop/host_posix_app.cpp index a8cdbbe..77e3072 100644 --- a/theseus/desktop/host_posix_app.cpp +++ b/theseus/desktop/host_posix_app.cpp @@ -584,6 +584,13 @@ void Host_OpenFolder(const char* dir) { } bool Host_RegistryString(const char*, const char*, char*, size_t) { return false; } +bool Host_RegistryValue(int, const char*, const char*, char*, size_t) { return false; } +int Host_RegistrySubkeys(int, const char*, char (*)[256], int) { return 0; } + +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..6d6bf49 100644 --- a/theseus/desktop/host_win_app.cpp +++ b/theseus/desktop/host_win_app.cpp @@ -497,9 +497,32 @@ void Host_OpenFolder(const char* dir) { ShellExecuteA(NULL, "open", dir, NULL, NULL, SW_SHOWNORMAL); } +static HKEY Hive(int hive) { + return hive == HOST_REG_MACHINE ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; +} + bool Host_RegistryString(const char* subKey, const char* value, char* out, size_t outSize) { + return Host_RegistryValue(HOST_REG_USER, subKey, value, out, outSize); +} + +int Host_RegistrySubkeys(int hive, const char* subKey, char (*out)[256], int max) { HKEY hKey; - if (RegOpenKeyExA(HKEY_CURRENT_USER, subKey, 0, KEY_READ, &hKey) != ERROR_SUCCESS) return false; + if (RegOpenKeyExA(Hive(hive), subKey, 0, KEY_READ, &hKey) != ERROR_SUCCESS) return 0; + int n = 0; + for (DWORD i = 0; n < max; i++) { + DWORD len = 256; + LONG r = RegEnumKeyExA(hKey, i, out[n], &len, NULL, NULL, NULL, NULL); + if (r == ERROR_NO_MORE_ITEMS) break; + if (r == ERROR_SUCCESS) n++; + } + RegCloseKey(hKey); + return n; +} + +bool Host_RegistryValue(int hive, const char* subKey, const char* value, char* out, size_t outSize) { + if (!outSize) return false; + HKEY hKey; + if (RegOpenKeyExA(Hive(hive), subKey, 0, KEY_READ, &hKey) != ERROR_SUCCESS) return false; DWORD size = (DWORD)outSize; DWORD type = 0; bool ok = RegQueryValueExA(hKey, value, NULL, &type, (BYTE*)out, &size) == ERROR_SUCCESS; @@ -554,6 +577,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/http_util.cpp b/theseus/desktop/http_util.cpp index e2f76f3..6e196e6 100644 --- a/theseus/desktop/http_util.cpp +++ b/theseus/desktop/http_util.cpp @@ -2,9 +2,26 @@ #include "host.h" #include #include +#include #include #include +std::string Http_UrlEncode(const std::string& s) +{ + static const char* hex = "0123456789ABCDEF"; + std::string out; + for (unsigned char c : s) { + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + out.push_back((char)c); + } else { + out.push_back('%'); + out.push_back(hex[c >> 4]); + out.push_back(hex[c & 0xF]); + } + } + return out; +} + static std::once_flag s_initOnce; static void EnsureGlobalInit() { std::call_once(s_initOnce, []{ curl_global_init(CURL_GLOBAL_DEFAULT); }); diff --git a/theseus/desktop/http_util.h b/theseus/desktop/http_util.h index c252ace..18cd5d6 100644 --- a/theseus/desktop/http_util.h +++ b/theseus/desktop/http_util.h @@ -18,6 +18,9 @@ struct HttpResponse { std::string Http_GetToString(const std::string& url); bool Http_GetToFile(const std::string& url, const std::string& outPath); +// Percent-encodes everything but letters, digits and -_.~ for a query value. +std::string Http_UrlEncode(const std::string& s); + // True when a server-supplied id is fine as a bare filename: letters, digits, // '-', '_' and inner dots only, 1 to 128 chars, never "." or "..". bool Http_IsSafeFileId(const std::string& id); 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/jellyfin_client.cpp b/theseus/desktop/jellyfin_client.cpp index b1b1503..5dd08f4 100644 --- a/theseus/desktop/jellyfin_client.cpp +++ b/theseus/desktop/jellyfin_client.cpp @@ -5,6 +5,8 @@ #include "http_util.h" #include "json_util.h" #include "client_util.h" +#include "log_redact.h" +#include "media_player.h" #include #include @@ -14,6 +16,7 @@ #include #include #include +#include #include extern char g_jellyfinUrl[512]; @@ -67,6 +70,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 // ============================================================================ @@ -88,14 +132,24 @@ 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; +// The last search, its results under the "uix-search" library. +static std::string s_searchTerm; +static std::atomic s_searchState{0}; +static std::atomic s_searchSeq{0}; // ---------- Art download queue ---------- static std::mutex s_artMtx; static std::map*> s_artInFlight; +static std::map s_artFailed; // ============================================================================ @@ -118,8 +172,11 @@ void Jellyfin_Init() g_jellyfinUrl[0] ? g_jellyfinUrl : "(unset)"); } +static SerialWorker s_reports; + void Jellyfin_Shutdown() { + s_reports.Stop(); s_qcCancel = true; JoinIf(s_qcThread); JoinIf(s_syncThread); @@ -139,6 +196,11 @@ void Jellyfin_SignOut() s_cacheItems.clear(); s_cacheSeasons.clear(); s_cacheEpisodes.clear(); + s_cacheChildren.clear(); + s_fetchFailed.clear(); + s_syncFailed = false; + s_searchTerm.clear(); + s_searchState = JELLYFIN_SEARCH_NONE; s_syncGen++; s_syncReady = false; s_syncProgress = 0; @@ -196,7 +258,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 +322,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; @@ -316,6 +378,14 @@ 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"); + 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); @@ -324,26 +394,40 @@ static JellyfinItem ParseItem(const std::string& obj) return it; } -static std::vector FetchItemsForLibrary(const std::string& libraryId) +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]; 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; + 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; } @@ -359,6 +443,9 @@ static void SetSyncPhase(unsigned gen, const std::string& phase, int progressOf1 s_syncProgress = progressOf1000; } +static void FetchShelves(std::vector& shelves, + std::map>& items); + static void SyncWorker() { const unsigned gen = s_syncGen; @@ -369,6 +456,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) { @@ -390,7 +480,17 @@ 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]); + } + + // Continue Watching and Next Up go above the libraries, when there's + // anything in them. + SetSyncPhase(gen, "Loading Continue Watching", 950); + std::vector shelves; + FetchShelves(shelves, itemsById); + if (!libs.empty()) { + libs.insert(libs.begin(), shelves.begin(), shelves.end()); + libs.push_back({ "uix-search", "Search", "search" }); } size_t nLibs = libs.size(); @@ -419,6 +519,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() { @@ -445,16 +558,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", + 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"); @@ -464,23 +576,23 @@ 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; + 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", + "%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"); @@ -492,9 +604,10 @@ 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; + return true; } // Map from seasonId -> parent showId, populated as we fetch seasons. Lets @@ -502,54 +615,292 @@ 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; - } + 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; +} + + +// ============================================================================ +// Folder contents (lazy, in the background) +// ============================================================================ + +static void ChildrenWorker(unsigned gen, std::string parentId) +{ + std::vector items; + bool ok = FetchItemsForLibrary(parentId, items); + std::lock_guard lk(g_mtx); + 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) +{ + 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 (ClaimFetch(parentId)) + std::thread(ChildrenWorker, (unsigned)s_syncGen, parentId).detach(); + return false; +} + + +// ============================================================================ +// Playback reports + watch state refresh +// ============================================================================ + +static std::atomic s_watchStamp{0}; + +unsigned Jellyfin_WatchStamp() { return s_watchStamp; } + +// New watch state for every cached copy of this id. +template +static void PatchList(std::vector& list, const std::string& id, const JellyfinDetails& d) +{ + for (auto& e : list) + if (e.id == id) static_cast(e) = d; +} + +static void PatchDetails(const std::string& id, const JellyfinDetails& d) +{ + for (auto& kv : s_cacheItems) PatchList(kv.second, id, d); + for (auto& kv : s_cacheChildren) PatchList(kv.second, id, d); + for (auto& kv : s_cacheSeasons) PatchList(kv.second, id, d); + for (auto& kv : s_cacheEpisodes) PatchList(kv.second, id, d); +} + +// The item's watch state, and the series it belongs to (itself for a series). +static bool FetchDetails(const std::string& id, JellyfinDetails& d, std::string* seriesId = NULL, + std::string* type = NULL) +{ + HttpResponse r = Http_Get(std::string(g_jellyfinUrl) + "/Users/" + g_jellyfinUserId + "/Items/" + id, + JellyfinHeaders(g_jellyfinToken)); + if (!r.ok()) return false; + ParseDetails(r.body, d); + std::string t = Json_GetString(r.body, "Type"); + if (type) *type = t; + if (seriesId) *seriesId = t == "Series" ? id : Json_GetString(r.body, "SeriesId"); + return true; +} + +static void FetchShelves(std::vector& shelves, + std::map>& items) +{ + 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); + if (!resume.empty()) { + shelves.push_back({ "uix-resume", "Continue Watching", "resume" }); + items["uix-resume"] = std::move(resume); + } + if (!nextUp.empty()) { + shelves.push_back({ "uix-nextup", "Next Up", "nextup" }); + items["uix-nextup"] = std::move(nextUp); + } +} + +static bool IsShelf(const std::string& id) { return id == "uix-resume" || id == "uix-nextup"; } + +// After playback or a mark: the item, its series and seasons, and the shelves. +static void RefreshWatchState(unsigned gen, const std::string& id) +{ + JellyfinDetails d, series; + std::string seriesId, type; + bool haveItem = FetchDetails(id, d, &seriesId, &type); + bool haveSeries = false, haveSeasons = false; + std::vector seasons; + if (!seriesId.empty()) { + haveSeries = seriesId == id ? false : FetchDetails(seriesId, series); + haveSeasons = FetchSeasonsForShow(seriesId, seasons); + } + std::vector shelves; + std::map> shelfItems; + FetchShelves(shelves, shelfItems); + + std::lock_guard lk(g_mtx); + if (gen != s_syncGen) return; + if (haveItem) PatchDetails(id, d); + if (haveSeries) PatchDetails(seriesId, series); + // A whole series or season was marked: its episodes load fresh next time. + if (type == "Series" || type == "Season") { + auto cached = s_cacheSeasons.find(seriesId); + if (cached != s_cacheSeasons.end()) + for (const auto& se : cached->second) s_cacheEpisodes.erase(se.id); + s_cacheEpisodes.erase(id); + } + if (haveSeasons && s_cacheSeasons.count(seriesId)) s_cacheSeasons[seriesId] = std::move(seasons); + if (!s_cacheLibs.empty()) { + s_cacheLibs.erase(std::remove_if(s_cacheLibs.begin(), s_cacheLibs.end(), + [](const JellyfinLibrary& l) { return IsShelf(l.id); }), s_cacheLibs.end()); + s_cacheItems.erase("uix-resume"); + s_cacheItems.erase("uix-nextup"); + s_cacheLibs.insert(s_cacheLibs.begin(), shelves.begin(), shelves.end()); + for (auto& kv : shelfItems) s_cacheItems[kv.first] = std::move(kv.second); } - std::string showId; + s_watchStamp++; +} + +static void PostReport(const std::string& path, const std::string& body) +{ + HttpResponse r = Http_Post(std::string(g_jellyfinUrl) + path, body, JellyfinHeaders(g_jellyfinToken)); + if (!r.ok()) fprintf(stderr, "[Jellyfin] %s failed (status %ld)\n", path.c_str(), r.status); +} + +void Jellyfin_ReportPlayback(const std::string& itemId, int event, long long posTicks, bool paused) +{ + if (itemId.empty() || !Jellyfin_HasToken()) return; + if (posTicks < 0) posTicks = 0; + char body[256]; + snprintf(body, sizeof(body), + "{\"ItemId\":\"%s\",\"PositionTicks\":%lld,\"IsPaused\":%s,\"CanSeek\":true,\"PlayMethod\":\"DirectPlay\"}", + itemId.c_str(), posTicks, paused ? "true" : "false"); + std::string b = body; + unsigned gen = s_syncGen; + if (event == MEDIA_REPORT_START) + s_reports.Post([b] { PostReport("/Sessions/Playing", b); }); + else if (event == MEDIA_REPORT_PROGRESS) + s_reports.Post([b] { PostReport("/Sessions/Playing/Progress", b); }); + else + s_reports.Post([b, gen, itemId] { + PostReport("/Sessions/Playing/Stopped", b); + RefreshWatchState(gen, itemId); + }); +} + + +void Jellyfin_SetPlayed(const std::string& itemId, bool played) +{ + if (itemId.empty() || !Jellyfin_HasToken()) return; { + // Show it right away; the refresh after the request has the final word. std::lock_guard lk(g_mtx); - auto it = s_seasonToShow.find(seasonId); - if (it != s_seasonToShow.end()) showId = it->second; + auto mark = [&](JellyfinDetails& e) { + e.played = played; + e.posTicks = 0; + if (played) e.unplayed = 0; + }; + for (auto* m : { &s_cacheItems, &s_cacheChildren }) + for (auto& kv : *m) for (auto& e : kv.second) if (e.id == itemId) mark(e); + for (auto& kv : s_cacheSeasons) for (auto& e : kv.second) if (e.id == itemId) mark(e); + for (auto& kv : s_cacheEpisodes) for (auto& e : kv.second) if (e.id == itemId) mark(e); + s_watchStamp++; } - if (showId.empty()) return false; - std::vector fetched = FetchEpisodesForSeason(seasonId, showId); + unsigned gen = s_syncGen; + s_reports.Post([=] { + std::string base = std::string(g_jellyfinUrl); + HttpHeaders h = JellyfinHeaders(g_jellyfinToken); + std::string url = base + "/UserPlayedItems/" + itemId + "?userId=" + g_jellyfinUserId; + HttpResponse r = played ? Http_Post(url, "", h) : Http_Delete(url, h); + // Servers older than 10.9 only know the per-user path. + if (r.status == 404) { + url = base + "/Users/" + g_jellyfinUserId + "/PlayedItems/" + itemId; + r = played ? Http_Post(url, "", h) : Http_Delete(url, h); + } + if (!r.ok()) fprintf(stderr, "[Jellyfin] marking %s failed (status %ld)\n", itemId.c_str(), r.status); + RefreshWatchState(gen, itemId); + }); +} + + +// ============================================================================ +// Search +// ============================================================================ + +static void SearchWorker(unsigned gen, unsigned seq, std::string term) +{ + std::vector found; + bool ok = FetchItemList(std::string(g_jellyfinUrl) + "/Users/" + g_jellyfinUserId + + "/Items?searchTerm=" + Http_UrlEncode(term) + + "&Recursive=true&IncludeItemTypes=Movie,Series,Episode,Audio,MusicAlbum,BoxSet&Limit=50" + "&Fields=Overview,ProductionYear,Genres&EnableUserData=true", found); + std::lock_guard lk(g_mtx); + if (gen != s_syncGen || seq != s_searchSeq) return; + s_cacheItems["uix-search"] = std::move(found); + s_searchState = ok ? JELLYFIN_SEARCH_DONE : JELLYFIN_SEARCH_FAILED; +} + +void Jellyfin_Search(const std::string& term) +{ + if (term.empty() || !Jellyfin_HasToken()) return; + unsigned seq; { std::lock_guard lk(g_mtx); - s_cacheEpisodes[seasonId] = fetched; - out = fetched; + s_searchTerm = term; + s_cacheItems.erase("uix-search"); + s_searchState = JELLYFIN_SEARCH_BUSY; + seq = ++s_searchSeq; } - return true; + std::thread(SearchWorker, (unsigned)s_syncGen, seq, term).detach(); +} + +std::string Jellyfin_SearchTerm() +{ + std::lock_guard lk(g_mtx); + return s_searchTerm; } +int Jellyfin_SearchState() { return s_searchState; } + // ============================================================================ // Stream URL @@ -562,11 +913,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; @@ -609,6 +960,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; } } { @@ -622,13 +975,27 @@ 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; { 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..326a860 100644 --- a/theseus/desktop/jellyfin_client.h +++ b/theseus/desktop/jellyfin_client.h @@ -11,23 +11,38 @@ 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 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) + std::string seriesName; // episodes in Continue Watching / Next Up + std::string seasonIndex; + std::string episodeIndex; }; -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 @@ -57,9 +72,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 @@ -68,10 +89,34 @@ 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); 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); + +// Playback reports (MEDIA_REPORT_* from media_player.h), so the server keeps +// the resume point and marks it watched. Sent in order, off the main thread; +// a stop also reloads the item and the Continue Watching and Next Up shelves. +void Jellyfin_ReportPlayback(const std::string& itemId, int event, + long long posTicks, bool paused); +// Bumped whenever watch state in the cache changes, so the scene redraws. +unsigned Jellyfin_WatchStamp(); +// Marks it watched or not on the server; the cache shows it straight away. +void Jellyfin_SetPlayed(const std::string& itemId, bool played); + +// Search across the libraries, in the background. Results show up as the +// items of the "uix-search" library at the end of the list. +enum { JELLYFIN_SEARCH_NONE, JELLYFIN_SEARCH_BUSY, JELLYFIN_SEARCH_DONE, JELLYFIN_SEARCH_FAILED }; +void Jellyfin_Search(const std::string& term); +std::string Jellyfin_SearchTerm(); +int Jellyfin_SearchState(); diff --git a/theseus/desktop/joystick.cpp b/theseus/desktop/joystick.cpp index 3ad42ef..7651386 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,16 +114,10 @@ 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; } - CJoystick *CJoystick::c_pActivePad = NULL; CJoystick *CJoystick::c_pLastActivePad = NULL; @@ -272,8 +263,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 +334,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) @@ -386,58 +344,64 @@ 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) +// 1 when the pad was used last, 0 for the keyboard. +static int s_lastDevice = 0; +int Joy_LastDevice() { return s_lastDevice; } + +static bool AnyHeld(const JoySnapshot* s) { - 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; - } + JoySnapshot none; + memset(&none, 0, sizeof(none)); + return memcmp(s, &none, sizeof(none)) != 0; +} + +// Every pad's buttons and sticks as one snapshot. holdB drops the B of LT+B. +static void ReadPad(bool holdB, JoySnapshot* out) +{ + // 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(SDL_GameController* gc, JoySnapshot* out) +void CJoystick::PollSDL(JoySnapshot* out) { memset(out, 0, sizeof(*out)); @@ -447,9 +411,10 @@ void CJoystick::PollSDL(SDL_GameController* gc, 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); + const bool padHeld = AnyHeld(out); // --- Keyboard overlay (OR on top) --- extern bool ImGui_WantsKeyboard(); @@ -514,24 +479,30 @@ void CJoystick::PollSDL(SDL_GameController* gc, JoySnapshot* out) else if (keys[SDL_SCANCODE_S]) out->thumbLY = -1.0f; } } + const bool keysHeld = !padHeld && AnyHeld(out); + JoySnapshot before = *out; DevPadScript(out); + if (padHeld || memcmp(&before, out, sizeof(before)) != 0) s_lastDevice = 1; + else if (keysHeld) s_lastDevice = 0; } // 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, Pads_Map(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() && @@ -567,6 +538,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,12 +649,11 @@ unsigned Joy_GuideButtons(int* device) { extern SDL_Window* g_pSDLWindow; extern bool ImGui_WantsKeyboard(); - SDL_GameController* gc = CJoystick::c_controller; - 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; @@ -706,6 +681,8 @@ unsigned Joy_GuideButtons(int* device) if (k[SDL_SCANCODE_RIGHT] || k[SDL_SCANCODE_D]) keys |= GUIDE_RIGHT; if (k[SDL_SCANCODE_Q]) keys |= GUIDE_LB; if (k[SDL_SCANCODE_E]) keys |= GUIDE_RB; + if (k[SDL_SCANCODE_F]) keys |= GUIDE_X; // the game lists' filter + if (k[SDL_SCANCODE_O]) keys |= GUIDE_Y; // and All Games' order } if (bits) *device = 1; else if (keys) *device = 0; @@ -714,6 +691,33 @@ unsigned Joy_GuideButtons(int* device) return bits | keys; } +unsigned Joy_PadButtons() +{ + JoySnapshot pad; + memset(&pad, 0, sizeof(pad)); + ReadPad(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) // ============================================================================ @@ -835,10 +839,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 +852,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/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/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/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/gog.cpp b/theseus/desktop/launchers/gog.cpp new file mode 100644 index 0000000..96f33b4 --- /dev/null +++ b/theseus/desktop/launchers/gog.cpp @@ -0,0 +1,136 @@ +// gog.cpp: GOG installs. GOG Galaxy and the offline installers register each +// game under Software\GOG.com\Games\ on Windows; those launch the game's +// own exe so play time counts. Heroic lists its GOG installs in +// gog_store/installed.json and launches them through heroic://. + +#include "stores.h" + +#include +#include + +#include "host.h" +#include "../json_util.h" + +// 32 bit installers land under WOW6432Node, a few write the plain key, and a +// per-user install goes under HKEY_CURRENT_USER. +static const struct { int hive; const char* key; } kGogKeys[] = { + { HOST_REG_MACHINE, "Software\\WOW6432Node\\GOG.com\\Games" }, + { HOST_REG_MACHINE, "Software\\GOG.com\\Games" }, + { HOST_REG_USER, "Software\\GOG.com\\Games" }, +}; +static const int kGogKeyCount = (int)(sizeof(kGogKeys) / sizeof(kGogKeys[0])); + +static std::string RegValue(int hive, const std::string& key, const char* name) +{ + char buf[1024]; + return Host_RegistryValue(hive, key.c_str(), name, buf, sizeof(buf)) ? buf : ""; +} + +static void HeroicFiles(std::vector& dirs) +{ + std::vector heroic; + Store_HeroicDirs(heroic); + dirs.clear(); + for (size_t i = 0; i < heroic.size(); i++) + if (Store_IsFile(heroic[i] + "/gog_store/installed.json")) dirs.push_back(heroic[i]); +} + +bool Gog_Found() +{ + char ids[1][256]; + for (int k = 0; k < kGogKeyCount; k++) + if (Host_RegistrySubkeys(kGogKeys[k].hive, kGogKeys[k].key, ids, 1) > 0) return true; + std::vector heroic; + HeroicFiles(heroic); + return !heroic.empty(); +} + +// goggame-.ico sits next to most GOG games and looks better than the exe's. +static std::string GameIcon(const std::string& dir, const std::string& id, const std::string& exe) +{ + std::string ico = Store_Join(dir, "goggame-" + id + ".ico"); + return Store_IsFile(ico) ? ico : exe; +} + +static void ScanRegistry(std::vector& out) +{ + std::vector seen; + static char ids[512][256]; + for (int k = 0; k < kGogKeyCount; k++) { + int n = Host_RegistrySubkeys(kGogKeys[k].hive, kGogKeys[k].key, ids, 512); + for (int i = 0; i < n; i++) { + std::string id = ids[i]; + bool dup = false; + for (size_t s = 0; s < seen.size(); s++) dup |= seen[s] == id; + if (dup) continue; + seen.push_back(id); + + std::string key = std::string(kGogKeys[k].key) + "\\" + id; + int hive = kGogKeys[k].hive; + if (!RegValue(hive, key, "dependsOn").empty()) continue; // DLC + std::string exe = RegValue(hive, key, "exe"); + std::string name = RegValue(hive, key, "gameName"); + std::string cmd = RegValue(hive, key, "launchCommand"); + if (name.empty() || (exe.empty() && cmd.empty())) continue; + + StoreGame g; + g.name = name; + g.launch = exe.empty() ? cmd : "\"" + exe + "\""; + std::string param = RegValue(hive, key, "launchParam"); + if (!exe.empty() && !param.empty()) g.launch += " " + param; + std::string path = RegValue(hive, key, "path"); + g.workdir = RegValue(hive, key, "workingDir"); + if (g.workdir.empty()) g.workdir = path; + g.icon = GameIcon(path, id, exe); + out.push_back(g); + } + } +} + +// The name GOG wrote into the install folder, for a game Heroic's cache doesn't list. +static std::string InfoName(const std::string& dir, const std::string& id) +{ + std::string text; + if (!Store_ReadFile(Store_Join(dir, "goggame-" + id + ".info"), text)) return ""; + return Store_JsonString(text, "name"); +} + +static void ScanHeroic(const std::string& heroicDir, std::vector& out) +{ + std::string text; + if (!Store_ReadFile(heroicDir + "/gog_store/installed.json", text)) return; + size_t arr = Json_FindArray(text, "installed"); + if (arr == std::string::npos) return; + std::map lib; + Store_HeroicLibrary(heroicDir, "gog_library.json", lib); + std::vector games = Json_SplitArray(text, arr); + for (size_t i = 0; i < games.size(); i++) { + const std::string& e = games[i]; + std::string id = Store_JsonString(e, "appName"); + if (id.empty() || Store_JsonBool(e, "is_dlc")) continue; + std::string path = Store_JsonString(e, "install_path"); + StoreGame g; + std::map::iterator it = lib.find(id); + if (it != lib.end()) { g.name = it->second.title; g.artUrl = it->second.art; } + if (g.name.empty()) g.name = InfoName(path, id); + if (g.name.empty() && !path.empty()) { + size_t slash = path.find_last_of("/\\", path.size() - 2); + g.name = slash == std::string::npos ? path : path.substr(slash + 1); + while (!g.name.empty() && (g.name[g.name.size() - 1] == '/' || g.name[g.name.size() - 1] == '\\')) + g.name.erase(g.name.size() - 1); + } + if (g.name.empty()) continue; + g.launch = "heroic://launch/gog/" + id; + g.icon = GameIcon(path, id, ""); + out.push_back(g); + } +} + +void Gog_Scan(std::vector& out) +{ + out.clear(); + ScanRegistry(out); + std::vector heroic; + HeroicFiles(heroic); + for (size_t i = 0; i < heroic.size(); i++) ScanHeroic(heroic[i], out); +} diff --git a/theseus/desktop/launchers/itch.cpp b/theseus/desktop/launchers/itch.cpp new file mode 100644 index 0000000..6c76ea0 --- /dev/null +++ b/theseus/desktop/launchers/itch.cpp @@ -0,0 +1,111 @@ +// itch.cpp: the itch.io app. Its installs live in butler.db (SQLite): a cave +// per install, with the verdict butler wrote after looking at the files, +// which names the programs it found. We launch the one that fits this OS +// directly, so play time counts, and use the game's cover from itch.io. + +#include "stores.h" + +#include +#include + +#include "host.h" +#include "../json_util.h" +#include "../sqlite_read.h" + +static void Dbs(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) + "/itch/db/butler.db"); + if (!home.empty()) { + tries.push_back(home + "/.config/itch/db/butler.db"); + tries.push_back(home + "/.var/app/io.itch.itch/config/itch/db/butler.db"); + tries.push_back(home + "/Library/Application Support/itch/db/butler.db"); + } + const char* appData = getenv("APPDATA"); + if (appData && *appData) tries.push_back(std::string(appData) + "\\itch\\db\\butler.db"); + 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_IsFile(tries[i])) out.push_back(tries[i]); + } +} + +bool Itch_Found() +{ + std::vector dbs; + Dbs(dbs); + return !dbs.empty(); +} + +// Which of butler's flavors run here, best first. +static int FlavorRank(const std::string& flavor) +{ + static const char* kWin[] = { "windows", "windows-script", NULL }; + static const char* kMac[] = { "app-macos", "macos", "script", NULL }; + static const char* kLinux[] = { "linux", "script", NULL }; + const char* os = Host_Name(); + const char** list = strcmp(os, "Windows") == 0 ? kWin : strcmp(os, "macOS") == 0 ? kMac : kLinux; + for (int i = 0; list[i]; i++) + if (flavor == list[i]) return i; + return -1; +} + +static void ScanDb(const std::string& db, std::vector& out) +{ + std::vector caves, games; + if (!Sqlite_ReadTable(db.c_str(), "caves", caves)) return; + Sqlite_ReadTable(db.c_str(), "games", games); + std::map byId; + for (size_t i = 0; i < games.size(); i++) byId[games[i]["id"]] = &games[i]; + + for (size_t i = 0; i < caves.size(); i++) { + const std::string& verdict = caves[i]["verdict"]; + std::string base = Store_JsonString(verdict, "basePath"); + size_t arr = Json_FindArray(verdict, "candidates"); + if (base.empty() || arr == std::string::npos) continue; + std::vector cands = Json_SplitArray(verdict, arr); + std::string path, flavor; + int best = -1; + for (size_t c = 0; c < cands.size(); c++) { + std::string f = Store_JsonString(cands[c], "flavor"); + int rank = FlavorRank(f); + if (rank < 0 || (best >= 0 && rank >= best)) continue; + std::string p = Store_JsonString(cands[c], "path"); + if (p.empty()) continue; + best = rank; + path = p; + flavor = f; + } + if (path.empty()) continue; + + std::map::iterator it = byId.find(caves[i]["game_id"]); + SqliteRow* game = it == byId.end() ? NULL : it->second; + StoreGame g; + g.name = game ? (*game)["title"] : ""; + if (g.name.empty()) g.name = caves[i]["install_folder_name"]; + if (g.name.empty()) continue; + std::string full = Store_Join(base, path); + g.launch = "\"" + full + "\""; + if (flavor == "app-macos") g.launch = "open -W " + g.launch; + g.workdir = base; + if (game) { + g.artUrl = (*game)["still_cover_url"]; + if (g.artUrl.empty()) g.artUrl = (*game)["cover_url"]; + if ((*game)["classification"] == "tool") g.category = "Applications"; + } + // The exe's own icon only when itch.io has no cover. + if (g.artUrl.empty()) g.icon = full; + out.push_back(g); + } +} + +void Itch_Scan(std::vector& out) +{ + out.clear(); + std::vector dbs; + Dbs(dbs); + for (size_t i = 0; i < dbs.size(); i++) ScanDb(dbs[i], out); +} diff --git a/theseus/desktop/launchers/lutris.cpp b/theseus/desktop/launchers/lutris.cpp new file mode 100644 index 0000000..abda27a --- /dev/null +++ b/theseus/desktop/launchers/lutris.cpp @@ -0,0 +1,92 @@ +// lutris.cpp: Lutris on Linux. Its library is the SQLite file pga.db; each +// installed game launches with lutris:rungameid/, through Flatpak when +// that's the Lutris that's here. Covers, banners and icons come from +// Lutris' own folders. + +#include "stores.h" + +#include + +#include "../sqlite_read.h" + +struct LutrisHome { + std::string db, data, cache, icons, run; +}; + +static void Homes(std::vector& out) +{ + out.clear(); + std::string home = Store_Home(); + if (home.empty()) return; + const char* xdgData = getenv("XDG_DATA_HOME"); + const char* xdgCache = getenv("XDG_CACHE_HOME"); + std::string data = xdgData && *xdgData ? xdgData : home + "/.local/share"; + std::string cache = xdgCache && *xdgCache ? xdgCache : home + "/.cache"; + LutrisHome native = { data + "/lutris/pga.db", data + "/lutris", cache + "/lutris", + data + "/icons/hicolor/128x128/apps", "lutris" }; + std::string fp = home + "/.var/app/net.lutris.Lutris"; + LutrisHome flatpak = { fp + "/data/lutris/pga.db", fp + "/data/lutris", fp + "/cache/lutris", + fp + "/data/icons/hicolor/128x128/apps", "flatpak run net.lutris.Lutris" }; + if (Store_IsFile(native.db)) out.push_back(native); + if (Store_IsFile(flatpak.db)) out.push_back(flatpak); +} + +bool Lutris_Found() +{ + std::vector homes; + Homes(homes); + return !homes.empty(); +} + +// Cover first, it's the shape the other stores' art is; then the banner, then the icon. +static std::string Art(const LutrisHome& h, const std::string& slug) +{ + if (slug.empty()) return ""; + const std::string tries[] = { + h.cache + "/coverart/" + slug + ".jpg", h.data + "/coverart/" + slug + ".jpg", + h.cache + "/banners/" + slug + ".jpg", h.data + "/banners/" + slug + ".jpg", + h.icons + "/lutris_" + slug + ".png", + }; + for (size_t i = 0; i < sizeof(tries) / sizeof(tries[0]); i++) + if (Store_IsFile(tries[i])) return tries[i]; + return ""; +} + +static void ScanHome(const LutrisHome& h, std::vector& out) +{ + std::vector games; + if (!Sqlite_ReadTable(h.db.c_str(), "games", games)) return; + + // Games you hid in Lutris sit in its ".hidden" category. + std::vector hidden; + std::vector cats, links; + if (Sqlite_ReadTable(h.db.c_str(), "categories", cats) && + Sqlite_ReadTable(h.db.c_str(), "games_categories", links)) { + std::string hiddenId; + for (size_t i = 0; i < cats.size(); i++) + if (cats[i]["name"] == ".hidden") hiddenId = cats[i]["id"]; + for (size_t i = 0; i < links.size() && !hiddenId.empty(); i++) + if (links[i]["category_id"] == hiddenId) hidden.push_back(links[i]["game_id"]); + } + + for (size_t i = 0; i < games.size(); i++) { + SqliteRow& r = games[i]; + if (r["installed"] != "1" || r["hidden"] == "1" || r["id"].empty() || r["name"].empty()) continue; + bool hide = false; + for (size_t k = 0; k < hidden.size(); k++) hide |= hidden[k] == r["id"]; + if (hide) continue; + StoreGame g; + g.name = r["name"]; + g.launch = h.run + " lutris:rungameid/" + r["id"]; + g.icon = Art(h, r["slug"]); + out.push_back(g); + } +} + +void Lutris_Scan(std::vector& out) +{ + out.clear(); + std::vector homes; + Homes(homes); + for (size_t i = 0; i < homes.size(); i++) ScanHome(homes[i], out); +} 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/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..3628b00 --- /dev/null +++ b/theseus/desktop/launchers/stores.h @@ -0,0 +1,62 @@ +// 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); + +// GOG: Galaxy and offline installs from the Windows registry, and Heroic's +// GOG installs. +bool Gog_Found(); +void Gog_Scan(std::vector& out); + +// Lutris: installed games from its pga.db, native or Flatpak. +bool Lutris_Found(); +void Lutris_Scan(std::vector& out); + +// itch.io app: installs from butler.db, launched straight from their folders. +bool Itch_Found(); +void Itch_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/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/log_redact.cpp b/theseus/desktop/log_redact.cpp index d9a71b4..dbaf701 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: sign-in token, home folder and IP address masking for logs. #include "log_redact.h" #include #include +#include static bool IsHex(char c) { return isxdigit((unsigned char)c) != 0; } @@ -50,8 +51,106 @@ 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; +} + +// 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(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..4535b1a 100644 --- a/theseus/desktop/log_redact.h +++ b/theseus/desktop/log_redact.h @@ -2,6 +2,9 @@ #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); + +// 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..882ff58 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 @@ -169,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); @@ -190,7 +201,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; } @@ -406,10 +417,17 @@ 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: 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..dd78930 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(); @@ -103,3 +104,11 @@ int MediaPlayer_GetSubtitleTrack(); // 0 = off, >0 = track index // Master volume (0.0 - 1.0). Applies immediately if a session is live and // is re-applied on every Open so subsequent playbacks inherit the value. void MediaPlayer_SetMasterVolume(float vol); + +// Playback reports for a media server (media_ui.cpp). Whoever opens a stream +// hands over a callback: it hears START once the stream knows its length, +// PROGRESS every 10 seconds and on pause or resume, and STOP with the last +// position when the video closes. Any other playback clears it. +enum { MEDIA_REPORT_START, MEDIA_REPORT_PROGRESS, MEDIA_REPORT_STOP }; +typedef void (*MediaReportFn)(int event, double position, double duration, bool paused); +void MediaUI_SetReporter(MediaReportFn fn); diff --git a/theseus/desktop/media_ui.cpp b/theseus/desktop/media_ui.cpp index e751315..50a1d21 100644 --- a/theseus/desktop/media_ui.cpp +++ b/theseus/desktop/media_ui.cpp @@ -10,6 +10,9 @@ #include "audio_sdl.h" #include "imgui.h" #include "playlist.h" +#include "guide.h" +#include "pads.h" +#include "ui_overlay.h" #include "d3d8_sdl.h" // for g_bgfxProgBlit / g_bgfxSamplerBlit on bgfx path #include @@ -48,12 +51,70 @@ void MediaUI_NoteActivity() s_lastActivity = NowSeconds(); } +// The hints name pad buttons while the pad is what's being used. +static bool s_hintPad = false; + +void MediaUI_NoteKey() +{ + s_hintPad = false; + MediaUI_NoteActivity(); +} + void MediaUI_ToggleTrackMenu() { s_trackMenuOpen = !s_trackMenuOpen; s_lastActivity = NowSeconds(); // keep OSD up while menu is around } +// ============================================================================ +// Server playback reports. Position is kept every frame because it's gone +// by the time the player has stopped. +// ============================================================================ + +static MediaReportFn s_report = NULL; +static bool s_reportStarted = false; +static bool s_reportPaused = false; +static double s_reportLast = 0.0; +static double s_reportPos = 0.0, s_reportDur = 0.0; + +static void EndReport() +{ + if (s_report && s_reportStarted) + s_report(MEDIA_REPORT_STOP, s_reportPos, s_reportDur, false); + s_report = NULL; + s_reportStarted = false; +} + +void MediaUI_SetReporter(MediaReportFn fn) +{ + EndReport(); + s_report = fn; + s_reportPos = s_reportDur = 0.0; +} + +static void ReportFrame() +{ + if (!s_report) return; + MediaPlayerState st = MediaPlayer_GetState(); + if (st != MP_PLAYING && st != MP_PAUSED) return; + double dur = MediaPlayer_GetDuration(); + if (dur <= 0.0) return; + s_reportPos = MediaPlayer_GetPosition(); + s_reportDur = dur; + bool paused = st == MP_PAUSED; + double now = NowSeconds(); + if (!s_reportStarted) { + s_report(MEDIA_REPORT_START, s_reportPos, dur, paused); + s_reportStarted = true; + } else if (paused != s_reportPaused || now - s_reportLast >= 10.0) { + s_report(MEDIA_REPORT_PROGRESS, s_reportPos, dur, paused); + } else { + return; + } + s_reportPaused = paused; + s_reportLast = now; +} + // ============================================================================ // Playback queue. Snapshot of a playlist captured at PlayPlaylist time so // edits to the source playlist while playing don't change what's queued. @@ -67,6 +128,7 @@ static int s_queueIdx = -1; static void OpenCurrentQueueItem() { if (s_queueIdx < 0 || s_queueIdx >= (int)s_queue.size()) return; const QueueItem& it = s_queue[s_queueIdx]; + MediaUI_SetReporter(NULL); if (!MediaPlayer_Open(it.path.c_str())) return; g_mediaFullscreen = true; @@ -106,6 +168,33 @@ 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(); + s_hintPad = Joy_LastDevice() == 1; + } + 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(); + s_hintPad = true; + 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 +242,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 +252,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); @@ -193,6 +284,66 @@ static void FormatTime(double seconds, char* buf, int sz) else snprintf(buf, sz, "%d:%02d", m, s); } +// The transport hints, in the guide's button style: pad buttons or key caps, +// whichever was used last. Drawn on the guide's overlay, which works in a +// 640x480 layout scaled to the window's height. +struct OsdHint { int button[2]; const char* key[2]; const char* word; }; + +static float HintGlyph(const OsdHint& h, int i, float size, float x, float y, unsigned int color, bool measure) +{ + if (!s_hintPad) + return measure ? ui_overlay_key_width(h.key[i], size) : ui_overlay_key(h.key[i], size, x, y, color); + return measure ? ui_overlay_button_width(h.button[i], size) : ui_overlay_button(h.button[i], size, x, y, color); +} + +static float DrawHint(const OsdHint& h, float size, float x, float y, unsigned int glyph, unsigned int text, bool measure) +{ + float w = 0.0f; + for (int i = 0; i < 2; i++) { + if (i == 1 && (s_hintPad ? h.button[1] < 0 : !h.key[1])) break; + if (i == 1) w += 2.0f; + w += HintGlyph(h, i, size, x + w, y, glyph, measure); + } + w += 4.0f; + float ts = size * 0.72f; + w += measure ? ui_overlay_text_width(UI_FONT_BOLD, ts, h.word) + : ui_overlay_text(UI_FONT_BOLD, ts, x + w, y + size * 0.14f, UI_ALIGN_LEFT, text, h.word); + return w; +} + +static void DrawHints(float alpha, float right, float y) +{ + static const OsdHint kPad[] = { + { { UI_BUTTON_B, -1 }, { "", NULL }, "Stop" }, + { { UI_BUTTON_A, -1 }, { "", NULL }, "Pause" }, + { { UI_BUTTON_DPAD_LEFT, UI_BUTTON_DPAD_RIGHT }, { "", NULL }, "Seek" }, + { { UI_BUTTON_LEFT_SHOULDER, UI_BUTTON_RIGHT_SHOULDER }, { "", NULL }, "Prev/Next" }, + }; + static const OsdHint kKeys[] = { + { { -1, -1 }, { "ESC", NULL }, "Stop" }, + { { -1, -1 }, { "SPACE", NULL }, "Pause" }, + { { -1, -1 }, { "\xE2\x80\xB9", "\xE2\x80\xBA" }, "Seek" }, + { { -1, -1 }, { "T", NULL }, "Tracks" }, + { { -1, -1 }, { "[", "]" }, "Prev/Next" }, + }; + const OsdHint* hints = s_hintPad ? kPad : kKeys; + int n = s_hintPad ? 3 : 4; + if (MediaUI_PlaylistActive()) n++; + + ui_overlay_set_device(s_hintPad ? 1 : 0); + ui_overlay_set_pad_style(Pads_Style()); + ui_overlay_set_pad_swap(g_padSwapConfirm); + ui_overlay_layer(0); + unsigned int a = (unsigned int)(alpha * 255.0f) & 0xFF; + unsigned int glyph = 0xFFFFFF00 | a; + unsigned int text = 0xD9FFD900 | (unsigned int)(alpha * 230.0f); + const float size = 15.0f, gap = 14.0f; + float total = 0.0f; + for (int i = 0; i < n; i++) total += DrawHint(hints[i], size, 0, 0, glyph, text, true) + (i ? gap : 0.0f); + float x = right - total; + for (int i = 0; i < n; i++) x += DrawHint(hints[i], size, x, y, glyph, text, false) + gap; +} + // Pack RGBA float -> ImU32 with alpha multiplier. static ImU32 RGBA(float r, float g, float b, float a) { @@ -214,6 +365,7 @@ void MediaUI_RenderOSD() // Auto-end: when libmpv reports stopped/idle (track finished), advance the // playlist queue if active, otherwise bail back to dashboard. + ReportFrame(); MediaPlayerState st = MediaPlayer_GetState(); if (st == MP_IDLE || st == MP_STOPPED) { if (MediaUI_PlaylistActive() && s_queueIdx + 1 < (int)s_queue.size()) { @@ -308,25 +460,18 @@ void MediaUI_RenderOSD() FormatTime(dur, tDur, sizeof(tDur)); ImU32 textCol = RGBA(0.85f, 1.00f, 0.85f, alpha); - ImU32 hintCol = RGBA(0.55f, 0.90f, 0.55f, alpha * 0.7f); ImFont* font = ImGui::GetFont(); float timeSize = 16.0f; - float hintSize = 12.0f; // Time on left char timeStr[64]; snprintf(timeStr, sizeof(timeStr), "%s / %s", tPos, tDur); dl->AddText(font, timeSize, ImVec2(28, y0 + 28), textCol, timeStr); - // Hint on right - const char* hint = MediaUI_PlaylistActive() - ? "ESC Stop SPACE Pause <-/-> Seek T Tracks [/] Prev/Next" - : "ESC Stop SPACE Pause <-/-> Seek T Tracks"; - ImVec2 hintSz = ImGui::CalcTextSize(hint); - // CalcTextSize uses default font size; estimate hint width by length. - float estHintW = (float)strlen(hint) * 6.5f; - dl->AddText(font, hintSize, ImVec2((float)ww - estHintW - 28.0f, y0 + 30), hintCol, hint); + // Hints on the right, in layout units: the window is 480 tall there. + float toLayout = 480.0f / (float)(wh > 0 ? wh : 1); + DrawHints(alpha, ui_overlay_layout_right() - 28.0f * toLayout, (y0 + 24.0f) * toLayout); // Progress bar, Xbox green track on dim bg. float barX = 28.0f; @@ -406,6 +551,7 @@ void MediaUI_RenderOSD() void MediaUI_StopFullscreen() { if (!g_mediaFullscreen) return; + EndReport(); MediaPlayer_Stop(); g_mediaFullscreen = false; s_queue.clear(); @@ -434,4 +580,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/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/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 new file mode 100644 index 0000000..69676e1 --- /dev/null +++ b/theseus/desktop/pads.cpp @@ -0,0 +1,313 @@ +// pads.cpp: every controller SDL sees, opened as it connects and closed as +// 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 +#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 +}; + +bool g_padRumble = true; +int g_padStyle = 0; +bool g_padSwapConfirm = false; + +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; +} + +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; +} + +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(); + 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; + 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 +// 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..d34d877 --- /dev/null +++ b/theseus/desktop/pads.h @@ -0,0 +1,33 @@ +// 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(); +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. 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 +// 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/plex_client.cpp b/theseus/desktop/plex_client.cpp index 67f23dc..8dbb7ba 100644 --- a/theseus/desktop/plex_client.cpp +++ b/theseus/desktop/plex_client.cpp @@ -6,6 +6,8 @@ #include "http_util.h" #include "json_util.h" #include "client_util.h" +#include "log_redact.h" +#include "media_player.h" #include #include @@ -15,6 +17,7 @@ #include #include #include +#include extern char g_plexToken[256]; extern char g_plexClientId[64]; @@ -73,6 +76,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}; @@ -87,6 +91,15 @@ 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; +// Seasons, episodes and children whose last fetch failed. Asking again +// doesn't refetch until the scene drills in again. +static std::map s_fetchFailed; +// The last search, its results under the "uix-search" library. +static std::string s_searchTerm; +static std::atomic s_searchState{0}; +static std::atomic s_searchSeq{0}; // ============================================================================ @@ -108,8 +121,11 @@ void Plex_Init() g_plexToken[0] ? "yes" : "no", g_plexClientId); } +static SerialWorker s_reports; + void Plex_Shutdown() { + s_reports.Stop(); s_pinCancel = true; JoinIf(s_pinThread); JoinIf(s_serversThread); @@ -131,6 +147,10 @@ void Plex_SignOut() s_cacheItems.clear(); s_cacheSeasons.clear(); s_cacheEpisodes.clear(); + s_cacheChildren.clear(); + s_fetchFailed.clear(); + s_searchTerm.clear(); + s_searchState = PLEX_SEARCH_NONE; s_syncGen++; s_syncReady = false; s_syncProgress = 0; @@ -155,7 +175,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; } @@ -324,31 +344,123 @@ 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"); + 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.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; +} + +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); + 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) +{ + 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_fetchFailed.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. // ============================================================================ +static std::vector ParseSeasons(const std::string& body, const std::string& serverUri) +{ + std::vector seasons; + size_t arr = Json_FindArray(body, "Metadata"); + if (arr == std::string::npos) return seasons; + for (const auto& obj : Json_SplitArray(body, arr)) { + // Skip Plex's synthetic "All episodes" pseudo-season (idx 0). + int idx = Json_GetInt(obj, "index"); + if (idx <= 0) continue; + PlexSeason s; + s.ratingKey = Json_GetString(obj, "ratingKey"); + s.title = Json_GetString(obj, "title"); + 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); + } + return seasons; +} + static void SeasonsWorker(std::string serverUri, std::string showRk) { std::string url = serverUri + "/library/metadata/" + showRk + "/children"; HttpResponse r = Http_Get(url, PlexHeaders(true, true)); std::vector seasons; if (r.ok()) { - size_t arr = Json_FindArray(r.body, "Metadata"); - if (arr != std::string::npos) { - for (const auto& obj : Json_SplitArray(r.body, arr)) { - // Skip Plex's synthetic "All episodes" pseudo-season (idx 0). - int idx = Json_GetInt(obj, "index"); - if (idx <= 0) continue; - PlexSeason s; - s.ratingKey = Json_GetString(obj, "ratingKey"); - s.title = Json_GetString(obj, "title"); - char ibuf[8]; snprintf(ibuf, sizeof(ibuf), "%d", idx); - s.index = ibuf; - s.thumbUrl = BuildAssetUrl(serverUri, Json_GetString(obj, "thumb")); - if (!s.ratingKey.empty()) seasons.push_back(s); - } - } + seasons = ParseSeasons(r.body, serverUri); } else { fprintf(stderr, "[Plex] seasons fetch failed (status %ld)\n", r.status); } @@ -356,7 +468,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; @@ -389,6 +502,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); } } @@ -399,7 +513,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; @@ -477,6 +592,23 @@ static void FinishSync(unsigned gen, const char* phase) s_syncRunning = false; } +static PlexLibrary OnDeckShelf() +{ + PlexLibrary shelf; + shelf.sectionKey = "uix-ondeck"; + shelf.title = "On Deck"; + shelf.type = "ondeck"; + return shelf; +} + +static bool FetchOnDeck(const std::string& serverUri, std::vector& out) +{ + HttpResponse r = Http_Get(serverUri + "/library/onDeck", PlexHeaders(true, true)); + if (!r.ok()) return false; + out = ParseItems(r.body, serverUri); + return true; +} + static void SyncWorker() { const unsigned gen = s_syncGen; @@ -557,29 +689,25 @@ 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); } + // On Deck (what you're partway through and the next episodes) goes above + // the libraries when there's anything on it. + std::vector deck; + if (FetchOnDeck(serverUri, deck) && !deck.empty() && !libs.empty()) { + libs.insert(libs.begin(), OnDeckShelf()); + itemsByKey[OnDeckShelf().sectionKey] = std::move(deck); + } + if (!libs.empty()) { + PlexLibrary search; + search.sectionKey = "uix-search"; + search.title = "Search"; + search.type = "search"; + libs.push_back(search); + } + // Publish atomically. Readers see old snapshot or whole new one. size_t nLibs = libs.size(); { @@ -606,6 +734,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() { @@ -637,6 +777,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. @@ -655,6 +796,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); @@ -662,6 +804,208 @@ bool Plex_Cache_GetEpisodes(const std::string& seasonRatingKey, } +// ============================================================================ +// Playback reports + watch state refresh +// ============================================================================ + +static std::atomic s_watchStamp{0}; + +unsigned Plex_WatchStamp() { return s_watchStamp; } + +template +static void PatchList(std::vector& list, const std::string& rk, const PlexDetails& d) +{ + for (auto& e : list) + if (e.ratingKey == rk) static_cast(e) = d; +} + +static void PatchDetails(const std::string& rk, const PlexDetails& d) +{ + for (auto& kv : s_cacheItems) PatchList(kv.second, rk, d); + for (auto& kv : s_cacheChildren) PatchList(kv.second, rk, d); + for (auto& kv : s_cacheSeasons) PatchList(kv.second, rk, d); + for (auto& kv : s_cacheEpisodes) PatchList(kv.second, rk, d); +} + +// The item's watch state, and the show it belongs to (itself for a show). +static bool FetchDetails(const std::string& uri, const std::string& rk, PlexDetails& d, + std::string* showRk = NULL, std::string* type = NULL) +{ + HttpResponse r = Http_Get(uri + "/library/metadata/" + rk, PlexHeaders(true, true)); + if (!r.ok()) return false; + size_t arr = Json_FindArray(r.body, "Metadata"); + if (arr == std::string::npos) return false; + std::vector objs = Json_SplitArray(r.body, arr); + if (objs.empty()) return false; + ParseDetails(objs[0], d); + std::string t = Json_GetString(objs[0], "type"); + if (type) *type = t; + if (showRk) *showRk = t == "show" ? rk + : t == "season" ? Json_GetString(objs[0], "parentRatingKey") + : Json_GetString(objs[0], "grandparentRatingKey"); + return true; +} + +// After playback or a mark: the item, its show and seasons, and On Deck. +static void RefreshWatchState(unsigned gen, const std::string& uri, const std::string& rk) +{ + PlexDetails d, show; + std::string showRk, type; + bool haveItem = FetchDetails(uri, rk, d, &showRk, &type); + bool haveShow = false, haveSeasons = false; + std::vector seasons; + if (!showRk.empty()) { + haveShow = showRk == rk ? false : FetchDetails(uri, showRk, show); + HttpResponse r = Http_Get(uri + "/library/metadata/" + showRk + "/children", PlexHeaders(true, true)); + if (r.ok()) { seasons = ParseSeasons(r.body, uri); haveSeasons = true; } + } + std::vector deck; + bool haveDeck = FetchOnDeck(uri, deck); + + std::lock_guard lk(g_mtx); + if (gen != s_syncGen) return; + if (haveItem) PatchDetails(rk, d); + if (haveShow) PatchDetails(showRk, show); + // A whole show or season was marked: its episodes load fresh next time. + if (type == "show" || type == "season") { + auto cached = s_cacheSeasons.find(showRk); + if (cached != s_cacheSeasons.end()) + for (const auto& se : cached->second) s_cacheEpisodes.erase(se.ratingKey); + s_cacheEpisodes.erase(rk); + } + if (haveSeasons && s_cacheSeasons.count(showRk)) s_cacheSeasons[showRk] = std::move(seasons); + if (haveDeck && !s_cacheLibs.empty()) { + const std::string key = OnDeckShelf().sectionKey; + s_cacheLibs.erase(std::remove_if(s_cacheLibs.begin(), s_cacheLibs.end(), + [&](const PlexLibrary& l) { return l.sectionKey == key; }), s_cacheLibs.end()); + s_cacheItems.erase(key); + if (!deck.empty()) { + s_cacheLibs.insert(s_cacheLibs.begin(), OnDeckShelf()); + s_cacheItems[key] = std::move(deck); + } + } + s_watchStamp++; +} + +static void GetReport(const std::string& url) +{ + HttpResponse r = Http_Get(url, PlexHeaders(true, true)); + if (!r.ok()) { + std::string path = url.substr(0, url.find('?')); + size_t at = path.find("/:/"); + fprintf(stderr, "[Plex] %s failed (status %ld)\n", + at == std::string::npos ? "report" : path.c_str() + at, r.status); + } +} + +void Plex_ReportPlayback(const std::string& ratingKey, int event, int timeMs, int durationMs, bool paused) +{ + std::string uri = Plex_GetActiveServerUri(); + if (ratingKey.empty() || uri.empty() || !Plex_HasToken()) return; + if (timeMs < 0) timeMs = 0; + const char* state = event == MEDIA_REPORT_STOP ? "stopped" : paused ? "paused" : "playing"; + char q[256]; + snprintf(q, sizeof(q), + "/:/timeline?ratingKey=%s&key=%%2Flibrary%%2Fmetadata%%2F%s&state=%s&time=%d&duration=%d", + ratingKey.c_str(), ratingKey.c_str(), state, timeMs, durationMs); + std::string url = uri + q; + if (event != MEDIA_REPORT_STOP) { + s_reports.Post([url] { GetReport(url); }); + return; + } + bool finished = durationMs > 0 && timeMs >= durationMs * 0.9; + std::string scrobble = uri + "/:/scrobble?identifier=com.plexapp.plugins.library&key=" + ratingKey; + unsigned gen = s_syncGen; + s_reports.Post([=] { + GetReport(url); + if (finished) GetReport(scrobble); + RefreshWatchState(gen, uri, ratingKey); + }); +} + + +void Plex_SetPlayed(const std::string& ratingKey, bool played) +{ + std::string uri = Plex_GetActiveServerUri(); + if (ratingKey.empty() || uri.empty() || !Plex_HasToken()) return; + { + // Show it right away; the refresh after the request has the final word. + std::lock_guard lk(g_mtx); + auto mark = [&](PlexDetails& e) { + e.viewCount = played ? (e.viewCount > 0 ? e.viewCount : 1) : 0; + e.viewedLeafCount = played ? e.leafCount : 0; + e.offsetMs = 0; + }; + for (auto* m : { &s_cacheItems, &s_cacheChildren }) + for (auto& kv : *m) for (auto& e : kv.second) if (e.ratingKey == ratingKey) mark(e); + for (auto& kv : s_cacheSeasons) for (auto& e : kv.second) if (e.ratingKey == ratingKey) mark(e); + for (auto& kv : s_cacheEpisodes) for (auto& e : kv.second) if (e.ratingKey == ratingKey) mark(e); + s_watchStamp++; + } + std::string url = uri + (played ? "/:/scrobble" : "/:/unscrobble") + + "?identifier=com.plexapp.plugins.library&key=" + ratingKey; + unsigned gen = s_syncGen; + s_reports.Post([=] { + GetReport(url); + RefreshWatchState(gen, uri, ratingKey); + }); +} + + +// ============================================================================ +// Search: /hubs/search answers with one hub per kind of thing. +// ============================================================================ + +static void SearchWorker(unsigned gen, unsigned seq, std::string uri, std::string term) +{ + HttpResponse r = Http_Get(uri + "/hubs/search?limit=20&query=" + Http_UrlEncode(term), + PlexHeaders(true, true)); + std::vector found; + if (r.ok()) { + size_t hubs = Json_FindArray(r.body, "Hub"); + if (hubs != std::string::npos) { + for (const auto& hub : Json_SplitArray(r.body, hubs)) { + for (auto& it : ParseItems(hub, uri)) { + const std::string& t = it.type; + if (t == "movie" || t == "show" || t == "episode" || t == "artist" || + t == "album" || t == "track" || t == "collection") + found.push_back(std::move(it)); + } + } + } + } else { + fprintf(stderr, "[Plex] search failed (status %ld)\n", r.status); + } + std::lock_guard lk(g_mtx); + if (gen != s_syncGen || seq != s_searchSeq) return; + s_cacheItems["uix-search"] = std::move(found); + s_searchState = r.ok() ? PLEX_SEARCH_DONE : PLEX_SEARCH_FAILED; +} + +void Plex_Search(const std::string& term) +{ + std::string uri = Plex_GetActiveServerUri(); + if (term.empty() || uri.empty() || !Plex_HasToken()) return; + unsigned seq; + { + std::lock_guard lk(g_mtx); + s_searchTerm = term; + s_cacheItems.erase("uix-search"); + s_searchState = PLEX_SEARCH_BUSY; + seq = ++s_searchSeq; + } + std::thread(SearchWorker, (unsigned)s_syncGen, seq, uri, term).detach(); +} + +std::string Plex_SearchTerm() +{ + std::lock_guard lk(g_mtx); + return s_searchTerm; +} + +int Plex_SearchState() { return s_searchState; } + + // ============================================================================ // Art cache // ============================================================================ @@ -690,6 +1034,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; } } { @@ -703,13 +1049,27 @@ 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; { 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..1be60a4 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 @@ -25,16 +41,19 @@ struct PlexItem { 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 { +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 @@ -77,6 +96,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 @@ -86,9 +109,33 @@ 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. 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); + +// Playback reports (MEDIA_REPORT_* from media_player.h) through /:/timeline, +// with a scrobble once it's played past 90%. Sent in order, off the main +// thread; a stop also reloads the item and the On Deck shelf. +void Plex_ReportPlayback(const std::string& ratingKey, int event, + int timeMs, int durationMs, bool paused); +// Bumped whenever watch state in the cache changes, so the scene redraws. +unsigned Plex_WatchStamp(); +// Scrobbles or unscrobbles it on the server; the cache shows it straight away. +void Plex_SetPlayed(const std::string& ratingKey, bool played); + +// Search across the server, in the background. Results show up as the items +// of the "uix-search" library at the end of the list. +enum { PLEX_SEARCH_NONE, PLEX_SEARCH_BUSY, PLEX_SEARCH_DONE, PLEX_SEARCH_FAILED }; +void Plex_Search(const std::string& term); +std::string Plex_SearchTerm(); +int Plex_SearchState(); diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index 98959a4..d03cab5 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" @@ -444,6 +444,7 @@ extern bool g_xcloudClosed; void RenderXcloudOverlay(); void MediaPlayer_Update(); void MediaUI_NoteActivity(); +void MediaUI_NoteKey(); bool MediaUI_OsdVisible(); static void PreSwapOverlays() { @@ -980,6 +981,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()); @@ -1405,6 +1410,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: @@ -1507,7 +1513,7 @@ int main(int argc, char* argv[]) { break; } } - if (g_mediaFullscreen) MediaUI_NoteActivity(); + if (g_mediaFullscreen) MediaUI_NoteKey(); // Esc / Q / Backspace exits fullscreen video, before any // other key handling (so it works even when keyboard is // captured by an XAP keyboard widget). @@ -1627,6 +1633,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 +1689,12 @@ 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_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 (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{}; @@ -1729,6 +1731,8 @@ int main(int argc, char* argv[]) { } Guide_Frame(); + extern void MediaUI_PadFrame(); + MediaUI_PadFrame(); if (!g_mediaFullscreen && !g_xcloudFullscreen) { FramePhaseScope advance(FP_ADVANCE); @@ -1798,9 +1802,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 (CJoystick::c_controller) { - padXY = SDL_GameControllerGetButton(CJoystick::c_controller, SDL_CONTROLLER_BUTTON_X) - && SDL_GameControllerGetButton(CJoystick::c_controller, 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; @@ -1881,6 +1886,7 @@ int main(int argc, char* argv[]) { // Cleanup XapEditor_Cleanup(); Guide_Shutdown(); + Pads_Shutdown(); { extern void ImGui_ImplBgfx_Shutdown(); ImGui_ImplBgfx_Shutdown(); diff --git a/theseus/desktop/settings_backup.h b/theseus/desktop/settings_backup.h new file mode 100644 index 0000000..138ee47 --- /dev/null +++ b/theseus/desktop/settings_backup.h @@ -0,0 +1,180 @@ +// settings_backup.h: copies of your settings and library in Backups/ under +// the user data folder, and putting one back. Plain folders, no archive. +// Everything it reads or writes sits under the root it's handed. +#pragma once + +#include +#include +#include +#include +#include +#include +#include "host.h" + +// What a backup holds, relative to the user data folder. +static const char* const kBackupFiles[] = { + "Configs/games.ini", "Configs/games_live.ini", "Configs/desktop.ini", "Configs/Icons.ini", + "Configs/playlists.ini", +}; +static const char* const kBackupFolders[] = { "Configs/icons" }; + +#define BACKUP_DIR "Backups" + +static bool Backup_Exists(const std::string& path, bool* isDir = NULL) +{ + HostFileInfo info; + if (!Host_Stat(path.c_str(), &info)) return false; + if (isDir) *isDir = (info.attrs & HOST_ATTR_DIR) != 0; + return true; +} + +// Makes every folder down to path. Only ever called below the root. +static bool Backup_MakeDirs(const std::string& root, const std::string& rel) +{ + std::string at = root; + size_t from = 0; + while (from <= rel.size()) { + size_t slash = rel.find('/', from); + std::string part = rel.substr(from, slash == std::string::npos ? std::string::npos : slash - from); + if (!part.empty()) { + at += "/" + part; + if (!Host_MakeDir(at.c_str())) return false; + } + if (slash == std::string::npos) break; + from = slash + 1; + } + return true; +} + +// A name from the list, never a path that climbs out. +static bool Backup_NameOk(const std::string& name) +{ + return !name.empty() && name[0] != '.' && name.find_first_of("/\\:") == std::string::npos && + name.find("..") == std::string::npos; +} + +// Swaps one file in the way SafeSave does: a copy next to it, flushed, then +// one rename. A settings file it replaces stays as .old. +static bool Backup_Replace(const std::string& from, const std::string& to, bool keepOld) +{ + std::string tmp = to + ".new"; + if (!Host_CopyFile(from.c_str(), tmp.c_str(), false) || !Host_FlushToDisk(tmp.c_str())) { + Host_RemoveFile(tmp.c_str()); + return false; + } + if (keepOld && Backup_Exists(to)) Host_CopyFile(to.c_str(), (to + ".old").c_str(), false); + if (!Host_RenameReplace(tmp.c_str(), to.c_str())) { Host_RemoveFile(tmp.c_str()); return false; } + return true; +} + +static bool Backup_EndsWith(const std::string& s, const char* end) +{ + size_t n = strlen(end); + return s.size() >= n && s.compare(s.size() - n, n, end) == 0; +} + +// Every file in a folder and the ones below it, relative to it. A swap's +// leftovers aren't worth keeping. +static void Backup_ListFiles(const std::string& dir, const std::string& rel, std::vector& out) +{ + HostDir* d = Host_OpenDir(dir.c_str()); + if (!d) return; + char name[512]; + bool isDir = false; + std::vector subs; + while (Host_ReadDirType(d, name, sizeof(name), &isDir)) { + std::string n = name; + if (n == "." || n == ".." || Backup_EndsWith(n, ".old") || Backup_EndsWith(n, ".new")) continue; + if (isDir) subs.push_back(n); + else out.push_back(rel.empty() ? n : rel + "/" + n); + } + Host_CloseDir(d); + for (size_t i = 0; i < subs.size(); i++) + Backup_ListFiles(dir + "/" + subs[i], rel.empty() ? subs[i] : rel + "/" + subs[i], out); +} + +// Copies what there is into Backups/. Gives back the +// folder's name, or empty when nothing could be written. +static std::string Backup_Make(const std::string& root, const char* suffix, int* outFiles) +{ + if (outFiles) *outFiles = 0; + char stamp[64]; + time_t now = time(NULL); + strftime(stamp, sizeof(stamp), "%Y-%m-%d %H.%M.%S", localtime(&now)); + std::string name = std::string(stamp) + (suffix ? suffix : ""); + // Two in the same second get a number. + for (int n = 2; Backup_Exists(root + "/" BACKUP_DIR "/" + name); n++) { + char num[16]; + snprintf(num, sizeof(num), " %d", n); + name = std::string(stamp) + (suffix ? suffix : "") + num; + } + std::string rel = std::string(BACKUP_DIR "/") + name; + if (!Backup_MakeDirs(root, rel + "/Configs")) return ""; + std::string dest = root + "/" + rel; + int files = 0; + bool ok = true; + for (size_t i = 0; i < sizeof(kBackupFiles) / sizeof(kBackupFiles[0]); i++) { + std::string src = root + "/" + kBackupFiles[i]; + if (!Backup_Exists(src)) continue; + if (Host_CopyFile(src.c_str(), (dest + "/" + kBackupFiles[i]).c_str(), false)) files++; + else ok = false; + } + for (size_t i = 0; i < sizeof(kBackupFolders) / sizeof(kBackupFolders[0]); i++) { + std::string src = root + "/" + kBackupFolders[i]; + std::vector list; + Backup_ListFiles(src, "", list); + for (size_t k = 0; k < list.size(); k++) { + std::string to = std::string(kBackupFolders[i]) + "/" + list[k]; + size_t cut = to.find_last_of('/'); + if (!Backup_MakeDirs(dest, to.substr(0, cut)) || + !Host_CopyFile((src + "/" + list[k]).c_str(), (dest + "/" + to).c_str(), false)) { ok = false; continue; } + files++; + } + } + if (outFiles) *outFiles = files; + return ok ? name : ""; +} + +// Backup names, newest first. The names sort by date already. +static void Backup_List(const std::string& root, std::vector& out) +{ + out.clear(); + HostDir* d = Host_OpenDir((root + "/" BACKUP_DIR).c_str()); + if (!d) return; + char name[512]; + bool isDir = false; + while (Host_ReadDirType(d, name, sizeof(name), &isDir)) + if (isDir && Backup_NameOk(name)) out.push_back(name); + Host_CloseDir(d); + std::sort(out.begin(), out.end(), [](const std::string& a, const std::string& b) { return a > b; }); +} + +// Puts a backup back. Whatever's there now is backed up first, so a restore +// can always be undone. A settings file the backup didn't have is removed, +// icons only ever get added or replaced. +static bool Backup_Restore(const std::string& root, const std::string& name, std::string* outSaved) +{ + if (!Backup_NameOk(name)) return false; + std::string src = root + "/" BACKUP_DIR "/" + name; + bool isDir = false; + if (!Backup_Exists(src + "/Configs", &isDir) || !isDir) return false; + std::string saved = Backup_Make(root, " before restore", NULL); + if (saved.empty()) return false; + if (outSaved) *outSaved = saved; + bool ok = true; + for (size_t i = 0; i < sizeof(kBackupFiles) / sizeof(kBackupFiles[0]); i++) { + std::string from = src + "/" + kBackupFiles[i], to = root + "/" + kBackupFiles[i]; + if (Backup_Exists(from)) ok = Backup_Replace(from, to, true) && ok; + else if (Backup_Exists(to)) ok = Host_RemoveFile(to.c_str()) && ok; + } + for (size_t i = 0; i < sizeof(kBackupFolders) / sizeof(kBackupFolders[0]); i++) { + std::vector list; + Backup_ListFiles(src + "/" + kBackupFolders[i], "", list); + for (size_t k = 0; k < list.size(); k++) { + std::string rel = std::string(kBackupFolders[i]) + "/" + list[k]; + if (!Backup_MakeDirs(root, rel.substr(0, rel.find_last_of('/')))) { ok = false; continue; } + ok = Backup_Replace(src + "/" + rel, root + "/" + rel, false) && ok; + } + } + return ok; +} diff --git a/theseus/desktop/sqlite_read.cpp b/theseus/desktop/sqlite_read.cpp new file mode 100644 index 0000000..e124050 --- /dev/null +++ b/theseus/desktop/sqlite_read.cpp @@ -0,0 +1,361 @@ +// sqlite_read.cpp: walks an SQLite table's b-tree straight off the file. +// Follows the published file format: 100 byte header, table b-tree pages, +// overflow chains, records of varint serial types. Anything that doesn't +// look right ends the read instead of guessing. + +#include "sqlite_read.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +uint32_t Be16(const uint8_t* p) { return (uint32_t)p[0] << 8 | p[1]; } +uint32_t Be32(const uint8_t* p) { return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; } + +// Bytes used, 0 when it runs off the end. +int Varint(const uint8_t* p, const uint8_t* end, uint64_t* out) +{ + uint64_t v = 0; + for (int i = 0; i < 9; i++) { + if (p + i >= end) return 0; + if (i == 8) { *out = (v << 8) | p[i]; return 9; } + v = (v << 7) | (p[i] & 0x7f); + if (!(p[i] & 0x80)) { *out = v; return i + 1; } + } + return 0; +} + +struct Db { + FILE* f = NULL; + uint32_t pageSize = 0, usable = 0; + std::map > wal; // committed pages from the -wal file + int pagesRead = 0; + + ~Db() { if (f) fclose(f); } + + bool Page(uint32_t n, std::vector& out) + { + // A loop in a corrupt file shouldn't spin forever. + if (n == 0 || ++pagesRead > 2000000) return false; + std::map >::iterator w = wal.find(n); + if (w != wal.end()) { out = w->second; return true; } + out.resize(pageSize); + if (fseek(f, (long)(n - 1) * (long)pageSize, SEEK_SET) != 0) return false; + return fread(&out[0], 1, pageSize, f) == pageSize; + } +}; + +// The WAL checksum: pairs of 32 bit words, big or little endian as the magic says. +void WalSum(const uint8_t* p, size_t n, bool big, uint32_t* s0, uint32_t* s1) +{ + for (size_t i = 0; i + 8 <= n; i += 8) { + uint32_t a = big ? Be32(p + i) : (uint32_t)p[i] | p[i + 1] << 8 | p[i + 2] << 16 | (uint32_t)p[i + 3] << 24; + uint32_t b = big ? Be32(p + i + 4) : (uint32_t)p[i + 4] | p[i + 5] << 8 | p[i + 6] << 16 | (uint32_t)p[i + 7] << 24; + *s0 += a + *s1; + *s1 += b + *s0; + } +} + +void LoadWal(Db& db, const std::string& path) +{ + FILE* f = fopen(path.c_str(), "rb"); + if (!f) return; + uint8_t hdr[32]; + if (fread(hdr, 1, 32, f) != 32) { fclose(f); return; } + uint32_t magic = Be32(hdr); + bool big = magic == 0x377f0683; + if ((magic & 0xfffffffe) != 0x377f0682 || Be32(hdr + 8) != db.pageSize) { fclose(f); return; } + uint32_t s0 = 0, s1 = 0; + WalSum(hdr, 24, big, &s0, &s1); + if (s0 != Be32(hdr + 24) || s1 != Be32(hdr + 28)) { fclose(f); return; } + + std::map > pending; + std::vector frame(24 + db.pageSize); + while (fread(&frame[0], 1, frame.size(), f) == frame.size()) { + // A frame from an older generation, or a torn write, ends the log. + if (memcmp(&frame[8], hdr + 16, 8) != 0) break; + WalSum(&frame[0], 8, big, &s0, &s1); + WalSum(&frame[24], db.pageSize, big, &s0, &s1); + if (s0 != Be32(&frame[16]) || s1 != Be32(&frame[20])) break; + pending[Be32(&frame[0])].assign(frame.begin() + 24, frame.end()); + if (Be32(&frame[4]) != 0) { // a commit + for (std::map >::iterator it = pending.begin(); it != pending.end(); ++it) + db.wal[it->first].swap(it->second); + pending.clear(); + } + } + fclose(f); +} + +// The cell's whole payload, overflow pages and all. +bool Payload(Db& db, const uint8_t* p, const uint8_t* end, uint64_t size, std::vector& out) +{ + if (size > (16u << 20)) return false; + uint64_t U = db.usable, X = U - 35, M = ((U - 12) * 32 / 255) - 23; + uint64_t local = size; + if (size > X) { + uint64_t K = M + ((size - M) % (U - 4)); + local = K <= X ? K : M; + } + if (p + local > end) return false; + out.assign(p, p + local); + if (local == size) return true; + if (p + local + 4 > end) return false; + uint32_t next = Be32(p + local); + std::vector page; + while (out.size() < size) { + if (!db.Page(next, page)) return false; + size_t take = (size_t)(size - out.size()); + if (take > U - 4) take = (size_t)(U - 4); + out.insert(out.end(), page.begin() + 4, page.begin() + 4 + take); + next = Be32(&page[0]); + } + return true; +} + +struct Cell { int64_t rowid; std::vector payload; }; + +bool Walk(Db& db, uint32_t pageNo, int depth, std::vector& out) +{ + if (depth > 32) return false; + std::vector page; + if (!db.Page(pageNo, page)) return false; + size_t hdr = pageNo == 1 ? 100 : 0; + const uint8_t* base = &page[0]; + const uint8_t* end = base + db.usable; + uint8_t type = base[hdr]; + uint32_t cells = Be16(base + hdr + 3); + if (hdr + 12 + cells * 2 > db.usable) return false; + if (type == 0x0d) { + for (uint32_t i = 0; i < cells; i++) { + size_t at = Be16(base + hdr + 8 + i * 2); + if (at >= db.usable) return false; + const uint8_t* p = base + at; + uint64_t size, rowid; + int n = Varint(p, end, &size); + if (!n) return false; + p += n; + n = Varint(p, end, &rowid); + if (!n) return false; + p += n; + Cell c; + c.rowid = (int64_t)rowid; + if (!Payload(db, p, end, size, c.payload)) return false; + out.push_back(c); + } + return true; + } + if (type != 0x05) return false; + for (uint32_t i = 0; i < cells; i++) { + size_t at = Be16(base + hdr + 12 + i * 2); + if (at + 4 > db.usable) return false; + if (!Walk(db, Be32(base + at), depth + 1, out)) return false; + } + return Walk(db, Be32(base + hdr + 8), depth + 1, out); +} + +// One record's values as text, NULLs empty. +bool Record(const std::vector& rec, std::vector& vals, std::vector& null) +{ + vals.clear(); + null.clear(); + if (rec.empty()) return false; + const uint8_t* p = &rec[0]; + const uint8_t* end = p + rec.size(); + uint64_t hsize; + int n = Varint(p, end, &hsize); + if (!n || hsize > rec.size()) return false; + const uint8_t* h = p + n; + const uint8_t* hend = p + hsize; + const uint8_t* body = hend; + while (h < hend) { + uint64_t t; + n = Varint(h, hend, &t); + if (!n) return false; + h += n; + std::string v; + size_t len = 0; + bool isNull = t == 0; + if (t >= 1 && t <= 6) { + static const size_t kLen[] = { 0, 1, 2, 3, 4, 6, 8 }; + len = kLen[t]; + if (body + len > end) return false; + int64_t x = (body[0] & 0x80) ? -1 : 0; + for (size_t i = 0; i < len; i++) x = (int64_t)((uint64_t)x << 8 | body[i]); + char buf[32]; + snprintf(buf, sizeof(buf), "%lld", (long long)x); + v = buf; + } else if (t == 7) { + len = 8; + if (body + len > end) return false; + uint64_t bits = 0; + for (int i = 0; i < 8; i++) bits = bits << 8 | body[i]; + double d; + memcpy(&d, &bits, 8); + char buf[64]; + snprintf(buf, sizeof(buf), "%.17g", d); + v = buf; + } else if (t == 8 || t == 9) { + v = t == 8 ? "0" : "1"; + } else if (t >= 12) { + len = (size_t)((t - 12) / 2); + if (body + len > end) return false; + v.assign((const char*)body, len); + } + body += len; + vals.push_back(v); + null.push_back(isNull); + } + return true; +} + +std::string Upper(const std::string& s) +{ + std::string o = s; + for (size_t i = 0; i < o.size(); i++) o[i] = (char)toupper((unsigned char)o[i]); + return o; +} + +std::string Unquote(const std::string& s) +{ + if (s.size() >= 2 && (s[0] == '"' || s[0] == '`' || s[0] == '[' || s[0] == '\'')) + return s.substr(1, s.size() - 2); + return s; +} + +// Column names from CREATE TABLE, and which one is the rowid in disguise. +bool Columns(const std::string& sql, std::vector& cols, int* rowidCol) +{ + cols.clear(); + *rowidCol = -1; + std::string up = Upper(sql); + if (up.find("WITHOUT ROWID") != std::string::npos) return false; + size_t open = sql.find('('), close = sql.rfind(')'); + if (open == std::string::npos || close == std::string::npos || close < open) return false; + std::vector defs; + std::string cur; + int depth = 0; + char quote = 0; + for (size_t i = open + 1; i < close; i++) { + char c = sql[i]; + if (quote) { if (c == quote) quote = 0; cur += c; continue; } + if (c == '"' || c == '`' || c == '\'') quote = c; + else if (c == '[') quote = ']'; + else if (c == '(') depth++; + else if (c == ')') depth--; + else if (c == ',' && depth == 0) { defs.push_back(cur); cur.clear(); continue; } + cur += c; + } + defs.push_back(cur); + + std::vector types; + std::string pkCol; + for (size_t d = 0; d < defs.size(); d++) { + std::string def = defs[d]; + size_t s = def.find_first_not_of(" \t\r\n"); + if (s == std::string::npos) continue; + def = def.substr(s); + std::string upDef = Upper(def); + bool constraint = false; + static const char* kTableBits[] = { "CONSTRAINT", "PRIMARY", "UNIQUE", "CHECK", "FOREIGN" }; + for (size_t k = 0; k < 5; k++) + if (upDef.compare(0, strlen(kTableBits[k]), kTableBits[k]) == 0 && + (upDef.size() == strlen(kTableBits[k]) || !isalnum((unsigned char)upDef[strlen(kTableBits[k])]))) + constraint = true; + if (constraint) { + // PRIMARY KEY ("id") on one INTEGER column makes it the rowid too. + size_t pk = upDef.find("PRIMARY KEY"); + size_t a = def.find('(', pk == std::string::npos ? 0 : pk), b = def.find(')', a); + if (pk != std::string::npos && a != std::string::npos && b != std::string::npos) { + std::string inner = def.substr(a + 1, b - a - 1); + if (inner.find(',') == std::string::npos) { + size_t f = inner.find_first_not_of(" \t"), l = inner.find_last_not_of(" \t"); + if (f != std::string::npos) pkCol = Unquote(inner.substr(f, l - f + 1)); + } + } + continue; + } + std::string name; + size_t rest; + if (def[0] == '"' || def[0] == '`' || def[0] == '[') { + char q = def[0] == '[' ? ']' : def[0]; + size_t e = def.find(q, 1); + if (e == std::string::npos) return false; + name = def.substr(1, e - 1); + rest = e + 1; + } else { + size_t e = def.find_first_of(" \t\r\n"); + name = def.substr(0, e); + rest = e == std::string::npos ? def.size() : e; + } + std::string tail = Upper(def.substr(rest)); + size_t t = tail.find_first_not_of(" \t\r\n"); + std::string type = t == std::string::npos ? "" : tail.substr(t, tail.find_first_of(" \t\r\n(", t) - t); + if (type == "INTEGER" && tail.find("PRIMARY KEY") != std::string::npos) *rowidCol = (int)cols.size(); + cols.push_back(name); + types.push_back(type); + } + if (*rowidCol < 0 && !pkCol.empty()) + for (size_t i = 0; i < cols.size(); i++) + if (strcasecmp(cols[i].c_str(), pkCol.c_str()) == 0 && types[i] == "INTEGER") *rowidCol = (int)i; + return !cols.empty(); +} + +} // namespace + +bool Sqlite_ReadTable(const char* dbPath, const char* table, std::vector& rows) +{ + rows.clear(); + Db db; + db.f = fopen(dbPath, "rb"); + if (!db.f) return false; + uint8_t hdr[100]; + if (fread(hdr, 1, 100, db.f) != 100 || memcmp(hdr, "SQLite format 3", 16) != 0) return false; + db.pageSize = Be16(hdr + 16); + if (db.pageSize == 1) db.pageSize = 65536; + if (db.pageSize < 512 || (db.pageSize & (db.pageSize - 1))) return false; + if (hdr[20] >= db.pageSize - 480) return false; + db.usable = db.pageSize - hdr[20]; + if (Be32(hdr + 56) > 1) return false; // UTF-16 text, not something we'll meet + LoadWal(db, std::string(dbPath) + "-wal"); + + std::vector master; + if (!Walk(db, 1, 0, master)) return false; + uint32_t root = 0; + std::string sql; + std::vector vals; + std::vector null; + for (size_t i = 0; i < master.size(); i++) { + if (!Record(master[i].payload, vals, null) || vals.size() < 5) continue; + if (vals[0] != "table" || strcasecmp(vals[1].c_str(), table) != 0) continue; + root = (uint32_t)strtoul(vals[3].c_str(), NULL, 10); + sql = vals[4]; + break; + } + std::vector cols; + int rowidCol; + if (!root || !Columns(sql, cols, &rowidCol)) return false; + + std::vector cells; + if (!Walk(db, root, 0, cells)) return false; + for (size_t i = 0; i < cells.size(); i++) { + if (!Record(cells[i].payload, vals, null)) continue; + SqliteRow row; + for (size_t c = 0; c < cols.size(); c++) { + if ((int)c == rowidCol) { + char buf[32]; + snprintf(buf, sizeof(buf), "%lld", (long long)cells[i].rowid); + row[cols[c]] = buf; + } else { + row[cols[c]] = c < vals.size() ? vals[c] : ""; + } + } + rows.push_back(row); + } + return true; +} diff --git a/theseus/desktop/sqlite_read.h b/theseus/desktop/sqlite_read.h new file mode 100644 index 0000000..e2a853f --- /dev/null +++ b/theseus/desktop/sqlite_read.h @@ -0,0 +1,16 @@ +// sqlite_read.h: reads one table out of an SQLite database file, enough for +// the stores that keep their library in one (Lutris, itch.io). Read only, +// plain file reads, no SQLite library. Committed pages in a -wal file next +// to it count, so a store that's running still reads current. + +#pragma once + +#include +#include +#include + +typedef std::map SqliteRow; + +// Every row of table, column name to value as text. NULL and columns a row +// doesn't have come back empty. False when the file or table can't be read. +bool Sqlite_ReadTable(const char* dbPath, const char* table, std::vector& rows); 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(); + } +} diff --git a/theseus/desktop/title_maker.cpp b/theseus/desktop/title_maker.cpp index 722e940..3de0480 100644 --- a/theseus/desktop/title_maker.cpp +++ b/theseus/desktop/title_maker.cpp @@ -11,11 +11,13 @@ #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" #include "launchers/retroarch.h" #include "launchers/xemu.h" +#include "launchers/pcsx2.h" #include "imgui.h" #include "imfilebrowser.h" #include "stb_image.h" @@ -34,6 +36,8 @@ bool g_titleMakerOpen = false; +extern int Title_SanitizeName(const char*, char*, size_t); + // ============================================================================ // Helpers // ============================================================================ @@ -750,6 +754,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; @@ -762,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) { @@ -774,6 +781,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; @@ -861,42 +873,46 @@ 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"); } + // 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 @@ -1166,6 +1182,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 { @@ -1237,28 +1279,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 { @@ -1342,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; } @@ -1354,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(); diff --git a/theseus/desktop/tmdb.cpp b/theseus/desktop/tmdb.cpp index 78f398b..76319b7 100644 --- a/theseus/desktop/tmdb.cpp +++ b/theseus/desktop/tmdb.cpp @@ -118,24 +118,6 @@ static std::string HttpGet(const std::string& url) return out; } -// URL-encode a query string component (alpha/digit/-_. preserved, rest -// percent-encoded). Sufficient for TMDB query params. -static std::string UrlEncode(const char* s) -{ - static const char* hex = "0123456789ABCDEF"; - std::string out; - for (const char* p = s; *p; p++) { - unsigned char c = (unsigned char)*p; - if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { - out.push_back((char)c); - } else { - out.push_back('%'); - out.push_back(hex[c >> 4]); - out.push_back(hex[c & 0xF]); - } - } - return out; -} // First object in "results": [{...}, ...], or empty. @@ -211,7 +193,7 @@ static TmdbMovie DoMovieLookup(const std::string& title, int year, const std::st std::string url = "https://api.themoviedb.org/3/search/movie?api_key="; url += g_tmdbKey; url += "&query="; - url += UrlEncode(title.c_str()); + url += Http_UrlEncode(title); if (year > 0) { char y[16]; snprintf(y, sizeof(y), "&year=%d", year); @@ -241,7 +223,7 @@ static TmdbShow DoShowLookup(const std::string& title, const std::string& key) std::string url = "https://api.themoviedb.org/3/search/tv?api_key="; url += g_tmdbKey; url += "&query="; - url += UrlEncode(title.c_str()); + url += Http_UrlEncode(title); url += "&include_adult=false"; body = HttpGet(url); (void)key; diff --git a/theseus/desktop/ui_overlay.cpp b/theseus/desktop/ui_overlay.cpp index ce66e9e..eb2bebf 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, padSwap; float scale, originX, originY; // last present's layout -> pixels Vertex vertices[MAX_QUADS * 6]; @@ -315,12 +315,34 @@ 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; +} + +void ui_overlay_set_pad_swap(int swap) { ov.padSwap = swap != 0; } -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\x80\xB9", "\xE2\x80\xBA", +}; +// 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" }, }; +// 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][Position(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 +351,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 +382,72 @@ 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. + 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 = 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..8f83fac 100644 --- a/theseus/desktop/ui_overlay.h +++ b/theseus/desktop/ui_overlay.h @@ -44,6 +44,12 @@ 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); +// 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); diff --git a/theseus/desktop/virtual_games.h b/theseus/desktop/virtual_games.h index 642e9dd..8edc1a2 100644 --- a/theseus/desktop/virtual_games.h +++ b/theseus/desktop/virtual_games.h @@ -46,6 +46,13 @@ 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]; + // Collections it's in, split by ';'. Yours, like favorite. + char collections[256]; }; struct VirtualGameDB { @@ -127,6 +134,14 @@ 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); + else if (strcmp(key, "Collections") == 0) + strncpy(cur->collections, val, sizeof(cur->collections) - 1); } fclose(fp); g_vgames.generation++; @@ -196,6 +211,10 @@ 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); + if (g.collections[0]) fprintf(fp, "Collections=%s\n", g.collections); fprintf(fp, "\n"); } save.Commit(); @@ -393,7 +412,7 @@ inline int VGames_MakeShortcutContent(int idx, char* buf, int bufSize) { // Favorites, hidden and last played for live rows (ES-DE, xCloud), which // never reach games.ini. Keyed by title id, which both keep stable. -struct VGameMarks { bool favorite, hidden; long long lastPlayed, playTime; }; +struct VGameMarks { bool favorite, hidden; long long lastPlayed, playTime; std::string collections; }; #define VGAMES_LIVE_INI AppPath("Configs/games_live.ini") inline std::map& VGames_LiveMarks() { @@ -411,7 +430,7 @@ inline std::map& VGames_LiveMarks() { char* end = strrchr(line, ']'); if (!end) { cur = NULL; continue; } *end = 0; - VGameMarks blank = { false, false, 0, 0 }; + VGameMarks blank = { false, false, 0, 0, "" }; cur = &(s_marks[line + 1] = blank); continue; } @@ -422,6 +441,7 @@ inline std::map& VGames_LiveMarks() { else if (strcmp(line, "Hidden") == 0) cur->hidden = atoi(eq + 1) != 0; else if (strcmp(line, "LastPlayed") == 0) cur->lastPlayed = atoll(eq + 1); else if (strcmp(line, "PlayTime") == 0) cur->playTime = atoll(eq + 1); + else if (strcmp(line, "Collections") == 0) cur->collections = eq + 1; } fclose(fp); return s_marks; @@ -434,12 +454,13 @@ inline void VGames_SaveLiveMarks() { std::map& m = VGames_LiveMarks(); for (std::map::iterator it = m.begin(); it != m.end(); ++it) { const VGameMarks& k = it->second; - if (!k.favorite && !k.hidden && !k.lastPlayed && !k.playTime) continue; + if (!k.favorite && !k.hidden && !k.lastPlayed && !k.playTime && k.collections.empty()) continue; fprintf(save.f, "[%s]\n", it->first.c_str()); if (k.favorite) fprintf(save.f, "Favorite=1\n"); if (k.hidden) fprintf(save.f, "Hidden=1\n"); if (k.lastPlayed) fprintf(save.f, "LastPlayed=%lld\n", k.lastPlayed); if (k.playTime) fprintf(save.f, "PlayTime=%lld\n", k.playTime); + if (!k.collections.empty()) fprintf(save.f, "Collections=%s\n", k.collections.c_str()); fprintf(save.f, "\n"); } save.Commit(); @@ -456,6 +477,7 @@ inline void VGames_ApplyLiveMarks(int idx) { g.hidden = it->second.hidden; g.lastPlayed = it->second.lastPlayed; g.playTime = it->second.playTime; + snprintf(g.collections, sizeof(g.collections), "%s", it->second.collections.c_str()); } // Writes the row's marks wherever that row lives. @@ -464,7 +486,7 @@ inline void VGames_StoreMarks(int idx) { VirtualGame& g = g_vgames.games[idx]; g_vgames.generation++; if (!VGames_IsLive(g)) { VGames_Save(); return; } - VGameMarks k = { g.favorite, g.hidden, g.lastPlayed, g.playTime }; + VGameMarks k = { g.favorite, g.hidden, g.lastPlayed, g.playTime, g.collections }; VGames_LiveMarks()[g.titleID] = k; VGames_SaveLiveMarks(); } @@ -586,19 +608,112 @@ inline bool VGames_IsShown(const VirtualGame& g) { return !g.duplicate; } +// The launcher asks for a collection as "Collection:", so one called +// Games can't be mistaken for the Games category. +#define VGAMES_COLLECTION_PREFIX "Collection:" +#define VGAMES_COLLECTION_NAME_MAX 40 + +inline const char* VGames_CollectionOf(const char* category) { + size_t n = strlen(VGAMES_COLLECTION_PREFIX); + return category && strncasecmp(category, VGAMES_COLLECTION_PREFIX, n) == 0 ? category + n : NULL; +} + +// Case blind, one name out of the ';' list. +inline bool VGames_InCollection(const VirtualGame& g, const char* name) { + if (!name || !*name) return false; + size_t n = strlen(name); + for (const char* p = g.collections; *p;) { + const char* end = strchr(p, ';'); + size_t len = end ? (size_t)(end - p) : strlen(p); + if (len == n && strncasecmp(p, name, n) == 0) return true; + if (!end) break; + p = end + 1; + } + return false; +} + +// Names can't carry the separator or the brackets games_live.ini keys on. +inline std::string VGames_CleanCollectionName(const char* in) { + std::string out; + for (const char* p = in; *p && out.size() < VGAMES_COLLECTION_NAME_MAX; p++) { + unsigned char c = (unsigned char)*p; + if (c < 0x20 || c == ';' || c == '[' || c == ']' || c == '=') continue; + if (c == ' ' && (out.empty() || out[out.size() - 1] == ' ')) continue; + out += (char)c; + } + while (!out.empty() && out[out.size() - 1] == ' ') out.erase(out.size() - 1); + return out; +} + +// False when the list is full. +inline bool VGames_SetInCollection(int idx, const char* name, bool on) { + if (idx < 0 || idx >= g_vgames.count || !name || !*name) return false; + VirtualGame& g = g_vgames.games[idx]; + if (VGames_InCollection(g, name) == on) return true; + std::string keep; + if (on) { + keep = g.collections; + if (!keep.empty()) keep += ";"; + keep += name; + if (keep.size() >= sizeof(g.collections)) return false; + } else { + size_t n = strlen(name); + for (const char* p = g.collections; *p;) { + const char* end = strchr(p, ';'); + size_t len = end ? (size_t)(end - p) : strlen(p); + if (!(len == n && strncasecmp(p, name, n) == 0)) { + if (!keep.empty()) keep += ";"; + keep.append(p, len); + } + if (!end) break; + p = end + 1; + } + } + snprintf(g.collections, sizeof(g.collections), "%s", keep.c_str()); + VGames_StoreMarks(idx); + return true; +} + +// Every collection name A to Z, spelled the way it was first seen. shownOnly +// leaves out the ones whose games are all hidden. +inline void VGames_Collections(std::vector& out, bool shownOnly) { + VGames_Load(); + out.clear(); + for (int i = 0; i < g_vgames.count; i++) { + const VirtualGame& g = g_vgames.games[i]; + if (!g.valid || !g.collections[0]) continue; + if (shownOnly && !VGames_IsShown(g)) continue; + for (const char* p = g.collections; *p;) { + const char* end = strchr(p, ';'); + std::string name = end ? std::string(p, end - p) : std::string(p); + bool have = name.empty(); + for (size_t k = 0; k < out.size() && !have; k++) + have = strcasecmp(out[k].c_str(), name.c_str()) == 0; + if (!have) out.push_back(name); + if (!end) break; + p = end + 1; + } + } + std::sort(out.begin(), out.end(), [](const std::string& a, const std::string& b) { + return strcasecmp(a.c_str(), b.c_str()) < 0; + }); +} + inline bool VGames_IsMarkList(const char* category) { - return category && (strcasecmp(category, VGAMES_FAVORITES) == 0 || strcasecmp(category, VGAMES_RECENT) == 0); + return category && (strcasecmp(category, VGAMES_FAVORITES) == 0 || strcasecmp(category, VGAMES_RECENT) == 0 || + VGames_CollectionOf(category)); } -// Favorites by name, or recently played newest first. +// Favorites or a collection by name, or recently played newest first. inline void VGames_MarkList(const char* category, std::vector& out) { VGames_Load(); out.clear(); bool recent = strcasecmp(category, VGAMES_RECENT) == 0; + const char* coll = VGames_CollectionOf(category); for (int i = 0; i < g_vgames.count; i++) { const VirtualGame& g = g_vgames.games[i]; if (!VGames_IsShown(g)) continue; - if (recent ? g.lastPlayed > 0 : g.favorite) out.push_back(i); + if (recent ? g.lastPlayed > 0 : coll ? VGames_InCollection(g, coll) : g.favorite) out.push_back(i); } if (recent) { std::sort(out.begin(), out.end(), [](int a, int b) { 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"); diff --git a/theseus/desktop/xdg_apps.cpp b/theseus/desktop/xdg_apps.cpp new file mode 100644 index 0000000..7fe0de3 --- /dev/null +++ b/theseus/desktop/xdg_apps.cpp @@ -0,0 +1,280 @@ +// 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, "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"); + } + 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++); + 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]; + 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..5d51ffa --- /dev/null +++ b/theseus/desktop/xdg_apps.h @@ -0,0 +1,36 @@ +// 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 + std::string workdir; // its Path, where it wants to start + 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); diff --git a/xips-source/default-desktop/Jellyfin.xap b/xips-source/default-desktop/Jellyfin.xap index a447aac..047519d 100644 --- a/xips-source/default-desktop/Jellyfin.xap +++ b/xips-source/default-desktop/Jellyfin.xap @@ -14,6 +14,10 @@ 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 +var sJfStatus; // what the empty list says (loading, can't reach); "" with rows +var nJfStamp; // watch state we drew; playback reports and marks bump it function initialize() @@ -27,6 +31,9 @@ function initialize() nJfCursorBackup0 = 0; nJfCursorBackup1 = 0; nJfCursorBackup2 = 0; + sJfPoster = ""; + sJfStatus = ""; + nJfStamp = -1; } @@ -47,7 +54,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) @@ -61,12 +68,12 @@ 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); - var showTitle = theJellyfinLibrary.GetItemTitle(nJfCursorBackup1); + return server + " / " + theJellyfinLibrary.GetListTitle(); + var showTitle = theJellyfinLibrary.GetItemName(nJfCursorBackup1); if (nJfView == 2) return showTitle; return showTitle + " / " + theJellyfinLibrary.GetSeasonTitle(nJfCursorBackup2); @@ -104,6 +111,8 @@ function StartJellyfinLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sJfPoster = ""; + bJfLoaded = 1; BindActiveList(); UpdateJellyfinList(); } @@ -112,6 +121,12 @@ function StartJellyfinLevel() function UpdateJellyfinList() { var c = theJellyfinMenu.children[0].children[0]; + var status = theJellyfinLibrary.GetStatus(nJfView); + nJfStamp = theJellyfinLibrary.GetWatchStamp(); + + // A shelf can shrink under the cursor once watch state reloads. + if ((nJfCursor >= nJfCount) & (nJfCount > 0)) + nJfCursor = nJfCount - 1; if (nJfCursor < nJfScroll) nJfScroll = nJfCursor; @@ -142,6 +157,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; @@ -150,6 +176,9 @@ function UpdateJellyfinList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sJfStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -157,6 +186,12 @@ function UpdateJellyfinList() UpdatePoster(c); + // X FROM START shows while the row has a resume point to skip. + if (theJellyfinLibrary.CanStartOver(nJfView, nJfCursor) == 1) + c.MU_x_cluster.visible = true; + else + c.MU_x_cluster.visible = false; + nJfLastCount = nJfCount; } @@ -165,28 +200,44 @@ 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 + 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"; +} + + +// The Search row asks for words first; the results open like a library. +function EnterLibrary() +{ + if (theJellyfinLibrary.GetMeta(nJfCursor) == "search") { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Jellyfin\\jellyfin_logo.png"; + nJfCursorBackup0 = nJfCursor; + ShowKeyboard("SEARCH JELLYFIN", theJellyfinLibrary.GetSearchTerm(), "theJellyfinInline.children[0].JellyfinSearchDone()", ""); + return; } + OpenLibrary(); } -function EnterLibrary() +function OpenLibrary() { theJellyfinLibrary.SetCurrent(nJfCursor); nJfCursorBackup0 = nJfCursor; @@ -198,11 +249,30 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +function JellyfinSearchDone() +{ + if (strKeyboardEdit == "") + return; + theJellyfinLibrary.Search(strKeyboardEdit); + nJfCursor = nJfCursorBackup0; + OpenLibrary(); +} + + +// 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; @@ -256,6 +326,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; @@ -396,7 +473,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. @@ -418,7 +527,22 @@ DEF theJellyfinMenu Level mc.MessageText.scrollDelay = 2; } function OnWhiteDown(){ PlaySoundError(); } - function OnBlackDown(){ PlaySoundError(); } + // Black (RB): flip the row's watched mark. + function OnBlackDown() + { + if ((nJfView == 0) | (nJfCount <= 0) | (theJellyfinLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (theJellyfinLibrary.ToggleWatched(nJfView, nJfCursor) < 0) + { + PlaySoundError(); + return; + } + PlaySoundA(); + UpdateJellyfinList(); + } } function OnArrival() @@ -437,7 +561,12 @@ DEF theJellyfinMenu Level { sleep .4; BindActiveList(); - if (nJfCount != nJfLastCount) + if (bJfLoaded == 1) + { + if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster) | (theJellyfinLibrary.GetStatus(nJfView) != sJfStatus) | (theJellyfinLibrary.GetWatchStamp() != nJfStamp)) + UpdateJellyfinList(); + } + else if (nJfCount != nJfLastCount) { UpdateJellyfinList(); } diff --git a/xips-source/default-desktop/Plex.xap b/xips-source/default-desktop/Plex.xap index 4d61250..a77b99e 100644 --- a/xips-source/default-desktop/Plex.xap +++ b/xips-source/default-desktop/Plex.xap @@ -14,6 +14,10 @@ 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 +var sPlexStatus; // what the empty list says (loading, can't reach); "" with rows +var nPlexStamp; // watch state we drew; playback reports and marks bump it function initialize() @@ -27,6 +31,9 @@ function initialize() nPlexCursorBackup0 = 0; nPlexCursorBackup1 = 0; nPlexCursorBackup2 = 0; + sPlexPoster = ""; + sPlexStatus = ""; + nPlexStamp = -1; } @@ -47,7 +54,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) @@ -61,12 +68,12 @@ 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); - var showTitle = thePlexLibrary.GetItemTitle(nPlexCursorBackup1); + return server + " / " + thePlexLibrary.GetListTitle(); + var showTitle = thePlexLibrary.GetItemName(nPlexCursorBackup1); if (nPlexView == 2) return showTitle; return showTitle + " / " + thePlexLibrary.GetSeasonTitle(nPlexCursorBackup2); @@ -104,6 +111,8 @@ function StartPlexLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sPlexPoster = ""; + bPlexLoaded = 1; BindActiveList(); UpdatePlexList(); } @@ -112,6 +121,12 @@ function StartPlexLevel() function UpdatePlexList() { var c = thePlexMenu.children[0].children[0]; + var status = thePlexLibrary.GetStatus(nPlexView); + nPlexStamp = thePlexLibrary.GetWatchStamp(); + + // A shelf can shrink under the cursor once watch state reloads. + if ((nPlexCursor >= nPlexCount) & (nPlexCount > 0)) + nPlexCursor = nPlexCount - 1; if (nPlexCursor < nPlexScroll) nPlexScroll = nPlexCursor; @@ -142,6 +157,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; @@ -150,6 +176,9 @@ function UpdatePlexList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sPlexStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -157,6 +186,12 @@ function UpdatePlexList() UpdatePoster(c); + // X FROM START shows while the row has a resume point to skip. + if (thePlexLibrary.CanStartOver(nPlexView, nPlexCursor) == 1) + c.MU_x_cluster.visible = true; + else + c.MU_x_cluster.visible = false; + nPlexLastCount = nPlexCount; } @@ -165,28 +200,44 @@ 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 + 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"; +} + + +// The Search row asks for words first; the results open like a library. +function EnterLibrary() +{ + if (thePlexLibrary.GetMeta(nPlexCursor) == "search") { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Plex\\plex_logo.png"; + nPlexCursorBackup0 = nPlexCursor; + ShowKeyboard("SEARCH PLEX", thePlexLibrary.GetSearchTerm(), "thePlexInline.children[0].PlexSearchDone()", ""); + return; } + OpenLibrary(); } -function EnterLibrary() +function OpenLibrary() { thePlexLibrary.SetCurrent(nPlexCursor); nPlexCursorBackup0 = nPlexCursor; @@ -198,11 +249,30 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +function PlexSearchDone() +{ + if (strKeyboardEdit == "") + return; + thePlexLibrary.Search(strKeyboardEdit); + nPlexCursor = nPlexCursorBackup0; + OpenLibrary(); +} + + +// 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; @@ -256,6 +326,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; @@ -396,7 +473,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. @@ -418,7 +527,22 @@ DEF thePlexMenu Level mc.MessageText.scrollDelay = 2; } function OnWhiteDown(){ PlaySoundError(); } - function OnBlackDown(){ PlaySoundError(); } + // Black (RB): flip the row's watched mark. + function OnBlackDown() + { + if ((nPlexView == 0) | (nPlexCount <= 0) | (thePlexLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (thePlexLibrary.ToggleWatched(nPlexView, nPlexCursor) < 0) + { + PlaySoundError(); + return; + } + PlaySoundA(); + UpdatePlexList(); + } } function OnArrival() @@ -437,7 +561,12 @@ DEF thePlexMenu Level { sleep .4; BindActiveList(); - if (nPlexCount != nPlexLastCount) + if (bPlexLoaded == 1) + { + if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster) | (thePlexLibrary.GetStatus(nPlexView) != sPlexStatus) | (thePlexLibrary.GetWatchStamp() != nPlexStamp)) + UpdatePlexList(); + } + else if (nPlexCount != nPlexLastCount) { UpdatePlexList(); } diff --git a/xips-source/default-desktop/harddrive.xap b/xips-source/default-desktop/harddrive.xap index 09376f3..1f401d2 100644 --- a/xips-source/default-desktop/harddrive.xap +++ b/xips-source/default-desktop/harddrive.xap @@ -345,6 +345,14 @@ function LoadMenuItems() arrMenuPaths[TotalSections] = "Favorites"; TotalSections = TotalSections + 1; } + // Your collections, same deal: a row each while something's in it. + var nCollections = theGamesCollection.GetCollectionCount(); + for (var k = 0; k < nCollections; k = k + 1) + { + arrMenuNames[TotalSections] = theGamesCollection.GetCollectionName(k); + arrMenuPaths[TotalSections] = "Collection:" + arrMenuNames[TotalSections]; + TotalSections = TotalSections + 1; + } for (var x = 0; x < 5; x = x + 1) { c.theMenuButtons.children[x].visible = false; @@ -740,7 +748,15 @@ DEF theLauncher Level { CurFillDir = arrMenuPaths[nCurLauncherItem0]; subTitle0 = mnuName; - TempTitleList = GetTitleList(mnuName); + // A collection is asked for by its path, so one named Games stays itself. + if(theGamesCollection.IsMixedList(CurFillDir) == 1) + { + TempTitleList = GetTitleList(CurFillDir); + } + else + { + TempTitleList = GetTitleList(mnuName); + } thePlayerPanelIn.Play(); StartTitleList(); } @@ -789,7 +805,7 @@ DEF theLauncher Level return; } // These lists mix categories, so there's no folder path to build. - if((CurFillDir == "Recently Played") | (CurFillDir == "Favorites")) + if(theGamesCollection.IsMixedList(CurFillDir) == 1) { theGamesCollection.LaunchTitle(nPlayCursor0); return; diff --git a/xips-source/jellyfin/jellyfin.xap b/xips-source/jellyfin/jellyfin.xap index a447aac..047519d 100644 --- a/xips-source/jellyfin/jellyfin.xap +++ b/xips-source/jellyfin/jellyfin.xap @@ -14,6 +14,10 @@ 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 +var sJfStatus; // what the empty list says (loading, can't reach); "" with rows +var nJfStamp; // watch state we drew; playback reports and marks bump it function initialize() @@ -27,6 +31,9 @@ function initialize() nJfCursorBackup0 = 0; nJfCursorBackup1 = 0; nJfCursorBackup2 = 0; + sJfPoster = ""; + sJfStatus = ""; + nJfStamp = -1; } @@ -47,7 +54,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) @@ -61,12 +68,12 @@ 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); - var showTitle = theJellyfinLibrary.GetItemTitle(nJfCursorBackup1); + return server + " / " + theJellyfinLibrary.GetListTitle(); + var showTitle = theJellyfinLibrary.GetItemName(nJfCursorBackup1); if (nJfView == 2) return showTitle; return showTitle + " / " + theJellyfinLibrary.GetSeasonTitle(nJfCursorBackup2); @@ -104,6 +111,8 @@ function StartJellyfinLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sJfPoster = ""; + bJfLoaded = 1; BindActiveList(); UpdateJellyfinList(); } @@ -112,6 +121,12 @@ function StartJellyfinLevel() function UpdateJellyfinList() { var c = theJellyfinMenu.children[0].children[0]; + var status = theJellyfinLibrary.GetStatus(nJfView); + nJfStamp = theJellyfinLibrary.GetWatchStamp(); + + // A shelf can shrink under the cursor once watch state reloads. + if ((nJfCursor >= nJfCount) & (nJfCount > 0)) + nJfCursor = nJfCount - 1; if (nJfCursor < nJfScroll) nJfScroll = nJfCursor; @@ -142,6 +157,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; @@ -150,6 +176,9 @@ function UpdateJellyfinList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sJfStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -157,6 +186,12 @@ function UpdateJellyfinList() UpdatePoster(c); + // X FROM START shows while the row has a resume point to skip. + if (theJellyfinLibrary.CanStartOver(nJfView, nJfCursor) == 1) + c.MU_x_cluster.visible = true; + else + c.MU_x_cluster.visible = false; + nJfLastCount = nJfCount; } @@ -165,28 +200,44 @@ 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 + 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"; +} + + +// The Search row asks for words first; the results open like a library. +function EnterLibrary() +{ + if (theJellyfinLibrary.GetMeta(nJfCursor) == "search") { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Jellyfin\\jellyfin_logo.png"; + nJfCursorBackup0 = nJfCursor; + ShowKeyboard("SEARCH JELLYFIN", theJellyfinLibrary.GetSearchTerm(), "theJellyfinInline.children[0].JellyfinSearchDone()", ""); + return; } + OpenLibrary(); } -function EnterLibrary() +function OpenLibrary() { theJellyfinLibrary.SetCurrent(nJfCursor); nJfCursorBackup0 = nJfCursor; @@ -198,11 +249,30 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +function JellyfinSearchDone() +{ + if (strKeyboardEdit == "") + return; + theJellyfinLibrary.Search(strKeyboardEdit); + nJfCursor = nJfCursorBackup0; + OpenLibrary(); +} + + +// 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; @@ -256,6 +326,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; @@ -396,7 +473,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. @@ -418,7 +527,22 @@ DEF theJellyfinMenu Level mc.MessageText.scrollDelay = 2; } function OnWhiteDown(){ PlaySoundError(); } - function OnBlackDown(){ PlaySoundError(); } + // Black (RB): flip the row's watched mark. + function OnBlackDown() + { + if ((nJfView == 0) | (nJfCount <= 0) | (theJellyfinLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (theJellyfinLibrary.ToggleWatched(nJfView, nJfCursor) < 0) + { + PlaySoundError(); + return; + } + PlaySoundA(); + UpdateJellyfinList(); + } } function OnArrival() @@ -437,7 +561,12 @@ DEF theJellyfinMenu Level { sleep .4; BindActiveList(); - if (nJfCount != nJfLastCount) + if (bJfLoaded == 1) + { + if ((nJfCount != nJfLastCount) | (GetPosterArt() != sJfPoster) | (theJellyfinLibrary.GetStatus(nJfView) != sJfStatus) | (theJellyfinLibrary.GetWatchStamp() != nJfStamp)) + UpdateJellyfinList(); + } + else if (nJfCount != nJfLastCount) { UpdateJellyfinList(); } diff --git a/xips-source/jellyfin/jellyfin/default.xap b/xips-source/jellyfin/jellyfin/default.xap index 73634aa..cf83790 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 @@ -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 { @@ -1703,6 +1701,108 @@ DEF Group07 Transform cycleInterval 14.300000 loop TRUE } + // X cluster: a copy of A's, set to its left, shown while the row + // under the cursor has a resume point. + DEF MU_x_cluster Transform + { + children + [ + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "FlatSurfaces" } } + geometry Mesh { url "MU_select_probearm-FACES.xm" } + } + ] + rotation -0.786500 0.499900 0.362600 -1.910000 + scale 0.465000 0.465000 0.465000 + scaleOrientation 0.000000 0.005536 1.000000 -0.474500 + translation -11.089000 15.920000 6.071000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "FlatSurfaces" } } + geometry Mesh { url "MU_select_probe-FACES.xm" } + } + ] + rotation -0.786500 0.499900 0.362600 -1.910000 + scale 0.465000 0.465000 0.465000 + scaleOrientation 0.000000 0.005536 1.000000 -0.474500 + translation -10.203000 15.060000 6.235000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "CellEgg/Parts" } } + geometry Mesh { url "MU_select_pod_inner-FACES.xm" } + } + Shape + { + appearance Appearance { material MaxMaterial { name "CellEgg/Parts" } } + geometry Mesh { url "MU_select_pod_outer-FACES.xm" } + } + Shape + { + appearance Appearance { material MaxMaterial { name "EggGlow" } } + geometry Mesh { url "MU_select_pod_HL-FACES.xm" } + } + ] + scale 0.465000 0.465000 0.465000 + translation -1.422000 -10.330000 3.150000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "TubesFade" } } + geometry Mesh { url "MU_select_tube-FACES.xm" } + } + ] + rotation -0.990900 0.095410 -0.095410 -1.580000 + scale 0.465000 0.465000 0.465000 + scaleOrientation -0.011110 0.412400 0.911000 -0.088980 + translation 31.620001 -26.790001 9.817000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "NavType" } } + geometry Text { font "heading" justify "middle" translate false text "X" } + } + ] + scale 0.605000 0.605000 0.000 + translation -3.559000 2.391000 -0.443200 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "XBOXgreen" } } + geometry Text { font "Body" text "FROM START" justify "end" } + } + ] + scale 0.375000 0.475000 0.00 + translation -4.265000 2.156000 -0.409300 + } + ] + } DEF MU_Text_a Transform { children diff --git a/xips-source/plex/plex.xap b/xips-source/plex/plex.xap index 4d61250..a77b99e 100644 --- a/xips-source/plex/plex.xap +++ b/xips-source/plex/plex.xap @@ -14,6 +14,10 @@ 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 +var sPlexStatus; // what the empty list says (loading, can't reach); "" with rows +var nPlexStamp; // watch state we drew; playback reports and marks bump it function initialize() @@ -27,6 +31,9 @@ function initialize() nPlexCursorBackup0 = 0; nPlexCursorBackup1 = 0; nPlexCursorBackup2 = 0; + sPlexPoster = ""; + sPlexStatus = ""; + nPlexStamp = -1; } @@ -47,7 +54,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) @@ -61,12 +68,12 @@ 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); - var showTitle = thePlexLibrary.GetItemTitle(nPlexCursorBackup1); + return server + " / " + thePlexLibrary.GetListTitle(); + var showTitle = thePlexLibrary.GetItemName(nPlexCursorBackup1); if (nPlexView == 2) return showTitle; return showTitle + " / " + thePlexLibrary.GetSeasonTitle(nPlexCursorBackup2); @@ -104,6 +111,8 @@ function StartPlexLevel() c.MU_cd_04.visible = false; c.MU_cd_05.visible = false; + sPlexPoster = ""; + bPlexLoaded = 1; BindActiveList(); UpdatePlexList(); } @@ -112,6 +121,12 @@ function StartPlexLevel() function UpdatePlexList() { var c = thePlexMenu.children[0].children[0]; + var status = thePlexLibrary.GetStatus(nPlexView); + nPlexStamp = thePlexLibrary.GetWatchStamp(); + + // A shelf can shrink under the cursor once watch state reloads. + if ((nPlexCursor >= nPlexCount) & (nPlexCount > 0)) + nPlexCursor = nPlexCount - 1; if (nPlexCursor < nPlexScroll) nPlexScroll = nPlexCursor; @@ -142,6 +157,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; @@ -150,6 +176,9 @@ function UpdatePlexList() c.MediaHeaderText.text = GetHeaderText(); c.MusicCountText.text = GetCountText(); + if (status != "") + c.MusicCountText.text = ""; + sPlexStatus = status; c.MusicType.text = ""; c.TimeNum.text = ""; @@ -157,6 +186,12 @@ function UpdatePlexList() UpdatePoster(c); + // X FROM START shows while the row has a resume point to skip. + if (thePlexLibrary.CanStartOver(nPlexView, nPlexCursor) == 1) + c.MU_x_cluster.visible = true; + else + c.MU_x_cluster.visible = false; + nPlexLastCount = nPlexCount; } @@ -165,28 +200,44 @@ 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 + 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"; +} + + +// The Search row asks for words first; the results open like a library. +function EnterLibrary() +{ + if (thePlexLibrary.GetMeta(nPlexCursor) == "search") { - c.MU_cd_01.children[0].children[0].appearance.texture.url = "E:\\Plex\\plex_logo.png"; + nPlexCursorBackup0 = nPlexCursor; + ShowKeyboard("SEARCH PLEX", thePlexLibrary.GetSearchTerm(), "thePlexInline.children[0].PlexSearchDone()", ""); + return; } + OpenLibrary(); } -function EnterLibrary() +function OpenLibrary() { thePlexLibrary.SetCurrent(nPlexCursor); nPlexCursorBackup0 = nPlexCursor; @@ -198,11 +249,30 @@ function EnterLibrary() } -// Movies/tracks play immediately; TV shows drill into seasons. +function PlexSearchDone() +{ + if (strKeyboardEdit == "") + return; + thePlexLibrary.Search(strKeyboardEdit); + nPlexCursor = nPlexCursorBackup0; + OpenLibrary(); +} + + +// 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; @@ -256,6 +326,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; @@ -396,7 +473,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. @@ -418,7 +527,22 @@ DEF thePlexMenu Level mc.MessageText.scrollDelay = 2; } function OnWhiteDown(){ PlaySoundError(); } - function OnBlackDown(){ PlaySoundError(); } + // Black (RB): flip the row's watched mark. + function OnBlackDown() + { + if ((nPlexView == 0) | (nPlexCount <= 0) | (thePlexLibrary.IsSyncReady() == 0)) + { + PlaySoundError(); + return; + } + if (thePlexLibrary.ToggleWatched(nPlexView, nPlexCursor) < 0) + { + PlaySoundError(); + return; + } + PlaySoundA(); + UpdatePlexList(); + } } function OnArrival() @@ -437,7 +561,12 @@ DEF thePlexMenu Level { sleep .4; BindActiveList(); - if (nPlexCount != nPlexLastCount) + if (bPlexLoaded == 1) + { + if ((nPlexCount != nPlexLastCount) | (GetPosterArt() != sPlexPoster) | (thePlexLibrary.GetStatus(nPlexView) != sPlexStatus) | (thePlexLibrary.GetWatchStamp() != nPlexStamp)) + UpdatePlexList(); + } + else if (nPlexCount != nPlexLastCount) { UpdatePlexList(); } diff --git a/xips-source/plex/plex/default.xap b/xips-source/plex/plex/default.xap index 73634aa..cf83790 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 @@ -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 { @@ -1703,6 +1701,108 @@ DEF Group07 Transform cycleInterval 14.300000 loop TRUE } + // X cluster: a copy of A's, set to its left, shown while the row + // under the cursor has a resume point. + DEF MU_x_cluster Transform + { + children + [ + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "FlatSurfaces" } } + geometry Mesh { url "MU_select_probearm-FACES.xm" } + } + ] + rotation -0.786500 0.499900 0.362600 -1.910000 + scale 0.465000 0.465000 0.465000 + scaleOrientation 0.000000 0.005536 1.000000 -0.474500 + translation -11.089000 15.920000 6.071000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "FlatSurfaces" } } + geometry Mesh { url "MU_select_probe-FACES.xm" } + } + ] + rotation -0.786500 0.499900 0.362600 -1.910000 + scale 0.465000 0.465000 0.465000 + scaleOrientation 0.000000 0.005536 1.000000 -0.474500 + translation -10.203000 15.060000 6.235000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "CellEgg/Parts" } } + geometry Mesh { url "MU_select_pod_inner-FACES.xm" } + } + Shape + { + appearance Appearance { material MaxMaterial { name "CellEgg/Parts" } } + geometry Mesh { url "MU_select_pod_outer-FACES.xm" } + } + Shape + { + appearance Appearance { material MaxMaterial { name "EggGlow" } } + geometry Mesh { url "MU_select_pod_HL-FACES.xm" } + } + ] + scale 0.465000 0.465000 0.465000 + translation -1.422000 -10.330000 3.150000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "TubesFade" } } + geometry Mesh { url "MU_select_tube-FACES.xm" } + } + ] + rotation -0.990900 0.095410 -0.095410 -1.580000 + scale 0.465000 0.465000 0.465000 + scaleOrientation -0.011110 0.412400 0.911000 -0.088980 + translation 31.620001 -26.790001 9.817000 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "NavType" } } + geometry Text { font "heading" justify "middle" translate false text "X" } + } + ] + scale 0.605000 0.605000 0.000 + translation -3.559000 2.391000 -0.443200 + } + Transform + { + children + [ + Shape + { + appearance Appearance { material MaxMaterial { name "XBOXgreen" } } + geometry Text { font "Body" text "FROM START" justify "end" } + } + ] + scale 0.375000 0.475000 0.00 + translation -4.265000 2.156000 -0.409300 + } + ] + } DEF MU_Text_a Transform { children