Xbox Cloud Gaming app for PS5 Homebrew
C
Console badges, games to buy, Triangle search per tab, region latency
Rafael Abud Ferreirae5205720c513
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 38b6b05..31a3a31 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -21,6 +21,8 @@ add_library(xcloud_core STATICsrc/auth/auth_manager.cppsrc/xcloud/gssv.cppsrc/xcloud/catalog.cpp+ src/xcloud/titlehub.cpp+ src/xcloud/regions.cppsrc/platform/posix_common.cpp)target_include_directories(xcloud_core PUBLIC src)diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cppindex f2efffc..c9be88a 100644--- a/src/app/cli_main.cpp+++ b/src/app/cli_main.cpp@@ -20,6 +20,7 @@#include "auth/auth_manager.h"#include "media/decoder.h"#include "net/http.h"+#include "util/json.h"#include "stream/stream_session.h"#include "platform/platform.h"#include "util/log.h"@@ -303,8 +304,8 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {app::Library library;auto onRows = [&] {app.setRows(library.rows());- app.setOwned(library.owned(), library.ownedKnown());- app.setSearchPool(library.searchPool());+ app.setOwned(library.owned(), library.purchasable(), library.ownedKnown());+ app.setSearchPools(library.gamePassSearchPool(), library.librarySearchPool());};if (!library.load(gssv, ui::catalogLanguage(), onRows, err)) {XC_LOGE("%s", err.c_str());@@ -312,21 +313,13 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {}library.loadOwned(gssv, onRows);library.loadCatalogNames(onRows);+ library.loadPlatforms(am.profile().xblAuthorization, 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);+ // "Your games" (its games, then those to buy), then searches typed+ // on the keyboard, in each tab.auto press = [&](auto set, int times) {for (int i = 0; i < times; ++i) {ui::NavInput n;@@ -334,19 +327,33 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {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);+ auto type = [&](const std::string& text) {+ for (char ch : text) {+ 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+ press([](ui::NavInput& n) { n.triangle = true; }, 1); // Game Pass search+ type("forza");+ save("search_gamepass", 3000);+ press([](ui::NavInput& n) { n.back = true; }, 1);+ press([](ui::NavInput& n) { n.r1 = true; }, 1);+ save("library", 3000);+ int ownedRows = static_cast<int>((library.owned().size() + 5) / 6);+ press([](ui::NavInput& n) { n.down = true; }, ownedRows); // into "Available to buy"+ save("library_buy", 3000);+ press([](ui::NavInput& n) { n.accept = true; }, 1);+ save("details_buy", 2000);+ press([](ui::NavInput& n) { n.back = true; }, 1);+ press([](ui::NavInput& n) { n.triangle = true; }, 1); // "Your games" search+ type("dead");+ save("search_library", 3000);+ press([](ui::NavInput& n) { n.back = true; }, 1);+ press([](ui::NavInput& n) { n.l1 = true; }, 1); // back to the Game Pass tab}ui::NavInput right;right.right = true;@@ -476,6 +483,26 @@ int main(int argc, char** argv) {if (cmd == "login") {xcloud::GssvClient gssv;rc = signIn(am, gssv) ? 0 : 1;+ } else if (cmd == "titlehub" && argi < argc) {+ // Debugging: titlehub's view of Xbox title ids (devices etc.).+ xcloud::GssvClient gssv;+ if (!signIn(am, gssv)) return 1;+ json::Value ids = json::Value::array();+ for (; argi < argc; ++argi) ids.push(std::string(argv[argi]));+ json::Value body = json::Value::object();+ body.set("pfns", nullptr);+ body.set("titleIds", ids);+ net::Request req;+ req.method = "POST";+ req.url = "https://titlehub.xboxlive.com/titles/batch/decoration/detail";+ req.headers = {{"Authorization", am.profile().xblAuthorization},+ {"x-xbl-contract-version", "2"},+ {"Content-Type", "application/json"},+ {"Accept-Language", "en-US"}};+ req.body = body.dump();+ auto r = net::perform(req);+ std::printf("HTTP %d\n%s\n", r.status, r.body.c_str());+ return r.ok() ? 0 : 1;} else if (cmd == "titles") {rc = cmdTitles(am, argi < argc && std::strcmp(argv[argi], "--recent") == 0);} else if (cmd == "provision" && argi < argc) {diff --git a/src/app/library.cpp b/src/app/library.cppindex 87663ee..0094138 100644--- a/src/app/library.cpp+++ b/src/app/library.cpp@@ -7,6 +7,7 @@#include "util/json.h"#include "util/log.h"#include "xcloud/catalog.h"+#include "xcloud/titlehub.h"#include <algorithm>#include <map>@@ -15,7 +16,7 @@ namespace xc::app {namespace {-constexpr int kCacheVersion = 1;+constexpr int kCacheVersion = 2;struct ListSpec {const char* sigl;@@ -25,6 +26,7 @@ struct ListSpec {json::Value productToJson(const xcloud::Product& p) {json::Value v = json::Value::object();v.set("xt", p.xcloudTitleId);+ v.set("xbox", p.xboxTitleId);v.set("title", p.title);v.set("publisher", p.publisher);v.set("description", p.description);@@ -41,6 +43,7 @@ xcloud::Product productFromJson(const std::string& id, const json::Value& v) {xcloud::Product p;p.productId = id;p.xcloudTitleId = v["xt"].str();+ p.xboxTitleId = v["xbox"].str();p.title = v["title"].str();p.publisher = v["publisher"].str();p.description = v["description"].str();@@ -51,6 +54,35 @@ xcloud::Product productFromJson(const std::string& id, const json::Value& v) {return p;}+json::Value itemsToJson(const std::vector<std::pair<std::string, std::string>>& items) {+ json::Value a = json::Value::array();+ for (const auto& [pid, tid] : items) {+ json::Value o = json::Value::object();+ o.set("p", pid);+ o.set("t", tid);+ a.push(o);+ }+ return a;+}++// 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);+}+} // namespaceui::GameTile Library::tile(const std::string& productId, const std::string& titleId) const {@@ -67,9 +99,24 @@ ui::GameTile Library::tile(const std::string& productId, const std::string& titlt.heroUrl = p.heroUrl;t.categories = p.categories;if (ownershipKnown_) t.playable = ownedTitles_.count(t.titleId) || ownedProducts_.count(t.productId);+ t.purchasable = !t.playable && purchasableSet_.count(productId);+ auto x = xboxTitleOf_.find(productId);+ std::string xbox = x != xboxTitleOf_.end() ? x->second : p.xboxTitleId;+ auto pl = platform_.find(xbox);+ if (pl != platform_.end()) t.platform = pl->second;return t;}+std::vector<ui::GameTile> Library::tiles(const std::vector<Item>& items) const {+ std::vector<ui::GameTile> out;+ for (const auto& [pid, tid] : items) {+ ui::GameTile t = tile(pid, tid);+ if (!t.productId.empty() && !t.titleId.empty() && !t.name.empty()) out.push_back(std::move(t));+ }+ dedupeByTitle(out);+ return out;+}+std::vector<ui::GameRow> Library::rows() const {std::vector<ui::GameRow> rows;for (const auto& r : layout_) {@@ -86,50 +133,19 @@ std::vector<ui::GameRow> Library::rows() const {return rows;}-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 { return tiles(owned_); }+std::vector<ui::GameTile> Library::purchasable() const { return tiles(purchasable_); }-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::gamePassSearchPool() const {+ std::vector<Item> items;+ for (const auto& id : allGames_) items.emplace_back(id, std::string());+ return tiles(items);}-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;+std::vector<ui::GameTile> Library::librarySearchPool() const {+ std::vector<Item> items = owned_;+ items.insert(items.end(), purchasable_.begin(), purchasable_.end());+ return tiles(items);}void Library::sortOwned() {@@ -153,19 +169,26 @@ 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);+ if (!j || (*j)["version"].asInt() != kCacheVersion || (*j)["market"].str() != market_) return false;+ // Names and descriptions are in the cache's language: only reused in it.+ if ((*j)["language"].str() == language_)+ for (const auto& [id, v] : (*j)["products"].members())+ if (!products_.count(id)) products_[id] = productFromJson(id, v);+ for (const auto& [id, code] : (*j)["platforms"].members()) platform_[id] = code.str();+ for (const auto& [pid, xbox] : (*j)["xboxTitles"].members()) xboxTitleOf_[pid] = xbox.str();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());+ for (const auto& o : (*j)["owned"].items()) owned_.emplace_back(o["p"].str(), o["t"].str());+ purchasable_.clear();+ for (const auto& o : (*j)["purchasable"].items()) {+ purchasable_.emplace_back(o["p"].str(), o["t"].str());+ purchasableSet_.insert(o["p"].str());+ }ownershipKnown_ = !ownedTitles_.empty();sortOwned();- XC_LOGI("library: cache: %zu of the account's games, %zu titles playable", owned_.size(), ownedTitles_.size());+ XC_LOGI("library: cache: %zu of the account's games, %zu to buy, %zu consoles known", owned_.size(),+ purchasable_.size(), platform_.size());return ownershipKnown_;}@@ -175,22 +198,26 @@ void Library::saveCache() const {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();+ json::Value titles = json::Value::array(), prods = 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("owned", itemsToJson(owned_));+ root.set("purchasable", itemsToJson(purchasable_));+ // Details of what "Your games" shows; the catalog rows are fetched anyway.+ json::Value details = json::Value::object();+ for (const auto* list : {&owned_, &purchasable_})+ for (const auto& [pid, tid] : *list) {+ auto it = products_.find(pid);+ if (it != products_.end()) details.set(pid, productToJson(it->second));+ }root.set("products", details);+ json::Value platforms = json::Value::object(), xboxTitles = json::Value::object();+ for (const auto& [id, code] : platform_) platforms.set(id, code);+ for (const auto& [pid, xbox] : xboxTitleOf_) xboxTitles.set(pid, xbox);+ root.set("platforms", platforms);+ root.set("xboxTitles", xboxTitles);if (!platform::writeFileAtomic(cachePath_, root.dump())) XC_LOGW("library: could not write %s", cachePath_.c_str());}@@ -201,11 +228,16 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constproducts_.clear();allGames_.clear();gamePass_.clear();+ popular_.clear();recent_.clear();ownershipKnown_ = false;ownedTitles_.clear();ownedProducts_.clear();owned_.clear();+ purchasable_.clear();+ purchasableSet_.clear();+ xboxTitleOf_.clear();+ platform_.clear();std::string lastErr;// The Game Pass catalog first: it decides what the other lists may show.@@ -230,6 +262,7 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constfor (const auto& t : recent) {if (t.productId.empty()) continue;recent_.push_back(t.productId);+ if (!t.xboxTitleId.empty()) xboxTitleOf_[t.productId] = t.xboxTitleId;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);@@ -254,7 +287,9 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constlastErr = e;continue;}- // "Most popular on cloud" also lists games to buy first (Cuphead...).+ // "Most popular on cloud" also lists games to buy first (Cuphead...):+ // those go to "Your games" (in this order), not to the Game Pass tab.+ if (spec.sigl == xcloud::sigl::kMostPopular) popular_ = list.productIds;if (!gamePass_.empty()) {size_t before = list.productIds.size();list.productIds.erase(std::remove_if(list.productIds.begin(), list.productIds.end(),@@ -294,37 +329,56 @@ void Library::loadOwned(xcloud::GssvClient gssv, const Changed& changed, const s}if (stop && *stop) return;std::set<std::string> ownedTitles, ownedProducts;- std::vector<std::pair<std::string, std::string>> mine;+ std::vector<Item> mine;+ std::map<std::string, std::string> toBuy; // productId -> titleIdfor (const auto& t : titles) {- if (!t.hasEntitlement) continue;- ownedTitles.insert(t.titleId);- if (t.productId.empty()) continue;- ownedProducts.insert(t.productId);- if (!gamePass_.count(t.productId)) mine.emplace_back(t.productId, t.titleId);+ if (!t.productId.empty() && !t.xboxTitleId.empty()) xboxTitleOf_[t.productId] = t.xboxTitleId;+ if (t.hasEntitlement) {+ ownedTitles.insert(t.titleId);+ if (t.productId.empty()) continue;+ ownedProducts.insert(t.productId);+ if (!gamePass_.count(t.productId)) mine.emplace_back(t.productId, t.titleId);+ } else if (!t.productId.empty() && !gamePass_.count(t.productId)) {+ toBuy[t.productId] = t.titleId;+ }+ }+ // Games to buy: the most popular in the cloud first, then the rest.+ std::vector<Item> buy;+ for (const auto& id : popular_) {+ auto it = toBuy.find(id);+ if (it == toBuy.end()) continue;+ buy.emplace_back(it->first, it->second);+ toBuy.erase(it);}+ for (const auto& [pid, tid] : toBuy) buy.emplace_back(pid, tid);+std::vector<std::string> missing;for (const auto& m : mine)if (!products_.count(m.first)) missing.push_back(m.first);if (!missing.empty() && !xcloud::fetchProducts(missing, market_, language_, products_, err, false))XC_LOGW("%s", err.c_str());if (stop && *stop) return;- // 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());ownedTitles_ = std::move(ownedTitles);ownedProducts_ = std::move(ownedProducts);owned_ = std::move(mine);+ purchasable_ = std::move(buy);+ purchasableSet_.clear();+ for (const auto& p : purchasable_) purchasableSet_.insert(p.first);ownershipKnown_ = true;sortOwned();saveCache();- XC_LOGI("library: account can stream %zu titles; %zu outside Game Pass", ownedTitles_.size(), owned_.size());+ XC_LOGI("library: account can stream %zu titles; %zu outside Game Pass; %zu more to buy", ownedTitles_.size(),+ owned_.size(), purchasable_.size());changed();}void Library::loadCatalogNames(const Changed& changed, const std::atomic<bool>* stop) {+ // The Game Pass catalog (for its search), then the games to buy.std::vector<std::string> missing;for (const auto& id : allGames_)if (!products_.count(id)) missing.push_back(id);+ for (const auto& [id, tid] : purchasable_)+ 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;@@ -335,8 +389,38 @@ void Library::loadCatalogNames(const Changed& changed, const std::atomic<bool>*XC_LOGW("%s", e.c_str());return;}+ if (i == 0 || i + kBatch >= missing.size()) changed();}- XC_LOGI("library: search covers %zu games", searchPool().size());+ saveCache();+ XC_LOGI("library: search covers %zu Game Pass games and %zu of yours or to buy", gamePassSearchPool().size(),+ librarySearchPool().size());+ changed();+}++void Library::loadPlatforms(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop) {+ if (xblAuth.empty()) return;+ std::set<std::string> want;+ auto add = [&](const std::string& pid) {+ auto x = xboxTitleOf_.find(pid);+ std::string xbox = x != xboxTitleOf_.end() ? x->second : std::string();+ if (xbox.empty()) {+ auto p = products_.find(pid);+ if (p != products_.end()) xbox = p->second.xboxTitleId;+ }+ if (!xbox.empty() && !platform_.count(xbox)) want.insert(xbox);+ };+ for (const auto& r : layout_)+ for (const auto& item : r.items) add(item.first);+ for (const auto& item : owned_) add(item.first);+ for (const auto& item : purchasable_) add(item.first);+ for (const auto& id : allGames_) add(id);+ if (want.empty() || (stop && *stop)) return;+ std::vector<std::string> ids(want.begin(), want.end());+ std::string err;+ size_t before = platform_.size();+ if (!xcloud::fetchPlatforms(xblAuth, ids, platform_, err)) XC_LOGW("%s", err.c_str());+ XC_LOGI("library: consoles of %zu more games", platform_.size() - before);+ saveCache();changed();}@@ -344,11 +428,10 @@ 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;+ std::set<std::string> queued;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);+ if (it != products_.end() && it->second.heroUrl.empty() && queued.insert(id).second) order.push_back(id);};for (const auto& r : layout_)for (const auto& item : r.items) want(item.first);diff --git a/src/app/library.h b/src/app/library.hindex 992658a..9b7ce60 100644--- a/src/app/library.h+++ b/src/app/library.h@@ -1,22 +1,25 @@// SPDX-License-Identifier: GPL-3.0-or-later// Copyright (C) 2026 RafaelNGP-// What the home screen shows, in three tabs:+// What the home screen shows, in two tabs://// - 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.+// free-to-play), recently played first, then alphabetical; and below it+// the games that stream in the cloud once bought, most popular first.+//+// Each tab searches its own games. Every game carries the console it was+// made for (Xbox 360 / Xbox One / Series X|S), from titlehub.//// 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.+// screen can show right away) and reads the cache of the previous run, so+// "Your games" and the console badges are there at once; loadOwned()+// refreshes the account's titles (~12 s for ~2700); loadCatalogNames() adds+// names and art for the search and the games to buy; loadPlatforms() asks+// titlehub for the consoles; hydrate() adds hero art and descriptions. All+// but load() can run on another thread, one after the other.#pragma once#include "ui/app_ui.h"@@ -34,35 +37,43 @@ namespace xc::app {class Library {public:- // Called whenever rows(), owned() or searchPool() changed.+ // Called whenever anything the getters return changed.using Changed = std::function<void()>;- // Where the account cache lives (read by load(), written by loadOwned()).+ // Where the cache lives (read by load(), written by the later phases).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.+ // The account's titles: what it can play, what it could buy. 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.+ // Names and art of the whole Game Pass catalog and of the games to buy.void loadCatalogNames(const Changed& changed, const std::atomic<bool>* stop = nullptr);+ // Console generation of every known game; `xblAuth` from the profile.+ void loadPlatforms(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop = nullptr);// Hero art and descriptions, in batches; stops early when `stop` is set.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;+ // Games that stream once bought, most popular first.+ std::vector<ui::GameTile> purchasable() const;+ // What each tab's search looks through.+ std::vector<ui::GameTile> gamePassSearchPool() const;+ std::vector<ui::GameTile> librarySearchPool() const;// True once the account's games are known (from the cache or the service).bool ownedKnown() const { return ownershipKnown_; }private:+ using Item = std::pair<std::string, std::string>; // productId, titleIdstruct RowIds {std::string title;bool badges = true;- std::vector<std::pair<std::string, std::string>> items; // productId, titleId+ std::vector<Item> items;};ui::GameTile tile(const std::string& productId, const std::string& titleId) const;+ std::vector<ui::GameTile> tiles(const std::vector<Item>& items) const;void sortOwned();bool loadCache();void saveCache() const;@@ -73,11 +84,16 @@ private:std::map<std::string, xcloud::Product> products_;std::vector<std::string> allGames_; // the Game Pass catalog, in its orderstd::set<std::string> gamePass_; // ... as a set+ std::vector<std::string> popular_; // "Most popular on cloud", all of it (Game Pass or not)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+ std::vector<Item> owned_; // outside Game Pass+ std::vector<Item> purchasable_; // streamable once bought+ std::set<std::string> purchasableSet_;+ std::map<std::string, std::string> xboxTitleOf_; // productId -> Xbox title id+ std::map<std::string, std::string> platform_; // Xbox title id -> platform code};} // namespace xc::appdiff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex 6680d1d..51e72af 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -19,6 +19,7 @@#include "util/log.h"#include "xcloud/catalog.h"#include "xcloud/gssv.h"+#include "xcloud/regions.h"#include <atomic>#include <map>@@ -174,6 +175,7 @@ std::string stream(xcloud::GssvClient& gssv) {uint64_t nextTick = started;bool snapshot1 = false, snapshot2 = false;bool autoplayDone = false;+ int bestRtt = -1; // lowest round trip seen: the region's latencywhile (player.running() && !g_cancel) {uint64_t elapsed = platform::nowMs() - started;if (!g_autoplayTitle.empty()) {@@ -198,7 +200,8 @@ std::string stream(xcloud::GssvClient& gssv) {auto st = player.stats();XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, ""%llu queued, %llu audio; rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, "- "%llu frames dropped; %llu kbps (remb %llu); %llu rumble; decode %.1f/%.1f ms, draw %.1f/%.1f ms, %llu late",+ "%llu frames dropped; %llu kbps (remb %llu); %llu rumble; decode %.1f/%.1f ms, draw %.1f/%.1f ms, %llu late; "+ "rtt %d ms",static_cast<unsigned long long>(st.videoFrames), static_cast<unsigned long long>(st.decodedFrames),static_cast<unsigned long long>(st.droppedFrames), static_cast<unsigned long long>(st.decodeFailures),static_cast<unsigned long long>(st.queueResets), static_cast<unsigned long long>(st.keyframeRequests),@@ -208,7 +211,8 @@ std::string stream(xcloud::GssvClient& gssv) {static_cast<unsigned long long>(st.rtpDroppedFrames), static_cast<unsigned long long>(st.rtpKbps),static_cast<unsigned long long>(st.rembKbps), static_cast<unsigned long long>(st.vibrations),st.decodeAvgUs / 1000.0, st.decodeMaxUs / 1000.0, st.drawAvgUs / 1000.0, st.drawMaxUs / 1000.0,- static_cast<unsigned long long>(st.lateFrames));+ static_cast<unsigned long long>(st.lateFrames), st.rttMs);+ if (st.rttMs > 0 && (bestRtt < 0 || st.rttMs < bestRtt)) bestRtt = st.rttMs;}platform::sleepMs(100);}@@ -218,6 +222,18 @@ std::string stream(xcloud::GssvClient& gssv) {}std::string reason = g_cancel ? "left the game" : autoplayDone ? "autoplay finished" : player.endReason();player.stop();+ if (bestRtt > 0) {+ // Remembered per region: Settings shows it, the region fallback uses it.+ std::map<std::string, int> rtt;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ g_settings.regionRtt[gssv.region().name] = bestRtt;+ g_settings.save(settingsPath());+ rtt = g_settings.regionRtt;+ }+ XC_LOGI("region %s: %d ms round trip", gssv.region().name.c_str(), bestRtt);+ g_ui->setRegionLatency(rtt);+ }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.@@ -307,6 +323,8 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Gamevoid loadLibrary(xcloud::GssvClient& gssv);+// Profile token for titlehub (memory only).+std::string g_xblAuth;void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {g_ui->showSplash(ui::tr(am.hasStoredAccount() ? ui::Str::SigningIn : ui::Str::RequestingCode));std::string err;@@ -318,6 +336,10 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {return;}g_ui->setProfile(am.profile().gamertag, am.profile().gamerpicUrl);+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ g_xblAuth = am.profile().xblAuthorization;+ }platform::notify(ui::trf(ui::Str::SignedInAs, am.profile().gamertag));std::vector<std::string> regions;for (const auto& r : gssv.session().regions) regions.push_back(r.name);@@ -336,8 +358,8 @@ void loadLibrary(xcloud::GssvClient& gssv) {// 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());+ g_ui->setOwned(lib.owned(), lib.purchasable(), lib.ownedKnown());+ g_ui->setSearchPools(lib.gamePassSearchPool(), lib.librarySearchPool());};bool ok = library->load(gssv, ui::catalogLanguage(),[&] {@@ -357,10 +379,16 @@ void loadLibrary(xcloud::GssvClient& gssv) {// 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, publish, owned = gssv] {+ std::string xblAuth;+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ xblAuth = g_xblAuth;+ }+ platform::startThread(g_hydrationThread, [library, publish, owned = gssv, xblAuth] {auto changed = [&] { publish(*library); };library->loadOwned(owned, changed, &g_stopHydration);library->loadCatalogNames(changed, &g_stopHydration);+ library->loadPlatforms(xblAuth, changed, &g_stopHydration);library->hydrate(changed, &g_stopHydration);});if (!g_autoplayTitle.empty() && g_autoplayTitle != "BENCH") {@@ -413,12 +441,22 @@ void worker() {std::string result = play(am, gssv, tile, failed, region);XC_LOGI("%s", result.c_str());// Some games fail to start in one region only (Dead Cells in- // Brazil South quits at once with 0x8027025B but runs in East- // US): with the region on automatic, try another one once.+ // Brazil South quit at once with 0x8027025B, now and then, and+ // ran in East US): with the region on automatic, try the+ // nearest other one once.if (failed && g_gameClosedOnServer && automatic && !g_cancel) {+ // The nearest other region: measured in past sessions, or+ // estimated from the distance (xcloud/regions.h).std::string tried = gssv.region().name, next;- for (const auto& r : gssv.session().regions)- if (r.name != tried && (next.empty() || strcasecmp(r.name.c_str(), "EASTUS") == 0)) next = r.name;+ std::vector<std::string> names;+ for (const auto& r : gssv.session().regions) names.push_back(r.name);+ std::map<std::string, int> measured;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ measured = g_settings.regionRtt;+ }+ auto order = xcloud::regionsByExpectedRtt(tried, names, measured);+ if (!order.empty()) next = order.front();if (!next.empty()) {XC_LOGI("%s closed on the server in %s; trying %s", tile.titleId.c_str(), tried.c_str(),next.c_str());@@ -499,6 +537,7 @@ int main(int argc, char** argv) {choice.resolution = g_settings.resolution == "720p" ? 1 : g_settings.resolution == "1440p" ? 2 : 0;choice.region = g_settings.region;g_ui->setSettings(choice);+ g_ui->setRegionLatency(g_settings.regionRtt);}ui::Canvas canvas(display::kWidth, display::kHeight);@@ -552,7 +591,8 @@ int main(int argc, char** argv) {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.square = pad.btnX && !prev.btnX; // Square (Xbox X)+ nav.triangle = pad.btnY && !prev.btnY; // Triangle (Xbox Y)nav.touchpad = pad.btnTouchpad;nav.nowMs = now;prev = pad;diff --git a/src/app/settings.cpp b/src/app/settings.cppindex c5561ad..761eeb2 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -16,6 +16,9 @@ bool Settings::load(const std::string& path) {resolution = (*j)["resolution"].str(resolution);region = (*j)["region"].str(region);if (resolution != "720p" && resolution != "1440p") resolution = "1080p";+ regionRtt.clear();+ for (const auto& [name, ms] : (*j)["regionRtt"].members())+ if (ms.asInt() > 0) regionRtt[name] = static_cast<int>(ms.asInt());return true;}@@ -24,6 +27,9 @@ bool Settings::save(const std::string& path) const {v.set("language", language);v.set("resolution", resolution);v.set("region", region);+ json::Value rtt = json::Value::object();+ for (const auto& [name, ms] : regionRtt) rtt.set(name, ms);+ v.set("regionRtt", rtt);return platform::writeFileAtomic(path, v.dump());}diff --git a/src/app/settings.h b/src/app/settings.hindex 2ca9ef1..8586be3 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -3,6 +3,7 @@// User settings, kept in <dataDir>/settings.json.#pragma once+#include <map>#include <string>namespace xc::app {@@ -11,6 +12,8 @@ struct Settings {std::string language = "en"; // ui::languageCode()std::string resolution = "1080p"; // "1080p", "720p" or "1440p" (experimental)std::string region; // gssv region name; empty = automatic+ // Round trip to the stream server measured in past sessions, per region (ms).+ std::map<std::string, int> regionRtt;bool load(const std::string& path);bool save(const std::string& path) const;diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex 66650ad..ed7c46d 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -405,6 +405,7 @@ StreamPlayer::Stats StreamPlayer::stats() const {st.rtpDroppedFrames = v.framesDropped;st.keyframeRequests += v.keyframeRequests;st.rtpKbps = v.receiveRate / 1000;+ st.rttMs = impl_->session->rttMs();st.rembKbps = v.estimate / 1000;}{diff --git a/src/app/stream_player.h b/src/app/stream_player.hindex f41a681..6168571 100644--- a/src/app/stream_player.h+++ b/src/app/stream_player.h@@ -38,7 +38,8 @@ public:// RTP: packets lost, recovered by NACK, frames the jitter buffer dropped.uint64_t rtpPackets = 0, rtpLost = 0, rtpRecovered = 0, rtpNacks = 0, rtpDroppedFrames = 0;uint64_t rtpKbps = 0, rembKbps = 0, vibrations = 0;- uint64_t lateFrames = 0; // decoded, not drawn: both flips still queued+ uint64_t lateFrames = 0;+ int rttMs = -1; // to the stream server // decoded, not drawn: both flips still queued// Since the previous stats() call (so call it from one place only).uint64_t decodeAvgUs = 0, decodeMaxUs = 0, drawAvgUs = 0, drawMaxUs = 0;};diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cppindex 7403693..47a0488 100644--- a/src/auth/auth_manager.cpp+++ b/src/auth/auth_manager.cpp@@ -111,6 +111,7 @@ bool AuthManager::xboxChain(xcloud::GssvClient& gssv, std::string& err) {if (xstsToken(user, rp::kXboxLive, profileXsts, perr)) {profile_.gamertag = profileXsts.gamertag;profile_.xuid = profileXsts.xuid;+ profile_.xblAuthorization = profileXsts.authorizationHeader();fetchGamerpic(profileXsts);} else {XC_LOGW("profile XSTS: %s", perr.c_str());diff --git a/src/auth/auth_manager.h b/src/auth/auth_manager.hindex 946aba8..652f841 100644--- a/src/auth/auth_manager.h+++ b/src/auth/auth_manager.h@@ -19,6 +19,9 @@ struct Profile {std::string gamertag;std::string xuid;std::string gamerpicUrl; // empty until fetched+ // "XBL3.0 x=...;token" for services on http://xboxlive.com (titlehub...).+ // Memory only: never logged or saved.+ std::string xblAuthorization;};class AuthManager {diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex 1b71615..9bbf690 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -607,6 +607,15 @@ void StreamSession::requestKeyframe() {}void StreamSession::tick() { impl_->tick(); }void StreamSession::close() { impl_->close(); }+int StreamSession::rttMs() const {+ try {+ if (impl_->pc)+ if (auto rtt = impl_->pc->rtt()) return static_cast<int>(rtt->count());+ } catch (const std::exception&) {+ }+ return -1;+}+const VideoReceiveStats& StreamSession::videoStats() const {if (impl_->videoReporter) {impl_->videoStats.receiveRate = impl_->videoReporter->receiveRate();diff --git a/src/stream/stream_session.h b/src/stream/stream_session.hindex 4f33c42..aec3d09 100644--- a/src/stream/stream_session.h+++ b/src/stream/stream_session.h@@ -68,6 +68,8 @@ public:// second from the thread that owns the GssvClient.void tick();void close();+ // Round trip to the stream server (SCTP), ms; -1 while unknown.+ int rttMs() const;// RTP loss / retransmission counters of the video track.const VideoReceiveStats& videoStats() const;diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 73802c1..d4880d9 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -50,6 +50,7 @@ constexpr int kLibraryCols = 6;constexpr int kResultCols = 4;constexpr int kGridTop = 236; // y of the first card rowconstexpr int kResultsX = 760;+constexpr int kSectionHeaderH = 96; // "Available to buy" heading in the gridconstexpr size_t kMaxResults = 60;// The search keyboard: 6 x 6 letters and digits, then Space / Delete / Clear.@@ -204,26 +205,47 @@ void AppUi::setRows(std::vector<GameRow> rows) {dirty_ = true;}-void AppUi::setOwned(std::vector<GameTile> tiles, bool known) {+void AppUi::setOwned(std::vector<GameTile> owned, std::vector<GameTile> purchasable, 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);+ const GameTile* was = libraryTile(gridFocus_);+ std::string focused = was ? was->productId : "";+ owned_ = std::move(owned);+ purchasable_ = std::move(purchasable);ownedKnown_ = known;gridFocus_ = 0;- for (size_t i = 0; i < owned_.size(); ++i)- if (owned_[i].productId == focused) gridFocus_ = static_cast<int>(i);+ for (int i = 0; libraryTile(i); ++i)+ if (libraryTile(i)->productId == focused) gridFocus_ = i;refreshDetail();dirty_ = true;}-void AppUi::setSearchPool(std::vector<GameTile> pool) {+void AppUi::setSearchPools(std::vector<GameTile> gamePass, std::vector<GameTile> library) {std::lock_guard<std::mutex> lock(mutex_);- pool_ = std::move(pool);- runSearch();+ gamePassPool_ = std::move(gamePass);+ libraryPool_ = std::move(library);+ if (searching_) {+ int keep = resultFocus_;+ runSearch();+ resultFocus_ = std::min(keep, std::max(0, static_cast<int>(results_.size()) - 1));+ }refreshDetail();dirty_ = true;}+void AppUi::setRegionLatency(std::map<std::string, int> ms) {+ std::lock_guard<std::mutex> lock(mutex_);+ regionMs_ = std::move(ms);+ dirty_ = true;+}++const GameTile* AppUi::libraryTile(int index) const {+ if (index < 0) return nullptr;+ size_t i = static_cast<size_t>(index);+ if (i < owned_.size()) return &owned_[i];+ i -= owned_.size();+ return i < purchasable_.size() ? &purchasable_[i] : nullptr;+}+Tab AppUi::tab() const {std::lock_guard<std::mutex> lock(mutex_);return tab_;@@ -246,8 +268,8 @@ void AppUi::refreshDetail() {};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);+ for (const auto* list : {&owned_, &purchasable_, &gamePassPool_, &libraryPool_})+ for (const auto& t : *list) take(t);}void AppUi::runSearch() {@@ -270,7 +292,7 @@ void AppUi::runSearch() {const GameTile* tile;};std::vector<Hit> hits;- for (const auto& t : pool_) {+ for (const auto& t : tab_ == Tab::GamePass ? gamePassPool_ : libraryPool_) {std::string name = fold(t.name);bool all = true;for (const auto& w : words)@@ -278,7 +300,7 @@ void AppUi::runSearch() {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;+ if (!t.playable) score += 3; // in "Your games": owned before games to buyhits.push_back({score, &t});}std::stable_sort(hits.begin(), hits.end(), [](const Hit& a, const Hit& b) {@@ -406,12 +428,40 @@ float gridTarget(int focus, int cols) { return static_cast<float>(std::max(0, fo} // namespace+AppUi::LibraryLayout AppUi::libraryLayout() const {+ // Caller holds mutex_. The account's games, then (after a header) the+ // games to buy, both kLibraryCols wide.+ LibraryLayout L;+ L.cols = kLibraryCols;+ int y = 0, row = 0, index = 0;+ for (int section = 0; section < 2; ++section) {+ const auto& list = section == 0 ? owned_ : purchasable_;+ if (list.empty()) continue;+ if (section == 1) {+ if (row > 0) y += 30;+ L.headerY[1] = y;+ y += kSectionHeaderH;+ }+ for (size_t i = 0; i < list.size(); ++i, ++index) {+ int col = static_cast<int>(i) % L.cols;+ if (col == 0) {+ L.rowY.push_back(y + static_cast<int>(i) / L.cols * kGridPitchY);+ L.rowFirst.push_back(index);+ ++row;+ }+ L.rowOf.push_back(row - 1);+ L.colOf.push_back(col);+ }+ y = L.rowY.back() + kGridPitchY;+ }+ return L;+}+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;+ tab_ = tab_ == Tab::GamePass ? Tab::Library : Tab::GamePass;+ searching_ = false;dirty_ = true;return;}@@ -421,6 +471,44 @@ void AppUi::handleHome(const NavInput& in, UiEvent& ev) {dirty_ = true;return;}+ if (in.triangle && !searching_) { // search this tab+ searching_ = true;+ searchOnKeys_ = true;+ query_.clear();+ runSearch();+ dirty_ = true;+ return;+ }+ if (searching_) {+ if (searchOnKeys_) {+ if (in.back || in.triangle) { // close the search+ searching_ = false;+ dirty_ = true;+ return;+ }+ handleSearchKeys(in);+ return;+ }+ if (in.back || in.triangle || (in.left && resultFocus_ % kResultCols == 0)) { // back to the keys+ searchOnKeys_ = true;+ dirty_ = true;+ return;+ }+ if (in.square && !query_.empty()) { // delete without going back to the keys+ query_.pop_back();+ runSearch();+ searchOnKeys_ = results_.empty();+ dirty_ = true;+ return;+ }+ 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_)]);+ return;+ }switch (tab_) {case Tab::GamePass: {if (rows_.empty()) break;@@ -438,44 +526,32 @@ void AppUi::handleHome(const NavInput& in, UiEvent& ev) {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);+ case Tab::Library: {+ if (!libraryTile(0)) break;+ LibraryLayout L = libraryLayout();+ int count = static_cast<int>(L.rowOf.size());+ int f = std::min(gridFocus_, count - 1), before = f;+ int row = L.rowOf[static_cast<size_t>(f)], col = L.colOf[static_cast<size_t>(f)];+ int rows = static_cast<int>(L.rowY.size());+ auto rowLen = [&](int r) {+ int next = r + 1 < rows ? L.rowFirst[static_cast<size_t>(r + 1)] : count;+ return next - L.rowFirst[static_cast<size_t>(r)];+ };+ if (in.right && f + 1 < count && L.rowOf[static_cast<size_t>(f + 1)] == row) ++f;+ if (in.left && col > 0) --f;+ if (in.down && row + 1 < rows) f = L.rowFirst[static_cast<size_t>(row + 1)] + std::min(col, rowLen(row + 1) - 1);+ if (in.up && row > 0) f = L.rowFirst[static_cast<size_t>(row - 1)] + std::min(col, rowLen(row - 1) - 1);+ if (f != before) {+ gridFocus_ = f;+ int y = L.rowY[static_cast<size_t>(L.rowOf[static_cast<size_t>(f)])];+ gridScroll_.target = static_cast<float>(std::max(0, y - kGridPitchY - 40));dirty_ = true;}- 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_)]);+ if (in.accept && libraryTile(f)) openDetails(*libraryTile(f));break;+ }}+ (void)ev;}void AppUi::handleSearchKeys(const NavInput& in) {@@ -754,10 +830,10 @@ 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)};+ const char* labels[2] = {tr(Str::TabGamePass), tr(Str::YourGames)};constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;- int widths[3], total = 0;- for (int i = 0; i < 3; ++i) {+ int widths[2], total = 0;+ for (int i = 0; i < 2; ++i) {widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;total += widths[i] + (i ? kGap : 0);}@@ -768,7 +844,7 @@ void AppUi::drawTabs(Canvas& c) {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) {+ for (int i = 0; i < 2; ++i) {bool on = static_cast<int>(tab_) == i;Rect r{x, kY, widths[i], kH};if (on) c.fillRect(r, kWhite, kH / 2);@@ -778,6 +854,60 @@ void AppUi::drawTabs(Canvas& c) {shoulder("R1", x - kGap + 40);}+namespace {++const char* platformLabel(const std::string& code) {+ if (code == "360") return "XBOX 360";+ if (code == "ONE") return "XBOX ONE";+ if (code == "XS") return "SERIES X|S";+ return nullptr;+}++// A shopping bag centred on (cx, cy), about 22x24 px: a game to buy.+void drawBag(Canvas& c, int cx, int cy, Color color) {+ c.fillRect({cx - 11, cy - 5, 22, 17}, color, 3);+ c.strokeArc(static_cast<float>(cx), static_cast<float>(cy - 5), 6, 2.5f, 3.1416f, 3.1416f, color);+}++} // namespace++void AppUi::drawCard(Canvas& c, const GameTile& t, int x, int y, bool focused, bool gamePassBadge) {+ 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);+ }+ // Bottom-left: GAME PASS, or BUY with a bag; a padlock (top right) when+ // it can't be played or bought.+ if (t.purchasable) {+ c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 70), 10);+ std::string label = tr(Str::BuyBadge);+ int w = fonts_.bold.measure(label, 13) + 46;+ Rect badge{x + 10, y + kCard - 34, w, 24};+ c.fillRect(badge, rgba(16, 124, 16, 235), 4);+ drawBag(c, badge.x + 16, badge.y + 11, kWhite);+ fonts_.bold.draw(c, label, badge.x + 34, badge.y + 4, 13, kWhite);+ } else if (!t.playable) {+ c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 150), 10);+ drawLock(c, x + kCard - 34, y + 30);+ } else if (gamePassBadge) {+ Rect badge{x + 10, y + kCard - 34, 96, 24};+ c.fillRect(badge, rgba(0, 0, 0, 210), 4);+ fonts_.bold.draw(c, "GAME PASS", badge.x + 9, badge.y + 4, 13, kWhite);+ }+ // Bottom-right: the console it was made for.+ if (const char* p = platformLabel(t.platform)) {+ int w = fonts_.bold.measure(p, 13) + 18;+ Rect badge{x + kCard - 10 - w, y + kCard - 34, w, 24};+ c.fillRect(badge, t.platform == "360" ? rgba(60, 60, 60, 225) : rgba(0, 0, 0, 210), 4);+ fonts_.bold.draw(c, p, badge.x + 9, badge.y + 4, 13, t.platform == "XS" ? rgba(120, 230, 120) : kWhite);+ }+ if (focused) c.strokeRect({x - 7, y - 7, kCard + 14, kCard + 14}, kWhite, 4, 16);+}+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));@@ -787,23 +917,10 @@ void AppUi::drawGrid(Canvas& c, const std::vector<GameTile>& tiles, int x0, intint 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);+ drawCard(c, tiles[i], x, y, focused, false);+ auto name = fonts_.semibold.wrap(tiles[i].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);@@ -813,10 +930,37 @@ void AppUi::drawGrid(Canvas& c, const std::vector<GameTile>& tiles, int x0, intvoid 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);+ const int left = (kW - kGridW) / 2;+ const int clipTop = kGridTop - 20;+ LibraryLayout L = libraryLayout();+ int offset = static_cast<int>(std::lround(gridScroll_.value));+ // "Available to buy": a heading with what it means, inside the grid.+ if (!purchasable_.empty()) {+ int hy = kGridTop + L.headerY[1] - offset;+ if (hy > clipTop - 80 && hy < kH) {+ drawBag(c, left + 14, hy + 30, kGreen);+ fonts_.bold.draw(c, tr(Str::AvailableToBuy), left + 40, hy + 8, 34, kWhite);+ int w = fonts_.bold.measure(tr(Str::AvailableToBuy), 34);+ fonts_.semibold.draw(c, trf(Str::GamesCount, std::to_string(purchasable_.size())), left + 60 + w, hy + 20,+ 22, kDim);+ fonts_.regular.draw(c, tr(Str::BuyToPlay), left + 40, hy + 52, 22, kGray);+ }+ }+ for (size_t i = 0; i < L.rowOf.size(); ++i) {+ int y = kGridTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;+ if (y + kCard + 40 < clipTop) continue;+ if (y > kH) break;+ int x = left + L.colOf[i] * kCardPitch;+ const GameTile* t = libraryTile(static_cast<int>(i));+ bool focused = static_cast<int>(i) == gridFocus_;+ drawCard(c, *t, x, y, focused, false);+ 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);+ }+ c.fillRect({0, 0, kW, clipTop}, kBg);+ c.gradientV({0, clipTop, kW, 12}, kBg, withAlpha(kBg, 0));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()));@@ -825,12 +969,15 @@ void AppUi::drawLibrary(Canvas& c, uint64_t nowMs) {drawSpinner(c, kW / 2.0f, 470, 26, nowMs);drawCentered(c, fonts_.semibold, tr(Str::LoadingGames), 530, 28, kGray);animating_ = true;- } else {+ } else if (purchasable_.empty()) {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)}});+ drawHints(c, {{kIconCross, tr(Str::Select)},+ {kIconTriangle, tr(Str::TabSearch)},+ {kIconOptions, tr(Str::Settings)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});drawToast(c, nowMs);}@@ -841,6 +988,7 @@ void AppUi::drawSearch(Canvas& c, uint64_t nowMs) {kGridTop - 20);drawTopBar(c);drawTabs(c);+ const char* scope = tab_ == Tab::GamePass ? tr(Str::TabGamePass) : tr(Str::YourGames);if (query_.empty()) {fonts_.semibold.draw(c, tr(Str::SearchHint), kResultsX, 150, 26, kDim);} else if (results_.empty()) {@@ -856,12 +1004,12 @@ void AppUi::drawSearch(Canvas& c, uint64_t nowMs) {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);+ fonts_.regular.draw(c, trf(Str::SearchIn, scope), tx, box.y + 22, 26, 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_ && (nowMs / 530) % 2 == 0) c.fillRect({query_.empty() ? box.x + 20 : tx, box.y + 18, 3, 40}, kWhite);if (searchOnKeys_) animating_ = true; // the caret blinks// The keys.@@ -885,15 +1033,15 @@ void AppUi::drawSearch(Canvas& c, uint64_t nowMs) {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)}});+ drawHints(c, {{kIconCross, tr(Str::KeyType)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconCircle, tr(Str::Back)}});elsedrawHints(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 (searching_) return drawSearch(c, 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);@@ -932,31 +1080,17 @@ void AppUi::drawHome(Canvas& c, uint64_t nowMs) {int x = kMargin + static_cast<int>(col) * kCardPitch - scroll;if (x > kW) break;if (x + kCard < 0) continue;- const GameTile& t = row.tiles[col];bool focused = static_cast<int>(r) == focusRow_ && static_cast<int>(col) == focusCol_[r];- if (auto img = images_.get(t.tileUrl, kCard, kCard)) {- c.drawImage(*img, x, cardY, 255, 10);- } else {- c.fillRect({x, cardY, kCard, kCard}, kPlaceholder, 10);- auto lines = fonts_.semibold.wrap(t.name, 22, kCard - 32, 3);- for (size_t i = 0; i < lines.size(); ++i)- fonts_.semibold.draw(c, lines[i], x + 16, cardY + 16 + static_cast<int>(i) * 30, 22, kGray);- }- if (!t.playable) { // dimmed, with a lock: can't be streamed on this account- c.fillRect({x, cardY, kCard, kCard}, rgba(0, 0, 0, 150), 10);- drawLock(c, x + kCard - 34, cardY + 30);- } else if (row.gamePassBadges) {- Rect badge{x + 10, cardY + kCard - 34, 96, 24};- c.fillRect(badge, rgba(0, 0, 0, 210), 4);- fonts_.bold.draw(c, "GAME PASS", badge.x + 9, badge.y + 4, 13, kWhite);- }- if (focused) c.strokeRect({x - 7, cardY - 7, kCard + 14, kCard + 14}, kWhite, 4, 16);+ drawCard(c, row.tiles[col], x, cardY, focused, row.gamePassBadges);}}// Fade the rows out under the button hints.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)}});+ drawHints(c, {{kIconCross, tr(Str::Select)},+ {kIconTriangle, tr(Str::TabSearch)},+ {kIconOptions, tr(Str::Settings)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});drawToast(c, nowMs);}@@ -964,7 +1098,19 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {const GameTile* g = &detail_;c.clear(kBg);if (g->productId.empty()) return;- drawHero(c, nowMs, g->heroUrl, true);+ // Without hero art yet (games to buy, search results): the cover on the+ // right instead of another game's backdrop.+ constexpr int kCover = 420;+ const Rect cover{kW - kMargin - kCover, 170, kCover, kCover};+ if (g->heroUrl.empty()) {+ drawBackground(c);+ prevHeroUrl_.clear();+ heroUrl_.clear();+ if (auto img = images_.get(g->tileUrl, kCover, kCover)) c.drawImage(*img, cover.x, cover.y, 255, 16);+ else c.fillRect(cover, kPlaceholder, 16);+ } else {+ drawHero(c, nowMs, g->heroUrl, true);+ }drawTopBar(c);int y = 260;for (const auto& line : fonts_.bold.wrap(g->name, 68, 960, 2)) {@@ -977,6 +1123,7 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {y += 40;}std::string cats;+ if (const char* p = platformLabel(g->platform)) cats = p;for (const auto& cat : g->categories) cats += (cats.empty() ? "" : " \xE2\x80\xA2 ") + cat;if (!cats.empty()) {fonts_.regular.draw(c, cats, kMargin, y, 24, kDim);@@ -987,6 +1134,39 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {fonts_.regular.draw(c, line, kMargin, y, 24, kGray);y += 34;}+ if (g->purchasable) {+ // Streams once bought: say where to buy it, with a QR code of the+ // store page for the phone.+ int ny = std::max(y + 40, 600);+ Rect note{kMargin, ny, 620, 76};+ c.fillRect(note, rgba(16, 124, 16, 235), 38);+ drawBag(c, note.x + 50, note.y + note.h / 2, kWhite);+ fonts_.semibold.draw(c, tr(Str::BuyToPlay), note.x + 86, note.y + 22, 26, kWhite);+ auto hint = fonts_.regular.wrap(tr(Str::BuyHint), 22, 760, 2);+ for (size_t i = 0; i < hint.size(); ++i)+ fonts_.regular.draw(c, hint[i], kMargin, ny + 100 + static_cast<int>(i) * 32, 22, kGray);+ std::string url = "https://www.xbox.com/games/store/p/" + g->productId;+ uint8_t qr[qrcodegen_BUFFER_LEN_MAX], tmp[qrcodegen_BUFFER_LEN_MAX];+ if (qrcodegen_encodeText(url.c_str(), tmp, qr, qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN,+ qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {+ // Under the cover, centred, on a dark panel with its caption.+ int n = qrcodegen_getSize(qr);+ int module = 220 / (n + 2), size = module * (n + 2);+ int w = fonts_.regular.measure(tr(Str::ScanToBuy), 20);+ Rect panel{cover.x + (cover.w - std::max(size + 40, w + 40)) / 2, cover.y + cover.h + 24,+ std::max(size + 40, w + 40), size + 76};+ c.fillRect(panel, rgba(20, 20, 20, 235), 18);+ Rect box{panel.x + (panel.w - size - 20) / 2, panel.y + 14, size + 20, size + 20};+ c.fillRect(box, kWhite, 12);+ int ox = box.x + 10 + module, oy = box.y + 10 + module;+ for (int yy = 0; yy < n; ++yy)+ for (int xx = 0; xx < n; ++xx)+ if (qrcodegen_getModule(qr, xx, yy)) c.fillRect({ox + xx * module, oy + yy * module, module, module}, kBg);+ fonts_.regular.draw(c, tr(Str::ScanToBuy), panel.x + (panel.w - w) / 2, box.y + box.h + 12, 20, kGray);+ }+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+ return;+ }if (!g->playable) {// Bought separately or outside the subscription: no Play button.Rect note{kMargin, std::max(y + 48, 620), 560, 76};@@ -1046,6 +1226,11 @@ void AppUi::drawSettings(Canvas& c) {std::string region = settings_.region.empty()? trf(Str::RegionAuto, defaultRegion_.empty() ? "-" : prettyRegion(defaultRegion_)): prettyRegion(settings_.region);+ {+ const std::string& shown = settings_.region.empty() ? defaultRegion_ : settings_.region;+ auto ms = regionMs_.find(shown);+ if (ms != regionMs_.end()) region += " \xE2\x80\xA2 " + std::to_string(ms->second) + " ms";+ }const Row rows[] = {{tr(Str::Language), languageName(static_cast<Language>(settings_.language))},{tr(Str::Resolution), tr(settings_.resolution == 1 ? Str::Res720: settings_.resolution == 2 ? Str::Res1440diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 452aee0..af14e1c 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -13,6 +13,7 @@#include "ui/image_cache.h"#include <cstdint>+#include <map>#include <mutex>#include <string>#include <vector>@@ -31,6 +32,11 @@ struct GameTile {// False once the account's titles are known and this one isn't among// them (bought separately, or not in the subscription).bool playable = true;+ // Not playable, but streams in the cloud once bought.+ bool purchasable = false;+ // Console it was made for: "360", "ONE", "XS" (xcloud/titlehub.h); empty+ // while unknown.+ std::string platform;};struct GameRow {@@ -41,13 +47,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 };+// The home screen's tabs (L1 / R1). Triangle searches the current one.+enum class Tab { GamePass, Library };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 l1 = false, r1 = false, square = false, triangle = false;bool touchpad = false; // held right now (sign out needs a 5 s hold)uint64_t nowMs = 0;};@@ -80,10 +86,13 @@ 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);+ // "Your games": the account's games, then those to buy; `known` false+ // while the account's games load.+ void setOwned(std::vector<GameTile> owned, std::vector<GameTile> purchasable, bool known);+ // What each tab's search looks through.+ void setSearchPools(std::vector<GameTile> gamePass, std::vector<GameTile> library);+ // Measured round trip to each region, ms (shown in Settings).+ void setRegionLatency(std::map<std::string, int> ms);void showHome(const std::string& toast = {});void showLaunching(const GameTile& game, const std::string& status);void setLaunchStatus(const std::string& status);@@ -123,9 +132,21 @@ private:void drawTabs(Canvas& c);void drawLibrary(Canvas& c, uint64_t nowMs);void drawSearch(Canvas& c, uint64_t nowMs);+ void drawCard(Canvas& c, const GameTile& t, int x, int y, bool focused, bool gamePassBadge);// 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);+ // "Your games" as one grid of two sections: the tile index of `focus`,+ // its row, and each section's first row and header position.+ struct LibraryLayout {+ int cols = 6;+ std::vector<int> rowOf, colOf; // per tile index (owned, then purchasable)+ std::vector<int> rowY; // per row, y relative to the grid top+ std::vector<int> rowFirst; // first tile index of each row+ int headerY[2] = {0, 0}; // section headers, relative+ };+ LibraryLayout libraryLayout() const;+ const GameTile* libraryTile(int index) const;void handleHome(const NavInput& in, UiEvent& ev);void handleSearchKeys(const NavInput& in);void runSearch();@@ -153,11 +174,12 @@ private:std::vector<Anim> rowScroll_;Anim rowY_;Tab tab_ = Tab::GamePass;- std::vector<GameTile> owned_;+ std::vector<GameTile> owned_, purchasable_;bool ownedKnown_ = false;int gridFocus_ = 0;Anim gridScroll_;- std::vector<GameTile> pool_, results_;+ bool searching_ = false; // the search of `tab_` is open+ std::vector<GameTile> gamePassPool_, libraryPool_, results_;std::string query_;bool searchOnKeys_ = true;int keyRow_ = 0, keyCol_ = 0;@@ -169,6 +191,7 @@ private:SettingsChoice settings_;std::vector<std::string> regions_;std::string defaultRegion_;+ std::map<std::string, int> regionMs_;int settingsRow_ = 0;uint64_t signOutHoldStart_ = 0; // TOUCHPAD hold in progressbool signOutLatched_ = false; // fired; wait for releasediff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex 7a4fd73..0639115 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -89,6 +89,12 @@ constexpr Column kEnglish = {"%s games", // GamesCount"Type", // KeyType"Trying another region: %s", // TryingRegion+ "Available to buy", // AvailableToBuy+ "BUY", // BuyBadge+ "Buy this game to play it in the cloud", // BuyToPlay+ "Buy it on xbox.com or in the Xbox app; it then shows up in Your games.", // BuyHint+ "Scan to open the store page", // ScanToBuy+ "Search in %s", // SearchIn};constexpr Column kPortugueseBR = {@@ -148,6 +154,12 @@ constexpr Column kPortugueseBR = {"%s jogos","Digitar","Tentando outra região: %s",+ "Disponíveis para comprar",+ "COMPRAR",+ "Compre este jogo para jogá-lo na nuvem",+ "Compre em xbox.com ou no app Xbox; depois ele aparece em Seus jogos.",+ "Escaneie para abrir a página da loja",+ "Pesquisar em %s",};constexpr Column kSpanish = {@@ -207,6 +219,12 @@ constexpr Column kSpanish = {"%s juegos","Escribir","Probando otra región: %s",+ "Disponibles para comprar",+ "COMPRAR",+ "Compra este juego para jugarlo en la nube",+ "Cómpralo en xbox.com o en la app de Xbox; luego aparecerá en Tus juegos.",+ "Escanea para abrir la página de la tienda",+ "Buscar en %s",};constexpr Column kFrench = {@@ -266,6 +284,12 @@ constexpr Column kFrench = {"%s jeux","Taper","Essai d'une autre région : %s",+ "Disponibles à l'achat",+ "ACHETER",+ "Achetez ce jeu pour y jouer dans le cloud",+ "Achetez-le sur xbox.com ou dans l'app Xbox ; il apparaîtra ensuite dans Vos jeux.",+ "Scannez pour ouvrir la page du magasin",+ "Rechercher dans %s",};constexpr Column kGerman = {@@ -325,6 +349,12 @@ constexpr Column kGerman = {"%s Spiele","Tippen","Andere Region wird versucht: %s",+ "Zum Kaufen verfügbar",+ "KAUFEN",+ "Kaufe dieses Spiel, um es in der Cloud zu spielen",+ "Kaufe es auf xbox.com oder in der Xbox-App; danach erscheint es unter Deine Spiele.",+ "Scannen, um die Store-Seite zu öffnen",+ "Suchen in %s",};constexpr Column kItalian = {@@ -384,6 +414,12 @@ constexpr Column kItalian = {"%s giochi","Scrivi","Provo un'altra regione: %s",+ "Disponibili per l'acquisto",+ "ACQUISTA",+ "Acquista questo gioco per giocarci nel cloud",+ "Acquistalo su xbox.com o nell'app Xbox; poi apparirà in I tuoi giochi.",+ "Scansiona per aprire la pagina dello store",+ "Cerca in %s",};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex 3480548..adbfd79 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -66,6 +66,12 @@ enum class Str {GamesCount, // "%s" = numberKeyType, // hint: press to type the focused keyTryingRegion, // "%s" = region name+ AvailableToBuy, // section of games that stream once bought+ BuyBadge, // short, on the card+ BuyToPlay,+ BuyHint,+ ScanToBuy,+ SearchIn, // "%s" = tab nameCount};diff --git a/src/xcloud/catalog.cpp b/src/xcloud/catalog.cppindex 6b95fdc..dd6791e 100644--- a/src/xcloud/catalog.cpp+++ b/src/xcloud/catalog.cpp@@ -73,6 +73,8 @@ bool fetchProducts(const std::vector<std::string>& ids, const std::string& markeprod.productId = id;prod.xcloudTitleId = p["XCloudTitleId"].str();prod.title = p["ProductTitle"].str();+ prod.xboxTitleId = p["XboxTitleId"].str();+ if (prod.xboxTitleId.empty()) prod.xboxTitleId = p["ChildXboxTitleIds"][0].str();prod.publisher = p["PublisherName"].str();prod.description = p["ProductDescriptionShort"].str();if (prod.description.empty()) prod.description = p["ProductDescription"].str();diff --git a/src/xcloud/catalog.h b/src/xcloud/catalog.hindex ca4ef17..51bbac2 100644--- a/src/xcloud/catalog.h+++ b/src/xcloud/catalog.h@@ -15,6 +15,7 @@ namespace xc::xcloud {struct Product {std::string productId; // Store "big id"std::string xcloudTitleId; // empty: not streamable+ std::string xboxTitleId; // Xbox Live title id (titlehub), may be emptystd::string title;std::string publisher;std::string description;diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cppindex 8e59817..bf87806 100644--- a/src/xcloud/gssv.cpp+++ b/src/xcloud/gssv.cpp@@ -235,6 +235,7 @@ bool GssvClient::listTitles(std::vector<Title>& out, std::string& err, bool recetitle.titleId = t["titleId"].str();title.productId = t["details"]["productId"].str();title.hasEntitlement = t["details"]["hasEntitlement"].asBool();+ title.xboxTitleId = t["details"]["xboxTitleId"].str();if (!title.titleId.empty()) out.push_back(std::move(title));}continuation = recentOnly ? std::string() : (*j)["continuationToken"].str();diff --git a/src/xcloud/gssv.h b/src/xcloud/gssv.hindex 7467b66..2b3c781 100644--- a/src/xcloud/gssv.h+++ b/src/xcloud/gssv.h@@ -36,6 +36,7 @@ struct Title {std::string name; // filled in by hydrateTitles()std::string imageUrl; // box art / tilebool hasEntitlement = false;+ std::string xboxTitleId; // Xbox Live title id (titlehub)};enum class SessionState { Unknown, Provisioning, WaitingForResources, ReadyToConnect, Provisioned, Failed };diff --git a/src/xcloud/regions.cpp b/src/xcloud/regions.cppnew file mode 100644index 0000000..c8739a0--- /dev/null+++ b/src/xcloud/regions.cpp@@ -0,0 +1,76 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "xcloud/regions.h"++#include <algorithm>+#include <cctype>+#include <cmath>++namespace xc::xcloud {++namespace {++struct Location {+ const char* name;+ double lat, lon;+};++// Approximate datacenter cities of the Azure regions xCloud uses.+constexpr Location kRegions[] = {+ {"AUSTRALIAEAST", -33.87, 151.21}, {"AUSTRALIASOUTHEAST", -37.81, 144.96},+ {"BRAZILSOUTH", -23.55, -46.63}, {"CANADACENTRAL", 43.65, -79.38},+ {"CENTRALINDIA", 18.52, 73.86}, {"CENTRALUS", 41.59, -93.60},+ {"CHILECENTRAL", -33.45, -70.67}, {"EASTASIA", 22.27, 114.19},+ {"EASTUS", 37.37, -79.82}, {"EASTUS2", 36.68, -78.39},+ {"FRANCECENTRAL", 46.30, 2.40}, {"GERMANYWESTCENTRAL", 50.11, 8.68},+ {"ITALYNORTH", 45.46, 9.19}, {"JAPANEAST", 35.68, 139.77},+ {"JAPANWEST", 34.69, 135.50}, {"KOREACENTRAL", 37.57, 126.98},+ {"MEXICOCENTRAL", 20.59, -100.39}, {"NORTHCENTRALUS", 41.88, -87.63},+ {"NORTHEUROPE", 53.35, -6.26}, {"POLANDCENTRAL", 52.23, 21.01},+ {"SOUTHCENTRALUS", 29.42, -98.49}, {"SOUTHEASTASIA", 1.28, 103.83},+ {"SOUTHINDIA", 12.98, 80.16}, {"SPAINCENTRAL", 40.42, -3.70},+ {"SWEDENCENTRAL", 60.67, 17.14}, {"UAENORTH", 25.27, 55.30},+ {"UKSOUTH", 51.51, -0.13}, {"WESTEUROPE", 52.37, 4.90},+ {"WESTUS", 37.78, -122.42}, {"WESTUS2", 47.23, -119.85},+ {"WESTUS3", 33.45, -112.07},+};++const Location* find(const std::string& name) {+ std::string upper = name;+ for (auto& ch : upper) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));+ for (const auto& r : kRegions)+ if (upper == r.name) return &r;+ return nullptr;+}++} // namespace++double regionDistanceKm(const std::string& a, const std::string& b) {+ const Location *p = find(a), *q = find(b);+ if (!p || !q) return -1;+ constexpr double kRad = 3.14159265358979 / 180.0;+ double dlat = (q->lat - p->lat) * kRad, dlon = (q->lon - p->lon) * kRad;+ double h = std::sin(dlat / 2) * std::sin(dlat / 2) ++ std::cos(p->lat * kRad) * std::cos(q->lat * kRad) * std::sin(dlon / 2) * std::sin(dlon / 2);+ return 2 * 6371.0 * std::asin(std::min(1.0, std::sqrt(h)));+}++std::vector<std::string> regionsByExpectedRtt(const std::string& from, const std::vector<std::string>& candidates,+ const std::map<std::string, int>& measured) {+ auto fromIt = measured.find(from);+ double base = fromIt != measured.end() ? fromIt->second : 30.0; // the default region: nearby+ std::vector<std::pair<double, std::string>> scored;+ for (const auto& c : candidates) {+ if (c == from) continue;+ auto m = measured.find(c);+ double km = regionDistanceKm(from, c);+ double expected = m != measured.end() ? m->second : km >= 0 ? base + km / 100.0 : 1e6;+ scored.emplace_back(expected, c);+ }+ std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first < b.first; });+ std::vector<std::string> out;+ for (const auto& s : scored) out.push_back(s.second);+ return out;+}++} // namespace xc::xclouddiff --git a/src/xcloud/regions.h b/src/xcloud/regions.hnew file mode 100644index 0000000..895007c--- /dev/null+++ b/src/xcloud/regions.h@@ -0,0 +1,25 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// Which xCloud region to fall back to. Latency to a region can't be measured+// before a session runs there: the regions' API hosts share one gateway per+// continent (brs/eus/wus3 all resolve to the same address) and the login's+// networkTestHostname entries no longer resolve. So: round trips measured in+// past sessions where known, otherwise an estimate from the distance between+// the regions (light in fibre: about 1 ms of round trip per 100 km).+#pragma once++#include <map>+#include <string>+#include <vector>++namespace xc::xcloud {++// Great-circle distance between two Azure regions, km; -1 if either is unknown.+double regionDistanceKm(const std::string& a, const std::string& b);++// `candidates` other than `from`, by expected round trip, lowest first.+// `measured`: ms per region from past sessions.+std::vector<std::string> regionsByExpectedRtt(const std::string& from, const std::vector<std::string>& candidates,+ const std::map<std::string, int>& measured);++} // namespace xc::xclouddiff --git a/src/xcloud/titlehub.cpp b/src/xcloud/titlehub.cppnew file mode 100644index 0000000..e8850d2--- /dev/null+++ b/src/xcloud/titlehub.cpp@@ -0,0 +1,57 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "xcloud/titlehub.h"++#include "net/http.h"+#include "util/json.h"++#include <algorithm>++namespace xc::xcloud {++bool fetchPlatforms(const std::string& auth, const std::vector<std::string>& xboxTitleIds,+ std::map<std::string, std::string>& out, std::string& err) {+ constexpr size_t kBatch = 100;+ for (size_t i = 0; i < xboxTitleIds.size(); i += kBatch) {+ json::Value ids = json::Value::array();+ for (size_t k = i; k < xboxTitleIds.size() && k < i + kBatch; ++k) ids.push(xboxTitleIds[k]);+ json::Value body = json::Value::object();+ body.set("pfns", nullptr);+ body.set("titleIds", ids);+ net::Request req;+ req.method = "POST";+ req.url = "https://titlehub.xboxlive.com/titles/batch/decoration/detail";+ req.headers = {{"Authorization", auth},+ {"x-xbl-contract-version", "2"},+ {"Content-Type", "application/json"},+ {"Accept-Language", "en-US"}};+ req.body = body.dump();+ auto r = net::perform(req);+ auto j = json::parse(r.body);+ if (!r.ok() || !j) {+ err = "titlehub: " + (r.status ? "HTTP " + std::to_string(r.status) : r.error);+ return false;+ }+ for (const auto& t : (*j)["titles"].items()) {+ bool has360 = false, hasOne = false, hasSeries = false, optimized = false;+ for (const auto& d : t["devices"].items()) {+ has360 |= d.str() == "Xbox360";+ hasOne |= d.str() == "XboxOne";+ hasSeries |= d.str() == "XboxSeries";+ }+ for (const auto& a : t["detail"]["attributes"].items()) optimized |= a["name"].str() == "ConsoleGen9Optimized";+ const char* code = has360 ? kPlatform360+ : optimized || (hasSeries && !hasOne) ? kPlatformSeries+ : hasOne || hasSeries ? kPlatformOne+ : nullptr; // PC-only entries+ if (!code) continue;+ // The id asked for may be an older one titlehub maps to its+ // current id: record both.+ out[t["titleId"].str()] = code;+ if (!t["modernTitleId"].str().empty()) out[t["modernTitleId"].str()] = code;+ }+ }+ return true;+}++} // namespace xc::xclouddiff --git a/src/xcloud/titlehub.h b/src/xcloud/titlehub.hnew file mode 100644index 0000000..d55e783--- /dev/null+++ b/src/xcloud/titlehub.h@@ -0,0 +1,24 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// Xbox Live titlehub: which console generation a game was made for. The+// store catalogs list Xbox 360 games that run through backward+// compatibility as Xbox One games; titlehub's "devices" still name Xbox 360.+#pragma once++#include <map>+#include <string>+#include <vector>++namespace xc::xcloud {++// Short platform codes for the badges.+constexpr const char* kPlatform360 = "360";+constexpr const char* kPlatformOne = "ONE";+constexpr const char* kPlatformSeries = "XS";++// `auth`: "XBL3.0 x=...;token" for http://xboxlive.com. Fills `out`+// (xbox title id -> platform code) for the ids titlehub knows; batched.+bool fetchPlatforms(const std::string& auth, const std::vector<std::string>& xboxTitleIds,+ std::map<std::string, std::string>& out, std::string& err);++} // namespace xc::xclouddiff --git a/tests/test_main.cpp b/tests/test_main.cppindex fdd2a4a..613a02a 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -7,6 +7,7 @@#include "ui/app_ui.h"#include "ui/strings.h"#include "util/json.h"+#include "xcloud/regions.h"#include <cstdio>#include <string>@@ -135,8 +136,25 @@ static void testStrings() {CHECK(prettyRegion("BRAZILSOUTH") == "Brazil South");}+static void testRegions() {+ using xc::xcloud::regionsByExpectedRtt;+ std::vector<std::string> all = {"BRAZILSOUTH", "EASTUS", "WESTEUROPE", "CHILECENTRAL", "JAPANEAST", "UNKNOWN"};+ // Nothing measured: by distance, the unknown region last.+ auto order = regionsByExpectedRtt("BRAZILSOUTH", all, {});+ CHECK(order.size() == 5);+ CHECK(order.front() == "CHILECENTRAL");+ CHECK(order[1] == "EASTUS");+ CHECK(order.back() == "UNKNOWN");+ // A measured round trip beats an estimate.+ order = regionsByExpectedRtt("BRAZILSOUTH", all, {{"BRAZILSOUTH", 15}, {"EASTUS", 40}});+ CHECK(order.front() == "EASTUS");+ double km = xc::xcloud::regionDistanceKm("brazilsouth", "CHILECENTRAL");+ CHECK(km > 2500 && km < 3000);+}+int main() {testStrings();+ testRegions();testJson();testUrl();testInputPacket();