Xbox Cloud Gaming app for PS5 Homebrew
C
Fast first screen, prices for games to buy, badge fixes
Rafael Abud Ferreiraf85956e3035c
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 31a3a31..4f4df41 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -23,6 +23,7 @@ add_library(xcloud_core STATICsrc/xcloud/catalog.cppsrc/xcloud/titlehub.cppsrc/xcloud/regions.cpp+ src/xcloud/prices.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 c9be88a..27cd245 100644--- a/src/app/cli_main.cpp+++ b/src/app/cli_main.cpp@@ -28,6 +28,7 @@#include "ui/brand.h"#include "ui/strings.h"#include "xcloud/gssv.h"+#include "xcloud/prices.h"#define STB_IMAGE_WRITE_IMPLEMENTATION#define STB_IMAGE_WRITE_STATIC@@ -345,6 +346,18 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {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"+ {+ // What the app's price thread does: ask for the cards on screen.+ std::map<std::string, xcloud::Price> got;+ std::string e;+ xcloud::fetchPrices(app.pricesWanted(40), gssv.session().market.empty() ? "US" : gssv.session().market,+ ui::catalogLanguage(), got, e);+ std::map<std::string, std::pair<std::string, std::string>> texts;+ for (const auto& [id, p] : got)+ texts[id] = {p.list < 0.005 ? ui::tr(ui::Str::Free) : xcloud::formatPrice(p.list, p.currency),+ p.msrp > p.list + 0.005 ? xcloud::formatPrice(p.msrp, p.currency) : std::string()};+ app.setPrices(texts);+ }save("library_buy", 3000);press([](ui::NavInput& n) { n.accept = true; }, 1);save("details_buy", 2000);diff --git a/src/app/library.cpp b/src/app/library.cppindex 0094138..03e54c0 100644--- a/src/app/library.cpp+++ b/src/app/library.cpp@@ -65,6 +65,10 @@ json::Value itemsToJson(const std::vector<std::pair<std::string, std::string>>&return a;}+bool namesSeries(const std::string& title) {+ return title.find("Series X|S") != std::string::npos || title.find("Series X/S") != std::string::npos;+}+// 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.@@ -100,10 +104,23 @@ ui::GameTile Library::tile(const std::string& productId, const std::string& titlt.categories = p.categories;if (ownershipKnown_) t.playable = ownedTitles_.count(t.titleId) || ownedProducts_.count(t.productId);t.purchasable = !t.playable && purchasableSet_.count(productId);+ if (siblingsFor_ != products_.size()) {+ seriesSiblings_.clear();+ for (const auto& [id, prod] : products_) {+ if (!namesSeries(prod.title)) continue;+ auto xs = xboxTitleOf_.find(id);+ seriesSiblings_.insert(xs != xboxTitleOf_.end() ? xs->second : prod.xboxTitleId);+ }+ siblingsFor_ = products_.size();+ }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;+ // Cross-gen pairs ("Call of Duty: Vanguard" and "... - Xbox Series X|S")+ // are two cloud titles sharing one Xbox title id: the name tells them apart.+ if (namesSeries(p.title)) t.platform = xcloud::kPlatformSeries;+ else if (t.platform == xcloud::kPlatformSeries && seriesSiblings_.count(xbox)) t.platform = xcloud::kPlatformOne;return t;}@@ -205,13 +222,17 @@ void Library::saveCache() const {root.set("ownedProducts", prods);root.set("owned", itemsToJson(owned_));root.set("purchasable", itemsToJson(purchasable_));- // Details of what "Your games" shows; the catalog rows are fetched anyway.+ // Details of everything on the home screen and in "Your games": the next+ // launch shows them, hero art and all, before the network answers.json::Value details = json::Value::object();+ auto keep = [&](const std::string& pid) {+ auto it = products_.find(pid);+ if (it != products_.end()) details.set(pid, productToJson(it->second));+ };+ for (const auto& r : layout_)+ for (const auto& item : r.items) keep(item.first);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));- }+ for (const auto& [pid, tid] : *list) keep(pid);root.set("products", details);json::Value platforms = json::Value::object(), xboxTitles = json::Value::object();for (const auto& [id, code] : platform_) platforms.set(id, code);@@ -268,7 +289,19 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constif (!products_.count(t.productId)) ids.push_back(t.productId);}sortOwned();- if (xcloud::fetchProducts(ids, market_, language_, products_, lastErr, false)) {+ // The first cards are the first thing seen: full details (hero art,+ // description) for them in this same round trip.+ constexpr size_t kFirst = 8;+ std::vector<std::string> first, rest;+ for (const auto& item : r.items) {+ auto it = products_.find(item.first);+ bool complete = it != products_.end() && !it->second.heroUrl.empty();+ if (complete) continue;+ (first.size() < kFirst ? first : rest).push_back(item.first);+ }+ bool ok = xcloud::fetchProducts(first, market_, language_, products_, lastErr, true) &&+ xcloud::fetchProducts(rest, market_, language_, products_, lastErr, false);+ if (ok) {layout_.push_back(std::move(r));changed();}@@ -397,10 +430,36 @@ void Library::loadCatalogNames(const Changed& changed, const std::atomic<bool>*changed();}-void Library::loadPlatforms(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop) {+bool Library::fetchFull(const std::vector<std::string>& ids, const Changed& changed, const std::atomic<bool>* stop,+ size_t firstBatch) {+ std::vector<std::string> order;+ std::set<std::string> queued;+ for (const auto& id : ids) {+ auto it = products_.find(id);+ if ((it == products_.end() || it->second.heroUrl.empty() || it->second.description.empty()) &&+ queued.insert(id).second)+ order.push_back(id);+ }+ for (size_t i = 0, n = firstBatch; i < order.size(); i += n, n = 20) {+ if (stop && *stop) return true;+ std::vector<std::string> batch(order.begin() + static_cast<long>(i),+ order.begin() + static_cast<long>(std::min(order.size(), i + n)));+ std::map<std::string, xcloud::Product> full;+ std::string e;+ if (!xcloud::fetchProducts(batch, market_, language_, full, e, true)) {+ XC_LOGW("%s", e.c_str());+ return false;+ }+ for (auto& [id, p] : full) products_[id] = std::move(p);+ changed();+ }+ return true;+}++void Library::fetchPlatformsFor(const std::vector<std::string>& ids, const std::string& xblAuth) {if (xblAuth.empty()) return;std::set<std::string> want;- auto add = [&](const std::string& pid) {+ for (const auto& pid : ids) {auto x = xboxTitleOf_.find(pid);std::string xbox = x != xboxTitleOf_.end() ? x->second : std::string();if (xbox.empty()) {@@ -408,18 +467,47 @@ void Library::loadPlatforms(const std::string& xblAuth, const Changed& changed,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());+ }+ if (want.empty()) return;+ std::vector<std::string> list(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());+ if (!xcloud::fetchPlatforms(xblAuth, list, platform_, err)) XC_LOGW("%s", err.c_str());XC_LOGI("library: consoles of %zu more games", platform_.size() - before);+}++void Library::loadFirstScreen(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop) {+ uint64_t t0 = platform::nowMs();+ // What is on screen at once: the first cards of each row (the focused+ // first row first), then the start of "Your games".+ constexpr size_t kPerRow = 8, kOwned = 12;+ std::vector<std::string> ids;+ for (const auto& r : layout_)+ for (size_t i = 0; i < r.items.size() && i < kPerRow; ++i) ids.push_back(r.items[i].first);+ for (size_t i = 0; i < owned_.size() && i < kOwned; ++i) ids.push_back(owned_[i].first);+ for (size_t i = 0; i < purchasable_.size() && i < kOwned; ++i) ids.push_back(purchasable_[i].first);+ // Badges for every card of the rows (one titlehub call), then the art.+ std::vector<std::string> badges = ids;+ for (const auto& r : layout_)+ for (const auto& item : r.items) badges.push_back(item.first);+ std::vector<std::string> firstRows(ids.begin(), ids.begin() + static_cast<long>(std::min<size_t>(ids.size(), 20)));+ fetchFull(firstRows, changed, stop);+ fetchPlatformsFor(badges, xblAuth);+ changed();+ fetchFull(ids, changed, stop);+ saveCache();+ XC_LOGI("library: first screen ready in %llu ms", static_cast<unsigned long long>(platform::nowMs() - t0));+}++void Library::loadPlatforms(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop) {+ if (stop && *stop) return;+ std::vector<std::string> ids;+ for (const auto& r : layout_)+ for (const auto& item : r.items) ids.push_back(item.first);+ for (const auto* list : {&owned_, &purchasable_})+ for (const auto& item : *list) ids.push_back(item.first);+ ids.insert(ids.end(), allGames_.begin(), allGames_.end());+ fetchPlatformsFor(ids, xblAuth);saveCache();changed();}@@ -427,35 +515,11 @@ void Library::loadPlatforms(const std::string& xblAuth, const Changed& changed,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() && queued.insert(id).second) order.push_back(id);- };+ std::vector<std::string> ids;for (const auto& r : layout_)- 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),- order.begin() + static_cast<long>(std::min(order.size(), i + n)));- std::map<std::string, xcloud::Product> full;- std::string e;- if (!xcloud::fetchProducts(batch, market_, language_, full, e, true)) {- XC_LOGW("%s", e.c_str());- return;- }- for (auto& [id, p] : full) {- if (ownedProducts_.count(id)) ownedChanged = true;- products_[id] = std::move(p);- }- if (stop && *stop) return;- changed();- }- if (ownedChanged) saveCache(); // descriptions and hero art for next time+ for (const auto& item : r.items) ids.push_back(item.first);+ for (const auto& item : owned_) ids.push_back(item.first);+ if (fetchFull(ids, changed, stop)) 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 9b7ce60..866c1a3 100644--- a/src/app/library.h+++ b/src/app/library.h@@ -45,6 +45,9 @@ public:// 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 first screen, before anything else: hero art, descriptions and+ // console badges of the first cards of every row and of "Your games".+ void loadFirstScreen(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop = nullptr);// 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);@@ -74,6 +77,12 @@ private:};ui::GameTile tile(const std::string& productId, const std::string& titleId) const;std::vector<ui::GameTile> tiles(const std::vector<Item>& items) const;+ // Full details (hero art, description) for `ids` lacking them, in batches,+ // `changed` after each; false on a network error.+ bool fetchFull(const std::vector<std::string>& ids, const Changed& changed, const std::atomic<bool>* stop,+ size_t firstBatch = 20);+ // titlehub for the products in `ids` whose console isn't known yet.+ void fetchPlatformsFor(const std::vector<std::string>& ids, const std::string& xblAuth);void sortOwned();bool loadCache();void saveCache() const;@@ -94,6 +103,10 @@ private:std::set<std::string> purchasableSet_;std::map<std::string, std::string> xboxTitleOf_; // productId -> Xbox title idstd::map<std::string, std::string> platform_; // Xbox title id -> platform code+ // Xbox title ids that have a "... - Xbox Series X|S" product, rebuilt+ // when products_ grows.+ mutable std::set<std::string> seriesSiblings_;+ mutable size_t siblingsFor_ = 0;};} // namespace xc::appdiff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex 51e72af..e5d4c2c 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -16,12 +16,15 @@#include "platform/platform.h"#include "ui/app_ui.h"#include "ui/strings.h"+#include "util/json.h"#include "util/log.h"#include "xcloud/catalog.h"#include "xcloud/gssv.h"+#include "xcloud/prices.h"#include "xcloud/regions.h"#include <atomic>+#include <ctime>#include <map>#include <strings.h>#include <cstdio>@@ -325,6 +328,75 @@ void loadLibrary(xcloud::GssvClient& gssv);// Profile token for titlehub (memory only).std::string g_xblAuth;++// --- Store prices ---------------------------------------------------------------+// Asked for the games to buy as they come on screen; kept a day in+// <dataDir>/prices.json.+std::mutex g_priceMutex;+std::string g_priceMarket, g_priceLanguage; // set by loadLibrary()+platform::Thread g_priceThread;+std::atomic<bool> g_stopPrices{false};+constexpr int64_t kPriceTtlSeconds = 24 * 3600;++std::string pricesPath() { return platform::dataDir() + "/prices.json"; }++std::pair<std::string, std::string> priceTexts(const xcloud::Price& p) {+ std::string now = p.list < 0.005 ? ui::tr(ui::Str::Free) : xcloud::formatPrice(p.list, p.currency);+ std::string was = p.msrp > p.list + 0.005 ? xcloud::formatPrice(p.msrp, p.currency) : std::string();+ return {now, was};+}++void priceLoop() {+ json::Value cache = json::Value::object();+ {+ std::string text;+ if (platform::readFile(pricesPath(), text))+ if (auto j = json::parse(text)) cache = *j;+ }+ // Fresh cached prices to the UI right away.+ int64_t now = static_cast<int64_t>(std::time(nullptr));+ std::map<std::string, std::pair<std::string, std::string>> shown;+ json::Value kept = json::Value::object();+ for (const auto& [id, v] : cache.members()) {+ if (now - v["t"].asInt() > kPriceTtlSeconds) continue;+ kept.set(id, v);+ xcloud::Price p{v["list"].asNumber(), v["msrp"].asNumber(), v["cur"].str()};+ shown[id] = priceTexts(p);+ }+ cache = kept;+ if (!shown.empty()) g_ui->setPrices(shown);+ while (!g_stopPrices) {+ std::string market, language;+ {+ std::lock_guard<std::mutex> lock(g_priceMutex);+ market = g_priceMarket;+ language = g_priceLanguage;+ }+ std::vector<std::string> ids = market.empty() ? std::vector<std::string>() : g_ui->pricesWanted(20);+ if (ids.empty()) {+ platform::sleepMs(300);+ continue;+ }+ std::map<std::string, xcloud::Price> got;+ std::string err;+ if (!xcloud::fetchPrices(ids, market, language, got, err)) XC_LOGW("%s", err.c_str());+ std::map<std::string, std::pair<std::string, std::string>> texts;+ now = static_cast<int64_t>(std::time(nullptr));+ for (const auto& [id, p] : got) {+ texts[id] = priceTexts(p);+ json::Value v = json::Value::object();+ v.set("list", p.list);+ v.set("msrp", p.msrp);+ v.set("cur", p.currency);+ v.set("t", now);+ cache.set(id, v);+ }+ if (!texts.empty()) {+ g_ui->setPrices(texts);+ platform::writeFileAtomic(pricesPath(), cache.dump());+ }+ }+}void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {g_ui->showSplash(ui::tr(am.hasStoredAccount() ? ui::Str::SigningIn : ui::Str::RequestingCode));std::string err;@@ -354,6 +426,11 @@ void loadLibrary(xcloud::GssvClient& gssv) {stopHydration();auto library = std::make_shared<app::Library>();library->setCachePath(platform::dataDir() + "/library.json");+ {+ std::lock_guard<std::mutex> lock(g_priceMutex);+ g_priceMarket = gssv.session().market.empty() ? "US" : gssv.session().market;+ g_priceLanguage = ui::catalogLanguage();+ }bool shown = false;// Hands the library's current state to the UI (copies).auto publish = [](const app::Library& lib) {@@ -386,6 +463,7 @@ void loadLibrary(xcloud::GssvClient& gssv) {}platform::startThread(g_hydrationThread, [library, publish, owned = gssv, xblAuth] {auto changed = [&] { publish(*library); };+ library->loadFirstScreen(xblAuth, changed, &g_stopHydration);library->loadOwned(owned, changed, &g_stopHydration);library->loadCatalogNames(changed, &g_stopHydration);library->loadPlatforms(xblAuth, changed, &g_stopHydration);@@ -531,6 +609,7 @@ int main(int argc, char** argv) {},160u << 20, platform::dataDir() + "/imgcache");g_ui = std::make_unique<ui::AppUi>(fonts, *g_images);+ platform::startThread(g_priceThread, priceLoop);{ui::SettingsChoice choice;choice.language = static_cast<int>(ui::language());diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex d4880d9..e60de5a 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -238,6 +238,35 @@ void AppUi::setRegionLatency(std::map<std::string, int> ms) {dirty_ = true;}+void AppUi::setPrices(const std::map<std::string, std::pair<std::string, std::string>>& prices) {+ std::lock_guard<std::mutex> lock(mutex_);+ for (const auto& [id, p] : prices) prices_[id] = p;+ dirty_ = true;+}++std::vector<std::string> AppUi::pricesWanted(size_t max) {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<std::string> out;+ auto want = [&](const GameTile& t) {+ if (out.size() < max && t.purchasable && !prices_.count(t.productId) && pricesAsked_.insert(t.productId).second)+ out.push_back(t.productId);+ };+ if (screen_ == Screen::Details) want(detail_);+ if (screen_ != Screen::Home && screen_ != Screen::Details) return out;+ if (searching_) {+ for (const auto& t : results_) want(t);+ } else if (tab_ == Tab::Library && !purchasable_.empty()) {+ // The rows on screen and the two below.+ LibraryLayout L = libraryLayout();+ float top = gridScroll_.target - kGridPitchY, bottom = gridScroll_.target + kH + 2 * kGridPitchY;+ for (size_t i = owned_.size(); i < L.rowOf.size(); ++i) {+ int y = L.rowY[static_cast<size_t>(L.rowOf[i])];+ if (y >= top && y <= bottom) want(purchasable_[i - owned_.size()]);+ }+ }+ return out;+}+const GameTile* AppUi::libraryTile(int index) const {if (index < 0) return nullptr;size_t i = static_cast<size_t>(index);@@ -884,7 +913,8 @@ void AppUi::drawCard(Canvas& c, const GameTile& t, int x, int y, bool focused, b// 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);+ auto price = prices_.find(t.productId);+ std::string label = price != prices_.end() ? price->second.first : 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);@@ -895,15 +925,16 @@ void AppUi::drawCard(Canvas& c, const GameTile& t, int x, int y, bool focused, bdrawLock(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);+ c.fillRect(badge, rgba(0, 0, 0, 220), 4);+ fonts_.bold.draw(c, "GAME PASS", badge.x + (96 - fonts_.bold.measure("GAME PASS", 13)) / 2, badge.y + 4, 13,+ kWhite);}- // Bottom-right: the console it was made for.+ // Bottom-right: the console it was made for; one style and width for all.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);+ constexpr int kBadgeW = 96;+ Rect badge{x + kCard - 10 - kBadgeW, y + kCard - 34, kBadgeW, 24};+ c.fillRect(badge, rgba(0, 0, 0, 220), 4);+ fonts_.bold.draw(c, p, badge.x + (kBadgeW - fonts_.bold.measure(p, 13)) / 2, badge.y + 4, 13, kWhite);}if (focused) c.strokeRect({x - 7, y - 7, kCard + 14, kCard + 14}, kWhite, 4, 16);}@@ -1137,7 +1168,20 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {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);+ auto price = prices_.find(g->productId);+ int ny = std::max(y + (price != prices_.end() ? 120 : 40), 600);+ if (price != prices_.end()) {+ // The price, and the regular one crossed out while on sale.+ int px = kMargin;+ fonts_.bold.draw(c, price->second.first, px, ny - 70, 44, kWhite);+ px += fonts_.bold.measure(price->second.first, 44) + 20;+ if (!price->second.second.empty()) {+ int w = fonts_.semibold.measure(price->second.second, 28);+ fonts_.semibold.draw(c, price->second.second, px, ny - 58, 28, kDim);+ c.line(static_cast<float>(px), static_cast<float>(ny - 42), static_cast<float>(px + w),+ static_cast<float>(ny - 42), 2, kDim);+ }+ }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);diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex af14e1c..f0daf50 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -14,6 +14,7 @@#include <cstdint>#include <map>+#include <set>#include <mutex>#include <string>#include <vector>@@ -93,6 +94,11 @@ public: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);+ // Store prices, formatted: productId -> {now, regular (empty unless on sale)}.+ void setPrices(const std::map<std::string, std::pair<std::string, std::string>>& prices);+ // Games to buy on screen (or about to be) whose price hasn't been asked+ // for yet; marks them asked.+ std::vector<std::string> pricesWanted(size_t max);void showHome(const std::string& toast = {});void showLaunching(const GameTile& game, const std::string& status);void setLaunchStatus(const std::string& status);@@ -192,6 +198,8 @@ private:std::vector<std::string> regions_;std::string defaultRegion_;std::map<std::string, int> regionMs_;+ std::map<std::string, std::pair<std::string, std::string>> prices_;+ std::set<std::string> pricesAsked_;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 0639115..8f4380d 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -95,6 +95,7 @@ constexpr Column kEnglish = {"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+ "FREE", // Free};constexpr Column kPortugueseBR = {@@ -160,6 +161,7 @@ constexpr Column kPortugueseBR = {"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",+ "GRÁTIS",};constexpr Column kSpanish = {@@ -225,6 +227,7 @@ constexpr Column kSpanish = {"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",+ "GRATIS",};constexpr Column kFrench = {@@ -290,6 +293,7 @@ constexpr Column kFrench = {"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",+ "GRATUIT",};constexpr Column kGerman = {@@ -355,6 +359,7 @@ constexpr Column kGerman = {"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",+ "KOSTENLOS",};constexpr Column kItalian = {@@ -420,6 +425,7 @@ constexpr Column kItalian = {"Acquistalo su xbox.com o nell'app Xbox; poi apparirà in I tuoi giochi.","Scansiona per aprire la pagina dello store","Cerca in %s",+ "GRATIS",};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex adbfd79..1123020 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -72,6 +72,7 @@ enum class Str {BuyHint,ScanToBuy,SearchIn, // "%s" = tab name+ Free, // price 0 (free-to-play games still "bought" in the store)Count};diff --git a/src/xcloud/prices.cpp b/src/xcloud/prices.cppnew file mode 100644index 0000000..dc0979b--- /dev/null+++ b/src/xcloud/prices.cpp@@ -0,0 +1,76 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "xcloud/prices.h"++#include "net/http.h"+#include "util/json.h"++#include <cmath>+#include <cstdio>++namespace xc::xcloud {++bool fetchPrices(const std::vector<std::string>& productIds, const std::string& market, const std::string& language,+ std::map<std::string, Price>& out, std::string& err) {+ constexpr size_t kBatch = 20;+ for (size_t i = 0; i < productIds.size(); i += kBatch) {+ std::string ids;+ for (size_t k = i; k < productIds.size() && k < i + kBatch; ++k) ids += (ids.empty() ? "" : ",") + productIds[k];+ net::Request req;+ req.url = "https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=" + ids + "&market=" + market ++ "&languages=" + language + "&fieldsTemplate=browse";+ auto r = net::perform(req);+ auto j = json::parse(r.body);+ if (!r.ok() || !j) {+ err = "prices: " + (r.status ? "HTTP " + std::to_string(r.status) : r.error);+ return false;+ }+ for (const auto& p : (*j)["Products"].items()) {+ // The first availability that can be bought, among the SKUs.+ for (const auto& dsa : p["DisplaySkuAvailabilities"].items()) {+ bool found = false;+ for (const auto& av : dsa["Availabilities"].items()) {+ bool purchase = false;+ for (const auto& a : av["Actions"].items()) purchase |= a.str() == "Purchase";+ const auto& price = av["OrderManagementData"]["Price"];+ if (!purchase || !price.isObject()) continue;+ Price pr;+ pr.list = price["ListPrice"].asNumber();+ pr.msrp = price["MSRP"].asNumber();+ pr.currency = price["CurrencyCode"].str();+ out[p["ProductId"].str()] = pr;+ found = true;+ break;+ }+ if (found) break;+ }+ }+ }+ return true;+}++std::string formatPrice(double amount, const std::string& currency) {+ long cents = std::lround(amount * 100);+ long whole = cents / 100, frac = cents % 100;+ // Thousands with `sep`, cents after `dec`.+ auto number = [&](char sep, char dec) {+ std::string digits = std::to_string(whole), grouped;+ for (size_t i = 0; i < digits.size(); ++i) {+ if (i && (digits.size() - i) % 3 == 0) grouped += sep;+ grouped += digits[i];+ }+ char tail[8];+ std::snprintf(tail, sizeof tail, "%c%02ld", dec, frac);+ return grouped + tail;+ };+ if (currency == "BRL") return "R$ " + number('.', ',');+ if (currency == "USD") return "$" + number(',', '.');+ if (currency == "CAD") return "CA$" + number(',', '.');+ if (currency == "MXN") return "MX$" + number(',', '.');+ if (currency == "GBP") return "\xC2\xA3" + number(',', '.');+ if (currency == "EUR") return number('.', ',') + " \xE2\x82\xAC";+ if (currency == "JPY") return "\xC2\xA5" + std::to_string(std::lround(amount));+ return currency + " " + number(',', '.');+}++} // namespace xc::xclouddiff --git a/src/xcloud/prices.h b/src/xcloud/prices.hnew file mode 100644index 0000000..832b2f7--- /dev/null+++ b/src/xcloud/prices.h@@ -0,0 +1,27 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// Store prices (displaycatalog): the purchase offer of a product in the+// account's market. About 14 KB per product, so asked for the games on+// screen only.+#pragma once++#include <map>+#include <string>+#include <vector>++namespace xc::xcloud {++struct Price {+ double list = 0; // what it costs now+ double msrp = 0; // the regular price (higher while on sale)+ std::string currency; // ISO code, "BRL"+};++// Fills `out` for the products that have a purchase offer; batched by 20.+bool fetchPrices(const std::vector<std::string>& productIds, const std::string& market, const std::string& language,+ std::map<std::string, Price>& out, std::string& err);++// "R$ 78,82", "$59.99", "59,99 €"...+std::string formatPrice(double amount, const std::string& currency);++} // namespace xc::xclouddiff --git a/src/xcloud/titlehub.cpp b/src/xcloud/titlehub.cppindex e8850d2..f9804cd 100644--- a/src/xcloud/titlehub.cpp+++ b/src/xcloud/titlehub.cpp@@ -40,11 +40,12 @@ bool fetchPlatforms(const std::string& auth, const std::vector<std::string>& xbohasSeries |= d.str() == "XboxSeries";}for (const auto& a : t["detail"]["attributes"].items()) optimized |= a["name"].str() == "ConsoleGen9Optimized";- const char* code = has360 ? kPlatform360+ // No console in "devices": the id is the PC / Play Anywhere entry+ // (ARK, #IDARB). Every cloud title is a console game, and one that+ // isn't marked for Series X|S is the Xbox One version.+ const char* code = has360 ? kPlatform360: optimized || (hasSeries && !hasOne) ? kPlatformSeries- : hasOne || hasSeries ? kPlatformOne- : nullptr; // PC-only entries- if (!code) continue;+ : kPlatformOne;// The id asked for may be an older one titlehub maps to its// current id: record both.out[t["titleId"].str()] = code;diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 613a02a..d0b661d 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/prices.h"#include "xcloud/regions.h"#include <cstdio>@@ -152,9 +153,19 @@ static void testRegions() {CHECK(km > 2500 && km < 3000);}+static void testPrices() {+ using xc::xcloud::formatPrice;+ CHECK(formatPrice(78.82, "BRL") == "R$ 78,82");+ CHECK(formatPrice(1299.9, "BRL") == "R$ 1.299,90");+ CHECK(formatPrice(59.99, "USD") == "$59.99");+ CHECK(formatPrice(69.99, "EUR") == "69,99 \xE2\x82\xAC");+ CHECK(formatPrice(4, "XYZ") == "XYZ 4.00");+}+int main() {testStrings();testRegions();+ testPrices();testJson();testUrl();testInputPacket();