diff --git a/Data/Xips/default.xip b/Data/Xips/default.xip index ec5fc98..74b5d40 100644 Binary files a/Data/Xips/default.xip and b/Data/Xips/default.xip differ diff --git a/build/Makefile b/build/Makefile index 1857dd4..dc4dbd9 100644 --- a/build/Makefile +++ b/build/Makefile @@ -901,6 +901,7 @@ DESKTOP_SRCS_PLATFORM = \ $(THESEUS_SRC)/desktop/esde.cpp \ $(THESEUS_SRC)/desktop/esde_vgames.cpp \ $(THESEUS_SRC)/desktop/icon_compress.cpp \ + $(THESEUS_SRC)/desktop/game_art.cpp \ $(THESEUS_SRC)/desktop/playlist.cpp \ $(THESEUS_SRC)/desktop/playlist_maker.cpp \ $(THESEUS_SRC)/desktop/preloader.cpp \ diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index e9e4ecf..3342bc0 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -4253,7 +4253,7 @@ extern void DesktopLaunchTitle(const char* devicePath); class CGamesCollection : public CNode { public: - CGamesCollection() : m_gen(0) + CGamesCollection() : m_gen(0), m_showHidden(false) { m_category[0] = 0; m_group[0] = 0; @@ -4273,6 +4273,8 @@ class CGamesCollection : public CNode std::vector m_slice; // Last seen generation. Re-filter when it changes. unsigned int m_gen; + // Hidden titles come back so a scene can offer to unhide them. + bool m_showHidden; // Rows are folders first, then titles, so an index below the folder count // addresses m_folders and anything above it addresses m_slice. @@ -4293,6 +4295,11 @@ class CGamesCollection : public CNode m_gen = g_vgames.generation; return; } + if (VGames_IsMarkList(m_category)) { + VGames_MarkList(m_category, m_slice); + m_gen = g_vgames.generation; + return; + } // Match what xboxfs / Title Maker do: drive defaults to "E" for the // harddrive view. Future-proofed for F/G if those ever come back. int tmp[VGAMES_MAX]; @@ -4300,6 +4307,7 @@ class CGamesCollection : public CNode size_t glen = strlen(m_group); for (int i = 0; i < n; i++) { + if (!m_showHidden && !VGames_IsShown(g_vgames.games[tmp[i]])) continue; const char* grp = g_vgames.games[tmp[i]].group; const char* rest; if (glen == 0) { @@ -4369,14 +4377,50 @@ class CGamesCollection : public CNode { VGames_Load(); if (!cat || !*cat) return 0; + if (VGames_IsMarkList(cat)) { + std::vector list; + VGames_MarkList(cat, list); + return (int)list.size(); + } int n = 0; for (int i = 0; i < g_vgames.count; i++) { const VirtualGame& g = g_vgames.games[i]; - if (g.valid && strcasecmp(g.category, cat) == 0) n++; + if (VGames_IsShown(g) && strcasecmp(g.category, cat) == 0) n++; } return n; } + // The DB row behind a list row, or -1 for folders and anything past the end. + int Row(int i) + { + EnsureFresh(); + int t = TitleIndex(i); + return (t >= 0 && t < (int)m_slice.size()) ? m_slice[t] : -1; + } + + int IsFavorite(int i) { int r = Row(i); return (r >= 0 && g_vgames.games[r].favorite) ? 1 : 0; } + int IsHidden(int i) { int r = Row(i); return (r >= 0 && g_vgames.games[r].hidden) ? 1 : 0; } + void SetFavorite(int i, int on) { VGames_SetFavorite(Row(i), on != 0); } + void SetHidden(int i, int on) { VGames_SetHidden(Row(i), on != 0); } + + // 1 lists hidden titles too, 0 goes back to normal. + void ShowHidden(int on) + { + m_showHidden = on != 0; + Rebuild(); + } + + // "2026-11-12 18:40", or empty for never. + CStrObject* GetLastPlayed(int i) + { + int r = Row(i); + if (r < 0 || !g_vgames.games[r].lastPlayed) return new CStrObject; + time_t t = (time_t)g_vgames.games[r].lastPlayed; + char buf[32]; + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", localtime(&t)); + return new CStrObject(buf); + } + // 1 when the row drills down instead of launching. int IsFolder(int i) { @@ -4506,6 +4550,12 @@ START_NODE_FUN(CGamesCollection, CNode) NODE_FUN_SI(GetIcon) NODE_FUN_VI(LaunchTitle) NODE_FUN_VV(Refresh) + NODE_FUN_II(IsFavorite) + NODE_FUN_VII(SetFavorite) + NODE_FUN_II(IsHidden) + NODE_FUN_VII(SetHidden) + NODE_FUN_VI(ShowHidden) + NODE_FUN_SI(GetLastPlayed) END_NODE_FUN() diff --git a/theseus/desktop/desktop_settings.cpp b/theseus/desktop/desktop_settings.cpp index 7c141e0..9af10ab 100644 --- a/theseus/desktop/desktop_settings.cpp +++ b/theseus/desktop/desktop_settings.cpp @@ -9,6 +9,7 @@ #include "settings_schema.h" #include "audio_sdl.h" #include "media_player.h" +#include "virtual_games.h" extern char s_xemuPath[512]; extern char g_qcowPath[512]; @@ -27,6 +28,8 @@ extern float g_masterVolume; extern bool g_useMilkdropViz, g_showAlbumCover; extern char g_musicRoot[512], g_moviesRoot[512], g_tvRoot[512]; extern char g_tmdbKey[128], g_romsDir[512]; +extern bool g_fetchGameArt; +extern char g_steamGridDbKey[128]; extern char g_plexToken[256], g_plexClientId[64]; extern char g_xcloudRefreshToken[2048]; extern char g_jellyfinUrl[512], g_jellyfinToken[256], g_jellyfinUserId[64]; @@ -43,6 +46,10 @@ char g_currentSkin[64] = "Stock"; static int s_startupModeSaved = 0; static void ApplyStartupMode() { g_startupMode = s_startupModeSaved; } +// The same game from two sources shows once, from the best one. +bool g_hideDuplicateGames = true; +static void ApplyDuplicates() { g_vgames.generation++; } + static void ApplyMsaa() { g_msaaChangeRequested = true; } static void ApplyVsync() { g_vsyncChangeRequested = true; } static void ApplyDisplay() { g_displayChangeRequested = true; } @@ -158,6 +165,10 @@ static const SettingDef kDefs[] = { S_FOLDER("TvRoot", "Library", "Media", "TV Shows Folder", g_tvRoot, ApplyLibrary), S_STR("TMDBKey", "Library", "Media", "TMDB API Key", g_tmdbKey, "", SF_SECRET), S_PATH("RomsDir", "Library", "Games", "ROMs Folder", g_romsDir, 0), + S_BOOL("FetchGameArt", "Library", "Games", "Download Game Art", g_fetchGameArt, "1", 0), + { "HideDuplicateGames", "Library", "Games", "Show Each Game Once", SK_BOOL, &g_hideDuplicateGames, 0, "1", 0, + NOENUM, 0, 0, 0, NULL, ApplyDuplicates }, + S_STR("SteamGridDBKey", "Library", "Games", "SteamGridDB API Key", g_steamGridDbKey, "", SF_SECRET), S_STR("PlexToken", "Library", "Media", "Plex Token", g_plexToken, "", SF_SECRET | SF_HIDDEN), S_STR("PlexClientId", "Library", "Media", "Plex Client", g_plexClientId, "", SF_SECRET | SF_HIDDEN), S_STR("XcloudRefreshToken", "Library", "Media", "Xbox Sign-in", g_xcloudRefreshToken, "", SF_SECRET | SF_HIDDEN), diff --git a/theseus/desktop/esde_vgames.cpp b/theseus/desktop/esde_vgames.cpp index ec5bff4..a1f9f5c 100644 --- a/theseus/desktop/esde_vgames.cpp +++ b/theseus/desktop/esde_vgames.cpp @@ -9,6 +9,7 @@ #include "esde.h" #include "esde_vgames.h" #include "virtual_games.h" +#include "game_art.h" #include #include @@ -115,11 +116,13 @@ void EsdeVGames_Sync(const char* esdeRoot) snprintf(group, sizeof(group), "%s", systems[s].fullname); VGames_SetGroup(idx, group); g_vgames.games[idx].transient = true; + VGames_ApplyLiveMarks(idx); // Their scraped art, cached the way Steam icons are. c0 = clock(); const char* art = Esde_FindArt(esdeRoot, &systems[s], &games[i]); if (art[0] && CacheIcon(art, titleID)) withArt++; + else GameArt_Hint(titleID, systems[s].name, games[i].path); tArt += (double)(clock() - c0) / CLOCKS_PER_SEC; total++; } diff --git a/theseus/desktop/game_art.cpp b/theseus/desktop/game_art.cpp new file mode 100644 index 0000000..6cc9b50 --- /dev/null +++ b/theseus/desktop/game_art.cpp @@ -0,0 +1,574 @@ +// game_art.cpp: box art for games that came in without an icon. +// +// Three places to look, no key needed for the first two: +// Steam's public CDN by appid, for steam:// launches. Also keeps the bigger +// capsule and header art in Configs/art for whatever wants it. +// 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. +// +// The icon lands in Configs/icons/.jpg, the same slot the Title Maker +// and the importers use, and only when that slot is empty. An icon somebody +// picked is never touched. Misses are remembered in Configs/art/misses.txt so +// a library without art doesn't ask the same servers again every launch. + +#include "game_art.h" +#include "virtual_games.h" +#include "http_util.h" +#include "json_util.h" +#include "icon_compress.h" +#include "safe_save.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +bool g_fetchGameArt = true; +char g_steamGridDbKey[128] = ""; + +static const int kWorkers = 4; +static const int kIconDim = 256; + +// ES-DE's system short names against libretro's playlist names, which are +// also the thumbnail repo names. +static const struct { const char* esde; const char* libretro; } kSystems[] = { + { "3do", "The 3DO Company - 3DO" }, + { "3ds", "Nintendo - Nintendo 3DS" }, + { "amiga", "Commodore - Amiga" }, + { "amstradcpc", "Amstrad - CPC" }, + { "arcade", "MAME" }, + { "mame", "MAME" }, + { "fbneo", "FBNeo - Arcade Games" }, + { "atari2600", "Atari - 2600" }, + { "atari5200", "Atari - 5200" }, + { "atari7800", "Atari - 7800" }, + { "atarijaguar", "Atari - Jaguar" }, + { "atarilynx", "Atari - Lynx" }, + { "atarist", "Atari - ST" }, + { "c64", "Commodore - 64" }, + { "colecovision", "Coleco - ColecoVision" }, + { "dreamcast", "Sega - Dreamcast" }, + { "fds", "Nintendo - Family Computer Disk System" }, + { "gamegear", "Sega - Game Gear" }, + { "gb", "Nintendo - Game Boy" }, + { "gba", "Nintendo - Game Boy Advance" }, + { "gbc", "Nintendo - Game Boy Color" }, + { "gc", "Nintendo - GameCube" }, + { "genesis", "Sega - Mega Drive - Genesis" }, + { "megadrive", "Sega - Mega Drive - Genesis" }, + { "mastersystem", "Sega - Master System - Mark III" }, + { "msx", "Microsoft - MSX" }, + { "n64", "Nintendo - Nintendo 64" }, + { "nds", "Nintendo - Nintendo DS" }, + { "neogeo", "SNK - Neo Geo" }, + { "neogeocd", "SNK - Neo Geo CD" }, + { "nes", "Nintendo - Nintendo Entertainment System" }, + { "famicom", "Nintendo - Nintendo Entertainment System" }, + { "ngp", "SNK - Neo Geo Pocket" }, + { "ngpc", "SNK - Neo Geo Pocket Color" }, + { "pcengine", "NEC - PC Engine - TurboGrafx 16" }, + { "tg16", "NEC - PC Engine - TurboGrafx 16" }, + { "pcenginecd", "NEC - PC Engine CD - TurboGrafx-CD" }, + { "tg-cd", "NEC - PC Engine CD - TurboGrafx-CD" }, + { "pcfx", "NEC - PC-FX" }, + { "pokemini", "Nintendo - Pokemon Mini" }, + { "ps2", "Sony - PlayStation 2" }, + { "psp", "Sony - PlayStation Portable" }, + { "psx", "Sony - PlayStation" }, + { "saturn", "Sega - Saturn" }, + { "sega32x", "Sega - 32X" }, + { "segacd", "Sega - Mega-CD - Sega CD" }, + { "megacd", "Sega - Mega-CD - Sega CD" }, + { "sg-1000", "Sega - SG-1000" }, + { "snes", "Nintendo - Super Nintendo Entertainment System" }, + { "sfc", "Nintendo - Super Nintendo Entertainment System" }, + { "vectrex", "GCE - Vectrex" }, + { "virtualboy", "Nintendo - Virtual Boy" }, + { "wii", "Nintendo - Wii" }, + { "wonderswan", "Bandai - WonderSwan" }, + { "wonderswancolor","Bandai - WonderSwan Color" }, + { "x68000", "Sharp - X68000" }, + { "xbox", "Microsoft - Xbox" }, + { "zxspectrum", "Sinclair - ZX Spectrum" }, + { "intellivision", "Mattel - Intellivision" }, + { "odyssey2", "Magnavox - Odyssey2" }, + { "dos", "DOS" }, + { "scummvm", "ScummVM" }, +}; + +// Extensions that only ever mean one system. Disc images and zips don't. +static const struct { const char* ext; const char* sys; } kExts[] = { + { "sfc", "snes" }, { "smc", "snes" }, { "nes", "nes" }, { "fds", "fds" }, + { "gba", "gba" }, { "gb", "gb" }, { "gbc", "gbc" }, + { "n64", "n64" }, { "z64", "n64" }, { "v64", "n64" }, + { "md", "genesis" }, { "gen", "genesis" }, { "smd", "genesis" }, + { "sms", "mastersystem" }, { "gg", "gamegear" }, { "32x", "sega32x" }, + { "nds", "nds" }, { "pce", "pcengine" }, { "a26", "atari2600" }, + { "a78", "atari7800" }, { "lnx", "atarilynx" }, { "j64", "atarijaguar" }, + { "ws", "wonderswan" }, { "wsc", "wonderswancolor" }, + { "ngp", "ngp" }, { "ngc", "ngpc" }, { "vb", "virtualboy" }, + { "col", "colecovision" }, { "min", "pokemini" }, { "vec", "vectrex" }, + { "gcm", "gc" }, { "rvz", "gc" }, { "wbfs", "wii" }, { "3ds", "3ds" }, +}; + +// RetroArch cores by file name prefix, for zips and discs. +static const struct { const char* core; const char* sys; } kCores[] = { + { "snes9x", "snes" }, { "bsnes", "snes" }, { "mesen-s", "snes" }, + { "nestopia", "nes" }, { "fceumm", "nes" }, { "quicknes", "nes" }, { "mesen", "nes" }, + { "mgba", "gba" }, { "vba", "gba" }, { "gpsp", "gba" }, + { "gambatte", "gbc" }, { "sameboy", "gbc" }, { "gearboy", "gbc" }, + { "mupen64plus", "n64" }, { "parallel_n64", "n64" }, + { "genesis_plus_gx", "genesis" }, { "picodrive", "genesis" }, { "blastem", "genesis" }, + { "swanstation", "psx" }, { "pcsx", "psx" }, { "mednafen_psx", "psx" }, { "beetle_psx", "psx" }, + { "duckstation", "psx" }, + { "ppsspp", "psp" }, { "flycast", "dreamcast" }, { "melonds", "nds" }, { "desmume", "nds" }, + { "mednafen_pce", "pcengine" }, { "beetle_pce", "pcengine" }, + { "mednafen_saturn", "saturn" }, { "beetle_saturn", "saturn" }, { "yabause", "saturn" }, + { "stella", "atari2600" }, { "prosystem", "atari7800" }, { "handy", "atarilynx" }, + { "virtualjaguar", "atarijaguar" }, { "dolphin", "gc" }, { "pcsx2", "ps2" }, + { "fbneo", "fbneo" }, { "mame", "mame" }, +}; + +static const char* LibretroSystem(const char* esde) +{ + if (!esde || !*esde) return NULL; + for (size_t i = 0; i < sizeof(kSystems) / sizeof(kSystems[0]); i++) + if (strcasecmp(kSystems[i].esde, esde) == 0) return kSystems[i].libretro; + return NULL; +} + +static const char* SystemForExt(const char* ext) +{ + for (size_t i = 0; i < sizeof(kExts) / sizeof(kExts[0]); i++) + if (strcasecmp(kExts[i].ext, ext) == 0) return kExts[i].sys; + return NULL; +} + +static const char* SystemForCore(const char* core) +{ + for (size_t i = 0; i < sizeof(kCores) / sizeof(kCores[0]); i++) + if (strncasecmp(core, kCores[i].core, strlen(kCores[i].core)) == 0) return kCores[i].sys; + return NULL; +} + +static std::string UrlDecode(const std::string& s) +{ + std::string out; + for (size_t i = 0; i < s.size(); i++) { + if (s[i] == '%' && i + 2 < s.size()) { + char hex[3] = { s[i + 1], s[i + 2], 0 }; + out.push_back((char)strtol(hex, NULL, 16)); + i += 2; + } else { + out.push_back(s[i] == '+' ? ' ' : s[i]); + } + } + return out; +} + +static std::string 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 & 15]); } + } + return out; +} + +// "a/b/Super Mario World (USA).sfc" -> stem and ext. An archive member +// ("game.zip#inner.nes") counts as the inner file. +static void SplitRom(const std::string& path, std::string& stem, std::string& ext) +{ + std::string p = path; + size_t hash = p.rfind('#'); + if (hash != std::string::npos) p = p.substr(hash + 1); + size_t slash = p.find_last_of("/\\"); + std::string file = (slash == std::string::npos) ? p : p.substr(slash + 1); + size_t dot = file.rfind('.'); + stem = (dot == std::string::npos) ? file : file.substr(0, dot); + ext = (dot == std::string::npos) ? "" : file.substr(dot + 1); +} + +// libretro's thumbnail names swap these for underscores. +static std::string LibretroName(const std::string& name) +{ + std::string out = name; + for (char& c : out) + if (strchr("&*/:`<>?\\|\"", c)) c = '_'; + return out; +} + +static bool Exists(const std::string& path) +{ + struct stat st; + return stat(path.c_str(), &st) == 0 && st.st_size > 0; +} + +struct ArtJob { + std::string titleID, name; + int appid = 0; + std::string system; // libretro name, empty when it isn't an emulated game + std::string romStem; + bool wantIcon = false, wantBig = false, trySgdb = false; + std::string iconDir, artDir, sgdbKey; +}; + +struct ArtDone { std::string titleID; bool gotIcon, miss, triedSgdb; }; + +static struct { + std::mutex mtx; + std::deque jobs; + std::vector done; + int workers = 0; +} s_q; + +// Main thread only from here down to the workers. +struct Hint { std::string system, rom; }; +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 +static bool s_missesLoaded = false; + +// Which key a miss was tried with, so a new or fixed key looks again. Never 0. +static unsigned KeyTag(const char* key) +{ + unsigned h = 2166136261u; + for (const char* p = key; *p; p++) { h ^= (unsigned char)*p; h *= 16777619u; } + return h ? h : 1; +} + +static std::string ArtDir() { return std::string(AppPath_Tree("Configs")) + "/art"; } +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; + h.system = system ? system : ""; + h.rom = romPath ? romPath : ""; + s_hints[titleID] = h; +} + +const char* GameArt_CachedPath(const char* titleID, const char* kind) +{ + static char buf[1024]; + if (!titleID || !Http_IsSafeFileId(titleID)) return NULL; + snprintf(buf, sizeof(buf), "%s/%s.%s.jpg", ArtDir().c_str(), titleID, kind); + return Exists(buf) ? buf : NULL; +} + +// Worker side + +static bool FetchTo(const std::string& url, const std::string& path) +{ + if (!Http_GetToFile(url, path)) return false; + struct stat st; + // A few hundred bytes is an error page or a blank placeholder, not art. + if (stat(path.c_str(), &st) != 0 || st.st_size < 1000) { remove(path.c_str()); return false; } + return true; +} + +// Writes the icon unless one showed up while we were downloading. +static bool PlaceIcon(const ArtJob& j, const std::string& src) +{ + std::string jpg = j.iconDir + "/" + j.titleID + ".jpg"; + std::string png = j.iconDir + "/" + j.titleID + ".png"; + if (Exists(jpg) || Exists(png)) return false; + Plat_MkdirP(j.iconDir.c_str()); + std::string tmp = j.artDir + "/" + j.titleID + ".icon.jpg"; + if (!Icons_FitFile(src.c_str(), tmp.c_str(), kIconDim, 90)) return false; + if (Exists(jpg) || Exists(png)) { remove(tmp.c_str()); return false; } + return Host_RenameReplace(tmp.c_str(), jpg.c_str()); +} + +static bool FromSteam(const ArtJob& j) +{ + std::string base = "https://cdn.akamai.steamstatic.com/steam/apps/" + std::to_string(j.appid) + "/"; + std::string cover = j.artDir + "/" + j.titleID + ".cover.jpg"; + std::string header = j.artDir + "/" + j.titleID + ".header.jpg"; + if (!Exists(cover)) FetchTo(base + "library_600x900.jpg", cover); + if (!Exists(header)) FetchTo(base + "header.jpg", header); + if (!j.wantIcon) return false; + if (Exists(cover) && PlaceIcon(j, cover)) return true; + if (Exists(header) && PlaceIcon(j, header)) return true; + return false; +} + +static bool FromLibretro(const ArtJob& j) +{ + std::string repo = j.system; + for (char& c : repo) if (c == ' ') c = '_'; + std::string base = "https://raw.githubusercontent.com/libretro-thumbnails/" + UrlEncode(repo) + + "/master/Named_Boxarts/"; + + // The rom's own file name is usually the No-Intro name libretro keys on. + // A scraped display name without the region tag gets a couple of guesses. + std::vector names; + auto add = [&](const std::string& n) { + if (n.empty()) return; + for (size_t i = 0; i < names.size(); i++) if (names[i] == n) return; + names.push_back(n); + }; + add(j.romStem); + add(j.name); + if (j.name.find('(') == std::string::npos) { add(j.name + " (USA)"); add(j.name + " (World)"); } + + std::string tmp = j.artDir + "/" + j.titleID + ".cover.png"; + for (size_t i = 0; i < names.size(); i++) { + if (!FetchTo(base + UrlEncode(LibretroName(names[i])) + ".png", tmp)) continue; + 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; + } + return false; +} + +// SteamGridDB: square grids first, they suit the orb. Never webp, stb can't read it. +static bool FromSteamGridDb(const ArtJob& j) +{ + HttpHeaders auth = { { "Authorization", "Bearer " + j.sgdbKey } }; + const std::string api = "https://www.steamgriddb.com/api/v2/"; + std::string grids; + if (j.appid > 0) { + grids = api + "grids/steam/" + std::to_string(j.appid); + } else { + HttpResponse r = Http_Get(api + "search/autocomplete/" + UrlEncode(j.name), auth); + if (!r.ok()) return false; + int id = Json_GetInt(r.body, "id"); + if (id <= 0) return false; + grids = api + "grids/game/" + std::to_string(id); + } + const char* shapes[] = { "?dimensions=512x512,1024x1024&mimes=image/png,image/jpeg", + "?mimes=image/png,image/jpeg" }; + for (int s = 0; s < 2; s++) { + HttpResponse r = Http_Get(grids + shapes[s], auth); + if (!r.ok()) return false; + std::string url = Json_GetString(r.body, "url"); + if (url.empty()) continue; + std::string tmp = j.artDir + "/" + j.titleID + ".sgdb"; + if (!FetchTo(url, tmp)) return false; + bool placed = PlaceIcon(j, tmp); + remove(tmp.c_str()); + return placed; + } + return false; +} + +static void Worker() +{ + for (;;) { + ArtJob j; + { + std::lock_guard lk(s_q.mtx); + if (s_q.jobs.empty()) { s_q.workers--; return; } + j = s_q.jobs.front(); + s_q.jobs.pop_front(); + } + Plat_MkdirP(j.artDir.c_str()); + bool got = false; + if (j.appid > 0) got = FromSteam(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()); + + bool miss = (j.wantIcon && !got) || + (j.wantBig && !Exists(j.artDir + "/" + j.titleID + ".cover.jpg")); + std::lock_guard lk(s_q.mtx); + s_q.done.push_back({ j.titleID, got, miss, j.trySgdb }); + } +} + +// Main thread side + +static void LoadMisses() +{ + s_missesLoaded = true; + FILE* f = fopen(MissFile().c_str(), "r"); + if (!f) return; + char line[256]; + while (fgets(line, sizeof(line), f)) { + char id[128]; + unsigned sg = 0; + if (sscanf(line, "%127s %u", id, &sg) >= 1) s_misses[id] = sg; + } + fclose(f); +} + +static void SaveMisses() +{ + Plat_MkdirP(ArtDir().c_str()); + SafeSave save(MissFile().c_str()); + if (!save.f) return; + for (std::map::iterator it = s_misses.begin(); it != s_misses.end(); ++it) + fprintf(save.f, "%s %u\n", it->first.c_str(), it->second); + save.Commit(); +} + +static int SteamAppId(const char* launch) +{ + const char* p = NULL; + if (strncmp(launch, "steam://rungameid/", 18) == 0) p = launch + 18; + else if (strncmp(launch, "steam://run/", 12) == 0) p = launch + 12; + else if ((p = strstr(launch, "steam://rungameid/")) != NULL) p += 18; + if (!p) return 0; + long id = strtol(p, NULL, 10); + // Non-Steam shortcuts carry 64 bit ids that the CDN has nothing for. + return (id > 0 && id < 0x7fffffff) ? (int)id : 0; +} + +// Pulls a rom path out of a launch line: RetroArch's url, else the last +// quoted or bare token with an extension we know. +static void RomFromLaunch(const char* launch, std::string& rom, std::string& core) +{ + rom.clear(); + core.clear(); + if (strncmp(launch, "retroarch://", 12) == 0) { + std::string s = launch; + size_t c = s.find("core="); + if (c != std::string::npos) core = UrlDecode(s.substr(c + 5, s.find('&', c) - (c + 5))); + size_t r = s.find("content="); + if (r != std::string::npos) rom = UrlDecode(s.substr(r + 8, s.find('&', r) - (r + 8))); + return; + } + std::string s = launch; + std::vector toks; + for (size_t i = 0; i < s.size();) { + if (s[i] == '"') { + size_t e = s.find('"', i + 1); + if (e == std::string::npos) e = s.size(); + toks.push_back(s.substr(i + 1, e - i - 1)); + i = e + 1; + } else if (s[i] == ' ') { + i++; + } else { + size_t e = s.find(' ', i); + if (e == std::string::npos) e = s.size(); + toks.push_back(s.substr(i, e - i)); + i = e; + } + } + for (size_t i = toks.size(); i-- > 0;) { + std::string stem, ext; + SplitRom(toks[i], stem, ext); + if (!ext.empty() && SystemForExt(ext.c_str())) { rom = toks[i]; return; } + } +} + +static void Queue(const ArtJob& j) +{ + std::lock_guard lk(s_q.mtx); + s_q.jobs.push_back(j); + if (s_q.workers < kWorkers) { + s_q.workers++; + std::thread(Worker).detach(); + } +} + +static void Scan() +{ + if (!s_missesLoaded) LoadMisses(); + std::string iconDir = VGAMES_ICONS, artDir = ArtDir(); + bool haveKey = g_steamGridDbKey[0] != 0; + int queued = 0; + + for (int i = 0; i < g_vgames.count; i++) { + const VirtualGame& g = g_vgames.games[i]; + if (!g.valid || VGames_IsStreaming(g)) continue; + // The copy that shows already has a source of its own. + if (g_hideDuplicateGames && (VGames_FindDuplicates(), g.duplicate)) continue; + if (!Http_IsSafeFileId(g.titleID) || s_seen.count(g.titleID)) continue; + + ArtJob j; + j.titleID = g.titleID; + j.name = g.name; + j.appid = SteamAppId(g.launch); + j.wantIcon = !VGames_GetIconPath(i); + j.wantBig = j.appid > 0 && !GameArt_CachedPath(g.titleID, "cover"); + if (!j.wantIcon && !j.wantBig) continue; + + std::map::iterator miss = s_misses.find(j.titleID); + bool missed = miss != s_misses.end(); + // A miss stays a miss until there's somewhere new to look. + if (missed && !(haveKey && miss->second != KeyTag(g_steamGridDbKey))) continue; + + if (j.appid == 0) { + 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); + 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()); + const char* lr = LibretroSystem(sys.c_str()); + if (lr && !missed) { j.system = lr; j.romStem = stem; } + } + j.trySgdb = haveKey && j.wantIcon; + if (!j.wantBig && j.system.empty() && !j.trySgdb) continue; + + j.iconDir = iconDir; + j.artDir = artDir; + j.sgdbKey = g_steamGridDbKey; + s_seen.insert(j.titleID); + Queue(j); + queued++; + } + if (queued) fprintf(stderr, "[art] looking for art for %d games\n", queued); +} + +void GameArt_Tick() +{ + static unsigned s_gen = ~0u; + static std::string s_key; + static std::chrono::steady_clock::time_point s_lastScan; + + std::vector done; + { + std::lock_guard lk(s_q.mtx); + done.swap(s_q.done); + } + bool gotAny = false, missesChanged = false; + for (size_t i = 0; i < done.size(); i++) { + gotAny |= done[i].gotIcon; + if (!done[i].miss) { + missesChanged |= s_misses.erase(done[i].titleID) > 0; + } else { + s_misses[done[i].titleID] = done[i].triedSgdb ? KeyTag(s_key.c_str()) : 0; + missesChanged = true; + } + } + if (missesChanged) SaveMisses(); + if (gotAny) { + // The memory grid's icon list is built once; have it look again. + extern bool s_iconsLoaded; + s_iconsLoaded = false; + } + + if (!g_fetchGameArt) return; + // A new key is somewhere new to look for everything that missed. + if (s_key != g_steamGridDbKey) { + s_key = g_steamGridDbKey; + s_seen.clear(); + s_gen = ~0u; + } + if (s_gen == g_vgames.generation) return; + // Imports bump the generation many times in a row; let them settle. + std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); + if (now - s_lastScan < std::chrono::seconds(2)) return; + s_lastScan = now; + s_gen = g_vgames.generation; + Scan(); +} diff --git a/theseus/desktop/game_art.h b/theseus/desktop/game_art.h new file mode 100644 index 0000000..72be37e --- /dev/null +++ b/theseus/desktop/game_art.h @@ -0,0 +1,17 @@ +// game_art.h: fetches box art for games that have no icon yet (game_art.cpp). +#pragma once + +// What an importer knows that games.ini doesn't: the ES-DE system short name +// ("snes") and the rom path. Main thread only. +void GameArt_Hint(const char* titleID, const char* system, const char* romPath); + +// 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(); + +// Host path of the bigger cached art for a title, or NULL. kind is "cover" +// (portrait box/capsule) or "header" (wide banner). +const char* GameArt_CachedPath(const char* titleID, const char* kind); + +extern bool g_fetchGameArt; // desktop.ini FetchGameArt +extern char g_steamGridDbKey[128]; // desktop.ini SteamGridDBKey, the user's own diff --git a/theseus/desktop/guide.cpp b/theseus/desktop/guide.cpp index c0a5971..3119c95 100644 --- a/theseus/desktop/guide.cpp +++ b/theseus/desktop/guide.cpp @@ -228,6 +228,8 @@ static const char* SettingHelp(const SettingDef& d) { "ShowAlbumCover", "Show album art in the orb when a soundtrack has it." }, { "CRT_Enabled", "Old TV look over the whole dashboard." }, { "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." }, }; for (size_t i = 0; i < sizeof(kHelp) / sizeof(kHelp[0]); i++) if (strcmp(kHelp[i].key, d.key) == 0) return kHelp[i].help; @@ -248,7 +250,10 @@ 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_SHORTCUTS, GV_ABOUT, GV_TOOLS, GV_EXIT, GV_WELCOME, GV_GAMES, GV_GAME, GV_LETTERS }; + +// What a game list shows. +enum GameList { GL_FAVORITES, GL_RECENT, GL_HIDDEN, GL_ALL, GL_LETTER, GL_SEARCH }; static const View kSectionViews[SEC_COUNT] = { GV_PAGE, GV_ACCOUNTS, GV_LIBRARY, GV_LOGS, GV_SHORTCUTS, GV_ABOUT, GV_TOOLS, GV_EXIT, @@ -262,6 +267,7 @@ enum Act { GA_BROWSEUP, GA_BROWSE, GA_PLAYLIST, 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_COUNT }; @@ -305,7 +311,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 }; +enum EditTarget { ED_SETTING, ED_NAME, ED_JELLYFIN, ED_SEARCH }; struct Editor { bool on, secret, shift, symbols; @@ -335,6 +341,10 @@ static struct Guide { std::vector entries; bool browseStale; int category, playlist; + int gameList, game; + char letter; // GL_LETTER's initial, '#' for digits and the rest + std::string search; // GL_SEARCH's text + unsigned gameLayout; // g_vgames.layout when game was picked std::vector targets; int promptButtons[6]; @@ -349,6 +359,63 @@ static void Add(const char* label, const char* value, const char* help, int act g.rows.push_back(r); } +// What a name files under: A to Z, everything else is '#'. +static char Initial(const char* name) +{ + char c = (char)toupper((unsigned char)name[0]); + return (c >= 'A' && c <= 'Z') ? c : '#'; +} + +// Case blind, so "halo" finds "Halo 2". +static bool NameHas(const char* name, const std::string& part) +{ + size_t n = strlen(name); + for (size_t i = 0; i + part.size() <= n; i++) { + size_t k = 0; + while (k < part.size() && tolower((unsigned char)name[i + k]) == tolower((unsigned char)part[k])) k++; + if (k == part.size()) return true; + } + return false; +} + +// The rows of one game list, as DB indices. +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; } + VGames_Load(); + for (int i = 0; i < g_vgames.count; i++) { + const VirtualGame& vg = g_vgames.games[i]; + if (list == GL_HIDDEN ? !(vg.valid && vg.hidden) : !VGames_IsShown(vg)) continue; + if (list == GL_LETTER && Initial(vg.name) != g.letter) continue; + if (list == GL_SEARCH && !NameHas(vg.name, g.search)) continue; + out.push_back(i); + } + std::sort(out.begin(), out.end(), [](int a, int b) { + return strcasecmp(g_vgames.games[a].name, g_vgames.games[b].name) < 0; + }); +} + +static std::string PlayedOn(long long t) +{ + if (!t) return "Never"; + time_t tt = (time_t)t; + char buf[32]; + strftime(buf, sizeof(buf), "%b %d, %H:%M", localtime(&tt)); + return buf; +} + +// The picked game, or NULL once the DB has moved rows around under us. +static VirtualGame* PickedGame() +{ + if (g.gameLayout != g_vgames.layout || g.game < 0 || g.game >= g_vgames.count) return NULL; + VirtualGame* vg = &g_vgames.games[g.game]; + return vg->valid ? vg : NULL; +} + +static const char* kGameListNames[] = { "Favorites", "Recently Played", "Hidden Games", "All Games", "", "" }; + static void Build() { g.rows.clear(); @@ -396,11 +463,25 @@ static void Build() break; } case GV_LIBRARY: { + 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); 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.", + }; + 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); + } snprintf(n, sizeof(n), "%d", Playlist_Count()); Add("Playlists", n, "Made in the Playlist Maker.", GA_VIEW, GV_PLAYLISTS); break; @@ -423,6 +504,49 @@ static void Build() for (size_t i = 0; i < g.entries.size(); i++) Add(g.entries[i].name.c_str(), g.entries[i].dir ? "Folder" : "", g.browseDir.c_str(), GA_BROWSE, (int)i); break; + case GV_GAMES: { + std::vector list; + GameListRows(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); + 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); + break; + } + case GV_LETTERS: { + // Only letters something starts with, so every row leads somewhere. + int counts[27] = {}; + std::vector all; + GameListRows(GL_ALL, all); + for (size_t i = 0; i < all.size(); i++) { + char c = Initial(g_vgames.games[all[i]].name); + counts[c == '#' ? 26 : c - 'A']++; + } + for (int k = 0; k < 27; k++) { + if (!counts[k]) continue; + char label[2] = { k == 26 ? '#' : (char)('A' + k), 0 }; + char n[16]; + 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."); + break; + } + case GV_GAME: { + VirtualGame* vg = PickedGame(); + if (!vg) { Add("This game moved", "", "Go back and pick it again."); break; } + Add("Launch", "", vg->launch, GA_LAUNCH); + 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); + std::string where = vg->group[0] ? std::string(vg->category) + "/" + vg->group : std::string(vg->category); + Add("Category", where.c_str(), NULL); + break; + } case GV_PLAYLISTS: for (int i = 0; i < Playlist_Count(); i++) { const Playlist* pl = Playlist_Get(i); @@ -537,6 +661,18 @@ static const char* ViewTitle() case GV_ADDGAME: return "Add a Game"; case GV_BROWSE: return "Choose a File"; case GV_PLAYLISTS: return "Playlists"; + case GV_LETTERS: return "Find a Game"; + case GV_GAMES: { + static char title[32]; + 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; + } + case GV_GAME: { + VirtualGame* vg = PickedGame(); + return vg ? vg->name : "Game"; + } case GV_PLAYLIST: { const Playlist* pl = Playlist_Get(g.playlist); return pl ? pl->name.c_str() : "Playlist"; @@ -711,8 +847,16 @@ static void EditDone() case ED_JELLYFIN: Jellyfin_SetServerUrl(Tidy(e.text, false)); break; + case ED_SEARCH: + g.search = Tidy(e.text, false); + break; } + bool search = e.what == ED_SEARCH && !g.search.empty(); EditClose(); + if (search) { + g.gameList = GL_SEARCH; + Push(GV_GAMES); + } } static void EditInsert(const char* s) @@ -881,6 +1025,9 @@ static void Select() case GA_JELLYFINURL: EditOpen(ED_JELLYFIN, 0, "Jellyfin Server", Jellyfin_GetServerUrl(), 500, false); break; + case GA_SEARCH: + EditOpen(ED_SEARCH, 0, "Search by Name", g.search, 60, false); + break; case GA_PADTOOLS: Close(); g_padModeActive = true; @@ -993,6 +1140,41 @@ static void Select() g.playlist = r.arg; Push(GV_PLAYLIST); break; + case GA_GAMELIST: + g.gameList = r.arg; + Push(GV_GAMES); + break; + case GA_LETTER: + g.gameList = GL_LETTER; + g.letter = (char)r.arg; + Push(GV_GAMES); + break; + case GA_GAME: + g.game = r.arg; + g.gameLayout = g_vgames.layout; + Push(GV_GAME); + break; + case GA_FAVORITE: + case GA_HIDE: { + VirtualGame* vg = PickedGame(); + if (!vg) break; + if (r.act == GA_FAVORITE) VGames_SetFavorite(g.game, !vg->favorite); + else VGames_SetHidden(g.game, !vg->hidden); + Build(); + break; + } + case GA_LAUNCH: { + VirtualGame* vg = PickedGame(); + if (!vg) break; + // The same Xbox-style path the launcher hands over. + char devicePath[512]; + snprintf(devicePath, sizeof(devicePath), "\\Device\\Harddisk0\\Partition1\\%s\\%s", + vg->category[0] ? vg->category : "Games", vg->name); + Close(); + extern void DesktopLaunchTitle(const char* devicePath); + DesktopLaunchTitle(devicePath); + break; + } case GA_OPENLOGS: Host_OpenFolder(Plat_UserDataDir()); break; @@ -1022,8 +1204,29 @@ static void MoveCursor(int step) if (g.cursor >= n) g.cursor = n - 1; } +// In a long game list LB and RB jump to the previous or next letter. +static void LetterStep(int step) +{ + int n = (int)g.rows.size(); + if (n == 0 || g.cursor < 0 || g.cursor >= n || g.rows[g.cursor].act != GA_GAME) return; + char cur = Initial(g.rows[g.cursor].label.c_str()); + int i = g.cursor; + if (step > 0) { + while (i < n && Initial(g.rows[i].label.c_str()) == cur) i++; + if (i >= n) return; + } else { + while (i > 0 && Initial(g.rows[i].label.c_str()) == cur) i--; + char prev = Initial(g.rows[i].label.c_str()); + if (prev == cur) return; + while (i > 0 && Initial(g.rows[i - 1].label.c_str()) == prev) i--; + } + g.cursor = i; + g.scroll = i; +} + static void PageStep(int step) { + if (g.view == GV_GAMES && g.gameList == GL_ALL) { LetterStep(step); return; } if (g.view != GV_PAGE) return; g.page = (g.page + step + kPageCount) % kPageCount; g.cursor = g.scroll = 0; diff --git a/theseus/desktop/icon_compress.cpp b/theseus/desktop/icon_compress.cpp index 4151b72..7de0c4e 100644 --- a/theseus/desktop/icon_compress.cpp +++ b/theseus/desktop/icon_compress.cpp @@ -140,3 +140,43 @@ IconCompressResult Icons_Compress(int maxDim, int quality) } return r; } + +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; } + + // 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; } + 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; + unsigned char* out = rgb; + if (big > maxDim) { + dw = (w * maxDim + big - 1) / big; + dh = (h * maxDim + big - 1) / big; + if (dw < 1) dw = 1; + if (dh < 1) dh = 1; + out = (unsigned char*)malloc((size_t)dw * dh * 3); + if (!out) { free(rgb); return false; } + Downscale(rgb, w, h, out, dw, dh); + } + + char tmp[1024]; + snprintf(tmp, sizeof(tmp), "%s.tmp", dst); + int ok = stbi_write_jpg(tmp, dw, dh, 3, out, quality); + if (out != rgb) free(out); + free(rgb); + if (!ok) { remove(tmp); return false; } + if (!Host_RenameReplace(tmp, dst)) { remove(tmp); return false; } + return true; +} diff --git a/theseus/desktop/icon_compress.h b/theseus/desktop/icon_compress.h index 039be71..cb3cf43 100644 --- a/theseus/desktop/icon_compress.h +++ b/theseus/desktop/icon_compress.h @@ -15,3 +15,7 @@ struct IconCompressResult { // Re-encode Configs/icons to fit maxDim on the long side. Already-small files // are skipped, so a second run costs one decode per new file. 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); diff --git a/theseus/desktop/launch.cpp b/theseus/desktop/launch.cpp index beab0ae..019e29d 100644 --- a/theseus/desktop/launch.cpp +++ b/theseus/desktop/launch.cpp @@ -189,6 +189,7 @@ static void SpawnLaunchSpec(const char* spec) { char finalCmd[2048]; if (!Launch_ExpandAndSpawn(spec, finalCmd, sizeof(finalCmd))) return; + VGames_MarkPlayed(spec); extern SDL_Window* g_pSDLWindow; if (g_pSDLWindow) SDL_MinimizeWindow(g_pSDLWindow); diff --git a/theseus/desktop/sdl_main.cpp b/theseus/desktop/sdl_main.cpp index 7d3f486..ab23459 100644 --- a/theseus/desktop/sdl_main.cpp +++ b/theseus/desktop/sdl_main.cpp @@ -1817,6 +1817,8 @@ int main(int argc, char* argv[]) { // Drive the xCloud->VGDB injection state machine (main-thread only). extern void XcloudVGames_Tick(); XcloudVGames_Tick(); + extern void GameArt_Tick(); + GameArt_Tick(); Frame_PhaseEnd(FP_TICKS); // bgfx owns presentation; its backend layer is the visible surface. diff --git a/theseus/desktop/virtual_games.h b/theseus/desktop/virtual_games.h index 6573285..ea90ca3 100644 --- a/theseus/desktop/virtual_games.h +++ b/theseus/desktop/virtual_games.h @@ -10,6 +10,11 @@ #include #include #include +#include +#include +#include +#include +#include #include "xboxfs_drive.h" #include "safe_save.h" @@ -34,6 +39,12 @@ struct VirtualGame { // as long as the app does, same deal as the streaming entries. bool transient; bool valid; + // Yours, kept in games.ini (live rows keep theirs in games_live.ini). + bool favorite; + bool hidden; + long long lastPlayed; // unix time of the last launch that started, 0 for never + // Another source has the same game and wins (VGames_FindDuplicates). + bool duplicate; }; struct VirtualGameDB { @@ -107,6 +118,12 @@ inline void VGames_Load() { strncpy(cur->category, val, sizeof(cur->category) - 1); else if (strcmp(key, "Group") == 0) strncpy(cur->group, val, sizeof(cur->group) - 1); + else if (strcmp(key, "Favorite") == 0) + cur->favorite = atoi(val) != 0; + else if (strcmp(key, "Hidden") == 0) + cur->hidden = atoi(val) != 0; + else if (strcmp(key, "LastPlayed") == 0) + cur->lastPlayed = atoll(val); } fclose(fp); g_vgames.generation++; @@ -172,6 +189,9 @@ inline void VGames_Save() { // Only written when set, so a library with no folders reads back // byte for byte the way it always did. if (g.group[0]) fprintf(fp, "Group=%s\n", g.group); + if (g.favorite) fprintf(fp, "Favorite=1\n"); + if (g.hidden) fprintf(fp, "Hidden=1\n"); + if (g.lastPlayed) fprintf(fp, "LastPlayed=%lld\n", g.lastPlayed); fprintf(fp, "\n"); } save.Commit(); @@ -366,3 +386,209 @@ inline int VGames_MakeShortcutContent(int idx, char* buf, int bufSize) { "[Title]\nName=%s\nTitleID=%s\nLaunch=%s\n", g.name, g.titleID, g.launch); } + +// 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; }; +#define VGAMES_LIVE_INI AppPath("Configs/games_live.ini") + +inline std::map& VGames_LiveMarks() { + static std::map s_marks; + static bool s_loaded = false; + if (s_loaded) return s_marks; + s_loaded = true; + FILE* fp = fopen(VGAMES_LIVE_INI, "r"); + if (!fp) return s_marks; + char line[512]; + VGameMarks* cur = NULL; + while (fgets(line, sizeof(line), fp)) { + line[strcspn(line, "\r\n")] = 0; + if (line[0] == '[') { + char* end = strrchr(line, ']'); + if (!end) { cur = NULL; continue; } + *end = 0; + VGameMarks blank = { false, false, 0 }; + cur = &(s_marks[line + 1] = blank); + continue; + } + char* eq = strchr(line, '='); + if (!cur || !eq) continue; + *eq = 0; + if (strcmp(line, "Favorite") == 0) cur->favorite = atoi(eq + 1) != 0; + else if (strcmp(line, "Hidden") == 0) cur->hidden = atoi(eq + 1) != 0; + else if (strcmp(line, "LastPlayed") == 0) cur->lastPlayed = atoll(eq + 1); + } + fclose(fp); + return s_marks; +} + +inline void VGames_SaveLiveMarks() { + Plat_MkdirP(AppPath_Tree("Configs")); + SafeSave save(VGAMES_LIVE_INI); + if (!save.f) return; + 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) 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); + fprintf(save.f, "\n"); + } + save.Commit(); +} + +// Importers call this right after injecting a live row. +inline void VGames_ApplyLiveMarks(int idx) { + if (idx < 0 || idx >= g_vgames.count) return; + VirtualGame& g = g_vgames.games[idx]; + std::map& m = VGames_LiveMarks(); + std::map::iterator it = m.find(g.titleID); + if (it == m.end()) return; + g.favorite = it->second.favorite; + g.hidden = it->second.hidden; + g.lastPlayed = it->second.lastPlayed; +} + +// Writes the row's marks wherever that row lives. +inline void VGames_StoreMarks(int idx) { + if (idx < 0 || idx >= g_vgames.count) return; + VirtualGame& g = g_vgames.games[idx]; + g_vgames.generation++; + if (!VGames_IsLive(g)) { VGames_Save(); return; } + VGameMarks k = { g.favorite, g.hidden, g.lastPlayed }; + VGames_LiveMarks()[g.titleID] = k; + VGames_SaveLiveMarks(); +} + +inline void VGames_SetFavorite(int idx, bool on) { + if (idx < 0 || idx >= g_vgames.count || g_vgames.games[idx].favorite == on) return; + g_vgames.games[idx].favorite = on; + VGames_StoreMarks(idx); +} + +inline void VGames_SetHidden(int idx, bool on) { + if (idx < 0 || idx >= g_vgames.count || g_vgames.games[idx].hidden == on) return; + g_vgames.games[idx].hidden = on; + VGames_StoreMarks(idx); +} + +// The launcher calls this once a launch has actually started. Matches on the +// launch line, since that's all the spawn knows. +inline void VGames_MarkPlayed(const char* launch) { + if (!launch || !*launch) return; + VGames_Load(); + long long now = (long long)time(NULL); + for (int i = 0; i < g_vgames.count; i++) { + VirtualGame& g = g_vgames.games[i]; + if (!g.valid || strcmp(g.launch, launch) != 0) continue; + g.lastPlayed = now; + VGames_StoreMarks(i); + } +} + +// The two lists the launcher builds from marks instead of a category. +#define VGAMES_FAVORITES "Favorites" +#define VGAMES_RECENT "Recently Played" +#define VGAMES_RECENT_MAX 20 + +extern bool g_hideDuplicateGames; // desktop.ini HideDuplicateGames + +// Which copy of a game wins when sources overlap: Steam, then anything you +// added yourself, then ES-DE. Streaming rows are a different way to play, so +// they never count. +inline int VGames_SourceRank(const VirtualGame& g) { + if (g.transient) return 2; + return strncmp(g.launch, "steam://", 8) == 0 ? 0 : 1; +} + +// "The Legend of Zelda: A Link to the Past (USA)" and "Legend of Zelda, The - +// A Link to the Past" both come out "legendofzeldaalinktopast". +inline std::string VGames_MatchName(const char* name) { + std::string out, word; + int depth = 0; + for (const char* p = name;; p++) { + unsigned char c = (unsigned char)*p; + if (c == '(' || c == '[') { depth++; continue; } + if ((c == ')' || c == ']') && depth > 0) { depth--; continue; } + if (depth > 0 && c) continue; + if (c && c < 0x80 && isalnum(c)) { word += (char)tolower(c); continue; } + // Accented letters and trademark signs drop out with the punctuation. + if (c >= 0x80) continue; + if (!word.empty() && word != "the") out += word; + word.clear(); + if (!c) break; + } + return out; +} + +// Marks the losing copies. Cheap to call, it only redoes the work when the DB changed. +inline void VGames_FindDuplicates() { + static unsigned s_gen = ~0u; + if (s_gen == g_vgames.generation) return; + s_gen = g_vgames.generation; + std::map best; + std::vector keys((size_t)g_vgames.count * 2); + for (int i = 0; i < g_vgames.count; i++) { + VirtualGame& g = g_vgames.games[i]; + g.duplicate = false; + if (!g.valid || VGames_IsStreaming(g)) continue; + const char* steam = strstr(g.launch, "steam://rungameid/"); + if (steam) keys[i * 2] = std::string("steam:") + std::to_string(atoll(steam + 18)); + std::string n = VGames_MatchName(g.name); + if (!n.empty()) keys[i * 2 + 1] = "name:" + n; + int rank = VGames_SourceRank(g); + for (int k = 0; k < 2; k++) { + const std::string& key = keys[i * 2 + k]; + if (key.empty()) continue; + std::map::iterator it = best.find(key); + if (it == best.end() || rank < it->second) best[key] = rank; + } + } + // Only a better source hides a row. Two copies from the same place are + // probably on purpose (two regions, two versions) and both stay. + for (int i = 0; i < g_vgames.count; i++) { + VirtualGame& g = g_vgames.games[i]; + if (!g.valid || VGames_IsStreaming(g)) continue; + int rank = VGames_SourceRank(g); + for (int k = 0; k < 2; k++) { + const std::string& key = keys[i * 2 + k]; + if (!key.empty() && best[key] < rank) g.duplicate = true; + } + } +} + +// What the launcher lists. Hidden rows stay in the DB, just out of sight. +inline bool VGames_IsShown(const VirtualGame& g) { + if (!g.valid || g.hidden) return false; + if (!g_hideDuplicateGames) return true; + VGames_FindDuplicates(); + return !g.duplicate; +} + +inline bool VGames_IsMarkList(const char* category) { + return category && (strcasecmp(category, VGAMES_FAVORITES) == 0 || strcasecmp(category, VGAMES_RECENT) == 0); +} + +// Favorites 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; + 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) { + std::sort(out.begin(), out.end(), [](int a, int b) { + return g_vgames.games[a].lastPlayed > g_vgames.games[b].lastPlayed; + }); + if ((int)out.size() > VGAMES_RECENT_MAX) out.resize(VGAMES_RECENT_MAX); + } else { + std::sort(out.begin(), out.end(), [](int a, int b) { + return strcasecmp(g_vgames.games[a].name, g_vgames.games[b].name) < 0; + }); + } +} diff --git a/theseus/desktop/xcloud_vgames.cpp b/theseus/desktop/xcloud_vgames.cpp index 56fd1b1..c4886bb 100644 --- a/theseus/desktop/xcloud_vgames.cpp +++ b/theseus/desktop/xcloud_vgames.cpp @@ -42,8 +42,9 @@ static void Inject() // The id doubles as the icon filename, so it has to be a safe one. if (!g.playable || !Http_IsSafeFileId(g.titleId)) continue; std::string launch = "xcloud://" + g.titleId; - if (VGames_Add(g.name.c_str(), g.titleId.c_str(), launch.c_str(), "E", "Cloud Gaming") < 0) - break; // DB full + int idx = VGames_Add(g.name.c_str(), g.titleId.c_str(), launch.c_str(), "E", "Cloud Gaming"); + if (idx < 0) break; // DB full + VGames_ApplyLiveMarks(idx); Xcloud_QueueArtDownload(g.titleId, g.artUrl); nGames++; } diff --git a/xips-source/default-desktop/harddrive.xap b/xips-source/default-desktop/harddrive.xap index 2008f8e..09376f3 100644 --- a/xips-source/default-desktop/harddrive.xap +++ b/xips-source/default-desktop/harddrive.xap @@ -331,6 +331,20 @@ function LoadMenuItems() TotalSections = 0; arrMenuNames = new Array; arrMenuPaths = new Array; + // Built from what you've played and starred, so like ES-DE they show up + // only once there's something in them. + if(theGamesCollection.CountInCategory("Recently Played") > 0) + { + arrMenuNames[TotalSections] = "Recently Played"; + arrMenuPaths[TotalSections] = "Recently Played"; + TotalSections = TotalSections + 1; + } + if(theGamesCollection.CountInCategory("Favorites") > 0) + { + arrMenuNames[TotalSections] = "Favorites"; + arrMenuPaths[TotalSections] = "Favorites"; + TotalSections = TotalSections + 1; + } for (var x = 0; x < 5; x = x + 1) { c.theMenuButtons.children[x].visible = false; @@ -774,6 +788,12 @@ DEF theLauncher Level UpdateTrackList(); return; } + // These lists mix categories, so there's no folder path to build. + if((CurFillDir == "Recently Played") | (CurFillDir == "Favorites")) + { + theGamesCollection.LaunchTitle(nPlayCursor0); + return; + } LaunchItem(CurFillDir,TempTitleList[nPlayCursor0]); } }