Xbox Cloud Gaming app for PS5 Homebrew
C
Tabs for Game Pass, your games and search; library and art caches
Rafael Abud Ferreira5d91330a5937
diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cppindex 3bdbd26..f2efffc 100644--- a/src/app/cli_main.cpp+++ b/src/app/cli_main.cpp@@ -301,15 +301,53 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {app.setProfile(am.profile().gamertag, am.profile().gamerpicUrl);std::string err;app::Library library;- auto onRows = [&](const std::vector<ui::GameRow>& rows) { app.setRows(rows); };+ auto onRows = [&] {+ app.setRows(library.rows());+ app.setOwned(library.owned(), library.ownedKnown());+ app.setSearchPool(library.searchPool());+ };if (!library.load(gssv, ui::catalogLanguage(), onRows, err)) {XC_LOGE("%s", err.c_str());return 1;}library.loadOwned(gssv, onRows);+ library.loadCatalogNames(onRows);library.hydrate(onRows);app.showHome();save("home", 4000);+ {+ // The other tabs: "Your games", then a search typed on the keyboard.+ ui::NavInput r1;+ r1.r1 = true;+ app.handle(r1);+ save("library", 3000);+ ui::NavInput down1;+ down1.down = true;+ app.handle(down1);+ app.handle(down1);+ save("library_scrolled", 1500);+ app.handle(r1);+ auto press = [&](auto set, int times) {+ for (int i = 0; i < times; ++i) {+ ui::NavInput n;+ set(n);+ app.handle(n);+ }+ };+ auto type = [&](char ch) {+ int idx = static_cast<int>(std::string("abcdefghijklmnopqrstuvwxyz0123456789").find(ch));+ press([](ui::NavInput& n) { n.up = true; }, 7);+ press([](ui::NavInput& n) { n.left = true; }, 6);+ press([](ui::NavInput& n) { n.down = true; }, idx / 6);+ press([](ui::NavInput& n) { n.right = true; }, idx % 6);+ press([](ui::NavInput& n) { n.accept = true; }, 1);+ };+ for (char ch : std::string("forza")) type(ch);+ save("search", 3000);+ press([](ui::NavInput& n) { n.right = true; }, 6); // over to the results+ save("search_results", 1500);+ press([](ui::NavInput& n) { n.l1 = true; }, 2); // back to the Game Pass tab+ }ui::NavInput right;right.right = true;for (int i = 0; i < 3; ++i) app.handle(right);diff --git a/src/app/library.cpp b/src/app/library.cppindex 387fbec..87663ee 100644--- a/src/app/library.cpp+++ b/src/app/library.cpp@@ -2,7 +2,9 @@// Copyright (C) 2026 RafaelNGP#include "app/library.h"+#include "platform/platform.h"#include "ui/strings.h"+#include "util/json.h"#include "util/log.h"#include "xcloud/catalog.h"@@ -13,8 +15,49 @@ namespace xc::app {namespace {-ui::GameTile toTile(const xcloud::Product& p, const std::string& titleId) {+constexpr int kCacheVersion = 1;++struct ListSpec {+ const char* sigl;+ size_t limit;+};++json::Value productToJson(const xcloud::Product& p) {+ json::Value v = json::Value::object();+ v.set("xt", p.xcloudTitleId);+ v.set("title", p.title);+ v.set("publisher", p.publisher);+ v.set("description", p.description);+ v.set("tile", p.tileUrl);+ v.set("poster", p.posterUrl);+ v.set("hero", p.heroUrl);+ json::Value cats = json::Value::array();+ for (const auto& c : p.categories) cats.push(c);+ v.set("categories", cats);+ return v;+}++xcloud::Product productFromJson(const std::string& id, const json::Value& v) {+ xcloud::Product p;+ p.productId = id;+ p.xcloudTitleId = v["xt"].str();+ p.title = v["title"].str();+ p.publisher = v["publisher"].str();+ p.description = v["description"].str();+ p.tileUrl = v["tile"].str();+ p.posterUrl = v["poster"].str();+ p.heroUrl = v["hero"].str();+ for (const auto& c : v["categories"].items()) p.categories.push_back(c.str());+ return p;+}++} // namespace++ui::GameTile Library::tile(const std::string& productId, const std::string& titleId) const {ui::GameTile t;+ auto it = products_.find(productId);+ if (it == products_.end()) return t;+ const xcloud::Product& p = it->second;t.productId = p.productId;t.titleId = titleId.empty() ? p.xcloudTitleId : titleId;t.name = p.title;@@ -23,16 +66,10 @@ ui::GameTile toTile(const xcloud::Product& p, const std::string& titleId) {t.tileUrl = p.tileUrl.empty() ? p.posterUrl : p.tileUrl;t.heroUrl = p.heroUrl;t.categories = p.categories;+ if (ownershipKnown_) t.playable = ownedTitles_.count(t.titleId) || ownedProducts_.count(t.productId);return t;}-struct ListSpec {- const char* sigl;- size_t limit;-};--} // namespace-std::vector<ui::GameRow> Library::rows() const {std::vector<ui::GameRow> rows;for (const auto& r : layout_) {@@ -40,51 +77,169 @@ std::vector<ui::GameRow> Library::rows() const {row.title = r.title;row.gamePassBadges = r.badges;for (const auto& [pid, tid] : r.items) {- auto it = products_.find(pid);- if (it == products_.end()) continue;- if (tid.empty() && it->second.xcloudTitleId.empty()) continue;- ui::GameTile tile = toTile(it->second, tid);- if (ownershipKnown_)- tile.playable = ownedTitles_.count(tile.titleId) || ownedProducts_.count(tile.productId);- row.tiles.push_back(std::move(tile));+ ui::GameTile t = tile(pid, tid);+ if (t.productId.empty() || t.titleId.empty()) continue;+ row.tiles.push_back(std::move(t));}if (!row.tiles.empty()) rows.push_back(std::move(row));}return rows;}-bool Library::load(xcloud::GssvClient& gssv, const std::string& language, const RowsCallback& onRows,- std::string& err) {+namespace {++// Editions of one game ("Forza Horizon 5", "... Standard Edition") are+// separate products that start the same cloud title: keep one, the shortest+// name, where the first one was.+void dedupeByTitle(std::vector<ui::GameTile>& tiles) {+ std::map<std::string, size_t> first;+ std::vector<ui::GameTile> out;+ for (auto& t : tiles) {+ auto it = first.find(t.titleId);+ if (it == first.end()) {+ first[t.titleId] = out.size();+ out.push_back(std::move(t));+ } else if (t.name.size() < out[it->second].name.size()) {+ out[it->second] = std::move(t);+ }+ }+ tiles = std::move(out);+}++} // namespace++std::vector<ui::GameTile> Library::owned() const {+ std::vector<ui::GameTile> out;+ for (const auto& [pid, tid] : owned_) {+ ui::GameTile t = tile(pid, tid);+ if (!t.productId.empty() && !t.titleId.empty()) out.push_back(std::move(t));+ }+ dedupeByTitle(out);+ return out;+}++std::vector<ui::GameTile> Library::searchPool() const {+ std::vector<ui::GameTile> out;+ std::set<std::string> seen;+ auto add = [&](const std::string& pid, const std::string& tid) {+ if (!seen.insert(pid).second) return;+ ui::GameTile t = tile(pid, tid);+ if (!t.productId.empty() && !t.titleId.empty() && !t.name.empty()) out.push_back(std::move(t));+ };+ for (const auto& [pid, tid] : owned_) add(pid, tid);+ for (const auto& id : allGames_) add(id, std::string());+ dedupeByTitle(out);+ return out;+}++void Library::sortOwned() {+ // Recently played first (newest first), then alphabetical.+ auto rank = [&](const std::string& pid) {+ auto it = std::find(recent_.begin(), recent_.end(), pid);+ return it == recent_.end() ? recent_.size() : static_cast<size_t>(it - recent_.begin());+ };+ auto name = [&](const std::string& pid) {+ auto it = products_.find(pid);+ return it == products_.end() ? std::string() : it->second.title;+ };+ std::stable_sort(owned_.begin(), owned_.end(), [&](const auto& a, const auto& b) {+ size_t ra = rank(a.first), rb = rank(b.first);+ if (ra != rb) return ra < rb;+ return name(a.first) < name(b.first);+ });+}++bool Library::loadCache() {+ std::string text;+ if (cachePath_.empty() || !platform::readFile(cachePath_, text)) return false;+ auto j = json::parse(text);+ if (!j || (*j)["version"].asInt() != kCacheVersion || (*j)["market"].str() != market_ ||+ (*j)["language"].str() != language_)+ return false;+ for (const auto& [id, v] : (*j)["products"].members())+ if (!products_.count(id)) products_[id] = productFromJson(id, v);+ for (const auto& t : (*j)["ownedTitles"].items()) ownedTitles_.insert(t.str());+ for (const auto& p : (*j)["ownedProducts"].items()) ownedProducts_.insert(p.str());+ owned_.clear();+ for (const auto& o : (*j)["owned"].items())+ if (products_.count(o["p"].str())) owned_.emplace_back(o["p"].str(), o["t"].str());+ ownershipKnown_ = !ownedTitles_.empty();+ sortOwned();+ XC_LOGI("library: cache: %zu of the account's games, %zu titles playable", owned_.size(), ownedTitles_.size());+ return ownershipKnown_;+}++void Library::saveCache() const {+ if (cachePath_.empty()) return;+ json::Value root = json::Value::object();+ root.set("version", kCacheVersion);+ root.set("market", market_);+ root.set("language", language_);+ json::Value titles = json::Value::array(), prods = json::Value::array(), owned = json::Value::array();+ for (const auto& t : ownedTitles_) titles.push(t);+ for (const auto& p : ownedProducts_) prods.push(p);+ json::Value details = json::Value::object();+ for (const auto& [pid, tid] : owned_) {+ json::Value o = json::Value::object();+ o.set("p", pid);+ o.set("t", tid);+ owned.push(o);+ auto it = products_.find(pid);+ if (it != products_.end()) details.set(pid, productToJson(it->second));+ }+ root.set("ownedTitles", titles);+ root.set("ownedProducts", prods);+ root.set("owned", owned);+ root.set("products", details);+ if (!platform::writeFileAtomic(cachePath_, root.dump())) XC_LOGW("library: could not write %s", cachePath_.c_str());+}++bool Library::load(xcloud::GssvClient& gssv, const std::string& language, const Changed& changed, std::string& err) {market_ = gssv.session().market.empty() ? "US" : gssv.session().market;language_ = language;layout_.clear();products_.clear();+ allGames_.clear();+ gamePass_.clear();+ recent_.clear();+ ownershipKnown_ = false;+ ownedTitles_.clear();+ ownedProducts_.clear();+ owned_.clear();std::string lastErr;- std::vector<xcloud::Title> recent;- if (gssv.listTitles(recent, lastErr, true)) {- RowIds r{ui::tr(ui::Str::JumpBackIn), false, {}};- std::vector<std::string> ids;- for (const auto& t : recent)- if (!t.productId.empty()) {- r.items.emplace_back(t.productId, t.titleId);- ids.push_back(t.productId);- }- if (xcloud::fetchProducts(ids, market_, language_, products_, lastErr, false)) {- layout_.push_back(std::move(r));- onRows(rows());- }- }-// The Game Pass catalog first: it decides what the other lists may show.xcloud::ProductList all;std::string e;if (xcloud::fetchList(xcloud::sigl::kAllGames, market_, language_, all, e)) {+ allGames_ = all.productIds;gamePass_.insert(all.productIds.begin(), all.productIds.end());} else {XC_LOGW("%s", e.c_str());lastErr = e;}+ // The account's games from the previous run, until loadOwned() refreshes them.+ loadCache();++ // "Jump back in": recently played Game Pass games (the others go first+ // in "Your games").+ std::vector<xcloud::Title> recent;+ if (gssv.listTitles(recent, lastErr, true)) {+ RowIds r{ui::tr(ui::Str::JumpBackIn), false, {}};+ std::vector<std::string> ids;+ for (const auto& t : recent) {+ if (t.productId.empty()) continue;+ recent_.push_back(t.productId);+ if (!gamePass_.empty() && !gamePass_.count(t.productId)) continue;+ r.items.emplace_back(t.productId, t.titleId);+ if (!products_.count(t.productId)) ids.push_back(t.productId);+ }+ sortOwned();+ if (xcloud::fetchProducts(ids, market_, language_, products_, lastErr, false)) {+ layout_.push_back(std::move(r));+ changed();+ }+ }const ListSpec lists[] = {{xcloud::sigl::kRecentlyAdded, 40},{xcloud::sigl::kMostPopular, 40},@@ -121,7 +276,7 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constRowIds r{list.title, true, {}};for (const auto& id : list.productIds) r.items.emplace_back(id, std::string());layout_.push_back(std::move(r));- onRows(rows());+ changed();}if (rows().empty()) {err = lastErr.empty() ? "no games found" : lastErr;@@ -130,20 +285,21 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constreturn true;}-void Library::loadOwned(xcloud::GssvClient gssv, const RowsCallback& onRows, const std::atomic<bool>* stop) {+void Library::loadOwned(xcloud::GssvClient gssv, const Changed& changed, const std::atomic<bool>* stop) {std::vector<xcloud::Title> titles;std::string err;if (!gssv.listTitles(titles, err, false)) {- XC_LOGW("%s", err.c_str()); // rows stay as they are, all playable+ XC_LOGW("%s", err.c_str()); // keep what the cache saidreturn;}if (stop && *stop) return;- std::vector<std::pair<std::string, std::string>> mine; // productId, titleId+ std::set<std::string> ownedTitles, ownedProducts;+ std::vector<std::pair<std::string, std::string>> mine;for (const auto& t : titles) {if (!t.hasEntitlement) continue;- ownedTitles_.insert(t.titleId);+ ownedTitles.insert(t.titleId);if (t.productId.empty()) continue;- ownedProducts_.insert(t.productId);+ ownedProducts.insert(t.productId);if (!gamePass_.count(t.productId)) mine.emplace_back(t.productId, t.titleId);}std::vector<std::string> missing;@@ -152,33 +308,53 @@ void Library::loadOwned(xcloud::GssvClient gssv, const RowsCallback& onRows, conif (!missing.empty() && !xcloud::fetchProducts(missing, market_, language_, products_, err, false))XC_LOGW("%s", err.c_str());if (stop && *stop) return;- // Alphabetical; products the catalog doesn't know have no name or art.+ // Products the catalog doesn't know have no name or art.mine.erase(std::remove_if(mine.begin(), mine.end(), [&](const auto& m) { return !products_.count(m.first); }),mine.end());- std::sort(mine.begin(), mine.end(), [&](const auto& a, const auto& b) {- return products_[a.first].title < products_[b.first].title;- });- RowIds row{ui::tr(ui::Str::YourGames), false, std::move(mine)};- size_t at = 0; // after "Jump back in"- if (!layout_.empty() && !layout_.front().badges) at = 1;- size_t count = row.items.size();- layout_.insert(layout_.begin() + static_cast<long>(at), std::move(row));+ ownedTitles_ = std::move(ownedTitles);+ ownedProducts_ = std::move(ownedProducts);+ owned_ = std::move(mine);ownershipKnown_ = true;- XC_LOGI("library: account can stream %zu titles; %zu outside Game Pass", ownedTitles_.size(), count);- onRows(rows());+ sortOwned();+ saveCache();+ XC_LOGI("library: account can stream %zu titles; %zu outside Game Pass", ownedTitles_.size(), owned_.size());+ changed();+}++void Library::loadCatalogNames(const Changed& changed, const std::atomic<bool>* stop) {+ std::vector<std::string> missing;+ for (const auto& id : allGames_)+ if (!products_.count(id)) missing.push_back(id);+ constexpr size_t kBatch = 100;+ for (size_t i = 0; i < missing.size(); i += kBatch) {+ if (stop && *stop) return;+ std::vector<std::string> batch(missing.begin() + static_cast<long>(i),+ missing.begin() + static_cast<long>(std::min(missing.size(), i + kBatch)));+ std::string e;+ if (!xcloud::fetchProducts(batch, market_, language_, products_, e, false)) {+ XC_LOGW("%s", e.c_str());+ return;+ }+ }+ XC_LOGI("library: search covers %zu games", searchPool().size());+ changed();}-void Library::hydrate(const RowsCallback& onRows, const std::atomic<bool>* stop) {- // Row order, so what is on screen first gets its art first.+void Library::hydrate(const Changed& changed, const std::atomic<bool>* stop) {+ // On-screen order, so what is shown first gets its art first: the rows,+ // then the account's games.std::vector<std::string> order;+ auto want = [&](const std::string& id) {+ auto it = products_.find(id);+ if (it != products_.end() && it->second.heroUrl.empty() &&+ std::find(order.begin(), order.end(), id) == order.end())+ order.push_back(id);+ };for (const auto& r : layout_)- for (const auto& item : r.items) {- auto it = products_.find(item.first);- if (it != products_.end() && it->second.heroUrl.empty() &&- std::find(order.begin(), order.end(), item.first) == order.end())- order.push_back(item.first);- }+ for (const auto& item : r.items) want(item.first);+ for (const auto& item : owned_) want(item.first);// A small first batch: the cards on screen get their hero art quickly.+ bool ownedChanged = false;for (size_t i = 0, n = 6; i < order.size(); i += n, n = 20) {if (stop && *stop) return;std::vector<std::string> batch(order.begin() + static_cast<long>(i),@@ -189,10 +365,14 @@ void Library::hydrate(const RowsCallback& onRows, const std::atomic<bool>* stop)XC_LOGW("%s", e.c_str());return;}- for (auto& [id, p] : full) products_[id] = std::move(p);+ for (auto& [id, p] : full) {+ if (ownedProducts_.count(id)) ownedChanged = true;+ products_[id] = std::move(p);+ }if (stop && *stop) return;- onRows(rows());+ changed();}+ if (ownedChanged) saveCache(); // descriptions and hero art for next timeXC_LOGI("library: %zu rows, %zu products with details", layout_.size(), products_.size());}diff --git a/src/app/library.h b/src/app/library.hindex dfe24f8..992658a 100644--- a/src/app/library.h+++ b/src/app/library.h@@ -1,18 +1,22 @@// SPDX-License-Identifier: GPL-3.0-or-later// Copyright (C) 2026 RafaelNGP-// Builds the home screen rows: "Jump back in" (the account's recently played-// cloud titles), "Your games" (what the account owns outside Game Pass:-// purchases, free-to-play) and the Game Pass lists xbox.com/play shows.+// What the home screen shows, in three tabs://-// The Game Pass rows only hold Game Pass games: xbox.com's "popular" list-// mixes in "stream your own game" titles that must be bought first, and-// those would fail to start.+// - Game Pass: "Jump back in" (recently played Game Pass games) and the Game+// Pass lists xbox.com/play shows. Only Game Pass games: xbox.com's+// "popular" list mixes in "stream your own game" titles that must be+// bought first, and those would fail to start.+// - Your games: what the account can stream outside Game Pass (purchases,+// free-to-play), recently played first, then alphabetical.+// - Search: the Game Pass catalog plus the account's games.//-// Three phases: load() fetches the catalog rows with the light payload (the-// home screen can show right away); loadOwned() then reads the account's-// titles (~12 s for ~2700) and adds "Your games" and the playable flags;-// hydrate() adds hero art and descriptions. The last two can run on their-// own thread, one after the other.+// Phases: load() fetches the catalog rows with the light payload (the home+// screen can show right away) and reads the account cache of the previous+// run, so "Your games" is there at once; loadOwned() refreshes the account's+// titles (~12 s for ~2700) and rewrites the cache; loadCatalogNames() adds+// the rest of the catalog for the search; hydrate() adds hero art and+// descriptions. The last three can run on another thread, one after the+// other.#pragma once#include "ui/app_ui.h"@@ -30,17 +34,27 @@ namespace xc::app {class Library {public:- using RowsCallback = std::function<void(const std::vector<ui::GameRow>&)>;+ // Called whenever rows(), owned() or searchPool() changed.+ using Changed = std::function<void()>;- // Calls `onRows` after each row arrives; false only when nothing loaded.- bool load(xcloud::GssvClient& gssv, const std::string& language, const RowsCallback& onRows, std::string& err);- // The account's titles: which games it can play, and the "Your games"- // row. Takes its own GssvClient (a copy) so it can run on another thread.- void loadOwned(xcloud::GssvClient gssv, const RowsCallback& onRows, const std::atomic<bool>* stop = nullptr);+ // Where the account cache lives (read by load(), written by loadOwned()).+ void setCachePath(std::string path) { cachePath_ = std::move(path); }++ // Calls `changed` after each row arrives; false only when nothing loaded.+ bool load(xcloud::GssvClient& gssv, const std::string& language, const Changed& changed, std::string& err);+ // The account's titles: which games it can play, and "Your games". Takes+ // its own GssvClient (a copy) so it can run on another thread.+ void loadOwned(xcloud::GssvClient gssv, const Changed& changed, const std::atomic<bool>* stop = nullptr);+ // Names and art of the whole Game Pass catalog, for the search.+ void loadCatalogNames(const Changed& changed, const std::atomic<bool>* stop = nullptr);// Hero art and descriptions, in batches; stops early when `stop` is set.- void hydrate(const RowsCallback& onRows, const std::atomic<bool>* stop = nullptr);+ void hydrate(const Changed& changed, const std::atomic<bool>* stop = nullptr);std::vector<ui::GameRow> rows() const;+ std::vector<ui::GameTile> owned() const;+ std::vector<ui::GameTile> searchPool() const;+ // True once the account's games are known (from the cache or the service).+ bool ownedKnown() const { return ownershipKnown_; }private:struct RowIds {@@ -48,13 +62,22 @@ private:bool badges = true;std::vector<std::pair<std::string, std::string>> items; // productId, titleId};+ ui::GameTile tile(const std::string& productId, const std::string& titleId) const;+ void sortOwned();+ bool loadCache();+ void saveCache() const;++ std::string cachePath_;std::string market_, language_;std::vector<RowIds> layout_;std::map<std::string, xcloud::Product> products_;- std::set<std::string> gamePass_; // product ids of the Game Pass catalog- // Filled by loadOwned(): what the account can stream.+ std::vector<std::string> allGames_; // the Game Pass catalog, in its order+ std::set<std::string> gamePass_; // ... as a set+ std::vector<std::string> recent_; // recently played product ids, newest first+ // The account (loadOwned() or the cache).bool ownershipKnown_ = false;std::set<std::string> ownedTitles_, ownedProducts_;+ std::vector<std::pair<std::string, std::string>> owned_; // productId, titleId outside Game Pass};} // namespace xc::appdiff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex 5e6741e..c3f853e 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -211,6 +211,9 @@ std::string stream(xcloud::GssvClient& gssv) {std::string reason = g_cancel ? "left the game" : autoplayDone ? "autoplay finished" : player.endReason();player.stop();auto st = player.stats();+ // Ended before a single frame: the game never started (e.g. it closed on+ // the server); say so on the error screen instead of going back quietly.+ if (st.decodedFrames == 0 && !g_cancel && !autoplayDone) return "ERROR: " + ui::trf(ui::Str::StreamFailed, reason);return "Stream ended (" + reason + "), " + std::to_string(st.decodedFrames) + " frames shown";}@@ -313,10 +316,17 @@ void loadLibrary(xcloud::GssvClient& gssv) {g_ui->showSplash(ui::tr(ui::Str::LoadingGames));stopHydration();auto library = std::make_shared<app::Library>();+ library->setCachePath(platform::dataDir() + "/library.json");bool shown = false;+ // Hands the library's current state to the UI (copies).+ auto publish = [](const app::Library& lib) {+ g_ui->setRows(lib.rows());+ g_ui->setOwned(lib.owned(), lib.ownedKnown());+ g_ui->setSearchPool(lib.searchPool());+ };bool ok = library->load(gssv, ui::catalogLanguage(),- [&](const std::vector<ui::GameRow>& r) {- g_ui->setRows(r);+ [&] {+ publish(*library);if (!shown) {shown = true;g_ui->showHome();@@ -328,13 +338,15 @@ void loadLibrary(xcloud::GssvClient& gssv) {return;}std::vector<ui::GameRow> rows = library->rows();- // The account's own games, then hero art and descriptions, keep arriving- // while the user browses/plays. The thread gets its own GssvClient copy.+ // The account's own games, the catalog names for the search, then hero+ // art and descriptions keep arriving while the user browses/plays. The+ // thread gets its own GssvClient copy.g_stopHydration = false;- platform::startThread(g_hydrationThread, [library, owned = gssv] {- auto onRows = [](const std::vector<ui::GameRow>& r) { g_ui->setRows(r); };- library->loadOwned(owned, onRows, &g_stopHydration);- library->hydrate(onRows, &g_stopHydration);+ platform::startThread(g_hydrationThread, [library, publish, owned = gssv] {+ auto changed = [&] { publish(*library); };+ library->loadOwned(owned, changed, &g_stopHydration);+ library->loadCatalogNames(changed, &g_stopHydration);+ library->hydrate(changed, &g_stopHydration);});if (!g_autoplayTitle.empty() && g_autoplayTitle != "BENCH") {platform::sleepMs(6000); // leave the home screen up for ui.ppm@@ -439,9 +451,11 @@ int main(int argc, char** argv) {ui::Fonts fonts;if (!fonts.load(platform::assetDir() + "/fonts")) XC_LOGE("fonts missing in %s", platform::assetDir().c_str());- g_images = std::make_unique<ui::ImageCache>([] {- if (g_ui) g_ui->invalidate();- });+ g_images = std::make_unique<ui::ImageCache>(+ [] {+ if (g_ui) g_ui->invalidate();+ },+ 160u << 20, platform::dataDir() + "/imgcache");g_ui = std::make_unique<ui::AppUi>(fonts, *g_images);{ui::SettingsChoice choice;@@ -500,6 +514,9 @@ int main(int argc, char** argv) {nav.accept = pad.btnA && !prev.btnA;nav.back = pad.btnB && !prev.btnB;nav.options = pad.btnOptions && !prev.btnOptions;+ nav.l1 = pad.btnL1 && !prev.btnL1;+ nav.r1 = pad.btnR1 && !prev.btnR1;+ nav.square = pad.btnX && !prev.btnX; // Square (Xbox X)nav.touchpad = pad.btnTouchpad;nav.nowMs = now;prev = pad;diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex 8941776..2c8a4bc 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -296,10 +296,16 @@ struct StreamSession::Impl {// A warning shares this message with the real kicks: the session// goes on (the xbox.com client only shows a notice).auto content = json::parse(body);- if (content && (*content)["reason"].str() == "WarningForBeingIdle") {+ std::string reason = content ? (*content)["reason"].str() : std::string();+ if (reason == "WarningForBeingIdle") {if (cb.idleWarning) cb.idleWarning(static_cast<int>((*content)["secondsUntilKick"].asInt(120)));+ } else if (reason == "KickForClosedGame") {+ // The game itself quit (or failed to start) on the server.+ char hr[16];+ std::snprintf(hr, sizeof hr, "0x%08X", static_cast<unsigned>((*content)["hr"].asInt()));+ fail(std::string("the game closed on the server (") + hr + ")");} else {- fail("the server ended the session");+ fail(reason.empty() ? "the server ended the session" : "the server ended the session (" + reason + ")");}} else if (target == "/streaming/systemUi/messages/ShowMessageDialog") {// No dialog UI yet: log it and pick the first (default) button.diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 0bf2200..73802c1 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -42,7 +42,57 @@ constexpr Color kGreen = rgba(16, 124, 16);constexpr Color kPanel = rgba(36, 36, 36);constexpr Color kPlaceholder = rgba(44, 44, 44);-enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle, kIconTouchpad };+enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle, kIconTouchpad, kIconSquare };++// Grids ("Your games", search results): cards with the name below.+constexpr int kGridPitchY = 300;+constexpr int kLibraryCols = 6;+constexpr int kResultCols = 4;+constexpr int kGridTop = 236; // y of the first card row+constexpr int kResultsX = 760;+constexpr size_t kMaxResults = 60;++// The search keyboard: 6 x 6 letters and digits, then Space / Delete / Clear.+constexpr const char* kKeys = "abcdefghijklmnopqrstuvwxyz0123456789";+constexpr int kKeyCols = 6, kKeyRows = 6; // + the row of wide keys+constexpr int kKeyW = 90, kKeyH = 62, kKeyGap = 10;+constexpr int kKeysY = 262;+constexpr int kWideCols[3] = {0, 3, 5}; // first column of Space, Delete, Clear+constexpr int kWideSpan[3] = {3, 2, 1};++// Lower case, accents dropped (Latin-1 range), anything else a space: what+// the search compares.+std::string fold(const std::string& s) {+ static const char kLatin1[] = "aaaaaaaceeeeiiiidnooooo ouuuuytsaaaaaaaceeeeiiiidnooooo ouuuuyty";+ std::string out;+ out.reserve(s.size());+ for (size_t i = 0; i < s.size();) {+ unsigned char c = static_cast<unsigned char>(s[i]);+ uint32_t cp = ' ';+ size_t n = 1;+ if (c < 0x80) {+ cp = c;+ } else if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) {+ cp = ((c & 0x1Fu) << 6) | (static_cast<unsigned char>(s[i + 1]) & 0x3Fu);+ n = 2;+ } else if ((c & 0xF0) == 0xE0) {+ n = 3;+ } else if ((c & 0xF8) == 0xF0) {+ n = 4;+ }+ i += n;+ char ch = ' ';+ if (cp < 0x80 && std::isalnum(static_cast<int>(cp))) ch = static_cast<char>(std::tolower(static_cast<int>(cp)));+ else if (cp >= 0xC0 && cp <= 0xFF) ch = kLatin1[cp - 0xC0];+ out += ch;+ }+ return out;+}++std::string withoutSpaces(std::string s) {+ s.erase(std::remove(s.begin(), s.end(), ' '), s.end());+ return s;+}constexpr uint64_t kSignOutHoldMs = 5000;@@ -150,9 +200,94 @@ void AppUi::setRows(std::vector<GameRow> rows) {for (auto& a : rowScroll_) a.value = a.target;rowY_.value = rowY_.target;}+ refreshDetail();+ dirty_ = true;+}++void AppUi::setOwned(std::vector<GameTile> tiles, bool known) {+ std::lock_guard<std::mutex> lock(mutex_);+ std::string focused = gridFocus_ < static_cast<int>(owned_.size()) ? owned_[static_cast<size_t>(gridFocus_)].productId : "";+ owned_ = std::move(tiles);+ ownedKnown_ = known;+ gridFocus_ = 0;+ for (size_t i = 0; i < owned_.size(); ++i)+ if (owned_[i].productId == focused) gridFocus_ = static_cast<int>(i);+ refreshDetail();dirty_ = true;}+void AppUi::setSearchPool(std::vector<GameTile> pool) {+ std::lock_guard<std::mutex> lock(mutex_);+ pool_ = std::move(pool);+ runSearch();+ refreshDetail();+ dirty_ = true;+}++Tab AppUi::tab() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return tab_;+}++void AppUi::openDetails(const GameTile& tile) {+ // Caller holds mutex_.+ detail_ = tile;+ screen_ = Screen::Details;+ dirty_ = true;+}++void AppUi::refreshDetail() {+ // Caller holds mutex_. Hero art and descriptions arrive after the page opened.+ if (screen_ != Screen::Details || detail_.productId.empty()) return;+ auto take = [&](const GameTile& t) {+ if (t.productId == detail_.productId && t.heroUrl.size() + t.description.size() >+ detail_.heroUrl.size() + detail_.description.size())+ detail_ = t;+ };+ for (const auto& row : rows_)+ for (const auto& t : row.tiles) take(t);+ for (const auto& t : owned_) take(t);+ for (const auto& t : pool_) take(t);+}++void AppUi::runSearch() {+ // Caller holds mutex_.+ results_.clear();+ resultFocus_ = 0;+ resultScroll_ = Anim{};+ std::string q = fold(query_);+ std::vector<std::string> words;+ for (size_t i = 0; i < q.size();) {+ size_t j = q.find(' ', i);+ if (j == std::string::npos) j = q.size();+ if (j > i) words.push_back(q.substr(i, j - i));+ i = j + 1;+ }+ if (words.empty()) return;+ std::string compact = withoutSpaces(q);+ struct Hit {+ int score;+ const GameTile* tile;+ };+ std::vector<Hit> hits;+ for (const auto& t : pool_) {+ std::string name = fold(t.name);+ bool all = true;+ for (const auto& w : words)+ if (name.find(w) == std::string::npos) all = false;+ if (!all && withoutSpaces(name).find(compact) == std::string::npos) continue;+ // Starts with the query, then a word starting with it, then the rest.+ int score = name.rfind(words[0], 0) == 0 ? 0 : name.find(" " + words[0]) != std::string::npos ? 1 : 2;+ if (!t.playable) score += 3;+ hits.push_back({score, &t});+ }+ std::stable_sort(hits.begin(), hits.end(), [](const Hit& a, const Hit& b) {+ if (a.score != b.score) return a.score < b.score;+ return a.tile->name < b.tile->name;+ });+ for (size_t i = 0; i < hits.size() && i < kMaxResults; ++i) results_.push_back(*hits[i].tile);+}+void AppUi::showHome(const std::string& toast) {std::lock_guard<std::mutex> lock(mutex_);screen_ = Screen::Home;@@ -253,19 +388,42 @@ void AppUi::retarget() {// --- Input ----------------------------------------------------------------------UiEvent AppUi::handle(const NavInput& in) {- std::lock_guard<std::mutex> lock(mutex_);- UiEvent ev;- switch (screen_) {- case Screen::Home: {- if (rows_.empty()) {- if (in.options) {- screen_ = Screen::Settings;- settingsRow_ = 0;- dirty_ = true;- }- break;- }+namespace {++// Moves `focus` in a grid of `count` items, `cols` wide. Returns true if it moved.+bool moveInGrid(int& focus, int count, int cols, const NavInput& in) {+ int before = focus;+ if (in.right && focus + 1 < count && (focus + 1) % cols != 0) ++focus;+ if (in.left && focus % cols != 0) --focus;+ if (in.down && focus + cols < count) focus += cols;+ else if (in.down && focus / cols < (count - 1) / cols) focus = count - 1; // onto a short last row+ if (in.up && focus >= cols) focus -= cols;+ return focus != before;+}++// Keeps the focused grid row on screen: scrolls once it passes the second row.+float gridTarget(int focus, int cols) { return static_cast<float>(std::max(0, focus / cols - 1) * kGridPitchY); }++} // namespace++void AppUi::handleHome(const NavInput& in, UiEvent& ev) {+ // Caller holds mutex_.+ if (in.l1 || in.r1) {+ int t = (static_cast<int>(tab_) + (in.r1 ? 1 : 2)) % 3;+ tab_ = static_cast<Tab>(t);+ if (tab_ == Tab::Search) searchOnKeys_ = true;+ dirty_ = true;+ return;+ }+ if (in.options) {+ screen_ = Screen::Settings;+ settingsRow_ = 0;+ dirty_ = true;+ return;+ }+ switch (tab_) {+ case Tab::GamePass: {+ if (rows_.empty()) break;int rows = static_cast<int>(rows_.size());int& col = focusCol_[static_cast<size_t>(focusRow_)];int cols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());@@ -277,17 +435,96 @@ UiEvent AppUi::handle(const NavInput& in) {retarget();dirty_ = true;}- if (in.accept && focusedTile()) {- screen_ = Screen::Details;+ if (in.accept && focusedTile()) openDetails(*focusedTile());+ break;+ }+ case Tab::Library:+ if (owned_.empty()) break;+ if (moveInGrid(gridFocus_, static_cast<int>(owned_.size()), kLibraryCols, in)) {+ gridScroll_.target = gridTarget(gridFocus_, kLibraryCols);dirty_ = true;}- if (in.options) {- screen_ = Screen::Settings;- settingsRow_ = 0;+ if (in.accept) openDetails(owned_[static_cast<size_t>(gridFocus_)]);+ break;+ case Tab::Search:+ if (searchOnKeys_) {+ handleSearchKeys(in);+ break;+ }+ if (in.back) { // back from the results to the keys+ searchOnKeys_ = true;dirty_ = true;+ break;}+ if (in.left && resultFocus_ % kResultCols == 0) {+ searchOnKeys_ = true;+ dirty_ = true;+ break;+ }+ if (in.square && !query_.empty()) { // delete without going back to the keys+ query_.pop_back();+ runSearch();+ searchOnKeys_ = results_.empty();+ dirty_ = true;+ break;+ }+ if (moveInGrid(resultFocus_, static_cast<int>(results_.size()), kResultCols, in)) {+ resultScroll_.target = gridTarget(resultFocus_, kResultCols);+ dirty_ = true;+ }+ if (in.accept && resultFocus_ < static_cast<int>(results_.size()))+ openDetails(results_[static_cast<size_t>(resultFocus_)]);break;+ }+}++void AppUi::handleSearchKeys(const NavInput& in) {+ // Caller holds mutex_. keyRow_ == kKeyRows is the row of wide keys, where+ // keyCol_ is 0..2 (Space, Delete, Clear).+ bool wide = keyRow_ == kKeyRows;+ if (in.up && keyRow_ > 0) {+ if (wide) keyCol_ = kWideCols[keyCol_];+ --keyRow_;+ } else if (in.down && keyRow_ < kKeyRows) {+ ++keyRow_;+ if (keyRow_ == kKeyRows) keyCol_ = keyCol_ < 3 ? 0 : keyCol_ < 5 ? 1 : 2;+ } else if (in.left && keyCol_ > 0) {+ --keyCol_;+ } else if (in.right) {+ int last = wide ? 2 : kKeyCols - 1;+ if (keyCol_ < last) {+ ++keyCol_;+ } else if (!results_.empty()) { // on to the results+ searchOnKeys_ = false;+ resultFocus_ = 0;}+ }+ bool edited = false;+ if (in.accept) {+ if (!wide) {+ query_ += kKeys[keyRow_ * kKeyCols + keyCol_];+ } else if (keyCol_ == 0) {+ if (!query_.empty() && query_.back() != ' ') query_ += ' ';+ } else if (keyCol_ == 1) {+ if (!query_.empty()) query_.pop_back();+ } else {+ query_.clear();+ }+ edited = true;+ }+ if (in.square && !query_.empty()) {+ query_.pop_back();+ edited = true;+ }+ if (edited) runSearch();+ if (in.up || in.down || in.left || in.right || edited) dirty_ = true;+}++UiEvent AppUi::handle(const NavInput& in) {+ std::lock_guard<std::mutex> lock(mutex_);+ UiEvent ev;+ switch (screen_) {+ case Screen::Home: handleHome(in, ev); break;case Screen::Settings:if (in.down && settingsRow_ < 2) ++settingsRow_, dirty_ = true;if (in.up && settingsRow_ > 0) --settingsRow_, dirty_ = true;@@ -301,9 +538,9 @@ UiEvent AppUi::handle(const NavInput& in) {}break;case Screen::Details:- if (in.accept && focusedTile() && focusedTile()->playable) {+ if (in.accept && detail_.playable && !detail_.titleId.empty()) {ev.action = Action::Play;- ev.game = *focusedTile();+ ev.game = detail_;}if (in.back) {screen_ = Screen::Home;@@ -401,6 +638,8 @@ void AppUi::drawHints(Canvas& c, const std::vector<std::pair<int, const char*>>&c.line(cx + 6, cy - 6, cx - 6, cy + 6, 2.5f, rgba(124, 178, 232));} else if (it->first == kIconCircle) {c.strokeArc(cx, cy, 6.5f, 2.5f, 0, 6.2832f, rgba(255, 102, 102));+ } else if (it->first == kIconSquare) {+ c.strokeRect({static_cast<int>(cx) - 6, static_cast<int>(cy) - 6, 12, 12}, rgba(240, 130, 200), 2);} else {c.line(cx, cy - 7, cx - 7, cy + 5, 2.5f, rgba(64, 226, 160));c.line(cx, cy - 7, cx + 7, cy + 5, 2.5f, rgba(64, 226, 160));@@ -513,11 +752,153 @@ void AppUi::drawSignIn(Canvas& c, uint64_t nowMs) {}}+void AppUi::drawTabs(Canvas& c) {+ // Centred pills in the top bar, between "L1" and "R1".+ const char* labels[3] = {tr(Str::TabGamePass), tr(Str::YourGames), tr(Str::TabSearch)};+ constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;+ int widths[3], total = 0;+ for (int i = 0; i < 3; ++i) {+ widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;+ total += widths[i] + (i ? kGap : 0);+ }+ int x = (kW - total) / 2;+ auto shoulder = [&](const char* name, int cx) {+ Rect r{cx - 22, kY + 8, 44, 28};+ c.fillRect(r, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, name, cx - fonts_.bold.measure(name, 16) / 2, kY + 13, 16, kGray);+ };+ shoulder("L1", x - 40);+ for (int i = 0; i < 3; ++i) {+ bool on = static_cast<int>(tab_) == i;+ Rect r{x, kY, widths[i], kH};+ if (on) c.fillRect(r, kWhite, kH / 2);+ fonts_.semibold.draw(c, labels[i], x + kPad, kY + 10, kPx, on ? kBg : kGray);+ x += widths[i] + kGap;+ }+ shoulder("R1", x - kGap + 40);+}++void AppUi::drawGrid(Canvas& c, const std::vector<GameTile>& tiles, int x0, int y0, int cols, float scroll, int focus,+ int clipTop) {+ int offset = static_cast<int>(std::lround(scroll));+ for (size_t i = 0; i < tiles.size(); ++i) {+ int col = static_cast<int>(i) % cols, row = static_cast<int>(i) / cols;+ int x = x0 + col * kCardPitch;+ int y = y0 + row * kGridPitchY - offset;+ if (y + kCard + 40 < clipTop) continue;+ if (y > kH) break;+ const GameTile& t = tiles[i];+ if (auto img = images_.get(t.tileUrl, kCard, kCard)) {+ c.drawImage(*img, x, y, 255, 10);+ } else {+ c.fillRect({x, y, kCard, kCard}, kPlaceholder, 10);+ auto lines = fonts_.semibold.wrap(t.name, 22, kCard - 32, 3);+ for (size_t k = 0; k < lines.size(); ++k)+ fonts_.semibold.draw(c, lines[k], x + 16, y + 16 + static_cast<int>(k) * 30, 22, kGray);+ }+ if (!t.playable) {+ c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 150), 10);+ drawLock(c, x + kCard - 34, y + 30);+ }+ bool focused = static_cast<int>(i) == focus;+ auto name = fonts_.semibold.wrap(t.name, 20, kCard, 1);+ if (!name.empty()) fonts_.semibold.draw(c, name[0], x, y + kCard + 12, 20, focused ? kWhite : kGray);+ if (focused) c.strokeRect({x - 7, y - 7, kCard + 14, kCard + 14}, kWhite, 4, 16);+ }+ // Rows scrolled up (cards and names) disappear under the header.+ c.fillRect({0, 0, kW, clipTop}, kBg);+ c.gradientV({0, clipTop, kW, 12}, kBg, withAlpha(kBg, 0));+}++void AppUi::drawLibrary(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ drawGrid(c, owned_, (kW - kGridW) / 2, kGridTop, kLibraryCols, gridScroll_.value, gridFocus_, kGridTop - 20);+ drawTopBar(c);+ drawTabs(c);+ const int left = (kW - (kLibraryCols * kCardPitch - kCardGap)) / 2;+ fonts_.bold.draw(c, tr(Str::YourGames), left, 130, 40, kWhite);+ if (!owned_.empty()) {+ std::string count = trf(Str::GamesCount, std::to_string(owned_.size()));+ fonts_.semibold.draw(c, count, left + fonts_.bold.measure(tr(Str::YourGames), 40) + 24, 144, 24, kDim);+ } else if (!ownedKnown_) {+ drawSpinner(c, kW / 2.0f, 470, 26, nowMs);+ drawCentered(c, fonts_.semibold, tr(Str::LoadingGames), 530, 28, kGray);+ animating_ = true;+ } else {+ drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 30, kGray);+ }+ c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));+ c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});+ drawToast(c, nowMs);+}++void AppUi::drawSearch(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ // Results on the right.+ drawGrid(c, results_, kResultsX, kGridTop, kResultCols, resultScroll_.value, searchOnKeys_ ? -1 : resultFocus_,+ kGridTop - 20);+ drawTopBar(c);+ drawTabs(c);+ if (query_.empty()) {+ fonts_.semibold.draw(c, tr(Str::SearchHint), kResultsX, 150, 26, kDim);+ } else if (results_.empty()) {+ fonts_.semibold.draw(c, tr(Str::NoResults), kResultsX, 150, 26, kGray);+ } else {+ fonts_.semibold.draw(c, trf(Str::ResultsCount, std::to_string(results_.size())), kResultsX, 150, 26, kGray);+ }++ // The query.+ const int kbW = kKeyCols * (kKeyW + kKeyGap) - kKeyGap;+ Rect box{kMargin, 140, kbW, 76};+ c.fillRect(box, kPanel, 14);+ if (searchOnKeys_) c.strokeRect(box, rgba(255, 255, 255, 90), 2, 14);+ int tx = box.x + 24;+ if (query_.empty()) {+ fonts_.regular.draw(c, tr(Str::TabSearch), tx, box.y + 20, 30, kDim);+ } else {+ fonts_.semibold.draw(c, query_, tx, box.y + 20, 30, kWhite);+ tx += fonts_.semibold.measure(query_, 30) + 4;+ }+ if (searchOnKeys_ && (nowMs / 530) % 2 == 0) c.fillRect({tx, box.y + 18, 3, 40}, kWhite);+ if (searchOnKeys_) animating_ = true; // the caret blinks++ // The keys.+ for (int r = 0; r <= kKeyRows; ++r) {+ int n = r == kKeyRows ? 3 : kKeyCols;+ for (int k = 0; k < n; ++k) {+ int col = r == kKeyRows ? kWideCols[k] : k;+ int span = r == kKeyRows ? kWideSpan[k] : 1;+ Rect key{kMargin + col * (kKeyW + kKeyGap), kKeysY + r * (kKeyH + kKeyGap),+ span * kKeyW + (span - 1) * kKeyGap, kKeyH};+ bool focused = searchOnKeys_ && keyRow_ == r && keyCol_ == k;+ c.fillRect(key, focused ? kWhite : kPanel, 10);+ std::string label = r == kKeyRows ? tr(k == 0 ? Str::KeySpace : k == 1 ? Str::KeyDelete : Str::KeyClear)+ : std::string(1, static_cast<char>(std::toupper(kKeys[r * kKeyCols + k])));+ int px = r == kKeyRows ? 22 : 28;+ int w = fonts_.semibold.measure(label, px);+ fonts_.semibold.draw(c, label, key.x + (key.w - w) / 2, key.y + (kKeyH - px) / 2 - 4, px,+ focused ? kBg : kWhite);+ }+ }+ c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));+ c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));+ if (searchOnKeys_)+ drawHints(c, {{kIconCross, tr(Str::KeyType)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconOptions, tr(Str::Settings)}});+ else+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconCircle, tr(Str::Back)}});+ drawToast(c, nowMs);+}+void AppUi::drawHome(Canvas& c, uint64_t nowMs) {+ if (tab_ == Tab::Library) return drawLibrary(c, nowMs);+ if (tab_ == Tab::Search) return drawSearch(c, nowMs);const GameTile* focus = focusedTile();c.clear(kBg);drawHero(c, nowMs, focus ? focus->heroUrl : std::string(), false);drawTopBar(c);+ drawTabs(c);if (rows_.empty()) {drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 32, kGray);@@ -580,9 +961,9 @@ void AppUi::drawHome(Canvas& c, uint64_t nowMs) {}void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {- const GameTile* g = focusedTile();+ const GameTile* g = &detail_;c.clear(kBg);- if (!g) return;+ if (g->productId.empty()) return;drawHero(c, nowMs, g->heroUrl, true);drawTopBar(c);int y = 260;@@ -716,6 +1097,8 @@ void AppUi::render(Canvas& c, uint64_t nowMs) {lastRender_ = nowMs;animating_ = rowY_.step(dt);for (auto& a : rowScroll_) animating_ |= a.step(dt);+ animating_ |= gridScroll_.step(dt);+ animating_ |= resultScroll_.step(dt);dirty_ = false;switch (screen_) {case Screen::Splash: drawSplash(c, nowMs); break;diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 2392fad..452aee0 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -41,9 +41,13 @@ struct GameRow {enum class Screen { Splash, SignIn, Home, Details, Launching, Streaming, Error, Settings };+// The home screen's tabs (L1 / R1).+enum class Tab { GamePass, Library, Search };+struct NavInput {bool up = false, down = false, left = false, right = false;bool accept = false, back = false, options = false;+ bool l1 = false, r1 = false, square = false;bool touchpad = false; // held right now (sign out needs a 5 s hold)uint64_t nowMs = 0;};@@ -76,6 +80,10 @@ public:void setProfile(const std::string& gamertag, const std::string& gamerpicUrl);// Replaces the rows, keeping the focus on the same game when possible.void setRows(std::vector<GameRow> rows);+ // "Your games" grid; `known` false while the account's games load.+ void setOwned(std::vector<GameTile> tiles, bool known);+ // Everything the search looks through.+ void setSearchPool(std::vector<GameTile> pool);void showHome(const std::string& toast = {});void showLaunching(const GameTile& game, const std::string& status);void setLaunchStatus(const std::string& status);@@ -86,6 +94,7 @@ public:// one "Automatic" picks.void setRegions(std::vector<std::string> regions, const std::string& defaultRegion);Screen screen() const;+ Tab tab() const;void invalidate();// --- UI thread -----------------------------------------------------------@@ -111,6 +120,17 @@ private:void drawSplash(Canvas& c, uint64_t nowMs);void drawSignIn(Canvas& c, uint64_t nowMs);void drawHome(Canvas& c, uint64_t nowMs);+ void drawTabs(Canvas& c);+ void drawLibrary(Canvas& c, uint64_t nowMs);+ void drawSearch(Canvas& c, uint64_t nowMs);+ // A grid of cards with names below; `focus` < 0: none highlighted.+ void drawGrid(Canvas& c, const std::vector<GameTile>& tiles, int x0, int y0, int cols, float scroll, int focus,+ int clipTop);+ void handleHome(const NavInput& in, UiEvent& ev);+ void handleSearchKeys(const NavInput& in);+ void runSearch();+ void openDetails(const GameTile& tile);+ void refreshDetail();void drawDetails(Canvas& c, uint64_t nowMs);void drawLaunching(Canvas& c, uint64_t nowMs);void drawError(Canvas& c);@@ -132,6 +152,18 @@ private:std::vector<int> focusCol_;std::vector<Anim> rowScroll_;Anim rowY_;+ Tab tab_ = Tab::GamePass;+ std::vector<GameTile> owned_;+ bool ownedKnown_ = false;+ int gridFocus_ = 0;+ Anim gridScroll_;+ std::vector<GameTile> pool_, results_;+ std::string query_;+ bool searchOnKeys_ = true;+ int keyRow_ = 0, keyCol_ = 0;+ int resultFocus_ = 0;+ Anim resultScroll_;+ GameTile detail_; // the game the details page showsGameTile launching_;std::string error_;SettingsChoice settings_;diff --git a/src/ui/image_cache.cpp b/src/ui/image_cache.cppindex 5f23201..85e4260 100644--- a/src/ui/image_cache.cpp+++ b/src/ui/image_cache.cpp@@ -16,6 +16,10 @@#define STB_IMAGE_RESIZE_STATIC#include "stb_image_resize2.h"+#include <dirent.h>+#include <sys/stat.h>+#include <unistd.h>+#include <algorithm>#include <cstring>@@ -65,8 +69,13 @@ std::string sizedUrl(std::string url, int w, int h) {} // namespace-ImageCache::ImageCache(std::function<void()> onReady, size_t budgetBytes)- : onReady_(std::move(onReady)), budget_(budgetBytes) {+ImageCache::ImageCache(std::function<void()> onReady, size_t budgetBytes, std::string diskDir,+ size_t diskBudgetBytes)+ : onReady_(std::move(onReady)), budget_(budgetBytes), diskDir_(std::move(diskDir)), diskBudget_(diskBudgetBytes) {+ if (!diskDir_.empty()) {+ ::mkdir(diskDir_.c_str(), 0755);+ trimDisk();+ }threads_.resize(3);for (auto& t : threads_) platform::startThread(t, [this] { loop(); }, 2u << 20);}@@ -107,6 +116,49 @@ void ImageCache::evict() {}}+std::string ImageCache::diskPath(const std::string& url) const {+ uint64_t h = 1469598103934665603ull; // FNV-1a of the sized URL+ for (unsigned char ch : url) h = (h ^ ch) * 1099511628211ull;+ char name[24];+ std::snprintf(name, sizeof name, "%016llx", static_cast<unsigned long long>(h));+ return diskDir_ + "/" + name;+}++void ImageCache::trimDisk() {+ struct File {+ std::string path;+ off_t size;+ time_t mtime;+ };+ std::vector<File> files;+ size_t total = 0;+ if (DIR* d = ::opendir(diskDir_.c_str())) {+ while (dirent* e = ::readdir(d)) {+ if (e->d_name[0] == '.') continue;+ std::string path = diskDir_ + "/" + e->d_name;+ struct stat st {};+ if (::stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) continue;+ files.push_back({path, st.st_size, st.st_mtime});+ total += static_cast<size_t>(st.st_size);+ }+ ::closedir(d);+ }+ if (total <= diskBudget_) {+ XC_LOGI("image cache: %zu files, %zu MB on disk", files.size(), total >> 20);+ return;+ }+ std::sort(files.begin(), files.end(), [](const File& a, const File& b) { return a.mtime < b.mtime; });+ size_t removed = 0;+ for (const auto& f : files) {+ if (total <= diskBudget_ * 3 / 4) break; // some headroom+ if (::unlink(f.path.c_str()) == 0) {+ total -= static_cast<size_t>(f.size);+ ++removed;+ }+ }+ XC_LOGI("image cache: trimmed %zu files, %zu MB left", removed, total >> 20);+}+void ImageCache::loop() {for (;;) {Job job;@@ -120,10 +172,22 @@ void ImageCache::loop() {net::Request req;req.url = sizedUrl(job.url, job.w, job.h);req.headers = {{"Accept", "image/*"}};- auto r = net::perform(req);Image decoded;std::shared_ptr<Image> result;- if (r.ok() && decodeImage(r.body, decoded)) {+ std::string cached;+ std::string path = diskDir_.empty() ? std::string() : diskPath(req.url);+ net::Response r;+ if (!path.empty() && platform::readFile(path, cached) && decodeImage(cached, decoded)) {+ r.status = 200; // from disk+ } else {+ r = net::perform(req);+ if (r.ok() && !path.empty() && decodeImage(r.body, decoded)) {+ platform::writeFileAtomic(path, r.body);+ } else if (r.ok()) {+ decodeImage(r.body, decoded);+ }+ }+ if (r.ok() && decoded.w > 0) {result = std::make_shared<Image>(decoded.w == job.w && decoded.h == job.h? std::move(decoded): coverResize(decoded, job.w, job.h));diff --git a/src/ui/image_cache.h b/src/ui/image_cache.hindex 0028b72..6cd9e89 100644--- a/src/ui/image_cache.h+++ b/src/ui/image_cache.h@@ -3,6 +3,9 @@// Box art and hero images: downloaded and decoded on background threads,// scaled to exactly the size they are drawn at ("cover": fill and crop), and// kept in memory up to a byte budget (least recently used dropped first).+// With a disk directory, downloads are also kept there (as fetched, already+// sized by the image server) so the next launch doesn't download them again;+// the directory is trimmed to a size limit, oldest files first.#pragma once#include "platform/platform.h"@@ -28,7 +31,8 @@ Image coverResize(const Image& src, int w, int h);class ImageCache {public:// `onReady` is called (from a loader thread) whenever an image arrives.- explicit ImageCache(std::function<void()> onReady, size_t budgetBytes = 160u << 20);+ explicit ImageCache(std::function<void()> onReady, size_t budgetBytes = 160u << 20, std::string diskDir = {},+ size_t diskBudgetBytes = 256u << 20);~ImageCache();// The image scaled to w x h, or nullptr while it loads (or if it failed).@@ -46,9 +50,13 @@ private:};void loop();void evict();+ std::string diskPath(const std::string& url) const;+ void trimDisk();std::function<void()> onReady_;size_t budget_;+ std::string diskDir_;+ size_t diskBudget_;std::mutex mutex_;std::condition_variable cv_;std::map<std::string, Entry> entries_;diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex a875d97..d093213 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -78,6 +78,16 @@ constexpr Column kEnglish = {"No input for a while: you will be disconnected in %s seconds", // IdleWarning"Your games", // YourGames"Not available on your account", // NotPlayable+ "Game Pass", // TabGamePass+ "Search", // TabSearch+ "Type the name of a game", // SearchHint+ "No games found", // NoResults+ "%s results", // ResultsCount+ "Space", // KeySpace+ "Delete", // KeyDelete+ "Clear", // KeyClear+ "%s games", // GamesCount+ "Type", // KeyType};constexpr Column kPortugueseBR = {@@ -126,6 +136,16 @@ constexpr Column kPortugueseBR = {"Sem atividade: você será desconectado em %s segundos","Seus jogos","Indisponível na sua conta",+ "Game Pass",+ "Pesquisar",+ "Digite o nome de um jogo",+ "Nenhum jogo encontrado",+ "%s resultados",+ "Espaço",+ "Apagar",+ "Limpar",+ "%s jogos",+ "Digitar",};constexpr Column kSpanish = {@@ -174,6 +194,16 @@ constexpr Column kSpanish = {"Sin actividad: se te desconectará en %s segundos","Tus juegos","No disponible en tu cuenta",+ "Game Pass",+ "Buscar",+ "Escribe el nombre de un juego",+ "No se encontraron juegos",+ "%s resultados",+ "Espacio",+ "Borrar",+ "Limpiar",+ "%s juegos",+ "Escribir",};constexpr Column kFrench = {@@ -222,6 +252,16 @@ constexpr Column kFrench = {"Aucune activité : vous serez déconnecté dans %s secondes","Vos jeux","Indisponible sur votre compte",+ "Game Pass",+ "Rechercher",+ "Tapez le nom d'un jeu",+ "Aucun jeu trouvé",+ "%s résultats",+ "Espace",+ "Effacer",+ "Tout effacer",+ "%s jeux",+ "Taper",};constexpr Column kGerman = {@@ -270,6 +310,16 @@ constexpr Column kGerman = {"Keine Aktivität: Die Verbindung wird in %s Sekunden getrennt","Deine Spiele","Für dein Konto nicht verfügbar",+ "Game Pass",+ "Suchen",+ "Gib den Namen eines Spiels ein",+ "Keine Spiele gefunden",+ "%s Ergebnisse",+ "Leerzeichen",+ "Löschen",+ "Leeren",+ "%s Spiele",+ "Tippen",};constexpr Column kItalian = {@@ -318,6 +368,16 @@ constexpr Column kItalian = {"Nessuna attività: verrai disconnesso tra %s secondi","I tuoi giochi","Non disponibile sul tuo account",+ "Game Pass",+ "Cerca",+ "Scrivi il nome di un gioco",+ "Nessun gioco trovato",+ "%s risultati",+ "Spazio",+ "Cancella",+ "Svuota",+ "%s giochi",+ "Scrivi",};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex 8d9ef69..1815b08 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -55,6 +55,16 @@ enum class Str {IdleWarning, // "%s" = seconds until the server disconnectsYourGames, // row of the account's own (non-Game Pass) gamesNotPlayable, // the account can't stream this game+ TabGamePass,+ TabSearch,+ SearchHint,+ NoResults,+ ResultsCount, // "%s" = number+ KeySpace,+ KeyDelete,+ KeyClear,+ GamesCount, // "%s" = number+ KeyType, // hint: press to type the focused keyCount};