Xbox Cloud Gaming app for PS5 Homebrew
C
feat(release): modularization, performance optimizations, UI bug fixes, and bump to v1.5.4
Rafael Abud Ferreira84f973793678
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e2c3b0a..543c556 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1,7 +1,7 @@# SPDX-License-Identifier: GPL-3.0-or-later# Copyright (C) 2026 RafaelNGPcmake_minimum_required(VERSION 3.20)-project(xcloud_ps5 VERSION 1.5.3 LANGUAGES C CXX)+project(xcloud_ps5 VERSION 1.5.4 LANGUAGES C CXX)set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)@@ -88,6 +88,10 @@ add_library(xcloud_ui STATICsrc/ui/font.cppsrc/ui/image_cache.cppsrc/ui/app_ui.cpp+ src/ui/app_ui_search.cpp+ src/ui/app_ui_settings.cpp+ src/ui/app_ui_input.cpp+ src/ui/app_ui_render.cppsrc/ui/settings_choice.cppsrc/ui/stream_menu.cppsrc/ui/toast_view.cpp@@ -96,6 +100,7 @@ add_library(xcloud_ui STATICsrc/ui/accent_color.cppsrc/ui/brand.cppsrc/app/library.cpp+ src/app/library_sync.cppsrc/app/settings.cppsrc/app/update_check.cppsrc/app/report.cpp@@ -103,6 +108,8 @@ add_library(xcloud_ui STATICsrc/app/updater.cppsrc/app/auto_deband.cppsrc/app/web_server.cpp+ src/app/web_server_html.cpp+ src/app/web_server_gamepad.cppextern/qrcodegen/qrcodegen.c)target_compile_definitions(xcloud_ui PUBLIC XC_APP_VERSION="${PROJECT_VERSION}")@@ -116,6 +123,8 @@ add_library(xcloud_appcore OBJECTsrc/app/app_state.cppsrc/app/app_core.cppsrc/app/worker.cpp+ src/app/worker_stream.cpp+ src/app/worker_diagnostics.cppsrc/app/stream_screen.cppsrc/app/price_loop.cppsrc/app/autoplay.cppdiff --git a/ps5/sce_sys/param.json b/ps5/sce_sys/param.jsonindex d4db75d..04ef0c8 100644--- a/ps5/sce_sys/param.json+++ b/ps5/sce_sys/param.json@@ -10,7 +10,7 @@"conceptId": "99810","contentBadgeType": 1,"contentId": "UP9000-PPSA99810_00-XCLOUDPS5CLI0000",- "contentVersion": "01.503.000",+ "contentVersion": "01.504.000","downloadDataSize": 256,"gameIntent": {"permittedIntents": [diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex f0bc341..cd57985 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -324,6 +324,7 @@ bool coreStartup() {root.set("triggerStrength", g_settings.triggerStrength);root.set("audioHaptics", g_settings.audioHaptics);root.set("queueReadyAlert", g_settings.queueReadyAlert);+ root.set("previewFeatures", g_settings.previewFeatures);root.set("videoDecoder", g_settings.videoDecoder);root.set("voiceRouting", g_settings.voiceRouting);root.set("padSpeakerVolume", g_settings.padSpeakerVolume);@@ -394,6 +395,10 @@ bool coreStartup() {g_settings.queueReadyAlert = root["queueReadyAlert"].asBool(g_settings.queueReadyAlert);changed = true;}+ if (root.has("previewFeatures")) {+ g_settings.previewFeatures = root["previewFeatures"].asBool(g_settings.previewFeatures);+ changed = true;+ }if (root.has("videoDecoder")) {g_settings.videoDecoder = static_cast<int>(std::clamp<int64_t>(root["videoDecoder"].asInt(g_settings.videoDecoder), 0, 1));changed = true;@@ -663,12 +668,9 @@ bool coreStartup() {initialLib->setWishlist(g_settings.wishlist);if (initialLib->loadCache(true)) {setInitialLibrary(initialLib);- if (!initialLib->rows().empty()) {- g_ui->setRows(initialLib->rows());- }- g_ui->setOwned(initialLib->owned(), initialLib->purchasable(), initialLib->ownedKnown());- g_ui->setMembership(initialLib->gamePassMember());- g_ui->setSearchPools(initialLib->gamePassSearchPool(), initialLib->librarySearchPool());+ g_ui->setCatalogState(initialLib->rows(), initialLib->owned(), initialLib->purchasable(),+ initialLib->ownedKnown(), initialLib->gamePassMember(),+ initialLib->gamePassSearchPool(), initialLib->librarySearchPool());XC_LOGI("instant-resume: loaded offline cache (%zu rows, %zu owned) in 0.01s",initialLib->rows().size(), initialLib->owned().size());}@@ -914,7 +916,12 @@ bool Core::frame() {std::abs(pad.rightStickX) > 0.5f || std::abs(pad.rightStickY) > 0.5f;bool keyboard = ui::g_keyboardHints;if (keyPressed || kbm.moved) keyboard = true, keyboardActiveAt = now0();- else if (padUsed) keyboard = false;+ else if (padUsed) {+ keyboard = false;+ if (g_ui->mouseCursorVisible()) {+ g_ui->setMouseCursor(g_ui->mouseCursorX(), g_ui->mouseCursorY(), false);+ }+ }if (keyboard != ui::g_keyboardHints) {ui::g_keyboardHints = keyboard;g_ui->invalidate();@@ -943,12 +950,12 @@ bool Core::frame() {if (k.pressed) g_ui->captureKey(k.vk), swallowedKeys.push_back(k.vk);for (int b = 0; b < 5; ++b)if ((kbm.buttons & ~mouseButtonsBefore) & (1 << b)) g_ui->captureKey(static_cast<uint8_t>(input::kMouseLeft + b));- } else if (!inGame || streamScreen->menuOpen()) {+ } else if ((!inGame || streamScreen->menuOpen()) && !shell::caps().window) {static float s_mouseCursorX = 960.0f;static float s_mouseCursorY = 540.0f;if (kbm.dx != 0 || kbm.dy != 0) {- s_mouseCursorX = std::clamp(s_mouseCursorX + static_cast<float>(kbm.dx), 0.0f, 1920.0f);- s_mouseCursorY = std::clamp(s_mouseCursorY + static_cast<float>(kbm.dy), 0.0f, 1080.0f);+ s_mouseCursorX = std::clamp(s_mouseCursorX + static_cast<float>(kbm.dx), 0.0f, 1919.0f);+ s_mouseCursorY = std::clamp(s_mouseCursorY + static_cast<float>(kbm.dy), 0.0f, 1079.0f);ui::UiEvent mev = g_ui->onMouseMove(s_mouseCursorX, s_mouseCursorY);if (mev.action != ui::Action::None) dispatchUiAction(mev);}diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex 77b7d4f..7118c54 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -34,6 +34,8 @@ bool uiSaved = false;bool settingsShot = false; // "settingstest": save the screen nowbool bitrateShot = false; // "bitratetest": save the screen nowbool donationShot = false; // "donationtest": save the screen now+bool signInCheckShot = false; // "checksignintest": save the screen now+bool freeUiShot = false, freeDetailsShot = false; // "freetest": save free account screenshotsconst char* keysShot = nullptr; // "keystest": the screen to save nowuint64_t homeSince = 0, launchSince = 0;bool launchSaved = false;@@ -123,6 +125,8 @@ void loadAutoplay() {if (opt == "pad") g_autoplay.pad = true;if (opt == "consoles") g_autoplay.consoles = true;if (opt == "consolestab") g_autoplay.consolesTab = true;+ if (opt == "checksignintest") g_autoplay.checkSignInTest = true;+ if (opt == "freetest") g_autoplay.freeTest = true;if (opt == "settingstest") g_autoplay.settingsTest = true;if (opt == "keystest") g_autoplay.keysTest = true;if (opt == "padmaptest") g_autoplay.padMapTest = true;@@ -317,9 +321,23 @@ void autoplayPad(input::ControllerState& pad) {// Step 0: Open detailsif (step == 0 && t >= 500) {ui::GameTile tile;- bool found = (!g_autoplay.title.empty() && g_ui->findTile(g_autoplay.title, tile)) ||+ bool found = (!g_autoplay.lockTitle.empty() && g_ui->findTile(g_autoplay.lockTitle, tile)) ||+ (!g_autoplay.title.empty() && g_autoplay.title != "AUTOTEST" && g_ui->findTile(g_autoplay.title, tile)) ||g_ui->firstTile(tile) || g_ui->purchasableAt(0, tile);if (found) {+ ui::SettingsChoice c = g_ui->settings();+ if (!tile.productId.empty() && !c.titlePlaytime.count(tile.productId)) c.titlePlaytime[tile.productId] = 240;+ if (!tile.titleId.empty() && !c.titlePlaytime.count(tile.titleId)) c.titlePlaytime[tile.titleId] = 240;+ g_ui->setSettings(c);+ if (!tile.xboxTitleId.empty()) {+ xcloud::TitleAchievements ach;+ ach.totalCount = 100;+ ach.unlockedCount = 47;+ ach.totalGamerscore = 1300;+ ach.unlockedGamerscore = 485;+ g_ui->setTitleAchievements(tile.xboxTitleId, ach);+ }+ g_ui->setQueueTime(tile.titleId, 10);g_ui->showDetails(tile);step = 1;// The test changes and saves this game's profile: what it was@@ -815,6 +833,63 @@ void autoplayNav(ui::NavInput& nav, bool& menuCombo, uint64_t now) {}}+ if (g_autoplay.checkSignInTest && uiSaved) {+ static uint64_t since = 0;+ static int step = 0;+ if (!since) since = now;+ static SettingsWalk walk;+ const uint64_t at[] = {500, 1500, 2500, 6000, 7000};+ if (step < 5 && now - since >= at[step]) {+ bool next = true;+ if (step == 0) nav.options = true;+ if (step == 1) next = walk.step(nav, downsTo(17)); // row 17: Sign in check+ if (step == 2) {+ if (onSettingsRow(17, "check signin test")) {+ nav.accept = true;+ } else {+ g_autoplay.checkSignInTest = false;+ g_ui->showHome();+ }+ }+ if (step == 3) {+ signInCheckShot = true;+ }+ if (step == 4) {+ nav.back = true;+ g_ui->showHome();+ g_autoplay.checkSignInTest = false;+ }+ if (next) ++step;+ }+ }++ if (g_autoplay.freeTest && uiSaved) {+ static uint64_t since = 0;+ static int step = 0;+ if (!since) {+ since = now;+ g_ui->setSubscription("");+ }+ const uint64_t at[] = {500, 1500, 2500, 4500, 5500};+ if (step < 5 && now - since >= at[step]) {+ if (step == 0) freeUiShot = true;+ if (step == 1) {+ nav.accept = true;+ }+ if (step == 2) {+ freeDetailsShot = true;+ }+ if (step == 3) {+ nav.back = true;+ }+ if (step == 4) {+ g_autoplay.freeTest = false;+ XC_LOGI("AUTOPLAY END: free test finished");+ }+ ++step;+ }+ }+if (g_autoplay.bitrateTest && uiSaved) {static uint64_t since = 0;static int step = 0;@@ -1105,6 +1180,21 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {saveCanvas("donation.ppm");XC_LOGI("AUTOPLAY END: donation screenshot saved");}+ if (signInCheckShot) {+ signInCheckShot = false;+ saveCanvas("signin_check.ppm");+ XC_LOGI("AUTOPLAY END: check signin test (saved signin_check.ppm)");+ }+ if (freeUiShot) {+ freeUiShot = false;+ saveCanvas("free_ui.ppm");+ XC_LOGI("AUTOPLAY: saved free_ui.ppm");+ }+ if (freeDetailsShot) {+ freeDetailsShot = false;+ saveCanvas("free_details.ppm");+ XC_LOGI("AUTOPLAY: saved free_details.ppm");+ }if (g_autoplay.consolesTab && uiSaved) {static uint64_t shownAt = 0;if (!shownAt) {diff --git a/src/app/autoplay.h b/src/app/autoplay.hindex 84b2154..7ea8851 100644--- a/src/app/autoplay.h+++ b/src/app/autoplay.h@@ -37,6 +37,8 @@ struct Autoplay {bool idle = false;bool consolesTab = false; // "consolestab": open My consoles, save consoles.ppmbool consolesEmpty = false; // with "consolestab": as if none were found+ bool checkSignInTest = false;// "checksignintest": open sign-in check, verify 6 stages, save signin_check.ppm+ bool freeTest = false; // "freetest": simulate free account, verify FREE badge and game locksbool settingsTest = false; // "settingstest": open the resolution list, save settings.ppmbool keysTest = false; // "keystest": Settings' groups, the keyboard keys' screen, a key chosen (keys*.ppm)bool padMapTest = false; // "padmaptest": the controller buttons' screen, a press captured, an incomplete map (padmap*.ppm)diff --git a/src/app/library.cpp b/src/app/library.cppindex f634e5e..a47db39 100644--- a/src/app/library.cpp+++ b/src/app/library.cpp@@ -1,18 +1,16 @@// SPDX-License-Identifier: GPL-3.0-or-later// Copyright (C) 2026 RafaelNGP-#include "app/library.h"+#include "app/library_internal.h"#include "platform/platform.h"#include "ui/strings.h"#include "util/json.h"#include "util/log.h"-#include "xcloud/catalog.h"#include "xcloud/purchase.h"-#include "xcloud/social.h"#include "xcloud/titlehub.h"#include <algorithm>-#include <cstring>+#include <cctype>#include <ctime>#include <map>@@ -20,13 +18,6 @@ namespace xc::app {namespace {-constexpr int kCacheVersion = 2;--struct ListSpec {- const char* sigl;- size_t limit;-};-json::Value productToJson(const xcloud::Product& p) {json::Value v = json::Value::object();v.set("xt", p.xcloudTitleId);@@ -74,7 +65,7 @@ xcloud::Product productFromJson(const std::string& id, const json::Value& v) {p.heroUrl = v["hero"].str();for (const auto& c : v["categories"].items()) p.categories.push_back(xcloud::categoryName(c.str()));p.isPcOnly = v["isPc"].asBool(false);- p.detailed = v["d"].asBool(false);+ p.detailed = v["d"].asBool(false) && !p.description.empty();// Details from before their date was kept count from now (not all due at once).p.detailedAt = v["at"].asInt(static_cast<int64_t>(std::time(nullptr)));p.modes = static_cast<uint32_t>(v["modes"].asInt(0));@@ -109,29 +100,6 @@ bool isStoreBigId(const std::string& s) {namespace {-bool namesSeries(const std::string& title) {- return title.find("Series X|S") != std::string::npos || title.find("Series X/S") != std::string::npos;-}--bool endsWith(const std::string& s, const char* tail) {- size_t n = std::strlen(tail);- return s.size() >= n && s.compare(s.size() - n, n, tail) == 0;-}--// Which version of a cross-gen pair (two products, one Xbox title id) a-// product is, from its cloud title id or its name: +1 Series X|S, -1 Xbox-// One, 0 can't tell. "HOGWARTSLEGACYXBOXONEVERSION", "...XBOXSERIESXSVERSION",-// "RUSTCONSOLEEDITIONXS" / "Rust Console Edition X|S", "... - Xbox Series X|S".-int pairVersion(const xcloud::Product& p) {- const std::string& c = p.xcloudTitleId;- if (c.find("XBOXONE") != std::string::npos) return -1;- if (c.find("XBOXSERIES") != std::string::npos || c.find("SERIESXS") != std::string::npos || endsWith(c, "XS"))- return 1;- if (namesSeries(p.title) || endsWith(p.title, "X|S") || endsWith(p.title, "X/S")) return 1;- if (p.title.find("Xbox One") != std::string::npos || p.title.find("Xbox 360") != std::string::npos) return -1;- return 0;-}-static int tileQualityScore(const ui::GameTile& t) {int score = 0;// Platform priority: Xbox Series X|S gets absolute highest priority over Xbox One and 360@@ -155,7 +123,7 @@ static int tileQualityScore(const ui::GameTile& t) {score += 3000; // Unknown console}- if (t.playable) score += 50;+ if (t.playable) score += 500;if (t.detailed) score += 10;if (!t.tileUrl.empty()) score += 10;if (!t.heroUrl.empty()) score += 5;@@ -288,190 +256,6 @@ void dedupeByTitle(std::vector<ui::GameTile>& tiles) {tiles = std::move(out);}-namespace {--struct KnownCloudGame {- const char* productId;- const char* cloudTitleId;- const char* xboxTitleId;- const char* fallbackTitle;- const char* publisher;- const char* tileUrl;- const char* posterUrl;- const char* heroUrl;- const char* category;- const char* description;- const char* ratingAge;- const char* ratingSystem;- const char* ratingDescriptors;- bool isFree;-};--static const KnownCloudGame kKnownCloudGames[] = {- {"9NCPSQQD1Z66", "CALLOFDUTYHQ", "2001700854", "Call of Duty®: Modern Warfare® 4", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.59792.13559635275456449.72d1efe7-e297-4b01-9ff5-81f9541bc9a1.f8f4e212-4f83-45fe-8db7-bbb19d5a9582",- "https://store-images.s-microsoft.com/image/apps.4715.13559635275456449.72d1efe7-e297-4b01-9ff5-81f9541bc9a1.a25cb344-59ba-49dd-8858-37563c544636",- "https://store-images.s-microsoft.com/image/apps.45467.13559635275456449.72d1efe7-e297-4b01-9ff5-81f9541bc9a1.98f47d6e-e5f3-4a70-8b61-43330deb2787",- "Shooter",- "War erupts on the Korean Peninsula as North Korea launches a full-scale invasion that threatens to destabilize global peace. Call of Duty®: Modern Warfare® 4 delivers an intense, gritty narrative campaign alongside signature multiplayer and cooperative operations.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",- false},- {"9N201KQXS5BM", "CALLOFDUTYHQ", "2001700854", "Call of Duty®", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.16691.13966330883349940.9de723b2-8834-4acf-92cc-c6ec73db1644.50de713a-16e0-4383-b422-7052a1cb99f0",- "https://store-images.s-microsoft.com/image/apps.30472.13966330883349940.9a0bbc3f-3231-4a17-ab16-55eb671f1755.d9aecc85-6637-4e56-a359-009944a02940",- "https://store-images.s-microsoft.com/image/apps.45467.13966330883349940.05d0b25a-8298-42a1-adba-3a6c21a95a32.eb8f770e-9122-4ab6-ab50-372aa6cc912c",- "Shooter",- "The Call of Duty® experience supports Modern Warfare® 4, Black Ops 7 and Call of Duty®: Warzone™.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",- false},- {"9NNFG8BQRCXL", "CALLOFDUTYHQ", "2001700854", "Call of Duty®: Warzone™", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.60826.13739535057760905.ee63b998-143e-4256-bd0e-3e78d667ab11.d72c1992-0383-4ff8-91c5-e310141d9a07",- "https://store-images.s-microsoft.com/image/apps.60826.13739535057760905.ee63b998-143e-4256-bd0e-3e78d667ab11.d72c1992-0383-4ff8-91c5-e310141d9a07",- "https://store-images.s-microsoft.com/image/apps.20908.13739535057760905.ee63b998-143e-4256-bd0e-3e78d667ab11.7315f232-c36d-4d7d-8581-edc82aebe238",- "Shooter",- "Welcome to Call of Duty®: Warzone™, the massive free-to-play combat arena. Experience thrilling modes and new gameplay features.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",- true},- {"9N8KMNW6942X", "CALLOFDUTYHQ", "2001700854", "Call of Duty®: Black Ops 7", "Activision Publishing Inc.",- nullptr, nullptr, nullptr, "Shooter",- "Call of Duty®: Black Ops 7 expands the Cold War universe into unprecedented covert operations.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",- false},- {"9N1N0NQNGK9W", "CALLOFDUTYBLACKOPS6", "1822992790", "Call of Duty®: Black Ops 6", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.21616.14207097610490811.5b338e31-5c12-4d95-9a2a-2f16ceb01377.5c60a78b-cc32-4777-9141-90ebd76e88ad",- "https://store-images.s-microsoft.com/image/apps.28966.14207097610490811.5b338e31-5c12-4d95-9a2a-2f16ceb01377.acc0294d-61eb-49e2-a059-758d5b1227d4",- "https://store-images.s-microsoft.com/image/apps.5449.14207097610490811.5b338e31-5c12-4d95-9a2a-2f16ceb01377.54d31648-9587-49a6-b312-7df6ce023530",- "Shooter",- "Call of Duty®: Black Ops 6 is a spy action thriller set in the early 90s, characterized by mind-bending narrative gameplay.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",- false},- {"9P22THR57FV7", "CALLOFDUTYBLACKOPS6", "1822992790", "Call of Duty®: Black Ops 6 - Launcher", "Activision Publishing Inc.",- nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},- {"9NLZZ74TFD7P", "CALLOFDUTYMODERNWARFAREIII", "2003727579", "Call of Duty®: Modern Warfare® III", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.44737.13702346117700120.96dcc05d-7589-4e95-abbc-4fbc3399d7ff.76cfb4be-3069-4cd2-a883-70654bf6898e",- "https://store-images.s-microsoft.com/image/apps.35931.13702346117700120.96dcc05d-7589-4e95-abbc-4fbc3399d7ff.bf621533-dad7-4478-8719-e8ff3da2223e",- "https://store-images.s-microsoft.com/image/apps.44508.13702346117700120.96dcc05d-7589-4e95-abbc-4fbc3399d7ff.aca3a7f0-6dab-4d13-be0a-c87a416eac22",- "Shooter",- "In the direct sequel to the record-breaking Call of Duty®: Modern Warfare® II, Captain Price and Task Force 141 face off against the ultimate threat.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"9PMFDKG5F9R7", "CALLOFDUTYMODERNWARFAREIII", "2003727579", "Call of Duty®: Modern Warfare® III", "Activision Publishing Inc.",- nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},- {"9NDKFJ6XDX2M", "CALLOFDUTYMODERNWARFAREIII", "2003727579", "Call of Duty®: Modern Warfare® III", "Activision Publishing Inc.",- nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},- {"9PNGFSX7S117", "CALLOFDUTYMODERNWARFAREII", "1959007243", "Call of Duty®: Modern Warfare® II", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.62866.14349375889218622.77ec9575-f44b-4013-97c6-f9cd0bbc53f5.b1790761-1d9e-4ffd-b146-3f68bdeb949e",- "https://store-images.s-microsoft.com/image/apps.34778.14349375889218622.77ec9575-f44b-4013-97c6-f9cd0bbc53f5.fd60100a-bbb6-4eb3-a03c-6da8e90db089",- "https://store-images.s-microsoft.com/image/apps.46802.14349375889218622.77ec9575-f44b-4013-97c6-f9cd0bbc53f5.041995ec-87c2-4c88-b7a6-98dbdbb5c975",- "Shooter",- "Call of Duty®: Modern Warfare® II drops players into an unprecedented global conflict that features the return of the iconic Operators of Task Force 141.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"9N872NBW5XG5", "CALLOFDUTYMODERNWARFAREII", "1959007243", "Call of Duty®: Modern Warfare® II", "Activision Publishing Inc.",- nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},- {"9P7RQ1QFFF8R", "CALLOFDUTYMODERNWARFAREII", "1959007243", "Call of Duty®: Modern Warfare® II", "Activision Publishing Inc.",- nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},- {"9NVQBQ3F6W9W", "CALLOFDUTYMODERNWARFARE", "609700427", "Call of Duty®: Modern Warfare®", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.52064.14393996338935986.84c4ee65-c726-49ae-925f-3dca581be2df.3e540e94-9e5a-41f5-9b00-c8f5190819f7",- "https://store-images.s-microsoft.com/image/apps.50528.14393996338935986.84c4ee65-c726-49ae-925f-3dca581be2df.31d66188-6781-49ce-a75a-b4247e73b89d",- "https://store-images.s-microsoft.com/image/apps.1926.14393996338935986.84c4ee65-c726-49ae-925f-3dca581be2df.46cd9cf0-2829-4517-a140-3d163199497f",- "Shooter",- "Experience a visceral Campaign or assemble your team in the ultimate online playground with multiple Special Ops challenges and a mix of Multiplayer maps and modes.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"C5DTJ99626K3", "CALLOFDUTYMODERNWARFARE", "609700427", "Call of Duty®: Modern Warfare®", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.52064.67185831113154542.823e899c-d262-40a0-91f6-eee04bdc3713.74be39c5-2d6e-4e6b-960b-7d8077da0142",- "https://store-images.s-microsoft.com/image/apps.50528.67185831113154542.823e899c-d262-40a0-91f6-eee04bdc3713.dd7010c6-9641-4c5a-b8b5-7eb16ddc67ea",- "https://store-images.s-microsoft.com/image/apps.1926.67185831113154542.823e899c-d262-40a0-91f6-eee04bdc3713.ca4b2ff5-8dc9-4774-a5f1-4e379a72cbda",- "Shooter",- "Experience a visceral Campaign or assemble your team in the ultimate online playground with multiple Special Ops challenges and a mix of Multiplayer maps and modes.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"9P7PFH4RMFZD", "CALLOFDUTYBLACKOPSCOLDWAR", "1790482525", "Call of Duty®: Black Ops Cold War", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.16401.14107985044965209.e8fed65f-093d-40d1-849f-6c564d2ad876.13b9c6b6-dddd-4f67-a303-b98250929229",- "https://store-images.s-microsoft.com/image/apps.25992.14107985044965209.e8fed65f-093d-40d1-849f-6c564d2ad876.89955624-8043-4f20-8620-4381e11a3546",- "https://store-images.s-microsoft.com/image/apps.52829.14107985044965209.e8fed65f-093d-40d1-849f-6c564d2ad876.8fe14720-2b8f-4b9c-aebf-07f1610816d5",- "Shooter",- "The iconic Black Ops series is back with Call of Duty®: Black Ops Cold War - the direct sequel to the original and fan-favorite Call of Duty®: Black Ops.\n\nWelcome to the brink. Welcome to Call of Duty®: Black Ops Cold War.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"9NPLRJ9CC870", "CALLOFDUTYBLACKOPSCOLDWARXBOXSERIESXS", "1790482525", "Call of Duty®: Black Ops Cold War - Xbox Series X|S", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.16401.13791444986287693.243003e9-8583-4df9-a0fc-2345d2f82ed4.e5e2cd4a-420a-41eb-bade-0eab002eab9c",- "https://store-images.s-microsoft.com/image/apps.25992.13791444986287693.243003e9-8583-4df9-a0fc-2345d2f82ed4.b477eb21-1438-49b1-bf72-a36ed8d74bb8",- "https://store-images.s-microsoft.com/image/apps.52829.13791444986287693.243003e9-8583-4df9-a0fc-2345d2f82ed4.92c561dc-948f-445a-ad29-5e287d884e0c",- "Shooter",- "The iconic Black Ops series is back with Call of Duty®: Black Ops Cold War - the direct sequel to the original and fan-favorite Call of Duty®: Black Ops.\n\nWelcome to the brink. Welcome to Call of Duty®: Black Ops Cold War.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"9PHP6HF58MB5", "CALLOFDUTYVANGUARD", "1929807318", "Call of Duty®: Vanguard", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.25644.14231872788446538.01bda410-79a7-42cd-a67b-497b17d840f1.b577a06e-1952-4f78-9ca8-6e43b94f985b",- "https://store-images.s-microsoft.com/image/apps.31712.14231872788446538.ec1df70e-1780-4ec2-90fc-de130713250f.37f86b3f-4921-4955-902e-3325f37a3e17",- "https://store-images.s-microsoft.com/image/apps.27881.14231872788446538.ec1df70e-1780-4ec2-90fc-de130713250f.b54d334f-52d0-45e1-ac31-c86b1d4b6ad6",- "Shooter",- "Call of Duty®: Vanguard includes a deeply engaging single player Campaign, a massive Multiplayer offering featuring over 20 maps including 16 built for core Multiplayer and an exciting new Zombies experience developed by Treyarch.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},- {"9MWHTW1SF7RW", "CALLOFDUTYVANGUARDXBOXSERIESXS", "1929807318", "Call of Duty®: Vanguard - Xbox Series X|S", "Activision Publishing Inc.",- "https://store-images.s-microsoft.com/image/apps.25644.13843233178803270.b12b929c-1b87-4fa1-900a-23a132dc9775.bdbacf51-1647-4c87-b9dc-6c455834d9bb",- "https://store-images.s-microsoft.com/image/apps.31712.13843233178803270.d4ae9cce-02bd-4f56-8f61-6e02568a7dfd.401708cf-3756-4e90-b73d-bd1a6d4e1c09",- "https://store-images.s-microsoft.com/image/apps.27881.13843233178803270.d4ae9cce-02bd-4f56-8f61-6e02568a7dfd.7b70ba8c-ba77-4fc3-af0d-cc1f87530bb0",- "Shooter",- "Call of Duty®: Vanguard includes a deeply engaging single player Campaign, a massive Multiplayer offering featuring over 20 maps including 16 built for core Multiplayer and an exciting new Zombies experience developed by Treyarch.",- "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},-};--static void seedKnownGames(std::map<std::string, std::string>& cloudTitleOf,- std::map<std::string, std::string>& xboxTitleOf,- std::set<std::string>& freeInStore,- std::set<std::string>& gamePass,- std::vector<std::string>& allGames,- std::map<std::string, xcloud::Product>& products) {- for (const auto& g : kKnownCloudGames) {- cloudTitleOf[g.productId] = g.cloudTitleId;- if (g.xboxTitleId && g.xboxTitleId[0]) xboxTitleOf[g.productId] = g.xboxTitleId;- if (g.isFree) freeInStore.insert(g.productId);- bool isCodHub = (std::string_view(g.productId) == "9NCPSQQD1Z66" ||- std::string_view(g.productId) == "9N201KQXS5BM" ||- std::string_view(g.productId) == "9NNFG8BQRCXL");- if (isCodHub) {- gamePass.insert(g.productId);- if (std::find(allGames.begin(), allGames.end(), g.productId) == allGames.end()) {- allGames.push_back(g.productId);- }- }- if (!products.count(g.productId)) {- xcloud::Product p;- p.productId = g.productId;- p.xcloudTitleId = g.cloudTitleId;- p.xboxTitleId = g.xboxTitleId ? g.xboxTitleId : "";- p.title = g.fallbackTitle;- p.publisher = g.publisher;- p.tileUrl = g.tileUrl ? g.tileUrl : "";- p.posterUrl = g.posterUrl ? g.posterUrl : "";- p.heroUrl = g.heroUrl ? g.heroUrl : "";- p.description = g.description ? g.description : "";- p.ratingAge = g.ratingAge ? g.ratingAge : "";- p.ratingSystem = g.ratingSystem ? g.ratingSystem : "";- if (g.ratingDescriptors && g.ratingDescriptors[0]) {- p.ratingDescriptors.push_back(g.ratingDescriptors);- }- if (g.category && g.category[0]) p.categories.push_back(g.category);- p.detailed = (g.description != nullptr && g.tileUrl != nullptr && g.heroUrl != nullptr);- p.plan = xcloud::kPlanUltimate;- products[g.productId] = std::move(p);- } else {- auto& p = products[g.productId];- if (p.xcloudTitleId.empty() || p.xcloudTitleId == "None") p.xcloudTitleId = g.cloudTitleId;- if (p.title.empty() && g.fallbackTitle) p.title = g.fallbackTitle;- if (p.description.empty() && g.description) p.description = g.description;- if (p.tileUrl.empty() && g.tileUrl) p.tileUrl = g.tileUrl;- if (p.posterUrl.empty() && g.posterUrl) p.posterUrl = g.posterUrl;- if (p.heroUrl.empty() && g.heroUrl) p.heroUrl = g.heroUrl;- if (p.publisher.empty() && g.publisher) p.publisher = g.publisher;- if (p.ratingAge.empty() && g.ratingAge) p.ratingAge = g.ratingAge;- if (p.ratingSystem.empty() && g.ratingSystem) p.ratingSystem = g.ratingSystem;- if (p.categories.empty() && g.category) p.categories.push_back(g.category);- if (!p.detailed && !p.description.empty() && !p.tileUrl.empty() && !p.heroUrl.empty())- p.detailed = true;- }- }-}--} // namespace-ui::GameTile Library::tile(const std::string& productId, const std::string& titleId) const {ui::GameTile t;t.productId = productId;@@ -703,11 +487,13 @@ std::vector<ui::GameTile> Library::tiles(const std::vector<Item>& items) const {}t.playable = true;t.purchasable = false;- t.freeInStore = false;}out.push_back(std::move(t));}dedupeByTitle(out);+ for (auto& t : out) {+ if (t.playable) t.purchasable = false;+ }return out;}@@ -998,7 +784,6 @@ bool Library::loadCache(bool withLayout) {for (const auto& pid : acquiredProducts_) {ownedProducts_.insert(pid);purchasableSet_.erase(pid);- freeInStore_.erase(pid);if (std::find(recent_.begin(), recent_.end(), pid) == recent_.end()) {recent_.insert(recent_.begin(), pid);}@@ -1027,7 +812,6 @@ bool Library::loadCache(bool withLayout) {acquiredProducts_.insert(p);ownedProducts_.insert(p);purchasableSet_.erase(p);- freeInStore_.erase(p);}}}@@ -1139,7 +923,6 @@ void Library::markAsOwned(const std::string& productId, const std::string& titleacquiredProducts_.insert(productId);ownedProducts_.insert(productId);purchasableSet_.erase(productId);- freeInStore_.erase(productId);if (!tid.empty() && tid != "None") {cloudTitleOf_[productId] = tid;}@@ -1160,7 +943,6 @@ void Library::markAsOwned(const std::string& productId, const std::string& titleacquiredProducts_.insert(p);ownedProducts_.insert(p);purchasableSet_.erase(p);- freeInStore_.erase(p);}}}@@ -1207,821 +989,4 @@ void Library::markUnclaimable(const std::string& productId) {saveCache();}-size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std::string& err) {- market_ = gssv.session().market.empty() ? "US" : gssv.session().market;- std::vector<xcloud::Title> titles;- std::string listErr;- if (!gssv.listTitles(titles, listErr, false)) {- err = listErr;- return 0;- }- for (const auto& t : titles) {- if (!t.productId.empty()) {- if (!t.titleId.empty() && t.titleId != "None") {- cloudTitleOf_[t.productId] = t.titleId;- auto it = products_.find(t.productId);- if (it != products_.end() && (it->second.xcloudTitleId.empty() || it->second.xcloudTitleId == "None")) {- it->second.xcloudTitleId = t.titleId;- }- }- if (!t.xboxTitleId.empty() && !xboxTitleOf_.count(t.productId)) {- xboxTitleOf_[t.productId] = t.xboxTitleId;- }- if (t.isFreeInStore) {- freeInStore_.insert(t.productId);- }- if (t.mouseKeyboard) {- mouseKeyboard_.insert(t.productId);- }- }- }-- std::vector<std::string> newProducts;- for (const auto& t : titles) {- if (!t.productId.empty() && !products_.count(t.productId)) {- newProducts.push_back(t.productId);- }- for (const auto& alt : t.alternateProductIds) {- if (!alt.empty() && !t.titleId.empty() && t.titleId != "None") {- cloudTitleOf_[alt] = t.titleId;- }- }- }- xcloud::ProductList allSigl;- std::string siglErr;- if (xcloud::fetchList(xcloud::sigl::kAllGames, market_, language_, allSigl, siglErr)) {- gamePass_.clear();- gamePass_.insert(allSigl.productIds.begin(), allSigl.productIds.end());- allGames_ = allSigl.productIds;- seedKnownGames(cloudTitleOf_, xboxTitleOf_, freeInStore_, gamePass_, allGames_, products_);- for (const auto& pid : allSigl.productIds) {- if (!pid.empty() && !products_.count(pid)) {- newProducts.push_back(pid);- }- }- }- std::sort(newProducts.begin(), newProducts.end());- newProducts.erase(std::unique(newProducts.begin(), newProducts.end()), newProducts.end());-- size_t newCount = 0;- if (!newProducts.empty()) {- std::string fetchErr;- xcloud::fetchProducts(newProducts, market_, language_, products_, fetchErr, false);-- std::vector<std::string> actuallyAdded;- for (const auto& pid : newProducts) {- auto it = products_.find(pid);- if (it != products_.end() && !it->second.title.empty()) {- actuallyAdded.push_back(pid);- } else {- products_[pid].productId = pid;- products_[pid].detailedAt = platform::nowMs();- }- }- newCount = actuallyAdded.size();- }- allGames_.erase(std::remove_if(allGames_.begin(), allGames_.end(),- [&](const std::string& id) {- return isPcOnly(id);- }),- allGames_.end());- for (auto it = gamePass_.begin(); it != gamePass_.end(); ) {- if (isPcOnly(*it)) it = gamePass_.erase(it);- else ++it;- }- for (auto& row : layout_) {- if (row.isGrid) {- row.items.clear();- for (const auto& pid : allGames_) {- std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";- row.items.emplace_back(pid, tid);- }- } else {- row.items.erase(std::remove_if(row.items.begin(), row.items.end(),- [&](const auto& item) {- return isPcOnly(item.first);- }),- row.items.end());- }- }- loadOwned(gssv, changed, nullptr, &titles);- loadCatalogNames(changed, nullptr);- saveCache();- changed();- return newCount;-}--bool Library::load(xcloud::GssvClient& gssv, const std::string& language, const Changed& changed, std::string& err,- bool forceRefresh) {- market_ = gssv.session().market.empty() ? "US" : gssv.session().market;- language_ = language;- layout_.clear();- products_.clear();- allGames_.clear();- gamePass_.clear();- popular_.clear();- recent_.clear();- ownershipKnown_ = false;- ownershipFresh_ = false;- knownGamePass_.clear();- ownedTitles_.clear();- ownedProducts_.clear();- owned_.clear();- purchasable_.clear();- purchasableSet_.clear();- freeInStore_.clear();- otherLanguage_.clear();- progress_ = {};- std::string lastErr;-- // The Game Pass catalog first: it decides what the other lists may show.- xcloud::ProductList all;- std::string e;- if (xcloud::fetchList(xcloud::sigl::kAllGames, market_, language_, all, e)) {- allGames_ = all.productIds;- gamePass_.insert(all.productIds.begin(), all.productIds.end());- } else {- XC_LOGW("%s", e.c_str());- lastErr = e;- }- seedKnownGames(cloudTitleOf_, xboxTitleOf_, freeInStore_, gamePass_, allGames_, products_);- // The account's games from the previous run, until loadOwned() refreshes- // them. Not its home rows: those are built below.- loadCache(false);-- // "Jump back in": recently played games, Game Pass or the account's own- // (rows() leaves out those it can't play; they also go first in "Your- // games").- std::vector<xcloud::Title> recent;- if (gssv.listTitles(recent, lastErr, true)) {- RowIds r{ui::tr(ui::Str::JumpBackIn), false, false, {}, true};- std::vector<std::string> ids;- std::vector<std::string> freshRecent;- for (const auto& t : recent) {- if (t.productId.empty()) continue;- if (std::find(freshRecent.begin(), freshRecent.end(), t.productId) == freshRecent.end()) {- freshRecent.push_back(t.productId);- }- if (!t.xboxTitleId.empty()) xboxTitleOf_[t.productId] = t.xboxTitleId;- // Its inputs come with it: the first cards show keyboard and- // mouse without waiting for the whole list (or a cache that has it).- if (t.mouseKeyboard) mouseKeyboard_.insert(t.productId);- r.items.emplace_back(t.productId, t.titleId);- if (!products_.count(t.productId)) ids.push_back(t.productId);- }- for (const auto& pid : recent_) {- if (!pid.empty() && std::find(freshRecent.begin(), freshRecent.end(), pid) == freshRecent.end()) {- freshRecent.push_back(pid);- }- }- recent_ = std::move(freshRecent);- for (const auto& pid : acquiredProducts_) {- auto it = std::find(recent_.begin(), recent_.end(), pid);- if (it != recent_.end()) recent_.erase(it);- recent_.insert(recent_.begin(), pid);- }- sortOwned();- // 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();- }- }-- const ListSpec lists[] = {{xcloud::sigl::kRecentlyAdded, 40},- {xcloud::sigl::kMostPopular, 40},- {xcloud::sigl::kFreeToPlay, 40},- {xcloud::sigl::kLeavingSoon, 40},- {xcloud::sigl::kAllGames, 0}};- uint8_t myPlan = xcloud::planTier(subscription_);- for (const auto& spec : lists) {- xcloud::ProductList list;- bool isAllGames = std::string_view(spec.sigl) == xcloud::sigl::kAllGames;- if (isAllGames && !allGames_.empty()) {- list.title = all.title.empty() ? "All games" : all.title;- list.productIds = allGames_;- } else if (!xcloud::fetchList(spec.sigl, market_, language_, list, e)) {- XC_LOGW("%s", e.c_str());- lastErr = e;- continue;- }- if (spec.sigl == xcloud::sigl::kRecentlyAdded) {- const char* const kNewCod[] = {"9NCPSQQD1Z66", "9N201KQXS5BM"};- for (const char* pid : kNewCod) {- auto it = std::find(list.productIds.begin(), list.productIds.end(), pid);- if (it != list.productIds.end()) {- list.productIds.erase(it);- size_t insertAt = std::min<size_t>(1, list.productIds.size());- list.productIds.insert(list.productIds.begin() + static_cast<long>(insertAt), pid);- }- }- }- // "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;- // Position key cloud titles (Modern Warfare 4, Call of Duty HQ, Warzone)- // within the visible most popular shelf if legitimately in the feed- const char* const kTopCod[] = {"9NCPSQQD1Z66", "9N201KQXS5BM", "9NNFG8BQRCXL"};- for (const char* pid : kTopCod) {- auto it = std::find(list.productIds.begin(), list.productIds.end(), pid);- if (it != list.productIds.end()) {- list.productIds.erase(it);- size_t insertAt = std::min<size_t>(2, list.productIds.size());- list.productIds.insert(list.productIds.begin() + static_cast<long>(insertAt), pid);- }- }- }- // Free-to-play: no Game Pass needed, so not filtered; each one the- // account hasn't got yet shows as free to get (tile()).- bool freeToPlay = spec.sigl == xcloud::sigl::kFreeToPlay;- if (freeToPlay) {- freeInStore_.insert(list.productIds.begin(), list.productIds.end());- XC_LOGI("library: %s: %zu games", list.title.c_str(), list.productIds.size());- }- bool isMostPopular = spec.sigl == xcloud::sigl::kMostPopular;- if (!gamePass_.empty() && !freeToPlay && !isMostPopular) {- size_t before = list.productIds.size();- list.productIds.erase(std::remove_if(list.productIds.begin(), list.productIds.end(),- [&](const std::string& id) {- if (!gamePass_.count(id)) return true;- if (myPlan > 0 && myPlan < xcloud::kPlanUltimate && !ownedProducts_.count(id) &&- !freeInStore_.count(id)) {- auto it = products_.find(id);- if (it != products_.end() &&- !xcloud::planIncludes(myPlan, it->second.plan, false))- return true;- }- return false;- }),- list.productIds.end());- if (list.productIds.size() != before)- XC_LOGI("library: %s: %zu of %zu not in Game Pass/plan, left out", list.title.c_str(),- before - list.productIds.size(), before);- }- list.productIds.erase(std::remove_if(list.productIds.begin(), list.productIds.end(),- [&](const std::string& id) {- return isPcOnly(id);- }),- list.productIds.end());- if (spec.limit > 0 && list.productIds.size() > spec.limit) list.productIds.resize(spec.limit);- std::vector<std::string> missing;- for (const auto& id : list.productIds) {- auto it = products_.find(id);- if (it == products_.end() || it->second.tileUrl.empty() || otherLanguage_.count(id))- missing.push_back(id);- }- if (!missing.empty() && !xcloud::fetchProducts(missing, market_, language_, products_, e, false)) {- XC_LOGW("%s", e.c_str());- lastErr = e;- }- RowIds r{list.title, !freeToPlay, isAllGames, {}};- for (const auto& id : list.productIds) r.items.emplace_back(id, std::string());- layout_.push_back(std::move(r));- changed();- }- if (rows().empty()) {- err = lastErr.empty() ? "no games found" : lastErr;- return false;- }- return true;-}--void Library::loadOwned(xcloud::GssvClient gssv, const Changed& changed, const std::atomic<bool>* stop,- const std::vector<xcloud::Title>* preloadedTitles) {- progress_ = {true, 0, 0}; // the account's list: no measure until the names- changed();- std::string err;- std::vector<xcloud::Title> fetchedTitles;- const std::vector<xcloud::Title>* titlesPtr = preloadedTitles;- if (!titlesPtr) {- if (!gssv.listTitles(fetchedTitles, err, false)) {- XC_LOGW("%s", err.c_str()); // keep what the cache said- progress_ = {};- changed();- return;- }- titlesPtr = &fetchedTitles;- }- const auto& titles = *titlesPtr;- if (stop && *stop) {- progress_ = {};- changed();- return;- }- std::set<std::string> ownedTitles, ownedProducts;- std::vector<Item> mine;- std::set<std::string> seenMine;- std::map<std::string, std::string> toBuy; // productId -> titleId- bool member = false;- auto registerCloudTitle = [&](const std::string& pid, const std::string& tid, const std::string& xboxId, bool freeStore, bool mkb) {- if (pid.empty()) return;- if (!tid.empty() && tid != "None") {- cloudTitleOf_[pid] = tid;- auto it = products_.find(pid);- if (it != products_.end() && (it->second.xcloudTitleId.empty() || it->second.xcloudTitleId == "None")) {- it->second.xcloudTitleId = tid;- }- }- if (!xboxId.empty() && !xboxTitleOf_.count(pid)) xboxTitleOf_[pid] = xboxId;- if (freeStore) freeInStore_.insert(pid);- if (mkb) mouseKeyboard_.insert(pid);- };-- for (const auto& t : titles) {- bool isAcquired = (!t.productId.empty() && acquiredProducts_.count(t.productId)) ||- (!t.titleId.empty() && acquiredTitles_.count(t.titleId));- for (const auto& alt : t.alternateProductIds) {- if (!alt.empty() && acquiredProducts_.count(alt)) { isAcquired = true; break; }- }- bool entitled = t.hasEntitlement || isAcquired;- member |= entitled && t.viaSubscription;- if (xcloud::isNonGameAddon(t.titleId)) continue;- if (entitled) ownedTitles.insert(t.titleId);-- registerCloudTitle(t.productId, t.titleId, t.xboxTitleId, t.isFreeInStore, t.mouseKeyboard);- for (const auto& alt : t.alternateProductIds) {- registerCloudTitle(alt, t.titleId, t.xboxTitleId, t.isFreeInStore, t.mouseKeyboard);- }-- if (entitled) {- if (!t.productId.empty()) ownedProducts.insert(t.productId);- for (const auto& alt : t.alternateProductIds) {- if (!alt.empty()) ownedProducts.insert(alt);- }- // Game Pass games the account owns itself (free-to-play ones- // like Fortnite, without the subscription) are its games too.- // Also games outside the Game Pass catalog.- if (!t.productId.empty()) {- if (!gamePass_.count(t.productId) || !t.viaSubscription || isAcquired) {- if (seenMine.insert(t.productId).second) {- mine.emplace_back(t.productId, t.titleId);- }- }- }- } else if (!t.productId.empty() && !gamePass_.count(t.productId)) {- toBuy[t.productId] = t.titleId;- }- }-- bool hasCod = member || ownedTitles.count("CALLOFDUTYHQ") || ownedTitles.count("CALLOFDUTYBLACKOPS6") ||- ownedTitles.count("CALLOFDUTYMODERNWARFAREIII");- if (hasCod) {- ownedTitles.insert("CALLOFDUTYHQ");- ownedTitles.insert("CALLOFDUTYBLACKOPS6");- ownedTitles.insert("CALLOFDUTYMODERNWARFAREIII");- }- for (const auto& g : kKnownCloudGames) {- registerCloudTitle(g.productId, g.cloudTitleId, g.xboxTitleId ? g.xboxTitleId : "", g.isFree, false);- if (ownedTitles.count(g.cloudTitleId)) {- ownedProducts.insert(g.productId);- if (g.isFree || std::string_view(g.productId) == "9NCPSQQD1Z66") {- if (seenMine.insert(g.productId).second) {- mine.emplace_back(g.productId, g.cloudTitleId);- }- }- } else if (!gamePass_.count(g.productId)) {- toBuy[g.productId] = g.cloudTitleId;- }- }- for (const auto& pid : acquiredProducts_) {- toBuy.erase(pid);- ownedProducts.insert(pid);- if (seenMine.insert(pid).second) {- std::string tid;- auto it = cloudTitleOf_.find(pid);- if (it != cloudTitleOf_.end()) tid = it->second;- if (tid.empty()) {- auto pit = products_.find(pid);- if (pit != products_.end() && !pit->second.xcloudTitleId.empty() && pit->second.xcloudTitleId != "None") {- tid = pit->second.xcloudTitleId;- }- }- mine.emplace_back(pid, tid);- }- }- for (const auto& tid : acquiredTitles_) {- if (!tid.empty()) {- ownedTitles.insert(tid);- for (const auto& [p, t] : cloudTitleOf_) {- if (t == tid) {- ownedProducts.insert(p);- toBuy.erase(p);- }- }- }- }- for (auto it = toBuy.begin(); it != toBuy.end(); ) {- bool isOwnedOrAcquired = acquiredProducts_.count(it->first) > 0 ||- ownedProducts.count(it->first) > 0 ||- (!it->second.empty() && (acquiredTitles_.count(it->second) > 0 || ownedTitles.count(it->second) > 0));- if (isOwnedOrAcquired) {- it = toBuy.erase(it);- } else {- ++it;- }- }- // 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);- for (const auto& [pid, _] : toBuy)- if (!products_.count(pid)) missing.push_back(pid);- if (!missing.empty() && !xcloud::fetchProducts(missing, market_, language_, products_, err, false))- XC_LOGW("%s", err.c_str());- if (stop && *stop) {- progress_ = {};- changed();- return;- }- ownedTitles_ = std::move(ownedTitles);- ownershipFresh_ = true;- ownedProducts_ = std::move(ownedProducts);- owned_ = std::move(mine);- purchasable_ = std::move(buy);- purchasable_.erase(std::remove_if(purchasable_.begin(), purchasable_.end(),- [&](const Item& item) {- return acquiredProducts_.count(item.first) > 0 ||- ownedProducts_.count(item.first) > 0 ||- (!item.second.empty() && (acquiredTitles_.count(item.second) > 0 || ownedTitles_.count(item.second) > 0));- }), purchasable_.end());- purchasableSet_.clear();- for (const auto& p : purchasable_) purchasableSet_.insert(p.first);- for (const auto& pid : acquiredProducts_) {- purchasableSet_.erase(pid);- freeInStore_.erase(pid);- }- for (const auto& [pid, tid] : cloudTitleOf_) {- if (acquiredTitles_.count(tid) || ownedTitles_.count(tid)) {- purchasableSet_.erase(pid);- freeInStore_.erase(pid);- }- }- for (const auto& pid : acquiredProducts_) {- if (!pid.empty() && std::find(recent_.begin(), recent_.end(), pid) == recent_.end()) {- recent_.insert(recent_.begin(), pid);- }- }- ownershipKnown_ = true;- gamePassMember_ = member;- sortOwned();- saveCache();- XC_LOGI("library: account can stream %zu titles; %zu outside Game Pass; %zu more to buy", ownedTitles_.size(),- owned_.size(), purchasable_.size());- progress_ = {};- changed();-}--void Library::loadCatalogNames(const Changed& changed, const std::atomic<bool>* stop) {- // Names and art: the account's games and the games to buy first (their- // lists are on screen), then the Game Pass catalog for its search. Also- // anything still in another language.- std::vector<std::string> missing;- std::set<std::string> queued;- auto want = [&](const std::string& id) {- auto it = products_.find(id);- bool needs = (it == products_.end()) ||- it->second.title.empty() ||- it->second.tileUrl.empty() ||- (it->second.xcloudTitleId.empty() || it->second.xcloudTitleId == "None") ||- otherLanguage_.count(id);- if (needs && queued.insert(id).second) missing.push_back(id);- };- for (const auto* list : {&owned_, &purchasable_})- for (const auto& item : *list) want(item.first);- for (const auto& id : allGames_) want(id);- progress_ = {true, 0, missing.size()};- changed();- constexpr size_t kBatch = 100;- for (size_t i = 0; i < missing.size(); i += kBatch) {- if (stop && *stop) break;- std::vector<std::string> batch(missing.begin() + static_cast<long>(i),- missing.begin() + static_cast<long>(std::min(missing.size(), i + kBatch)));- std::map<std::string, xcloud::Product> fetched;- std::string e;- if (!xcloud::fetchProducts(batch, market_, language_, fetched, e, false)) {- XC_LOGW("%s", e.c_str());- break;- }- for (auto& [id, p] : fetched) {- auto ct = cloudTitleOf_.find(id);- if (p.xcloudTitleId.empty() || p.xcloudTitleId == "None") {- if (ct != cloudTitleOf_.end()) p.xcloudTitleId = ct->second;- }- if (p.xcloudTitleId == "None") p.xcloudTitleId.clear();- // Keep the hero art and description already known, until they- // come in the new language (hydrate()).- auto old = products_.find(id);- if (old != products_.end()) {- if (p.heroUrl.empty()) p.heroUrl = old->second.heroUrl;- if (p.description.empty() && !otherLanguage_.count(id)) p.description = old->second.description;- if (p.xcloudTitleId.empty()) p.xcloudTitleId = old->second.xcloudTitleId;- if (!p.detailed && old->second.detailed) { // modes, languages and plan don't change with the language- p.detailed = true;- p.detailedAt = old->second.detailedAt;- p.modes = old->second.modes;- p.plan = old->second.plan;- p.languages = old->second.languages;- }- }- products_[id] = std::move(p);- otherLanguage_.erase(id);- }- progress_.done = std::min(missing.size(), i + kBatch);- changed(); // each batch: the lists fill in as names arrive- }- progress_ = {};- changed();- allGames_.erase(std::remove_if(allGames_.begin(), allGames_.end(),- [&](const std::string& id) {- return isPcOnly(id);- }),- allGames_.end());- for (auto it = gamePass_.begin(); it != gamePass_.end(); ) {- if (isPcOnly(*it)) it = gamePass_.erase(it);- else ++it;- }- for (auto& row : layout_) {- if (row.isGrid) {- row.items.clear();- for (const auto& pid : allGames_) {- std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";- row.items.emplace_back(pid, tid);- }- } else {- row.items.erase(std::remove_if(row.items.begin(), row.items.end(),- [&](const auto& item) {- return isPcOnly(item.first);- }),- row.items.end());- }- }- saveCache();- XC_LOGI("library: search covers %zu Game Pass games and %zu of yours or to buy", gamePassSearchPool().size(),- librarySearchPool().size());- changed();-}--bool Library::fetchFull(const std::vector<std::string>& ids, const Changed& changed, const std::atomic<bool>* stop,- size_t firstBatch) {- bool ok = true;- int batches = 0;- 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.detailed) && queued.insert(id).second)- order.push_back(id);- }- // Batches of 20 (~10 KB per product: bigger ones made the catalog time- // out, 504, and weren't faster).- 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;- // A batch that fails (a timeout now and then) is asked again; one- // that keeps failing is left for next time, and the rest carries on.- bool got = false;- for (int attempt = 0; attempt < 3 && !got; ++attempt) {- if (attempt) platform::sleepMs(1000);- got = xcloud::fetchProducts(batch, market_, language_, full, e, true);- if (!got) XC_LOGW("%s%s", e.c_str(), attempt < 2 ? " (asking again)" : " (skipped)");- }- if (!got) {- ok = false;- continue;- }- for (const auto& id : batch) {- // Not in the catalog's details: nothing more to know, not asked again.- auto known = products_.find(id);- if (!full.count(id) && known != products_.end()) known->second.detailed = true;- }- for (auto& [id, p] : full) products_[id] = std::move(p);- changed();- if (++batches % 4 == 0) saveCache(); // a long fetch keeps what it got if the app closes- }- return ok;-}--void Library::fetchPlatformsFor(const std::vector<std::string>& ids, const std::string& xblAuth) {- if (xblAuth.empty()) return;- std::set<std::string> want;- for (const auto& pid : ids) {- 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);- }- 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, 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();-}--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> ids;- for (const auto& r : layout_)- for (const auto& item : r.items) ids.push_back(item.first);- for (const auto& item : owned_) ids.push_back(item.first);- // Then every game the search goes through: its filters (play mode,- // language) need the full details.- for (const auto& item : purchasable_) ids.push_back(item.first);- ids.insert(ids.end(), allGames_.begin(), allGames_.end());- uint64_t t0 = platform::nowMs();- fetchFull(ids, changed, stop);- // The store changes descriptions and details now and then: the oldest- // few (over 30 days) are fetched again on each start, never all at once.- constexpr int64_t kRefreshAge = 30 * 24 * 3600;- constexpr size_t kRefreshPerStart = 40;- int64_t now = static_cast<int64_t>(std::time(nullptr));- std::vector<std::pair<int64_t, std::string>> old;- for (const auto& [id, p] : products_)- if (p.detailed && p.detailedAt && now - p.detailedAt > kRefreshAge) old.push_back({p.detailedAt, id});- std::sort(old.begin(), old.end());- if (old.size() > kRefreshPerStart) old.resize(kRefreshPerStart);- if (!old.empty() && !(stop && *stop)) {- std::vector<std::string> refresh;- for (const auto& [at, id] : old) refresh.push_back(id);- size_t done = 0;- for (size_t i = 0; i < refresh.size(); i += 20) {- std::vector<std::string> batch(refresh.begin() + static_cast<long>(i),- refresh.begin() + static_cast<long>(std::min(refresh.size(), i + 20)));- std::map<std::string, xcloud::Product> fresh;- std::string e;- if (!xcloud::fetchProducts(batch, market_, language_, fresh, e, true)) {- XC_LOGW("%s (refresh: next start)", e.c_str());- break;- }- for (const auto& id : batch) {- auto it = fresh.find(id);- if (it != fresh.end()) products_[id] = std::move(it->second), ++done;- else products_[id].detailedAt = now; // gone from the catalog's details: not asked again for a while- }- }- XC_LOGI("library: %zu of %zu old details refreshed (%zu over 30 days in all)", done, refresh.size(),- static_cast<size_t>(std::count_if(products_.begin(), products_.end(), [&](const auto& kv) {- return kv.second.detailed && now - kv.second.detailedAt > kRefreshAge;- })));- changed();- }- saveCache(); // descriptions, hero art, modes and languages for next time- size_t detailed = 0;- for (const auto& [id, p] : products_) detailed += p.detailed;- XC_LOGI("library: %zu rows, %zu of %zu products with details (%llu s)", layout_.size(), detailed, products_.size(),- static_cast<unsigned long long>((platform::nowMs() - t0) / 1000));-}--void Library::loadFriends(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop) {- if (xblAuth.empty() || (stop && *stop)) return;- std::vector<xcloud::FriendPresence> presence;- std::string err;- if (!xcloud::fetchFriendsPresence(xblAuth, presence, err, language_)) return;- if (stop && *stop) return;-- // Map Xbox Live Title ID / Cloud Title ID -> Store Product ID- std::map<std::string, std::string> productByXbox;- for (const auto& [pid, xid] : xboxTitleOf_) {- if (!xid.empty()) productByXbox[xid] = pid;- }- for (const auto& [pid, prod] : products_) {- productByXbox[pid] = pid;- if (!prod.xboxTitleId.empty() && !productByXbox.count(prod.xboxTitleId)) {- productByXbox[prod.xboxTitleId] = pid;- }- if (!prod.xcloudTitleId.empty() && !productByXbox.count(prod.xcloudTitleId)) {- productByXbox[prod.xcloudTitleId] = pid;- }- }- for (const auto& [pid, cid] : cloudTitleOf_) {- if (!cid.empty() && !productByXbox.count(cid)) {- productByXbox[cid] = pid;- }- }-- // Group friends playing accessible games- std::map<std::string, std::vector<ui::FriendPlaying>> friendsByProduct;- for (const auto& fp : presence) {- if (fp.presenceState != "Online" || fp.titleId.empty()) continue;- auto it = productByXbox.find(fp.titleId);- if (it == productByXbox.end()) continue;- const std::string& pid = it->second;-- // Check if game is playable on this account (Game Pass or owned)- ui::GameTile t = tile(pid);- if (!t.playable) continue;-- friendsByProduct[pid].push_back({fp.gamertag, fp.gamerpicUrl});- }-- std::vector<ui::GameTile> tiles;- std::vector<std::string> needDetails;- for (auto& [pid, friendsList] : friendsByProduct) {- ui::GameTile t = tile(pid);- if (t.productId.empty() || !t.playable) continue;- if (t.heroUrl.empty()) {- auto pit = products_.find(pid);- if (pit != products_.end() && !pit->second.heroUrl.empty()) {- t.heroUrl = pit->second.heroUrl;- } else {- for (const auto& [otherPid, otherProd] : products_) {- if (!otherProd.heroUrl.empty() &&- ((!t.titleId.empty() && otherProd.xcloudTitleId == t.titleId) ||- (!t.xboxTitleId.empty() && otherProd.xboxTitleId == t.xboxTitleId))) {- t.heroUrl = otherProd.heroUrl;- if (t.description.empty()) t.description = otherProd.description;- break;- }- }- }- }- if (t.heroUrl.empty() && !pid.empty()) {- needDetails.push_back(pid);- }- t.friends = std::move(friendsList);- tiles.push_back(std::move(t));- }-- friendsTiles_ = std::move(tiles);- if (!friendsTiles_.empty()) {- XC_LOGI("library: %zu friends playing %zu accessible games now", presence.size(), friendsTiles_.size());- changed();- if (!needDetails.empty()) {- fetchFull(needDetails, changed, stop);- for (auto& t : friendsTiles_) {- if (t.heroUrl.empty()) {- auto fresh = tile(t.productId, t.titleId);- if (!fresh.heroUrl.empty()) t.heroUrl = fresh.heroUrl;- if (!fresh.description.empty() && t.description.empty()) t.description = fresh.description;- }- }- changed();- }- }-}-} // namespace xc::appdiff --git a/src/app/library.h b/src/app/library.hindex bac391d..b40d72a 100644--- a/src/app/library.h+++ b/src/app/library.h@@ -112,7 +112,7 @@ public:acquiredTitles_.insert(titles.begin(), titles.end());}// Delta-sync: discovers new/updated titles, only fetches missing metadata, updates rows in-place.- size_t syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std::string& err);+ size_t syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std::string& err, const std::string& language = {});void markUnclaimable(const std::string& productId);// Generates a tile for a product/title.ui::GameTile tile(const std::string& productId, const std::string& titleId = {}) const;diff --git a/src/app/library_internal.h b/src/app/library_internal.hnew file mode 100644index 0000000..c360c22--- /dev/null+++ b/src/app/library_internal.h@@ -0,0 +1,224 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "app/library.h"+#include "xcloud/catalog.h"++#include <algorithm>+#include <cstring>+#include <map>+#include <set>+#include <string>+#include <string_view>+#include <vector>++namespace xc::app {++constexpr int kCacheVersion = 2;++struct ListSpec {+ const char* sigl;+ size_t limit;+};++inline bool namesSeries(const std::string& title) {+ return title.find("Series X|S") != std::string::npos || title.find("Series X/S") != std::string::npos;+}++inline bool endsWith(const std::string& s, const char* tail) {+ size_t n = std::strlen(tail);+ return s.size() >= n && s.compare(s.size() - n, n, tail) == 0;+}++inline int pairVersion(const xcloud::Product& p) {+ const std::string& c = p.xcloudTitleId;+ if (c.find("XBOXONE") != std::string::npos) return -1;+ if (c.find("XBOXSERIES") != std::string::npos || c.find("SERIESXS") != std::string::npos || endsWith(c, "XS"))+ return 1;+ if (namesSeries(p.title) || endsWith(p.title, "X|S") || endsWith(p.title, "X/S")) return 1;+ if (p.title.find("Xbox One") != std::string::npos || p.title.find("Xbox 360") != std::string::npos) return -1;+ return 0;+}++struct KnownCloudGame {+ const char* productId;+ const char* cloudTitleId;+ const char* xboxTitleId;+ const char* fallbackTitle;+ const char* publisher;+ const char* tileUrl;+ const char* posterUrl;+ const char* heroUrl;+ const char* category;+ const char* description;+ const char* ratingAge;+ const char* ratingSystem;+ const char* ratingDescriptors;+ bool isFree;+};++inline const KnownCloudGame kKnownCloudGames[] = {+ {"9NCPSQQD1Z66", "CALLOFDUTYHQ", "2001700854", "Call of Duty®: Modern Warfare® 4", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.59792.13559635275456449.72d1efe7-e297-4b01-9ff5-81f9541bc9a1.f8f4e212-4f83-45fe-8db7-bbb19d5a9582",+ "https://store-images.s-microsoft.com/image/apps.4715.13559635275456449.72d1efe7-e297-4b01-9ff5-81f9541bc9a1.a25cb344-59ba-49dd-8858-37563c544636",+ "https://store-images.s-microsoft.com/image/apps.45467.13559635275456449.72d1efe7-e297-4b01-9ff5-81f9541bc9a1.98f47d6e-e5f3-4a70-8b61-43330deb2787",+ "Shooter",+ "War erupts on the Korean Peninsula as North Korea launches a full-scale invasion that threatens to destabilize global peace. Call of Duty®: Modern Warfare® 4 delivers an intense, gritty narrative campaign alongside signature multiplayer and cooperative operations.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",+ false},+ {"9N201KQXS5BM", "CALLOFDUTYHQ", "2001700854", "Call of Duty®", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.16691.13966330883349940.9de723b2-8834-4acf-92cc-c6ec73db1644.50de713a-16e0-4383-b422-7052a1cb99f0",+ "https://store-images.s-microsoft.com/image/apps.30472.13966330883349940.9a0bbc3f-3231-4a17-ab16-55eb671f1755.d9aecc85-6637-4e56-a359-009944a02940",+ "https://store-images.s-microsoft.com/image/apps.45467.13966330883349940.05d0b25a-8298-42a1-adba-3a6c21a95a32.eb8f770e-9122-4ab6-ab50-372aa6cc912c",+ "Shooter",+ "The Call of Duty® experience supports Modern Warfare® 4, Black Ops 7 and Call of Duty®: Warzone™.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",+ false},+ {"9NNFG8BQRCXL", "CALLOFDUTYHQ", "2001700854", "Call of Duty®: Warzone™", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.60826.13739535057760905.ee63b998-143e-4256-bd0e-3e78d667ab11.d72c1992-0383-4ff8-91c5-e310141d9a07",+ "https://store-images.s-microsoft.com/image/apps.60826.13739535057760905.ee63b998-143e-4256-bd0e-3e78d667ab11.d72c1992-0383-4ff8-91c5-e310141d9a07",+ "https://store-images.s-microsoft.com/image/apps.20908.13739535057760905.ee63b998-143e-4256-bd0e-3e78d667ab11.7315f232-c36d-4d7d-8581-edc82aebe238",+ "Shooter",+ "Welcome to Call of Duty®: Warzone™, the massive free-to-play combat arena. Experience thrilling modes and new gameplay features.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",+ true},+ {"9N8KMNW6942X", "CALLOFDUTYHQ", "2001700854", "Call of Duty®: Black Ops 7", "Activision Publishing Inc.",+ nullptr, nullptr, nullptr, "Shooter",+ "Call of Duty®: Black Ops 7 expands the Cold War universe into unprecedented covert operations.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",+ false},+ {"9N1N0NQNGK9W", "CALLOFDUTYBLACKOPS6", "1822992790", "Call of Duty®: Black Ops 6", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.21616.14207097610490811.5b338e31-5c12-4d95-9a2a-2f16ceb01377.5c60a78b-cc32-4777-9141-90ebd76e88ad",+ "https://store-images.s-microsoft.com/image/apps.28966.14207097610490811.5b338e31-5c12-4d95-9a2a-2f16ceb01377.acc0294d-61eb-49e2-a059-758d5b1227d4",+ "https://store-images.s-microsoft.com/image/apps.5449.14207097610490811.5b338e31-5c12-4d95-9a2a-2f16ceb01377.54d31648-9587-49a6-b312-7df6ce023530",+ "Shooter",+ "Call of Duty®: Black Ops 6 is a spy action thriller set in the early 90s, characterized by mind-bending narrative gameplay.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria",+ false},+ {"9P22THR57FV7", "CALLOFDUTYBLACKOPS6", "1822992790", "Call of Duty®: Black Ops 6 - Launcher", "Activision Publishing Inc.",+ nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},+ {"9NLZZ74TFD7P", "CALLOFDUTYMODERNWARFAREIII", "2003727579", "Call of Duty®: Modern Warfare® III", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.44737.13702346117700120.96dcc05d-7589-4e95-abbc-4fbc3399d7ff.76cfb4be-3069-4cd2-a883-70654bf6898e",+ "https://store-images.s-microsoft.com/image/apps.35931.13702346117700120.96dcc05d-7589-4e95-abbc-4fbc3399d7ff.bf621533-dad7-4478-8719-e8ff3da2223e",+ "https://store-images.s-microsoft.com/image/apps.44508.13702346117700120.96dcc05d-7589-4e95-abbc-4fbc3399d7ff.aca3a7f0-6dab-4d13-be0a-c87a416eac22",+ "Shooter",+ "In the direct sequel to the record-breaking Call of Duty®: Modern Warfare® II, Captain Price and Task Force 141 face off against the ultimate threat.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"9PMFDKG5F9R7", "CALLOFDUTYMODERNWARFAREIII", "2003727579", "Call of Duty®: Modern Warfare® III", "Activision Publishing Inc.",+ nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},+ {"9NDKFJ6XDX2M", "CALLOFDUTYMODERNWARFAREIII", "2003727579", "Call of Duty®: Modern Warfare® III", "Activision Publishing Inc.",+ nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},+ {"9PNGFSX7S117", "CALLOFDUTYMODERNWARFAREII", "1959007243", "Call of Duty®: Modern Warfare® II", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.62866.14349375889218622.77ec9575-f44b-4013-97c6-f9cd0bbc53f5.b1790761-1d9e-4ffd-b146-3f68bdeb949e",+ "https://store-images.s-microsoft.com/image/apps.34778.14349375889218622.77ec9575-f44b-4013-97c6-f9cd0bbc53f5.fd60100a-bbb6-4eb3-a03c-6da8e90db089",+ "https://store-images.s-microsoft.com/image/apps.46802.14349375889218622.77ec9575-f44b-4013-97c6-f9cd0bbc53f5.041995ec-87c2-4c88-b7a6-98dbdbb5c975",+ "Shooter",+ "Call of Duty®: Modern Warfare® II drops players into an unprecedented global conflict that features the return of the iconic Operators of Task Force 141.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"9N872NBW5XG5", "CALLOFDUTYMODERNWARFAREII", "1959007243", "Call of Duty®: Modern Warfare® II", "Activision Publishing Inc.",+ nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},+ {"9P7RQ1QFFF8R", "CALLOFDUTYMODERNWARFAREII", "1959007243", "Call of Duty®: Modern Warfare® II", "Activision Publishing Inc.",+ nullptr, nullptr, nullptr, "Shooter", nullptr, "18", "ClassInd", nullptr, false},+ {"9NVQBQ3F6W9W", "CALLOFDUTYMODERNWARFARE", "609700427", "Call of Duty®: Modern Warfare®", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.52064.14393996338935986.84c4ee65-c726-49ae-925f-3dca581be2df.3e540e94-9e5a-41f5-9b00-c8f5190819f7",+ "https://store-images.s-microsoft.com/image/apps.50528.14393996338935986.84c4ee65-c726-49ae-925f-3dca581be2df.31d66188-6781-49ce-a75a-b4247e73b89d",+ "https://store-images.s-microsoft.com/image/apps.1926.14393996338935986.84c4ee65-c726-49ae-925f-3dca581be2df.46cd9cf0-2829-4517-a140-3d163199497f",+ "Shooter",+ "Experience a visceral Campaign or assemble your team in the ultimate online playground with multiple Special Ops challenges and a mix of Multiplayer maps and modes.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"C5DTJ99626K3", "CALLOFDUTYMODERNWARFARE", "609700427", "Call of Duty®: Modern Warfare®", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.52064.67185831113154542.823e899c-d262-40a0-91f6-eee04bdc3713.74be39c5-2d6e-4e6b-960b-7d8077da0142",+ "https://store-images.s-microsoft.com/image/apps.50528.67185831113154542.823e899c-d262-40a0-91f6-eee04bdc3713.dd7010c6-9641-4c5a-b8b5-7eb16ddc67ea",+ "https://store-images.s-microsoft.com/image/apps.1926.67185831113154542.823e899c-d262-40a0-91f6-eee04bdc3713.ca4b2ff5-8dc9-4774-a5f1-4e379a72cbda",+ "Shooter",+ "Experience a visceral Campaign or assemble your team in the ultimate online playground with multiple Special Ops challenges and a mix of Multiplayer maps and modes.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"9P7PFH4RMFZD", "CALLOFDUTYBLACKOPSCOLDWAR", "1790482525", "Call of Duty®: Black Ops Cold War", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.16401.14107985044965209.e8fed65f-093d-40d1-849f-6c564d2ad876.13b9c6b6-dddd-4f67-a303-b98250929229",+ "https://store-images.s-microsoft.com/image/apps.25992.14107985044965209.e8fed65f-093d-40d1-849f-6c564d2ad876.89955624-8043-4f20-8620-4381e11a3546",+ "https://store-images.s-microsoft.com/image/apps.52829.14107985044965209.e8fed65f-093d-40d1-849f-6c564d2ad876.8fe14720-2b8f-4b9c-aebf-07f1610816d5",+ "Shooter",+ "The iconic Black Ops series is back with Call of Duty®: Black Ops Cold War - the direct sequel to the original and fan-favorite Call of Duty®: Black Ops.\n\nWelcome to the brink. Welcome to Call of Duty®: Black Ops Cold War.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"9NPLRJ9CC870", "CALLOFDUTYBLACKOPSCOLDWARXBOXSERIESXS", "1790482525", "Call of Duty®: Black Ops Cold War - Xbox Series X|S", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.16401.13791444986287693.243003e9-8583-4df9-a0fc-2345d2f82ed4.e5e2cd4a-420a-41eb-bade-0eab002eab9c",+ "https://store-images.s-microsoft.com/image/apps.25992.13791444986287693.243003e9-8583-4df9-a0fc-2345d2f82ed4.b477eb21-1438-49b1-bf72-a36ed8d74bb8",+ "https://store-images.s-microsoft.com/image/apps.52829.13791444986287693.243003e9-8583-4df9-a0fc-2345d2f82ed4.92c561dc-948f-445a-ad29-5e287d884e0c",+ "Shooter",+ "The iconic Black Ops series is back with Call of Duty®: Black Ops Cold War - the direct sequel to the original and fan-favorite Call of Duty®: Black Ops.\n\nWelcome to the brink. Welcome to Call of Duty®: Black Ops Cold War.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"9PHP6HF58MB5", "CALLOFDUTYVANGUARD", "1929807318", "Call of Duty®: Vanguard", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.25644.14231872788446538.01bda410-79a7-42cd-a67b-497b17d840f1.b577a06e-1952-4f78-9ca8-6e43b94f985b",+ "https://store-images.s-microsoft.com/image/apps.31712.14231872788446538.ec1df70e-1780-4ec2-90fc-de130713250f.37f86b3f-4921-4955-902e-3325f37a3e17",+ "https://store-images.s-microsoft.com/image/apps.27881.14231872788446538.ec1df70e-1780-4ec2-90fc-de130713250f.b54d334f-52d0-45e1-ac31-c86b1d4b6ad6",+ "Shooter",+ "Call of Duty®: Vanguard includes a deeply engaging single player Campaign, a massive Multiplayer offering featuring over 20 maps including 16 built for core Multiplayer and an exciting new Zombies experience developed by Treyarch.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"9MWHTW1SF7RW", "CALLOFDUTYVANGUARDXBOXSERIESXS", "1929807318", "Call of Duty®: Vanguard - Xbox Series X|S", "Activision Publishing Inc.",+ "https://store-images.s-microsoft.com/image/apps.25644.13843233178803270.b12b929c-1b87-4fa1-900a-23a132dc9775.bdbacf51-1647-4c87-b9dc-6c455834d9bb",+ "https://store-images.s-microsoft.com/image/apps.31712.13843233178803270.d4ae9cce-02bd-4f56-8f61-6e02568a7dfd.401708cf-3756-4e90-b73d-bd1a6d4e1c09",+ "https://store-images.s-microsoft.com/image/apps.27881.13843233178803270.d4ae9cce-02bd-4f56-8f61-6e02568a7dfd.7b70ba8c-ba77-4fc3-af0d-cc1f87530bb0",+ "Shooter",+ "Call of Duty®: Vanguard includes a deeply engaging single player Campaign, a massive Multiplayer offering featuring over 20 maps including 16 built for core Multiplayer and an exciting new Zombies experience developed by Treyarch.",+ "18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+};++inline void seedKnownGames(std::map<std::string, std::string>& cloudTitleOf,+ std::map<std::string, std::string>& xboxTitleOf,+ std::set<std::string>& freeInStore,+ std::set<std::string>& gamePass,+ std::vector<std::string>& allGames,+ std::map<std::string, xcloud::Product>& products) {+ for (const auto& g : kKnownCloudGames) {+ cloudTitleOf[g.productId] = g.cloudTitleId;+ if (g.xboxTitleId && g.xboxTitleId[0]) xboxTitleOf[g.productId] = g.xboxTitleId;+ if (g.isFree) freeInStore.insert(g.productId);+ bool isCodHub = (std::string_view(g.productId) == "9NCPSQQD1Z66" ||+ std::string_view(g.productId) == "9N201KQXS5BM" ||+ std::string_view(g.productId) == "9NNFG8BQRCXL");+ if (isCodHub) {+ gamePass.insert(g.productId);+ if (std::find(allGames.begin(), allGames.end(), g.productId) == allGames.end()) {+ allGames.push_back(g.productId);+ }+ }+ if (!products.count(g.productId)) {+ xcloud::Product p;+ p.productId = g.productId;+ p.xcloudTitleId = g.cloudTitleId;+ p.xboxTitleId = g.xboxTitleId ? g.xboxTitleId : "";+ p.title = g.fallbackTitle;+ p.publisher = g.publisher;+ p.tileUrl = g.tileUrl ? g.tileUrl : "";+ p.posterUrl = g.posterUrl ? g.posterUrl : "";+ p.heroUrl = g.heroUrl ? g.heroUrl : "";+ p.description = g.description ? g.description : "";+ p.ratingAge = g.ratingAge ? g.ratingAge : "";+ p.ratingSystem = g.ratingSystem ? g.ratingSystem : "";+ if (g.ratingDescriptors && g.ratingDescriptors[0]) {+ p.ratingDescriptors.push_back(g.ratingDescriptors);+ }+ if (g.category && g.category[0]) p.categories.push_back(g.category);+ p.detailed = (g.description != nullptr && g.tileUrl != nullptr && g.heroUrl != nullptr);+ p.plan = xcloud::kPlanUltimate;+ products[g.productId] = std::move(p);+ } else {+ auto& p = products[g.productId];+ if (p.xcloudTitleId.empty() || p.xcloudTitleId == "None") p.xcloudTitleId = g.cloudTitleId;+ if (p.title.empty() && g.fallbackTitle) p.title = g.fallbackTitle;+ if (p.description.empty() && g.description) p.description = g.description;+ if (p.tileUrl.empty() && g.tileUrl) p.tileUrl = g.tileUrl;+ if (p.posterUrl.empty() && g.posterUrl) p.posterUrl = g.posterUrl;+ if (p.heroUrl.empty() && g.heroUrl) p.heroUrl = g.heroUrl;+ if (p.publisher.empty() && g.publisher) p.publisher = g.publisher;+ if (p.ratingAge.empty() && g.ratingAge) p.ratingAge = g.ratingAge;+ if (p.ratingSystem.empty() && g.ratingSystem) p.ratingSystem = g.ratingSystem;+ if (p.categories.empty() && g.category) p.categories.push_back(g.category);+ if (!p.detailed && !p.description.empty() && !p.tileUrl.empty() && !p.heroUrl.empty())+ p.detailed = true;+ }+ }+}++} // namespace xc::appdiff --git a/src/app/library_sync.cpp b/src/app/library_sync.cppnew file mode 100644index 0000000..7b3d250--- /dev/null+++ b/src/app/library_sync.cpp@@ -0,0 +1,892 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/library_internal.h"++#include "platform/platform.h"+#include "ui/strings.h"+#include "util/log.h"+#include "xcloud/purchase.h"+#include "xcloud/social.h"+#include "xcloud/titlehub.h"++#include <algorithm>+#include <ctime>+#include <map>+#include <set>++namespace xc::app {++size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std::string& err, const std::string& language) {+ market_ = gssv.session().market.empty() ? "US" : gssv.session().market;+ if (!language.empty()) language_ = language;+ std::vector<xcloud::Title> titles;+ std::string listErr;+ if (!gssv.listTitles(titles, listErr, false)) {+ err = listErr;+ return 0;+ }+ for (const auto& t : titles) {+ if (!t.productId.empty()) {+ if (!t.titleId.empty() && t.titleId != "None") {+ cloudTitleOf_[t.productId] = t.titleId;+ auto it = products_.find(t.productId);+ if (it != products_.end() && (it->second.xcloudTitleId.empty() || it->second.xcloudTitleId == "None")) {+ it->second.xcloudTitleId = t.titleId;+ }+ }+ if (!t.xboxTitleId.empty() && !xboxTitleOf_.count(t.productId)) {+ xboxTitleOf_[t.productId] = t.xboxTitleId;+ }+ if (t.isFreeInStore) {+ freeInStore_.insert(t.productId);+ }+ if (t.mouseKeyboard) {+ mouseKeyboard_.insert(t.productId);+ }+ }+ }++ std::vector<std::string> newProducts;+ for (const auto& t : titles) {+ if (!t.productId.empty() && !products_.count(t.productId)) {+ newProducts.push_back(t.productId);+ }+ for (const auto& alt : t.alternateProductIds) {+ if (!alt.empty() && !t.titleId.empty() && t.titleId != "None") {+ cloudTitleOf_[alt] = t.titleId;+ }+ }+ }+ xcloud::ProductList allSigl;+ std::string siglErr;+ if (xcloud::fetchList(xcloud::sigl::kAllGames, market_, language_, allSigl, siglErr)) {+ gamePass_.clear();+ gamePass_.insert(allSigl.productIds.begin(), allSigl.productIds.end());+ allGames_ = allSigl.productIds;+ seedKnownGames(cloudTitleOf_, xboxTitleOf_, freeInStore_, gamePass_, allGames_, products_);+ for (const auto& pid : allSigl.productIds) {+ if (!pid.empty() && !products_.count(pid)) {+ newProducts.push_back(pid);+ }+ }+ }+ std::sort(newProducts.begin(), newProducts.end());+ newProducts.erase(std::unique(newProducts.begin(), newProducts.end()), newProducts.end());++ size_t newCount = 0;+ if (!newProducts.empty()) {+ std::string fetchErr;+ xcloud::fetchProducts(newProducts, market_, language_, products_, fetchErr, false);++ std::vector<std::string> actuallyAdded;+ for (const auto& pid : newProducts) {+ auto it = products_.find(pid);+ if (it != products_.end() && !it->second.title.empty()) {+ actuallyAdded.push_back(pid);+ } else {+ products_[pid].productId = pid;+ products_[pid].detailedAt = platform::nowMs();+ }+ }+ newCount = actuallyAdded.size();+ }+ allGames_.erase(std::remove_if(allGames_.begin(), allGames_.end(),+ [&](const std::string& id) {+ return isPcOnly(id);+ }),+ allGames_.end());+ for (auto it = gamePass_.begin(); it != gamePass_.end(); ) {+ if (isPcOnly(*it)) it = gamePass_.erase(it);+ else ++it;+ }+ for (auto& row : layout_) {+ if (row.isGrid) {+ row.items.clear();+ for (const auto& pid : allGames_) {+ std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";+ row.items.emplace_back(pid, tid);+ }+ } else {+ row.items.erase(std::remove_if(row.items.begin(), row.items.end(),+ [&](const auto& item) {+ return isPcOnly(item.first);+ }),+ row.items.end());+ }+ }+ loadOwned(gssv, changed, nullptr, &titles);+ loadCatalogNames(changed, nullptr);+ saveCache();+ changed();+ return newCount;+}++bool Library::load(xcloud::GssvClient& gssv, const std::string& language, const Changed& changed, std::string& err,+ bool forceRefresh) {+ market_ = gssv.session().market.empty() ? "US" : gssv.session().market;+ language_ = language;+ layout_.clear();+ products_.clear();+ allGames_.clear();+ gamePass_.clear();+ popular_.clear();+ recent_.clear();+ ownershipKnown_ = false;+ ownershipFresh_ = false;+ knownGamePass_.clear();+ ownedTitles_.clear();+ ownedProducts_.clear();+ owned_.clear();+ purchasable_.clear();+ purchasableSet_.clear();+ freeInStore_.clear();+ otherLanguage_.clear();+ progress_ = {};+ std::string lastErr;++ // The Game Pass catalog first: it decides what the other lists may show.+ xcloud::ProductList all;+ std::string e;+ if (xcloud::fetchList(xcloud::sigl::kAllGames, market_, language_, all, e)) {+ allGames_ = all.productIds;+ gamePass_.insert(all.productIds.begin(), all.productIds.end());+ } else {+ XC_LOGW("%s", e.c_str());+ lastErr = e;+ }+ seedKnownGames(cloudTitleOf_, xboxTitleOf_, freeInStore_, gamePass_, allGames_, products_);+ // The account's games from the previous run, until loadOwned() refreshes+ // them. Not its home rows: those are built below.+ loadCache(false);++ // "Jump back in": recently played games, Game Pass or the account's own+ // (rows() leaves out those it can't play; they also go first in "Your+ // games").+ std::vector<xcloud::Title> recent;+ if (gssv.listTitles(recent, lastErr, true)) {+ RowIds r{ui::tr(ui::Str::JumpBackIn), false, false, {}, true};+ std::vector<std::string> ids;+ std::vector<std::string> freshRecent;+ for (const auto& t : recent) {+ if (t.productId.empty()) continue;+ if (std::find(freshRecent.begin(), freshRecent.end(), t.productId) == freshRecent.end()) {+ freshRecent.push_back(t.productId);+ }+ if (!t.xboxTitleId.empty()) xboxTitleOf_[t.productId] = t.xboxTitleId;+ // Its inputs come with it: the first cards show keyboard and+ // mouse without waiting for the whole list (or a cache that has it).+ if (t.mouseKeyboard) mouseKeyboard_.insert(t.productId);+ r.items.emplace_back(t.productId, t.titleId);+ if (!products_.count(t.productId)) ids.push_back(t.productId);+ }+ for (const auto& pid : recent_) {+ if (!pid.empty() && std::find(freshRecent.begin(), freshRecent.end(), pid) == freshRecent.end()) {+ freshRecent.push_back(pid);+ }+ }+ recent_ = std::move(freshRecent);+ for (const auto& pid : acquiredProducts_) {+ auto it = std::find(recent_.begin(), recent_.end(), pid);+ if (it != recent_.end()) recent_.erase(it);+ recent_.insert(recent_.begin(), pid);+ }+ sortOwned();+ // 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();+ }+ }++ const ListSpec lists[] = {{xcloud::sigl::kRecentlyAdded, 40},+ {xcloud::sigl::kMostPopular, 40},+ {xcloud::sigl::kFreeToPlay, 40},+ {xcloud::sigl::kLeavingSoon, 40},+ {xcloud::sigl::kAllGames, 0}};+ uint8_t myPlan = xcloud::planTier(subscription_);+ for (const auto& spec : lists) {+ xcloud::ProductList list;+ bool isAllGames = std::string_view(spec.sigl) == xcloud::sigl::kAllGames;+ if (isAllGames && !allGames_.empty()) {+ list.title = all.title.empty() ? "All games" : all.title;+ list.productIds = allGames_;+ } else if (!xcloud::fetchList(spec.sigl, market_, language_, list, e)) {+ XC_LOGW("%s", e.c_str());+ lastErr = e;+ continue;+ }+ if (spec.sigl == xcloud::sigl::kRecentlyAdded) {+ const char* const kNewCod[] = {"9NCPSQQD1Z66", "9N201KQXS5BM"};+ for (const char* pid : kNewCod) {+ auto it = std::find(list.productIds.begin(), list.productIds.end(), pid);+ if (it != list.productIds.end()) {+ list.productIds.erase(it);+ size_t insertAt = std::min<size_t>(1, list.productIds.size());+ list.productIds.insert(list.productIds.begin() + static_cast<long>(insertAt), pid);+ }+ }+ }+ // "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;+ // Position key cloud titles (Modern Warfare 4, Call of Duty HQ, Warzone)+ // within the visible most popular shelf if legitimately in the feed+ const char* const kTopCod[] = {"9NCPSQQD1Z66", "9N201KQXS5BM", "9NNFG8BQRCXL"};+ for (const char* pid : kTopCod) {+ auto it = std::find(list.productIds.begin(), list.productIds.end(), pid);+ if (it != list.productIds.end()) {+ list.productIds.erase(it);+ size_t insertAt = std::min<size_t>(2, list.productIds.size());+ list.productIds.insert(list.productIds.begin() + static_cast<long>(insertAt), pid);+ }+ }+ }+ // Free-to-play: no Game Pass needed, so not filtered; each one the+ // account hasn't got yet shows as free to get (tile()).+ bool freeToPlay = spec.sigl == xcloud::sigl::kFreeToPlay;+ if (freeToPlay) {+ freeInStore_.insert(list.productIds.begin(), list.productIds.end());+ XC_LOGI("library: %s: %zu games", list.title.c_str(), list.productIds.size());+ }+ bool isMostPopular = spec.sigl == xcloud::sigl::kMostPopular;+ if (!gamePass_.empty() && !freeToPlay && !isMostPopular) {+ size_t before = list.productIds.size();+ list.productIds.erase(std::remove_if(list.productIds.begin(), list.productIds.end(),+ [&](const std::string& id) {+ if (!gamePass_.count(id)) return true;+ if (myPlan > 0 && myPlan < xcloud::kPlanUltimate && !ownedProducts_.count(id) &&+ !freeInStore_.count(id)) {+ auto it = products_.find(id);+ if (it != products_.end() &&+ !xcloud::planIncludes(myPlan, it->second.plan, false))+ return true;+ }+ return false;+ }),+ list.productIds.end());+ if (list.productIds.size() != before)+ XC_LOGI("library: %s: %zu of %zu not in Game Pass/plan, left out", list.title.c_str(),+ before - list.productIds.size(), before);+ }+ list.productIds.erase(std::remove_if(list.productIds.begin(), list.productIds.end(),+ [&](const std::string& id) {+ return isPcOnly(id);+ }),+ list.productIds.end());+ if (spec.limit > 0 && list.productIds.size() > spec.limit) list.productIds.resize(spec.limit);+ std::vector<std::string> missing;+ for (const auto& id : list.productIds) {+ auto it = products_.find(id);+ if (it == products_.end() || it->second.tileUrl.empty() || otherLanguage_.count(id))+ missing.push_back(id);+ }+ if (!missing.empty() && !xcloud::fetchProducts(missing, market_, language_, products_, e, false)) {+ XC_LOGW("%s", e.c_str());+ lastErr = e;+ }+ RowIds r{list.title, !freeToPlay, isAllGames, {}};+ for (const auto& id : list.productIds) r.items.emplace_back(id, std::string());+ layout_.push_back(std::move(r));+ changed();+ }+ if (rows().empty()) {+ err = lastErr.empty() ? "no games found" : lastErr;+ return false;+ }+ return true;+}++void Library::loadOwned(xcloud::GssvClient gssv, const Changed& changed, const std::atomic<bool>* stop,+ const std::vector<xcloud::Title>* preloadedTitles) {+ progress_ = {true, 0, 0}; // the account's list: no measure until the names+ changed();+ std::string err;+ std::vector<xcloud::Title> fetchedTitles;+ const std::vector<xcloud::Title>* titlesPtr = preloadedTitles;+ if (!titlesPtr) {+ if (!gssv.listTitles(fetchedTitles, err, false)) {+ XC_LOGW("%s", err.c_str()); // keep what the cache said+ progress_ = {};+ changed();+ return;+ }+ titlesPtr = &fetchedTitles;+ }+ const auto& titles = *titlesPtr;+ if (stop && *stop) {+ progress_ = {};+ changed();+ return;+ }+ std::set<std::string> ownedTitles, ownedProducts;+ std::vector<Item> mine;+ std::set<std::string> seenMine;+ std::map<std::string, std::string> toBuy; // productId -> titleId+ bool member = false;+ auto registerCloudTitle = [&](const std::string& pid, const std::string& tid, const std::string& xboxId, bool freeStore, bool mkb) {+ if (pid.empty()) return;+ if (!tid.empty() && tid != "None") {+ cloudTitleOf_[pid] = tid;+ auto it = products_.find(pid);+ if (it != products_.end() && (it->second.xcloudTitleId.empty() || it->second.xcloudTitleId == "None")) {+ it->second.xcloudTitleId = tid;+ }+ }+ if (!xboxId.empty() && !xboxTitleOf_.count(pid)) xboxTitleOf_[pid] = xboxId;+ if (freeStore) freeInStore_.insert(pid);+ if (mkb) mouseKeyboard_.insert(pid);+ };++ for (const auto& t : titles) {+ bool isAcquired = (!t.productId.empty() && acquiredProducts_.count(t.productId)) ||+ (!t.titleId.empty() && acquiredTitles_.count(t.titleId));+ for (const auto& alt : t.alternateProductIds) {+ if (!alt.empty() && acquiredProducts_.count(alt)) { isAcquired = true; break; }+ }+ bool entitled = t.hasEntitlement || isAcquired;+ member |= entitled && t.viaSubscription;+ if (xcloud::isNonGameAddon(t.titleId)) continue;+ if (entitled) ownedTitles.insert(t.titleId);++ registerCloudTitle(t.productId, t.titleId, t.xboxTitleId, t.isFreeInStore, t.mouseKeyboard);+ for (const auto& alt : t.alternateProductIds) {+ registerCloudTitle(alt, t.titleId, t.xboxTitleId, t.isFreeInStore, t.mouseKeyboard);+ }++ if (entitled) {+ if (!t.productId.empty()) ownedProducts.insert(t.productId);+ for (const auto& alt : t.alternateProductIds) {+ if (!alt.empty()) ownedProducts.insert(alt);+ }+ // Game Pass games the account owns itself (free-to-play ones+ // like Fortnite, without the subscription) are its games too.+ // Also games outside the Game Pass catalog.+ if (!t.productId.empty()) {+ if (!gamePass_.count(t.productId) || !t.viaSubscription || isAcquired) {+ if (seenMine.insert(t.productId).second) {+ mine.emplace_back(t.productId, t.titleId);+ }+ }+ }+ } else if (!t.productId.empty() && !gamePass_.count(t.productId)) {+ toBuy[t.productId] = t.titleId;+ }+ }++ bool hasCod = member || ownedTitles.count("CALLOFDUTYHQ") || ownedTitles.count("CALLOFDUTYBLACKOPS6") ||+ ownedTitles.count("CALLOFDUTYMODERNWARFAREIII");+ if (hasCod) {+ ownedTitles.insert("CALLOFDUTYHQ");+ ownedTitles.insert("CALLOFDUTYBLACKOPS6");+ ownedTitles.insert("CALLOFDUTYMODERNWARFAREIII");+ }+ for (const auto& g : kKnownCloudGames) {+ registerCloudTitle(g.productId, g.cloudTitleId, g.xboxTitleId ? g.xboxTitleId : "", g.isFree, false);+ if (ownedTitles.count(g.cloudTitleId)) {+ ownedProducts.insert(g.productId);+ if (g.isFree || std::string_view(g.productId) == "9NCPSQQD1Z66") {+ if (seenMine.insert(g.productId).second) {+ mine.emplace_back(g.productId, g.cloudTitleId);+ }+ }+ } else if (!gamePass_.count(g.productId)) {+ toBuy[g.productId] = g.cloudTitleId;+ }+ }+ for (const auto& pid : acquiredProducts_) {+ toBuy.erase(pid);+ ownedProducts.insert(pid);+ if (seenMine.insert(pid).second) {+ std::string tid;+ auto it = cloudTitleOf_.find(pid);+ if (it != cloudTitleOf_.end()) tid = it->second;+ if (tid.empty()) {+ auto pit = products_.find(pid);+ if (pit != products_.end() && !pit->second.xcloudTitleId.empty() && pit->second.xcloudTitleId != "None") {+ tid = pit->second.xcloudTitleId;+ }+ }+ mine.emplace_back(pid, tid);+ }+ }+ for (const auto& tid : acquiredTitles_) {+ if (!tid.empty()) {+ ownedTitles.insert(tid);+ for (const auto& [p, t] : cloudTitleOf_) {+ if (t == tid) {+ ownedProducts.insert(p);+ toBuy.erase(p);+ }+ }+ }+ }+ for (auto it = toBuy.begin(); it != toBuy.end(); ) {+ bool isOwnedOrAcquired = acquiredProducts_.count(it->first) > 0 ||+ ownedProducts.count(it->first) > 0 ||+ (!it->second.empty() && (acquiredTitles_.count(it->second) > 0 || ownedTitles.count(it->second) > 0));+ if (isOwnedOrAcquired) {+ it = toBuy.erase(it);+ } else {+ ++it;+ }+ }+ // 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);+ for (const auto& [pid, _] : toBuy)+ if (!products_.count(pid)) missing.push_back(pid);+ if (!missing.empty() && !xcloud::fetchProducts(missing, market_, language_, products_, err, false))+ XC_LOGW("%s", err.c_str());+ if (stop && *stop) {+ progress_ = {};+ changed();+ return;+ }+ ownedTitles_ = std::move(ownedTitles);+ ownershipFresh_ = true;+ ownedProducts_ = std::move(ownedProducts);+ owned_ = std::move(mine);+ purchasable_ = std::move(buy);+ purchasable_.erase(std::remove_if(purchasable_.begin(), purchasable_.end(),+ [&](const Item& item) {+ return acquiredProducts_.count(item.first) > 0 ||+ ownedProducts_.count(item.first) > 0 ||+ (!item.second.empty() && (acquiredTitles_.count(item.second) > 0 || ownedTitles_.count(item.second) > 0));+ }), purchasable_.end());+ purchasableSet_.clear();+ for (const auto& p : purchasable_) purchasableSet_.insert(p.first);+ for (const auto& pid : acquiredProducts_) {+ purchasableSet_.erase(pid);+ }+ for (const auto& [pid, tid] : cloudTitleOf_) {+ if (acquiredTitles_.count(tid) || ownedTitles_.count(tid)) {+ purchasableSet_.erase(pid);+ }+ }+ for (const auto& pid : acquiredProducts_) {+ if (!pid.empty() && std::find(recent_.begin(), recent_.end(), pid) == recent_.end()) {+ recent_.insert(recent_.begin(), pid);+ }+ }+ ownershipKnown_ = true;+ gamePassMember_ = member;+ sortOwned();+ saveCache();+ XC_LOGI("library: account can stream %zu titles; %zu outside Game Pass; %zu more to buy", ownedTitles_.size(),+ owned_.size(), purchasable_.size());+ progress_ = {};+ changed();+}++void Library::loadCatalogNames(const Changed& changed, const std::atomic<bool>* stop) {+ // Names and art: the account's games and the games to buy first (their+ // lists are on screen), then the Game Pass catalog for its search. Also+ // anything still in another language.+ std::vector<std::string> missing;+ std::set<std::string> queued;+ auto want = [&](const std::string& id) {+ auto it = products_.find(id);+ bool needs = (it == products_.end()) ||+ it->second.title.empty() ||+ it->second.tileUrl.empty() ||+ (it->second.xcloudTitleId.empty() || it->second.xcloudTitleId == "None") ||+ otherLanguage_.count(id);+ if (needs && queued.insert(id).second) missing.push_back(id);+ };+ for (const auto* list : {&owned_, &purchasable_})+ for (const auto& item : *list) want(item.first);+ for (const auto& id : allGames_) want(id);+ progress_ = {true, 0, missing.size()};+ changed();+ constexpr size_t kBatch = 100;+ for (size_t i = 0; i < missing.size(); i += kBatch) {+ if (stop && *stop) break;+ std::vector<std::string> batch(missing.begin() + static_cast<long>(i),+ missing.begin() + static_cast<long>(std::min(missing.size(), i + kBatch)));+ std::map<std::string, xcloud::Product> fetched;+ std::string e;+ if (!xcloud::fetchProducts(batch, market_, language_, fetched, e, false)) {+ XC_LOGW("%s", e.c_str());+ break;+ }+ for (auto& [id, p] : fetched) {+ auto ct = cloudTitleOf_.find(id);+ if (p.xcloudTitleId.empty() || p.xcloudTitleId == "None") {+ if (ct != cloudTitleOf_.end()) p.xcloudTitleId = ct->second;+ }+ if (p.xcloudTitleId == "None") p.xcloudTitleId.clear();+ // Keep the hero art and description already known, until they+ // come in the new language (hydrate()).+ auto old = products_.find(id);+ if (old != products_.end()) {+ if (p.heroUrl.empty()) p.heroUrl = old->second.heroUrl;+ if (p.description.empty() && !otherLanguage_.count(id)) p.description = old->second.description;+ if (p.xcloudTitleId.empty()) p.xcloudTitleId = old->second.xcloudTitleId;+ if (!p.detailed && old->second.detailed) { // modes, languages and plan don't change with the language+ p.detailed = true;+ p.detailedAt = old->second.detailedAt;+ p.modes = old->second.modes;+ p.plan = old->second.plan;+ p.languages = old->second.languages;+ }+ }+ products_[id] = std::move(p);+ otherLanguage_.erase(id);+ }+ progress_.done = std::min(missing.size(), i + kBatch);+ changed(); // each batch: the lists fill in as names arrive+ }+ progress_ = {};+ changed();+ allGames_.erase(std::remove_if(allGames_.begin(), allGames_.end(),+ [&](const std::string& id) {+ return isPcOnly(id);+ }),+ allGames_.end());+ for (auto it = gamePass_.begin(); it != gamePass_.end(); ) {+ if (isPcOnly(*it)) it = gamePass_.erase(it);+ else ++it;+ }+ for (auto& row : layout_) {+ if (row.isGrid) {+ row.items.clear();+ for (const auto& pid : allGames_) {+ std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";+ row.items.emplace_back(pid, tid);+ }+ } else {+ row.items.erase(std::remove_if(row.items.begin(), row.items.end(),+ [&](const auto& item) {+ return isPcOnly(item.first);+ }),+ row.items.end());+ }+ }+ saveCache();+ XC_LOGI("library: search covers %zu Game Pass games and %zu of yours or to buy", gamePassSearchPool().size(),+ librarySearchPool().size());+ changed();+}++bool Library::fetchFull(const std::vector<std::string>& ids, const Changed& changed, const std::atomic<bool>* stop,+ size_t firstBatch) {+ bool ok = true;+ int batches = 0;+ std::vector<std::string> order;+ std::set<std::string> queued;+ for (const auto& id : ids) {+ auto it = products_.find(id);+ bool needFull = (it == products_.end() || !it->second.detailed || it->second.description.empty());+ if (needFull && queued.insert(id).second)+ order.push_back(id);+ }+ auto mergeProduct = [&](const std::string& id, xcloud::Product&& p) {+ auto ct = cloudTitleOf_.find(id);+ if (p.xcloudTitleId.empty() || p.xcloudTitleId == "None") {+ if (ct != cloudTitleOf_.end()) p.xcloudTitleId = ct->second;+ }+ if (p.xcloudTitleId == "None") p.xcloudTitleId.clear();+ auto oldIt = products_.find(id);+ if (oldIt != products_.end()) {+ const auto& old = oldIt->second;+ if (p.plan == 0) p.plan = old.plan;+ if (p.xcloudTitleId.empty()) p.xcloudTitleId = old.xcloudTitleId;+ if (p.xboxTitleId.empty()) p.xboxTitleId = old.xboxTitleId;+ if (p.title.empty()) p.title = old.title;+ if (p.publisher.empty()) p.publisher = old.publisher;+ if (p.tileUrl.empty()) p.tileUrl = old.tileUrl;+ if (p.posterUrl.empty()) p.posterUrl = old.posterUrl;+ if (p.heroUrl.empty()) p.heroUrl = old.heroUrl;+ if (p.description.empty()) p.description = old.description;+ if (p.categories.empty()) p.categories = old.categories;+ if (p.modes == 0) p.modes = old.modes;+ if (p.languages.empty()) p.languages = old.languages;+ if (p.ratingAge.empty()) p.ratingAge = old.ratingAge;+ if (p.ratingSystem.empty()) p.ratingSystem = old.ratingSystem;+ if (p.ratingDescriptors.empty()) p.ratingDescriptors = old.ratingDescriptors;+ }+ products_[id] = std::move(p);+ };+ // Batches of 20 (~10 KB per product: bigger ones made the catalog time+ // out, 504, and weren't faster).+ 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;+ // A batch that fails (a timeout now and then) is asked again; one+ // that keeps failing is left for next time, and the rest carries on.+ bool got = false;+ for (int attempt = 0; attempt < 3 && !got; ++attempt) {+ if (attempt) platform::sleepMs(1000);+ got = xcloud::fetchProducts(batch, market_, language_, full, e, true);+ if (!got) XC_LOGW("%s%s", e.c_str(), attempt < 2 ? " (asking again)" : " (skipped)");+ }+ if (!got) {+ ok = false;+ continue;+ }+ for (const auto& id : batch) {+ // Not in the catalog's details: nothing more to know, not asked again.+ auto known = products_.find(id);+ if (!full.count(id) && known != products_.end()) known->second.detailed = true;+ }+ for (auto& [id, p] : full) mergeProduct(id, std::move(p));+ changed();+ if (++batches % 4 == 0) saveCache(); // a long fetch keeps what it got if the app closes+ }+ return ok;+}++void Library::fetchPlatformsFor(const std::vector<std::string>& ids, const std::string& xblAuth) {+ if (xblAuth.empty()) return;+ std::set<std::string> want;+ for (const auto& pid : ids) {+ 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);+ }+ 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, 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();+}++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> ids;+ for (const auto& r : layout_)+ for (const auto& item : r.items) ids.push_back(item.first);+ for (const auto& item : owned_) ids.push_back(item.first);+ // Then every game the search goes through: its filters (play mode,+ // language) need the full details.+ for (const auto& item : purchasable_) ids.push_back(item.first);+ ids.insert(ids.end(), allGames_.begin(), allGames_.end());+ uint64_t t0 = platform::nowMs();+ fetchFull(ids, changed, stop);+ // The store changes descriptions and details now and then: the oldest+ // few (over 30 days) are fetched again on each start, never all at once.+ constexpr int64_t kRefreshAge = 30 * 24 * 3600;+ constexpr size_t kRefreshPerStart = 40;+ int64_t now = static_cast<int64_t>(std::time(nullptr));+ std::vector<std::pair<int64_t, std::string>> old;+ for (const auto& [id, p] : products_)+ if (p.detailed && p.detailedAt && now - p.detailedAt > kRefreshAge) old.push_back({p.detailedAt, id});+ std::sort(old.begin(), old.end());+ if (old.size() > kRefreshPerStart) old.resize(kRefreshPerStart);+ if (!old.empty() && !(stop && *stop)) {+ std::vector<std::string> refresh;+ for (const auto& [at, id] : old) refresh.push_back(id);+ size_t done = 0;+ for (size_t i = 0; i < refresh.size(); i += 20) {+ std::vector<std::string> batch(refresh.begin() + static_cast<long>(i),+ refresh.begin() + static_cast<long>(std::min(refresh.size(), i + 20)));+ std::map<std::string, xcloud::Product> fresh;+ std::string e;+ if (!xcloud::fetchProducts(batch, market_, language_, fresh, e, true)) {+ XC_LOGW("%s (refresh: next start)", e.c_str());+ break;+ }+ for (const auto& id : batch) {+ auto it = fresh.find(id);+ if (it != fresh.end()) {+ auto& p = it->second;+ auto ct = cloudTitleOf_.find(id);+ if (p.xcloudTitleId.empty() || p.xcloudTitleId == "None") {+ if (ct != cloudTitleOf_.end()) p.xcloudTitleId = ct->second;+ }+ if (p.xcloudTitleId == "None") p.xcloudTitleId.clear();+ auto oldIt = products_.find(id);+ if (oldIt != products_.end()) {+ const auto& prev = oldIt->second;+ if (p.plan == 0) p.plan = prev.plan;+ if (p.xcloudTitleId.empty()) p.xcloudTitleId = prev.xcloudTitleId;+ if (p.xboxTitleId.empty()) p.xboxTitleId = prev.xboxTitleId;+ if (p.title.empty()) p.title = prev.title;+ if (p.publisher.empty()) p.publisher = prev.publisher;+ if (p.tileUrl.empty()) p.tileUrl = prev.tileUrl;+ if (p.posterUrl.empty()) p.posterUrl = prev.posterUrl;+ if (p.heroUrl.empty()) p.heroUrl = prev.heroUrl;+ if (p.description.empty()) p.description = prev.description;+ if (p.categories.empty()) p.categories = prev.categories;+ if (p.modes == 0) p.modes = prev.modes;+ if (p.languages.empty()) p.languages = prev.languages;+ if (p.ratingAge.empty()) p.ratingAge = prev.ratingAge;+ if (p.ratingSystem.empty()) p.ratingSystem = prev.ratingSystem;+ if (p.ratingDescriptors.empty()) p.ratingDescriptors = prev.ratingDescriptors;+ }+ products_[id] = std::move(p);+ ++done;+ } else {+ products_[id].detailedAt = now; // gone from the catalog's details: not asked again for a while+ }+ }+ }+ XC_LOGI("library: %zu of %zu old details refreshed (%zu over 30 days in all)", done, refresh.size(),+ static_cast<size_t>(std::count_if(products_.begin(), products_.end(), [&](const auto& kv) {+ return kv.second.detailed && now - kv.second.detailedAt > kRefreshAge;+ })));+ changed();+ }+ saveCache(); // descriptions, hero art, modes and languages for next time+ size_t detailed = 0;+ for (const auto& [id, p] : products_) detailed += p.detailed;+ XC_LOGI("library: %zu rows, %zu of %zu products with details (%llu s)", layout_.size(), detailed, products_.size(),+ static_cast<unsigned long long>((platform::nowMs() - t0) / 1000));+}++void Library::loadFriends(const std::string& xblAuth, const Changed& changed, const std::atomic<bool>* stop) {+ if (xblAuth.empty() || (stop && *stop)) return;+ std::vector<xcloud::FriendPresence> presence;+ std::string err;+ if (!xcloud::fetchFriendsPresence(xblAuth, presence, err, language_)) return;+ if (stop && *stop) return;++ // Map Xbox Live Title ID / Cloud Title ID -> Store Product ID+ std::map<std::string, std::string> productByXbox;+ for (const auto& [pid, xid] : xboxTitleOf_) {+ if (!xid.empty()) productByXbox[xid] = pid;+ }+ for (const auto& [pid, prod] : products_) {+ productByXbox[pid] = pid;+ if (!prod.xboxTitleId.empty() && !productByXbox.count(prod.xboxTitleId)) {+ productByXbox[prod.xboxTitleId] = pid;+ }+ if (!prod.xcloudTitleId.empty() && !productByXbox.count(prod.xcloudTitleId)) {+ productByXbox[prod.xcloudTitleId] = pid;+ }+ }+ for (const auto& [pid, cid] : cloudTitleOf_) {+ if (!cid.empty() && !productByXbox.count(cid)) {+ productByXbox[cid] = pid;+ }+ }++ // Group friends playing accessible games+ std::map<std::string, std::vector<ui::FriendPlaying>> friendsByProduct;+ for (const auto& fp : presence) {+ if (fp.presenceState != "Online" || fp.titleId.empty()) continue;+ auto it = productByXbox.find(fp.titleId);+ if (it == productByXbox.end()) continue;+ const std::string& pid = it->second;++ // Check if game is playable on this account (Game Pass or owned)+ ui::GameTile t = tile(pid);+ if (!t.playable) continue;++ friendsByProduct[pid].push_back({fp.gamertag, fp.gamerpicUrl});+ }++ std::vector<ui::GameTile> tiles;+ std::vector<std::string> needDetails;+ for (auto& [pid, friendsList] : friendsByProduct) {+ ui::GameTile t = tile(pid);+ if (t.productId.empty() || !t.playable) continue;+ if (t.heroUrl.empty()) {+ auto pit = products_.find(pid);+ if (pit != products_.end() && !pit->second.heroUrl.empty()) {+ t.heroUrl = pit->second.heroUrl;+ } else {+ for (const auto& [otherPid, otherProd] : products_) {+ if (!otherProd.heroUrl.empty() &&+ ((!t.titleId.empty() && otherProd.xcloudTitleId == t.titleId) ||+ (!t.xboxTitleId.empty() && otherProd.xboxTitleId == t.xboxTitleId))) {+ t.heroUrl = otherProd.heroUrl;+ if (t.description.empty()) t.description = otherProd.description;+ break;+ }+ }+ }+ }+ if (t.heroUrl.empty() && !pid.empty()) {+ needDetails.push_back(pid);+ }+ t.friends = std::move(friendsList);+ tiles.push_back(std::move(t));+ }++ friendsTiles_ = std::move(tiles);+ if (!friendsTiles_.empty()) {+ XC_LOGI("library: %zu friends playing %zu accessible games now", presence.size(), friendsTiles_.size());+ changed();+ if (!needDetails.empty()) {+ fetchFull(needDetails, changed, stop);+ for (auto& t : friendsTiles_) {+ if (t.heroUrl.empty()) {+ auto fresh = tile(t.productId, t.titleId);+ if (!fresh.heroUrl.empty()) t.heroUrl = fresh.heroUrl;+ if (!fresh.description.empty() && t.description.empty()) t.description = fresh.description;+ }+ }+ changed();+ }+ }+}++} // namespace xc::appdiff --git a/src/app/settings.cpp b/src/app/settings.cppindex c77b2a0..73eb8e9 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -132,6 +132,7 @@ bool Settings::load(const std::string& path) {for (const auto& [name, ms] : (*j)["regionRtt"].members())if (ms.asInt() > 0) regionRtt[name] = static_cast<int>(ms.asInt());queueReadyAlert = (*j)["queueReadyAlert"].asBool(queueReadyAlert);+ previewFeatures = (*j)["previewFeatures"].asBool(previewFeatures);titlePlaytime.clear();for (const auto& [id, sec] : (*j)["titlePlaytime"].members())if (sec.asInt() > 0) titlePlaytime[id] = static_cast<uint64_t>(sec.asInt());@@ -273,6 +274,7 @@ bool Settings::save(const std::string& path) const {v.set("voiceRouting", voiceRouting);v.set("padSpeakerVolume", padSpeakerVolume);v.set("queueReadyAlert", queueReadyAlert);+ v.set("previewFeatures", previewFeatures);json::Value pt = json::Value::object();for (const auto& [id, sec] : titlePlaytime)if (sec > 0) pt.set(id, static_cast<int64_t>(sec));diff --git a/src/app/settings.h b/src/app/settings.hindex 8b6f234..681fc9f 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -120,6 +120,7 @@ struct Settings {int voiceRouting = 0; // 0: Auto (DualSense Speaker if available), 1: Always TV/Headsetint padSpeakerVolume = 100; // 0 to 100% (DualSense controller speaker)bool queueReadyAlert = true; // Queue-ready chime and rumble alert+ bool previewFeatures = true; // xCloud preview client identification & ad-supported F2P streamingstd::map<std::string, uint64_t> titlePlaytime; // accumulated playtime in seconds (productId or titleId -> seconds)uint64_t playtimeForGame(const std::string& productId, const std::string& titleId) const {diff --git a/src/app/web_server.cpp b/src/app/web_server.cppindex c57b272..18c6b0e 100644--- a/src/app/web_server.cpp+++ b/src/app/web_server.cpp@@ -35,2347 +35,6 @@ static WebServerHooks s_hooks;namespace {-const char* kIndexHtml = R"html(<!DOCTYPE html>-<html lang="pt-BR">-<head>-<meta charset="utf-8">-<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">-<title>PSBox Cloud Gaming - Smartglass WebUI</title>-<script>-(function() {- function applyInitScale() {- var w = window.innerWidth || (document.documentElement ? document.documentElement.clientWidth : 360);- var h = window.innerHeight || (document.documentElement ? document.documentElement.clientHeight : 640);- var isLand = w > h;- var pScale = Math.min(1, Math.max(0.4, (w - 28) / 412));- var lsScale = Math.min(1, Math.max(0.35, Math.min((w - 24) / 915, (h - 78) / 412)));- var fsScale = Math.min(1.2, Math.max(0.4, Math.min((w - 28) / 915, (h - 20) / 412)));- document.documentElement.style.setProperty('--gp-scale', (isLand ? lsScale : pScale).toFixed(3));- document.documentElement.style.setProperty('--gp-fs-scale', fsScale.toFixed(3));- }- applyInitScale();- window.addEventListener('resize', applyInitScale);-})();-</script>-<style>-:root {- --bg: #0b0d13;- --surface: #141722;- --surface-alt: #1c2130;- --border: #282f44;- --primary: #107C41;- --primary-hover: #169c53;- --accent: #0070d8;- --text: #f0f3f8;- --text-dim: #9aa4b8;- --danger: #d93838;-}-* { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }-html { width: 100%; max-width: 100%; background: var(--bg); }-body { width: 100%; max-width: 100%; margin: 0; padding: 0; overflow-x: hidden; overflow-y: auto; background: var(--bg); color: var(--text); -webkit-overflow-scrolling: touch; overscroll-behavior-y: none; }-header { box-sizing: border-box; background: var(--surface); border-bottom: 1px solid var(--border); padding-top: max(18px, env(safe-area-inset-top, 18px)); padding-bottom: 12px; padding-left: max(16px, env(safe-area-inset-left, 16px)); padding-right: max(16px, env(safe-area-inset-right, 16px)); display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; max-width: 100%; overflow-x: hidden; }-.brand { display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1 1 auto; }-.logo-icon { flex-shrink: 0; width: 32px; height: 32px; border-radius: 50%; box-shadow: 0 0 10px rgba(16, 124, 65, 0.45); }-.brand-text { min-width: 0; flex: 1 1 auto; }-.brand-text h1 { font-size: clamp(0.76rem, 3.6vw, 0.96rem); font-weight: 700; letter-spacing: 0.5px; color: #fff; text-transform: uppercase; line-height: 1.2; white-space: nowrap; }-.brand-subtitle { font-size: 0.70rem; color: var(--text-dim); display: block; font-weight: 500; white-space: nowrap; }-header .badge { background: var(--primary); color: #fff; font-size: 0.70rem; padding: 3px 7px; border-radius: 12px; font-weight: 600; text-transform: uppercase; flex-shrink: 0; }-.nav-tabs { display: grid; grid-template-columns: repeat(3, 1fr); background: var(--surface); border-bottom: 1px solid var(--border); width: 100%; max-width: 100%; overflow: hidden; }-.nav-tab { min-width: 0; text-align: center; padding: 11px 4px; min-height: 44px; display: flex; align-items: center; justify-content: center; font-size: clamp(0.74rem, 2.8vw, 0.86rem); font-weight: 600; color: var(--text-dim); border-bottom: 2px solid transparent; border-right: 1px solid rgba(40, 47, 68, 0.45); border-top: 1px solid rgba(40, 47, 68, 0.45); cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; user-select: none; -webkit-user-select: none; touch-action: manipulation; -webkit-tap-highlight-color: transparent; }-.nav-tab.active { color: #fff; border-bottom-color: var(--primary); background: var(--surface-alt); }-.tab-pane { display: none !important; height: 0 !important; max-height: 0 !important; overflow: hidden !important; width: 100%; }-.tab-pane.active { display: block !important; height: auto !important; max-height: none !important; overflow: visible !important; }-.content { max-width: 680px; width: 100%; margin: 12px auto 0 auto; padding: 0 12px 20px 12px; overflow-x: hidden; }-.subnav { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; width: 100%; max-width: 100%; }-.subnav .btn { flex: 1 1 120px; }-.subnav .btn.active { background: var(--primary); border-color: var(--primary); }-.card { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 14px; margin-bottom: 14px; width: 100%; max-width: 100%; overflow-x: hidden; }-.card:last-child { margin-bottom: 0 !important; }-.card h2 { font-size: 1.0rem; margin-bottom: 8px; font-weight: 600; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }-.card p { font-size: 0.82rem; color: var(--text-dim); margin-bottom: 12px; line-height: 1.4; word-break: break-word; }--/* Search tabs & chips */-.search-tabs { display: flex; gap: 8px; margin-bottom: 12px; width: 100%; max-width: 100%; }-.search-tab { flex: 1 1 0; min-width: 0; padding: 10px 8px; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; color: var(--text-dim); font-size: clamp(0.82rem, 3.4vw, 0.88rem); font-weight: 600; cursor: pointer; transition: all 0.2s; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; outline: none; }-.search-tab:hover { border-color: var(--primary); color: #fff; }-.search-tab.active { background: var(--primary); border-color: var(--primary); color: #fff; box-shadow: 0 2px 8px rgba(16, 124, 65, 0.4); }-.filter-section { margin-top: 12px; margin-bottom: 12px; width: 100%; max-width: 100%; }-.filter-label { font-size: 0.76rem; font-weight: 600; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }-.filter-chips { display: flex; flex-wrap: wrap; gap: 8px; width: 100%; max-width: 100%; }-.chip { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 6px 11px; border-radius: 20px; font-size: 0.80rem; font-weight: 600; background: var(--surface-alt); border: 1px solid var(--border); color: var(--text-dim); cursor: pointer; transition: all 0.2s; user-select: none; max-width: 100%; outline: none; white-space: nowrap; }-.chip:hover { border-color: var(--primary-hover); color: var(--text); }-.chip.active { background: rgba(16, 124, 65, 0.28); border-color: var(--primary); color: #4ade80; }-.chip-select { display: inline-flex; align-items: center; gap: 5px; padding: 4px 9px; border-radius: 20px; background: var(--surface-alt); border: 1px solid var(--border); font-size: 0.80rem; color: var(--text-dim); font-weight: 600; max-width: 100%; }-.chip-select.active { border-color: var(--primary); background: rgba(16, 124, 65, 0.28); color: #4ade80; }-.chip-select select { background: transparent; border: none; color: #fff; font-size: 0.80rem; font-weight: 600; outline: none; cursor: pointer; padding: 2px 0; max-width: 100%; }-.chip-select select option { background: var(--surface); color: #fff; }--.input-group { display: flex; gap: 8px; margin-bottom: 12px; width: 100%; max-width: 100%; }-input[type="text"] { flex: 1 1 auto; min-width: 0; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; font-size: 0.92rem; color: #fff; outline: none; transition: border-color 0.2s; }-input[type="text"]:focus { border-color: var(--primary); }-.btn { display: inline-flex; align-items: center; justify-content: center; background: var(--surface-alt); color: #fff; border: 1px solid var(--border); border-radius: 10px; padding: 10px 14px; min-height: 44px; font-size: 0.86rem; font-weight: 600; cursor: pointer; text-decoration: none; transition: background 0.15s, border-color 0.15s; max-width: 100%; white-space: normal; text-align: center; touch-action: manipulation; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; }-.btn:hover { background: var(--border); }-.btn-primary { background: var(--primary); border-color: var(--primary); color: #fff; }-.btn-primary:hover { background: var(--primary-hover); }-.status-pill { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 20px; font-size: 0.80rem; background: rgba(16, 124, 65, 0.2); color: #4ade80; border: 1px solid rgba(16, 124, 65, 0.4); margin-top: 4px; max-width: 100%; word-break: break-word; }-.status-dot { width: 8px; height: 8px; border-radius: 50%; background: #4ade80; flex-shrink: 0; }-.grid-map { display: grid; grid-template-columns: 1fr; gap: 8px; margin-top: 12px; width: 100%; max-width: 100%; }-@media (min-width: 580px) {- .grid-map { grid-template-columns: repeat(2, 1fr); }-}-.map-item { background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 9px 11px; display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%; max-width: 100%; min-width: 0; flex-wrap: wrap; }-.map-item label { font-size: 0.84rem; font-weight: 600; flex: 1 1 110px; min-width: 0; word-break: break-word; }-.selects-wrap { display: flex; gap: 6px; flex-wrap: wrap; flex: 1 1 180px; min-width: 0; justify-content: flex-end; }-.selects-wrap select { flex: 1 1 calc(50% - 4px); min-width: 85px; max-width: 100%; }-.map-item > select { flex: 0 1 auto; max-width: 100%; min-width: 0; }-select { background: var(--surface); color: #fff; border: 1px solid var(--border); border-radius: 8px; padding: 7px 9px; font-size: 0.80rem; outline: none; min-width: 0; }-.btn-row { margin-top: 16px; display: flex; gap: 8px; flex-wrap: wrap; width: 100%; max-width: 100%; }-.btn-row .btn { flex: 1 1 130px; }-pre { background: #07080b; border: 1px solid var(--border); border-radius: 10px; padding: 12px; font-family: monospace; font-size: 0.78rem; color: #c4ccdc; overflow-x: auto; max-height: 380px; white-space: pre-wrap; word-break: break-all; max-width: 100%; }-.toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: #169c53; color: #fff; padding: 10px 20px; border-radius: 24px; font-size: 0.88rem; font-weight: 600; box-shadow: 0 4px 16px rgba(0,0,0,0.5); opacity: 0; pointer-events: none; transition: opacity 0.3s; z-index: 10000; max-width: 90%; text-align: center; }-.toast.show { opacity: 1; }--/* Telemetry & interactive controls */-.telemetry-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 14px; width: 100%; }-.tel-item { background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 9px 6px; text-align: center; }-.tel-val { font-size: 1.10rem; font-weight: 700; color: #4ade80; }-.tel-lbl { font-size: 0.70rem; color: var(--text-dim); text-transform: uppercase; margin-top: 3px; }-.slider-group { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; width: 100%; }-.slider-header { display: flex; justify-content: space-between; font-size: 0.84rem; font-weight: 600; }-.slider-val { color: #4ade80; }-input[type="range"] { width: 100%; accent-color: var(--primary); margin: 6px 0; }-.toggle-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--border); }-.toggle-label { font-size: 0.86rem; font-weight: 600; }-.switch { position: relative; display: inline-block; width: 44px; height: 24px; flex-shrink: 0; }-.switch input { opacity: 0; width: 0; height: 0; }-.slider-sw { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--surface-alt); border: 1px solid var(--border); border-radius: 24px; transition: .25s; }-.slider-sw:before { position: absolute; content: ""; height: 16px; width: 16px; left: 3px; bottom: 3px; background-color: white; border-radius: 50%; transition: .25s; }-input:checked + .slider-sw { background-color: var(--primary); border-color: var(--primary); }-input:checked + .slider-sw:before { transform: translateX(20px); }-.btn-danger { background: var(--danger); border-color: var(--danger); color: #fff; }-.btn-danger:hover { background: #b82626; }-.section-sub { font-size: 0.86rem; font-weight: 700; color: #4ade80; margin: 14px 0 6px 0; display: flex; align-items: center; justify-content: space-between; }--/* Search overlay when streaming */-.search-disabled-overlay {- position: absolute;- top: 0; left: 0; right: 0; bottom: 0;- background: rgba(11, 13, 19, 0.85);- backdrop-filter: blur(8px);- -webkit-backdrop-filter: blur(8px);- display: none;- flex-direction: column;- align-items: center;- justify-content: center;- border-radius: 14px;- z-index: 50;- color: #fff;- text-align: center;- padding: 20px;-}-.search-disabled-overlay .msg {- font-size: 0.95rem;- font-weight: 700;- letter-spacing: 0.6px;- background: rgba(20, 23, 34, 0.95);- border: 1px solid var(--border);- padding: 12px 22px;- border-radius: 20px;- box-shadow: 0 4px 16px rgba(0,0,0,0.6);- display: inline-flex;- align-items: center;- gap: 8px;-}--/* Virtual Gamepad */-.gamepad-toolbar {- display: flex;- gap: 8px;- align-items: center;- justify-content: flex-end;- flex-wrap: wrap;- margin-bottom: 8px;-}-.gamepad-container {- user-select: none;- -webkit-user-select: none;- touch-action: none;- width: 100%;- max-width: 100%;- display: flex;- flex-direction: column;- gap: 12px;-}-.player-select-row {- display: grid;- grid-template-columns: repeat(4, 1fr);- gap: 6px;- width: 100%;- margin-bottom: 6px;-}-.player-btn {- padding: 8px 6px;- min-height: 42px;- display: flex;- align-items: center;- justify-content: center;- border-radius: 10px;- border: 1px solid var(--border);- background: var(--surface-alt);- color: var(--text-dim);- font-size: clamp(0.74rem, 2.8vw, 0.84rem);- font-weight: 700;- cursor: pointer;- text-align: center;- transition: all 0.15s;- touch-action: manipulation;- user-select: none;- -webkit-user-select: none;- -webkit-tap-highlight-color: transparent;-}-.player-btn.active {- background: var(--primary);- border-color: var(--primary);- color: #fff;- box-shadow: 0 2px 8px rgba(16, 124, 65, 0.4);-}-/* Virtual Gamepad Viewport & Modules (Exact Layout Studio Match) */-:root {- --gp-scale: 1;- --gp-fs-scale: 1;-}-#tab-gamepad #gamepadCard {- padding-left: 4px;- padding-right: 4px;-}--.gamepad-viewport-wrapper {- width: 100%;- display: flex;- justify-content: center;- align-items: flex-start;- overflow: hidden;-}-.gamepad-container {- position: relative;- background: transparent;- user-select: none;- -webkit-user-select: none;- touch-action: none !important;-}-.gamepad-module {- position: absolute;- transform-origin: center center;- display: flex;- align-items: center;- justify-content: center;- touch-action: none !important;- box-sizing: border-box;-}--/* Stick Styling (Matching Layout Studio) */-.stick-base {- position: relative;- width: 146px;- height: 146px;- border-radius: 50%;- background: radial-gradient(circle at 50% 50%, #1a2233 0%, #0d121c 100%);- border: 2px solid #334155;- box-shadow: inset 0 3px 10px rgba(0,0,0,0.8), 0 3px 8px rgba(0,0,0,0.5);- display: flex;- align-items: center;- justify-content: center;- touch-action: none;-}-.stick-head {- width: 62px;- height: 62px;- border-radius: 50%;- background: radial-gradient(circle at 35% 35%, #475569, #1e293b);- border: 2px solid #64748b;- box-shadow: 0 4px 12px rgba(0,0,0,0.7);- pointer-events: none;- transform: translate(0px, 0px);- display: flex;- align-items: center;- justify-content: center;-}-.stick-head::after {- content: '';- width: 45%;- height: 45%;- border-radius: 50%;- border: 1.5px solid rgba(255, 255, 255, 0.2);- background: radial-gradient(circle, #1e293b 0%, #334155 100%);- box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.7);-}--/* D-Pad Styling (Matching Layout Studio) */-.dpad-container {- position: relative;- width: 150px;- height: 150px;-}-.dpad-arm {- position: absolute;- border-radius: 10px;- background: #1e2538;- border: 1.5px solid #3e4d70;- color: #94a3b8;- font-weight: 900;- display: flex;- align-items: center;- justify-content: center;- box-shadow: 0 3px 6px rgba(0,0,0,0.4);- transition: transform 0.06s, background 0.06s;- cursor: pointer;- touch-action: none;- user-select: none;-}-.dpad-arm:active, .dpad-arm.pressed {- transform: scale(0.92);- background: #107c41 !important;- color: #fff !important;- border-color: #4ade80 !important;- box-shadow: 0 0 12px rgba(16, 124, 65, 0.8) !important;-}-.dpad-arm-up { top: 0; left: 33.33%; width: 33.33%; height: 35%; }-.dpad-arm-down { bottom: 0; left: 33.33%; width: 33.33%; height: 35%; }-.dpad-arm-left { top: 33.33%; left: 0; width: 35%; height: 33.33%; }-.dpad-arm-right { top: 33.33%; right: 0; width: 35%; height: 33.33%; }-.dpad-mid {- position: absolute;- top: 33.33%; left: 33.33%;- width: 33.33%; height: 33.33%;- background: #151a27;- border-radius: 4px;- pointer-events: none;-}--/* ABXY Styling (Matching Layout Studio) */-.abxy-container {- position: relative;- width: 156px;- height: 156px;-}-.abxy-key {- position: absolute;- width: 52px;- height: 52px;- border-radius: 50%;- font-weight: 900;- font-size: 1.3rem;- color: #fff;- display: flex;- align-items: center;- justify-content: center;- border-width: 2px;- box-shadow: 0 3px 8px rgba(0,0,0,0.5);- transition: filter 0.06s, box-shadow 0.06s;- cursor: pointer;- touch-action: none;- user-select: none;- -webkit-user-select: none;- -webkit-tap-highlight-color: transparent;-}-.abxy-key:active, .abxy-key.pressed {- box-shadow: 0 0 16px rgba(255,255,255,0.85) !important;- filter: brightness(1.35) !important;-}-.btn-y { top: 0; left: 52px; background: #c68900; border-color: #ffd000; }-.btn-a { bottom: 0; left: 52px; background: #0e6b37; border-color: #22c55e; }-.btn-x { top: 52px; left: 0; background: #006eb8; border-color: #38bdf8; }-.btn-b { top: 52px; right: 0; background: #b80d1b; border-color: #f87171; }--/* Buttons & System Styling */-.pad-btn {- display: inline-flex;- align-items: center;- justify-content: center;- background: #1e2538;- border: 1.5px solid #3e4d70;- border-radius: 10px;- color: #fff;- font-weight: 700;- box-shadow: 0 2px 6px rgba(0,0,0,0.3);- transition: transform 0.06s, background 0.06s;- cursor: pointer;- touch-action: none;- user-select: none;- width: 100%;- height: 100%;-}-.pad-btn:active, .pad-btn.pressed {- transform: scale(0.92);- background: #107c41 !important;- border-color: #4ade80 !important;- box-shadow: 0 0 12px rgba(16, 124, 65, 0.7) !important;-}-.pad-btn-trigger {- font-weight: 800;- font-size: 1.05rem;- background: linear-gradient(180deg, #2e3a54, #182030);- border: 1.5px solid #4a5c82;- border-radius: 12px;-}-.pad-btn-bumper {- font-weight: 700;- font-size: 0.92rem;- border-radius: 10px;-}-.pad-btn-stick-click {- font-size: 0.82rem;- color: #94a3b8;- border-radius: 8px;-}-.center-sys-container {- display: flex;- align-items: center;- justify-content: center;- gap: 6px;- width: 100%;- height: 100%;-}-.pad-btn-sys {- padding: 4px 10px;- font-size: 11px;- font-weight: 800;- height: 36px;- border-radius: 8px;-}-.pad-btn-nexus-btn {- width: 38px;- height: 38px;- border-radius: 50%;- background: #107c41;- border: 2px solid #ffffff;- font-weight: 900;- font-size: 12px;- color: #ffffff;- box-shadow: 0 4px 10px rgba(0,0,0,0.6);- display: flex;- align-items: center;- justify-content: center;- cursor: pointer;- touch-action: none;- flex-shrink: 0;-}-.pad-btn-nexus-btn:active, .pad-btn-nexus-btn.pressed {- transform: scale(0.92);- filter: brightness(1.2);-}--/* Player Bar Styling (Clean minimalist capsule matching studio) */-.player-bar-container {- display: flex;- align-items: center;- justify-content: center;- gap: 5px;- background: rgba(15, 23, 42, 0.9);- padding: 3px 6px;- border-radius: 12px;- border: 1px solid #1e293b;- width: 100%;- height: 100%;-}-.player-pill {- padding: 3px 8px;- font-size: 11px;- font-weight: 800;- border-radius: 8px;- background: transparent;- color: #94a3b8;- border: none;- cursor: pointer;- transition: all 0.1s;-}-.player-pill.active {- background: #107c41;- color: #ffffff;- box-shadow: 0 0 8px rgba(16, 124, 65, 0.6);-}-.fs-only-exit { display: none; }--/* Portrait Layout Positions (Exact Layout Studio Alignment) */-#gamepadArea {- width: 412px !important;- min-width: 412px !important;- max-width: 412px !important;- flex-shrink: 0 !important;- height: 680px;-}-#gamepadArea #mod_player_bar { left: 130px; top: 10px; width: 152px !important; height: 44px; transform: scale(1.0); }-#gamepadArea #mod_center_sys { left: 115px; top: 62px; width: 182px; height: 56px; transform: scale(1.0); }-#gamepadArea #mod_btn_ls { left: 16px; top: 132px; width: 56px; height: 52px; transform: scale(1.25); }-#gamepadArea #mod_btn_rs { left: 340px; top: 132px; width: 56px; height: 52px; transform: scale(1.25); }-#gamepadArea #mod_btn_lt { left: 10px; top: 206px; width: 98px; height: 56px; transform: scale(1.0); }-#gamepadArea #mod_btn_lb { left: 116px; top: 207px; width: 78px; height: 52px; transform: scale(1.0); }-#gamepadArea #mod_btn_rb { left: 218px; top: 207px; width: 78px; height: 52px; transform: scale(1.0); }-#gamepadArea #mod_btn_rt { left: 304px; top: 206px; width: 98px; height: 56px; transform: scale(1.0); }-#gamepadArea #mod_stick_left { left: 21px; top: 282px; width: 166px; height: 166px; transform: scale(1.15); }-#gamepadArea #mod_abxy { left: 218px; top: 282px; width: 176px; height: 176px; transform: scale(1.15); }-#gamepadArea #mod_dpad { left: 19px; top: 488px; width: 160px !important; height: 160px; transform: scale(1.0); }-#gamepadArea #mod_stick_right { left: 225px; top: 490px; width: 166px; height: 166px; transform: scale(1.0); }--/* Responsive scale wrapper for Portrait */-@media (orientation: portrait), (max-width: 600px) and (orientation: portrait) {- .gamepad-viewport-wrapper {- height: calc(680px * var(--gp-scale, 0.82));- }- #gamepadArea {- transform: scale(var(--gp-scale, 0.82));- transform-origin: top center;- }-}--/* Landscape Layout Positions (Exact Layout Studio Alignment) */-@media (orientation: landscape), (max-height: 520px) {- .gamepad-status-bar {- display: none !important;- }- .gamepad-viewport-wrapper {- height: calc(412px * var(--gp-scale, 0.8));- min-height: calc(412px * var(--gp-scale, 0.8));- display: flex;- justify-content: center;- align-items: flex-start;- overflow: hidden;- }- #gamepadArea {- width: 915px !important;- min-width: 915px !important;- max-width: 915px !important;- flex-shrink: 0 !important;- height: 412px !important;- transform: scale(var(--gp-scale, 0.8));- transform-origin: top center !important;- }- #gamepadArea #mod_btn_lt { left: 10px; top: 10px; width: 94px; height: 54px; transform: scale(1.0); }- #gamepadArea #mod_btn_lb { left: 110px; top: 11px; width: 76px; height: 52px; transform: scale(1.0); }- #gamepadArea #mod_btn_ls { left: 192px; top: 11px; width: 54px; height: 52px; transform: scale(1.0); }- #gamepadArea #mod_player_bar { left: 381px; top: 12px; width: 152px !important; height: 44px; transform: scale(1.0); }- #gamepadArea #mod_center_sys { left: 342px; top: 66px; width: 230px; height: 56px; transform: scale(1.0); }- #gamepadArea #mod_btn_rs { left: 669px; top: 11px; width: 54px; height: 52px; transform: scale(1.0); }- #gamepadArea #mod_btn_rb { left: 729px; top: 11px; width: 76px; height: 52px; transform: scale(1.0); }- #gamepadArea #mod_btn_rt { left: 811px; top: 10px; width: 94px; height: 54px; transform: scale(1.0); }- #gamepadArea #mod_stick_left { left: 32px; top: 97px; width: 166px; height: 166px; transform: scale(1.3); }- #gamepadArea #mod_abxy { left: 712px; top: 97px; width: 176px; height: 176px; transform: scale(1.3); }- #gamepadArea #mod_dpad { left: 205px; top: 242px; width: 160px !important; height: 160px; transform: scale(1.05); }- #gamepadArea #mod_stick_right { left: 545px; top: 240px; width: 166px; height: 166px; transform: scale(1.2); }-}--/* Fullscreen Mode (Landscape) */-#gamepadCard.gamepad-fullscreen, #gamepadCard:fullscreen, #gamepadCard:-webkit-full-screen {- position: fixed !important;- inset: 0 !important;- width: 100vw !important;- height: 100dvh !important;- max-width: 100vw !important;- margin: 0 !important;- border-radius: 0 !important;- border: none !important;- z-index: 9999 !important;- background: radial-gradient(circle at 50% 35%, #161c2c 0%, #090b11 100%) !important;- padding: env(safe-area-inset-top, 0) env(safe-area-inset-right, 14px) env(safe-area-inset-bottom, 8px) env(safe-area-inset-left, 14px) !important;- display: flex !important;- align-items: center !important;- justify-content: center !important;- overflow: hidden !important;-}-#gamepadCard.gamepad-fullscreen .gamepad-intro,-#gamepadCard:fullscreen .gamepad-intro,-#gamepadCard:-webkit-full-screen .gamepad-intro,-#gamepadCard.gamepad-fullscreen .gamepad-status-bar,-#gamepadCard:fullscreen .gamepad-status-bar,-#gamepadCard:-webkit-full-screen .gamepad-status-bar {- display: none !important;-}-#gamepadCard.gamepad-fullscreen .fs-only-exit,-#gamepadCard:fullscreen .fs-only-exit,-#gamepadCard:-webkit-full-screen .fs-only-exit {- display: inline-flex !important;-}-#gamepadCard.gamepad-fullscreen .gamepad-viewport-wrapper,-#gamepadCard:fullscreen .gamepad-viewport-wrapper,-#gamepadCard:-webkit-full-screen .gamepad-viewport-wrapper {- width: calc(915px * var(--gp-fs-scale, 0.85)) !important;- height: calc(412px * var(--gp-fs-scale, 0.85)) !important;- max-width: 100% !important;- max-height: 100% !important;- display: flex !important;- align-items: flex-start !important;- justify-content: center !important;- overflow: hidden !important;- position: relative !important;-}-#gamepadCard.gamepad-fullscreen #gamepadArea,-#gamepadCard:fullscreen #gamepadArea,-#gamepadCard:-webkit-full-screen #gamepadArea {- width: 915px !important;- min-width: 915px !important;- max-width: 915px !important;- flex-shrink: 0 !important;- height: 412px !important;- transform: scale(var(--gp-fs-scale, 0.85)) !important;- transform-origin: top center !important;-}-#gamepadCard.gamepad-fullscreen #mod_btn_lt { left: 10px !important; top: 10px !important; width: 94px !important; height: 54px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_btn_lb { left: 110px !important; top: 11px !important; width: 76px !important; height: 52px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_btn_ls { left: 192px !important; top: 11px !important; width: 54px !important; height: 52px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_player_bar { left: 381px !important; top: 12px !important; width: 152px !important; height: 44px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_center_sys { left: 342px !important; top: 66px !important; width: 230px !important; height: 56px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_btn_rs { left: 669px !important; top: 11px !important; width: 54px !important; height: 52px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_btn_rb { left: 729px !important; top: 11px !important; width: 76px !important; height: 52px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_btn_rt { left: 811px !important; top: 10px !important; width: 94px !important; height: 54px !important; transform: scale(1.0) !important; }-#gamepadCard.gamepad-fullscreen #mod_stick_left { left: 32px !important; top: 97px !important; width: 166px !important; height: 166px !important; transform: scale(1.3) !important; }-#gamepadCard.gamepad-fullscreen #mod_abxy { left: 712px !important; top: 97px !important; width: 176px !important; height: 176px !important; transform: scale(1.3) !important; }-#gamepadCard.gamepad-fullscreen #mod_dpad { left: 205px !important; top: 242px !important; width: 160px !important; height: 160px !important; transform: scale(1.05) !important; }-#gamepadCard.gamepad-fullscreen #mod_stick_right { left: 545px !important; top: 240px !important; width: 166px !important; height: 166px !important; transform: scale(1.2) !important; }--@media (max-width: 600px) {- .nav-tabs { grid-template-columns: repeat(3, 1fr); }- .nav-tab { padding: 9px 4px; font-size: 0.74rem; }- .telemetry-grid { grid-template-columns: repeat(2, 1fr); }- .content { padding-left: 6px; padding-right: 6px; }- #tab-gamepad #gamepadCard { padding-left: 2px; padding-right: 2px; }-}--@media (orientation: landscape), (max-height: 520px) {- .nav-tabs {- grid-template-columns: repeat(6, 1fr);- gap: 4px;- }- .nav-tab {- min-height: 36px;- padding: 5px 2px;- font-size: 0.72rem;- }- header {- display: none !important;- }- .content {- max-width: 960px;- margin: 2px auto 0 auto;- padding: 0 4px 6px 4px;- }- .card {- padding: 4px 8px;- margin-bottom: 0 !important;- }- .card h2 {- font-size: 0.88rem;- margin-bottom: 4px;- }- .card p {- font-size: 0.76rem;- margin-bottom: 6px;- }- .gamepad-intro {- display: block;- margin-bottom: 2px;- }- .gamepad-toolbar {- margin-bottom: 2px;- justify-content: flex-end;- }- .gamepad-status-bar {- display: none !important;- }-}-</style>-</head>-<body>-<header>- <div class="brand">- <svg class="logo-icon" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">- <circle cx="50" cy="50" r="50" fill="#ffffff"/>- <path fill="#107C41" d="M 50.00 40.10 s 0.12 0.00 0.00 0.00 c 15.07 11.46 40.60 39.60 32.88 47.57 -8.84 7.72 -20.30 12.33 -32.88 12.33 s -24.16 -4.61 -32.88 -12.33 c -7.85 -7.97 17.81 -36.11 32.75 -47.45 0.00 -0.12 0.12 -0.12 0.12 -0.12 z m 26.03 -32.75 C 68.43 2.74 60.09 0.00 50.00 0.00 s -18.43 2.74 -26.03 7.35 c -0.12 0.00 -0.12 0.12 -0.12 0.25 s 0.12 0.12 0.25 0.12 c 9.71 -2.12 24.41 6.23 25.78 7.10 h 0.25 c 1.37 -0.87 16.06 -9.22 25.78 -7.10 0.12 0.00 0.25 0.00 0.25 -0.12 s 0.00 -0.25 -0.12 -0.25 z M 15.01 14.32 c -0.12 0.00 -0.12 0.12 -0.25 0.12 -9.09 9.09 -14.69 21.67 -14.69 35.49 0.00 11.33 3.86 21.92 10.21 30.26 0.00 0.12 0.12 0.12 0.25 0.12 s 0.12 -0.12 0.00 -0.25 c -3.86 -11.83 15.69 -40.35 25.78 -52.30 l 0.12 -0.12 c 0.00 -0.12 0.00 -0.12 -0.12 -0.12 -15.32 -15.19 -20.42 -13.57 -21.30 -13.20 z m 48.69 13.08 l -0.12 0.12 s 0.00 0.12 0.12 0.12 c 10.09 11.96 29.51 40.47 25.78 52.30 v 0.25 c 0.12 0.00 0.25 0.00 0.25 -0.12 6.35 -8.34 10.21 -18.93 10.21 -30.26 0.00 -13.82 -5.60 -26.40 -14.82 -35.49 -0.12 -0.12 -0.12 -0.12 -0.25 -0.12 -0.75 -0.25 -5.85 -1.87 -21.17 13.20 z"/>- </svg>- <div class="brand-text">- <h1>PSBOX CLOUD GAMING</h1>- <span class="brand-subtitle">Smartglass WebUI</span>- </div>- </div>- <span class="badge">v)html" XC_APP_VERSION R"html(</span>-</header>--<div class="nav-tabs">- <div class="nav-tab active" id="navTab-search" onclick="switchTab('search')">🔍 Busca</div>- <div class="nav-tab" id="navTab-settings" onclick="switchTab('settings')">⚙️ Configurações</div>- <div class="nav-tab" id="navTab-stream" onclick="switchTab('stream')">📺 Jogo Atual</div>- <div class="nav-tab" id="navTab-remap" onclick="switchTab('remap')">🎮 Mapeamento</div>- <div class="nav-tab" id="navTab-gamepad" onclick="switchTab('gamepad')">🕹️ Controle</div>- <div class="nav-tab" id="navTab-logs" onclick="switchTab('logs')">📋 Logs</div>-</div>--<div class="content">- <!-- TAB: SETTINGS -->- <div id="tab-settings" class="tab-pane" style="display:none;">- <div class="card">- <h2>⚙️ Configurações Gerais</h2>- <p>Ajuste opções gráficas, de controle e comportamento do aplicativo.</p>-- <div class="slider-group">- <div class="slider-header">- <span>Bitrate Máximo</span>- <span class="slider-val" id="valBitrate">Auto</span>- </div>- <input type="range" id="inputBitrate" min="0" max="50" step="5" value="0" oninput="onBitrateInput(this.value)">- </div>-- <div class="toggle-row">- <span class="toggle-label">Modo 120 Hz (High Refresh / VRR)</span>- <label class="switch">- <input type="checkbox" id="check120Hz" onchange="markSettingsChanged()">- <span class="slider-sw"></span>- </label>- </div>-- <div class="slider-group" style="margin-top: 10px;">- <div class="slider-header">- <span>Zona Morta - Analógico Esquerdo (L)</span>- <span class="slider-val" id="valDeadzoneL">15%</span>- </div>- <input type="range" id="inputDeadzoneL" min="0" max="50" step="1" value="15" oninput="document.getElementById('valDeadzoneL').textContent=this.value+'%'; markSettingsChanged()">- </div>-- <div class="slider-group">- <div class="slider-header">- <span>Zona Morta - Analógico Direito (R)</span>- <span class="slider-val" id="valDeadzoneR">15%</span>- </div>- <input type="range" id="inputDeadzoneR" min="0" max="50" step="1" value="15" oninput="document.getElementById('valDeadzoneR').textContent=this.value+'%'; markSettingsChanged()">- </div>-- <div class="slider-group">- <div class="slider-header">- <span>Vibração dos Gatilhos</span>- <span class="slider-val" id="valTriggerStrength">2</span>- </div>- <input type="range" id="inputTriggerStrength" min="0" max="4" step="1" value="2" oninput="document.getElementById('valTriggerStrength').textContent=this.value; markSettingsChanged()">- </div>-- <div class="map-item" style="margin-bottom: 10px;">- <label>Barra de Luz DualSense</label>- <select id="selectLightBarMode" onchange="onLightBarModeChange()">- <option value="0">Cor do Jogo</option>- <option value="1">Cor Personalizada</option>- <option value="2">Desativada</option>- </select>- <input type="color" id="inputLightBarColor" value="#0070dc" style="margin-left: 8px; height: 32px; width: 44px; border: none; border-radius: 6px; cursor: pointer; display: none;" onchange="markSettingsChanged()">- </div>-- <div class="toggle-row">- <span class="toggle-label">Aviso Sonoro de Fila (Queue Chime)</span>- <label class="switch">- <input type="checkbox" id="checkQueueAlert" onchange="markSettingsChanged()">- <span class="slider-sw"></span>- </label>- </div>-- <div class="map-item" style="margin-top: 10px;">- <label>Decodificador de Vídeo</label>- <select id="selectVideoDecoder" onchange="markSettingsChanged()">- <option value="0">Hardware (libSceVideodec2 / HWAccel)</option>- <option value="1">Software (FFmpeg CPU)</option>- </select>- </div>-- <div class="map-item" style="margin-top: 10px;">- <label>Saída do Chat de Voz</label>- <select id="selectVoiceRouting" onchange="markSettingsChanged()">- <option value="0">Automático (Alto-falante DualSense se disponível)</option>- <option value="1">Sempre TV / Headset Principal</option>- </select>- </div>-- <div class="btn-row" style="margin-top: 16px;">- <button class="btn btn-primary" onclick="saveGeneralSettings()">Salvar Configurações</button>- </div>- </div>- </div>-- <!-- TAB: STREAM (JOGO ATUAL) -->- <div id="tab-stream" class="tab-pane" style="display:none;">- <div class="card">- <h2>📺 Jogo Atual & Telemetria</h2>- <p>Métricas de transmissão em tempo real e ajustes do menu de jogo (StreamMenu).</p>-- <div class="telemetry-grid">- <div class="tel-item"><div class="tel-val" id="telFps">--</div><div class="tel-lbl">FPS</div></div>- <div class="tel-item"><div class="tel-val" id="telRtt">-- ms</div><div class="tel-lbl">RTT (Ping)</div></div>- <div class="tel-item"><div class="tel-val" id="telMbps">-- Mbps</div><div class="tel-lbl">Bitrate</div></div>- <div class="tel-item"><div class="tel-val" id="telLoss">0.0%</div><div class="tel-lbl">Perda Pkts</div></div>- <div class="tel-item"><div class="tel-val" id="telQp">--</div><div class="tel-lbl">QP (Qualidade)</div></div>- <div class="tel-item"><div class="tel-val" id="telDec">-- ms</div><div class="tel-lbl">Decodificação</div></div>- </div>-- <div class="slider-group" style="margin-top: 10px;">- <div class="slider-header">- <span>Nitidez CAS (FidelityFX RCAS)</span>- <span class="slider-val" id="valCas">Média</span>- </div>- <input type="range" id="inputCas" min="0" max="3" step="1" value="2" oninput="sendStreamParam('sharpness', parseInt(this.value)); updateCasLabel(this.value);">- </div>-- <div class="map-item" style="margin-bottom: 10px;">- <label>Upscaler de Imagem</label>- <select id="selectUpscaler" onchange="sendStreamParam('upscaler', parseInt(this.value))">- <option value="0">FSR 1.0</option>- <option value="1">Anime4K</option>- <option value="2">FSR 1.0 + Clean-up</option>- <option value="3">Anime4K + Clean-up</option>- </select>- </div>-- <div class="map-item" style="margin-bottom: 10px;">- <label>Suavização de Blocos (Deband)</label>- <select id="selectDeband" onchange="sendStreamParam('deband', parseInt(this.value))">- <option value="0">Desativada</option>- <option value="1">Baixa</option>- <option value="2">Alta</option>- <option value="3">Automática (Bitrate-adaptive)</option>- </select>- </div>-- <div class="slider-group">- <div class="slider-header">- <span>Volume Alto-falante DualSense</span>- <span class="slider-val" id="valPadSpeaker">100%</span>- </div>- <input type="range" id="inputPadSpeaker" min="0" max="100" step="5" value="100" oninput="document.getElementById('valPadSpeaker').textContent=this.value+'%'; sendStreamParam('padSpeakerVolume', parseInt(this.value));">- </div>-- <div class="map-item" style="margin-bottom: 14px;">- <label>Perfis de Gatilho Inteligente</label>- <select id="selectSmartTriggers" onchange="sendStreamParam('triggerProfile', parseInt(this.value))">- <option value="0">Padrão (Standard Haptics)</option>- <option value="1">Tiro (Shooter - Hair Trigger)</option>- <option value="2">Corrida (Racing - Progressive Resistance)</option>- </select>- </div>-- <div class="btn-row">- <button class="btn btn-primary" onclick="sendStreamAction('xbox_guide')">Abrir Guia Xbox</button>- <button class="btn btn-danger" onclick="sendStreamAction('end_session')">Encerrar Sessão</button>- </div>- </div>- </div>-- <!-- TAB: SEARCH -->- <div id="tab-search" class="tab-pane active">- <div class="card" id="searchCard" style="position: relative;">- <div id="searchOverlay" class="search-disabled-overlay" style="display: none;">- <div class="msg">🔒 Desativado enquanto jogando</div>- </div>- <h2>🔍 Teclado Remoto para Busca</h2>- <p>Digite no celular para atualizar a pesquisa ativa na TV em tempo real sem precisar do controle.</p>-- <!-- Search destination tabs -->- <div class="search-tabs">- <button class="search-tab active" id="tabBtnGamePass" type="button" onclick="setSearchTab('gamepass')">🎮 Game Pass</button>- <button class="search-tab" id="tabBtnLibrary" type="button" onclick="setSearchTab('library')">📚 Meus jogos</button>- </div>-- <div class="input-group">- <input type="text" id="searchInput" placeholder="Digite o nome de um jogo..." autocomplete="off">- <button class="btn" onclick="clearSearch()">Limpar</button>- </div>-- <!-- Search filters -->- <div class="filter-section">- <div class="filter-label">Filtros da pesquisa:</div>-- <!-- Game Pass filters -->- <div id="filtersGamePass" class="filter-chips">- <div class="chip-select" id="chipSelectPlan">- <label for="filterPlan">👑 Plano:</label>- <select id="filterPlan" onchange="onFilterChange()">- <option value="0">Meu plano</option>- <option value="1">Ultimate</option>- <option value="2">Premium</option>- <option value="3">Essential</option>- <option value="4">Todos os planos</option>- </select>- </div>- <div class="chip-select" id="chipSelectConsoleGP">- <label for="filterConsoleGP">🎮 Console:</label>- <select id="filterConsoleGP" onchange="onFilterChange()">- <option value="0">Todos</option>- <option value="1">Series X|S</option>- <option value="2">Xbox One</option>- <option value="3">Xbox 360</option>- </select>- </div>- <button class="chip" id="chipMouseGP" type="button" onclick="toggleChip('chipMouseGP')">- ⌨️🖱️ Teclado e mouse- </button>- <div class="chip-select" id="chipSelectModeGP">- <label for="filterModeGP">👤 Modo:</label>- <select id="filterModeGP" onchange="onFilterChange()">- <option value="0">Todos</option>- <option value="1">Um jogador</option>- <option value="2">Multijogador online</option>- <option value="3">Cooperativo online</option>- <option value="4">Multijogador local</option>- </select>- </div>- <div class="chip-select" id="chipSelectLangGP">- <label for="filterLangGP">🌐 Idioma:</label>- <select id="filterLangGP" onchange="onFilterChange()">- <option value="0">Qualquer</option>- <option value="1">Legendas</option>- <option value="2">Dublado</option>- </select>- </div>- </div>-- <!-- Meus Jogos (Library) filters -->- <div id="filtersLibrary" class="filter-chips" style="display:none;">- <button class="chip" id="chipWishlist" type="button" onclick="toggleChip('chipWishlist')">- 💖 Lista de desejos- </button>- <button class="chip" id="chipFree" type="button" onclick="toggleChip('chipFree')">- 🎁 Grátis- </button>- <button class="chip" id="chipCheapest" type="button" onclick="toggleChip('chipCheapest')">- 🏷️ Menor preço- </button>- <div class="chip-select" id="chipSelectConsoleLib">- <label for="filterConsoleLib">🎮 Console:</label>- <select id="filterConsoleLib" onchange="onFilterChange()">- <option value="0">Todos</option>- <option value="1">Series X|S</option>- <option value="2">Xbox One</option>- <option value="3">Xbox 360</option>- </select>- </div>- <button class="chip" id="chipMouseLib" type="button" onclick="toggleChip('chipMouseLib')">- ⌨️🖱️ Teclado e mouse- </button>- <div class="chip-select" id="chipSelectModeLib">- <label for="filterModeLib">👤 Modo:</label>- <select id="filterModeLib" onchange="onFilterChange()">- <option value="0">Todos</option>- <option value="1">Um jogador</option>- <option value="2">Multijogador online</option>- <option value="3">Cooperativo online</option>- <option value="4">Multijogador local</option>- </select>- </div>- <div class="chip-select" id="chipSelectLangLib">- <label for="filterLangLib">🌐 Idioma:</label>- <select id="filterLangLib" onchange="onFilterChange()">- <option value="0">Qualquer</option>- <option value="1">Legendas</option>- <option value="2">Dublado</option>- </select>- </div>- </div>- </div>-- <div class="status-pill">- <div class="status-dot"></div>- <span id="searchStatus">Pronto para pesquisar</span>- </div>- </div>- </div>-- <!-- TAB: REMAP -->- <div id="tab-remap" class="tab-pane" style="display:none;">- <div class="subnav">- <button class="btn active" id="btnSubPad" onclick="switchRemapSub('pad')">🎮 DualSense</button>- <button class="btn" id="btnSubKey" onclick="switchRemapSub('key')">⌨️ Teclado</button>- <button class="btn" id="btnSubTouch" onclick="switchRemapSub('touch')">👆 Touchpad</button>- </div>-- <div id="subRemapPad">- <div class="card">- <h2>🎮 Remapeamento de Botões (DualSense)</h2>- <p>Ajuste os botões do controle para o jogo na nuvem. Suas alterações são sincronizadas e salvas automaticamente.</p>- <div class="grid-map" id="padGrid"></div>- <div class="btn-row">- <button class="btn btn-primary" onclick="saveSettings()">Salvar no Console</button>- <button class="btn" onclick="resetPadMap()">Restaurar Controle Padrão</button>- </div>- </div>- </div>-- <div id="subRemapKey" style="display:none;">- <div class="card">- <h2>⌨️ Remapeamento de Teclado (WASD / Teclas)</h2>- <p>Mapeie teclas e botões do mouse para os comandos do Xbox na nuvem. Cada ação possui tecla Primária e Secundária.</p>- <div class="grid-map" id="keyGrid"></div>- <div class="btn-row">- <button class="btn btn-primary" onclick="saveSettings()">Salvar no Console</button>- <button class="btn" onclick="resetKeyMap()">Restaurar Teclado Padrão</button>- </div>- </div>- </div>-- <div id="subRemapTouch" style="display:none;">- <div class="card">- <h2>👆 Atalhos do Touchpad (DualSense)</h2>- <p>Configure o que cada gesto (deslizar) ou clique físico (lado esquerdo/direito) no touchpad faz durante o streaming. <strong>Touchpad + Options</strong> permanece sempre fixo para abrir o Menu do Jogo.</p>- <div class="grid-map" id="remapTouchpadShortcutsGrid"></div>- <div class="btn-row">- <button class="btn btn-primary" onclick="saveSettings()">Salvar no Console</button>- <button class="btn" onclick="resetTouchpadShortcuts()">Restaurar Touchpad Padrão</button>- </div>- </div>- </div>- </div>-- <!-- TAB: GAMEPAD (CONTROLE VIRTUAL) -->- <div id="tab-gamepad" class="tab-pane" style="display:none;">- <div class="card" id="gamepadCard">- <div class="gamepad-intro">- <div class="gamepad-toolbar">- <button type="button" class="btn btn-primary" id="btnFullscreenPad" onclick="toggleGamepadFullscreen()" style="padding: 6px 12px; font-size: 0.78rem;">- ⛶ Tela Cheia- </button>- </div>- </div>-- <div class="gamepad-viewport-wrapper" id="gamepadScaleContainer">- <div class="gamepad-container" id="gamepadArea">-- <!-- MODULE 1: Left Stick -->- <div id="mod_stick_left" class="gamepad-module">- <div class="stick-base" id="leftStickZone">- <div class="stick-head" id="leftStickHead"></div>- </div>- </div>-- <!-- MODULE 2: D-Pad -->- <div id="mod_dpad" class="gamepad-module">- <div class="dpad-container" id="box_dpad">- <div class="dpad-arm dpad-arm-up" data-btn="dpadUp">▲</div>- <div class="dpad-arm dpad-arm-left" data-btn="dpadLeft">◀</div>- <div class="dpad-mid"></div>- <div class="dpad-arm dpad-arm-right" data-btn="dpadRight">▶</div>- <div class="dpad-arm dpad-arm-down" data-btn="dpadDown">▼</div>- </div>- </div>-- <!-- MODULE 3: ABXY Diamond -->- <div id="mod_abxy" class="gamepad-module">- <div class="abxy-container" id="box_abxy">- <div class="abxy-key btn-y" data-btn="btnY">Y</div>- <div class="abxy-key btn-x" data-btn="btnX">X</div>- <div class="abxy-key btn-b" data-btn="btnB">B</div>- <div class="abxy-key btn-a" data-btn="btnA">A</div>- </div>- </div>-- <!-- MODULE 4: Right Stick -->- <div id="mod_stick_right" class="gamepad-module">- <div class="stick-base" id="rightStickZone">- <div class="stick-head" id="rightStickHead"></div>- </div>- </div>-- <!-- INDIVIDUAL SHOULDER & TRIGGER BUTTONS -->- <!-- MODULE 5: LT Trigger -->- <div id="mod_btn_lt" class="gamepad-module pad-bumper-left">- <button type="button" class="pad-btn pad-btn-trigger" id="btn_lt" data-btn="triggerL2">LT</button>- </div>-- <!-- MODULE 6: LB Bumper -->- <div id="mod_btn_lb" class="gamepad-module pad-bumper-left">- <button type="button" class="pad-btn pad-btn-bumper" id="btn_lb" data-btn="btnL1">LB</button>- </div>-- <!-- MODULE 7: LS Button -->- <div id="mod_btn_ls" class="gamepad-module pad-bumper-left">- <button type="button" class="pad-btn pad-btn-stick-click pad-btn-stick-btn" id="btn_ls" data-btn="btnL3">LS</button>- </div>-- <!-- MODULE 8: RS Button -->- <div id="mod_btn_rs" class="gamepad-module pad-bumper-right">- <button type="button" class="pad-btn pad-btn-stick-click pad-btn-stick-btn" id="btn_rs" data-btn="btnR3">RS</button>- </div>-- <!-- MODULE 9: RB Bumper -->- <div id="mod_btn_rb" class="gamepad-module pad-bumper-right">- <button type="button" class="pad-btn pad-btn-bumper" id="btn_rb" data-btn="btnR1">RB</button>- </div>-- <!-- MODULE 10: RT Trigger -->- <div id="mod_btn_rt" class="gamepad-module pad-bumper-right">- <button type="button" class="pad-btn pad-btn-trigger" id="btn_rt" data-btn="triggerR2">RT</button>- </div>-- <!-- MODULE 11: Center System Buttons (VIEW, X, MENU) -->- <div id="mod_center_sys" class="gamepad-module">- <div class="center-sys-container">- <button type="button" class="pad-btn pad-btn-sys" id="btn_view" data-btn="btnView">VIEW</button>- <button type="button" class="pad-btn-nexus-btn" id="btn_nexus" data-btn="btnNexus" aria-label="Xbox Guide" title="Xbox Guide">- <svg viewBox="0 0 100 100" width="22" height="22" style="pointer-events:none;display:block;">- <circle cx="50" cy="50" r="48" fill="#ffffff"/>- <path fill="#107C41" d="M 50.00 40.10 s 0.12 0.00 0.00 0.00 c 15.07 11.46 40.60 39.60 32.88 47.57 -8.84 7.72 -20.30 12.33 -32.88 12.33 s -24.16 -4.61 -32.88 -12.33 c -7.85 -7.97 17.81 -36.11 32.75 -47.45 0.00 -0.12 0.12 -0.12 0.12 -0.12 z m 26.03 -32.75 C 68.43 2.74 60.09 0.00 50.00 0.00 s -18.43 2.74 -26.03 7.35 c -0.12 0.00 -0.12 0.12 -0.12 0.25 s 0.12 0.12 0.25 0.12 c 9.71 -2.12 24.41 6.23 25.78 7.10 h 0.25 c 1.37 -0.87 16.06 -9.22 25.78 -7.10 0.12 0.00 0.25 0.00 0.25 -0.12 s 0.00 -0.25 -0.12 -0.25 z M 15.01 14.32 c -0.12 0.00 -0.12 0.12 -0.25 0.12 -9.09 9.09 -14.69 21.67 -14.69 35.49 0.00 11.33 3.86 21.92 10.21 30.26 0.00 0.12 0.12 0.12 0.25 0.12 s 0.12 -0.12 0.00 -0.25 c -3.86 -11.83 15.69 -40.35 25.78 -52.30 l 0.12 -0.12 c 0.00 -0.12 0.00 -0.12 -0.12 -0.12 -15.32 -15.19 -20.42 -13.57 -21.30 -13.20 z m 48.69 13.08 l -0.12 0.12 s 0.00 0.12 0.12 0.12 c 10.09 11.96 29.51 40.47 25.78 52.30 v 0.25 c 0.12 0.00 0.25 0.00 0.25 -0.12 6.35 -8.34 10.21 -18.93 10.21 -30.26 0.00 -13.82 -5.60 -26.40 -14.82 -35.49 -0.12 -0.12 -0.12 -0.12 -0.25 -0.12 -0.75 -0.25 -5.85 -1.87 -21.17 13.20 z"/>- </svg>- </button>- <button type="button" class="pad-btn pad-btn-sys" id="btn_menu" data-btn="btnMenu">MENU</button>- <button type="button" class="pad-btn pad-btn-sys fs-only-exit" id="btn_exit_fs" onclick="toggleGamepadFullscreen()" style="background:#451a1a;border-color:#b91c1c;color:#fca5a5;">✕ Sair</button>- </div>- </div>-- <!-- MODULE 12: Player Selector (P1..P4) -->- <div id="mod_player_bar" class="gamepad-module">- <div class="player-bar-container">- <button type="button" class="player-pill active" id="btnPlayer1" onclick="setVirtualPlayer(1)">P1</button>- <button type="button" class="player-pill" id="btnPlayer2" onclick="setVirtualPlayer(2)">P2</button>- <button type="button" class="player-pill" id="btnPlayer3" onclick="setVirtualPlayer(3)">P3</button>- <button type="button" class="player-pill" id="btnPlayer4" onclick="setVirtualPlayer(4)">P4</button>- </div>- </div>-- </div>- </div>-- <div class="status-pill gamepad-status-bar" style="margin-top: 10px;">- <div class="status-dot"></div>- <span id="gamepadStatus">Controle ativo para Jogador 1 (Principal)</span>- </div>- </div>- </div>-- <!-- TAB: LOGS -->- <div id="tab-logs" class="tab-pane" style="display:none;">- <div class="card">- <h2>🐛 Enviar Relatório de Erro (GitHub)</h2>- <p>Gere um relatório completo da sessão atual com logs sanitizados (sem dados privados, e-mails ou tokens) formatado automaticamente para o repositório oficial no GitHub.</p>-- <div class="form-group" style="margin-bottom: 10px;">- <label for="reportTitle" style="font-weight: 600; font-size: 0.82rem; display: block; margin-bottom: 4px;">Título do Problema (Opcional):</label>- <input type="text" id="reportTitle" class="form-control" placeholder="Ex: Queda de transmissão ou erro de áudio" style="width: 100%; box-sizing: border-box; padding: 8px 10px; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 8px; color: #fff; font-size: 0.85rem;">- </div>-- <div class="form-group" style="margin-bottom: 12px;">- <label for="reportWhat" style="font-weight: 600; font-size: 0.82rem; display: block; margin-bottom: 4px;">O que aconteceu? (Opcional):</label>- <textarea id="reportWhat" class="form-control" rows="2" placeholder="Descreva brevemente o que você estava fazendo quando o erro ocorreu..." style="width: 100%; box-sizing: border-box; padding: 8px 10px; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 8px; color: #fff; font-size: 0.85rem; resize: vertical;"></textarea>- </div>-- <div class="btn-row" style="margin-top: 0; margin-bottom: 8px; gap: 8px; display: flex; flex-wrap: wrap;">- <button type="button" class="btn btn-primary" onclick="openGitHubReport()" id="btnOpenReport">🚀 Abrir Relatório no GitHub</button>- <button type="button" class="btn" onclick="copySanitizedReport()" id="btnCopyReport">📋 Copiar Relatório</button>- <button type="button" class="btn" onclick="previewReport()" id="btnPreviewReport">🔍 Pré-visualizar</button>- </div>- </div>-- <div class="card">- <h2>📋 Download de Logs Cru</h2>- <p>Baixe o arquivo <code>xcloud.log</code> sanitizado (sem tokens ou dados privados) para inspeção local ou envio manual.</p>- <div class="btn-row" style="margin-top: 0; margin-bottom: 14px; gap: 8px; display: flex; flex-wrap: wrap;">- <a href="/api/log" download="xcloud.log" class="btn btn-primary">⬇️ Baixar xcloud.log</a>- <button type="button" class="btn" onclick="loadLogPreview()">Visualizar Últimas Linhas</button>- </div>- <pre id="logPreview">Clique em "Visualizar Últimas Linhas" ou "Pré-visualizar" para inspecionar os dados...</pre>- </div>- </div>-</div>--<div id="toast" class="toast">Alterações salvas com sucesso!</div>--<script>-const padFunctions = [- "A (Sul / Cruz)", "B (Leste / Círculo)", "X (Oeste / Quadrado)", "Y (Norte / Triângulo)",- "LB (L1)", "RB (R1)", "LT (L2)", "RT (R2)", "LS (L3)", "RS (R3)",- "View (Touchpad / Share)", "Menu (Options)", "D-pad Cima", "D-pad Baixo", "D-pad Esquerda", "D-pad Direita"-];-const padSources = [- {id: 0, name: "Cruz (South)"}, {id: 1, name: "Círculo (East)"}, {id: 2, name: "Quadrado (West)"}, {id: 3, name: "Triângulo (North)"},- {id: 4, name: "L1 (LB)"}, {id: 5, name: "R1 (RB)"}, {id: 6, name: "L2 (LT)"}, {id: 7, name: "R2 (RT)"},- {id: 8, name: "L3 (LS)"}, {id: 9, name: "R3 (RS)"}, {id: 10, name: "Touchpad (View)"}, {id: 11, name: "Options (Menu)"},- {id: 12, name: "D-pad Cima"}, {id: 13, name: "D-pad Baixo"}, {id: 14, name: "D-pad Esquerda"}, {id: 15, name: "D-pad Direita"}-];--const touchpadTriggers = [- {key: "swipeUp", label: "Deslizar ↑ (Cima)"},- {key: "swipeDown", label: "Deslizar ↓ (Baixo)"},- {key: "swipeLeft", label: "Deslizar ← (Esquerda)"},- {key: "swipeRight", label: "Deslizar → (Direita)"},- {key: "clickLeft", label: "Clique Esquerdo"},- {key: "clickRight", label: "Clique Direito"}-];--const touchpadActions = [- {id: "none", name: "Desativado"},- {id: "game_menu", name: "Menu do Jogo"},- {id: "xbox_button", name: "Botão Xbox (Guia)"},- {id: "toggle_stats", name: "Alternar Telemetria"},- {id: "toggle_mic_mute", name: "Silenciar Microfone"},- {id: "cycle_gyro", name: "Alternar Giroscópio"},- {id: "cycle_trigger_profile", name: "Alternar Perfil de Gatilho"},- {id: "view", name: "View"},- {id: "menu", name: "Menu"},- {id: "l3", name: "LS (L3)"},- {id: "r3", name: "RS (R3)"},- {id: "a", name: "A (Cruz)"},- {id: "b", name: "B (Círculo)"},- {id: "x", name: "X (Quadrado)"},- {id: "y", name: "Y (Triângulo)"},- {id: "lb", name: "LB (L1)"},- {id: "rb", name: "RB (R1)"},- {id: "dpad_up", name: "D-pad Cima"},- {id: "dpad_down", name: "D-pad Baixo"},- {id: "dpad_left", name: "D-pad Esquerda"},- {id: "dpad_right", name: "D-pad Direita"}-];--const defaultTouchpadShortcuts = {- swipeUp: "xbox_button",- swipeDown: "game_menu",- swipeLeft: "game_menu",- swipeRight: "xbox_button",- clickLeft: "view",- clickRight: "view"-};--const keyActionNames = [- "Analógico Esq. Cima", "Analógico Esq. Baixo", "Analógico Esq. Esquerda", "Analógico Esq. Direita",- "D-pad Cima", "D-pad Baixo", "D-pad Esquerda", "D-pad Direita",- "A (Cruz)", "B (Círculo)", "X (Quadrado)", "Y (Triângulo)",- "LB (L1)", "RB (R1)", "LT (L2)", "RT (R2)", "LS (L3)", "RS (R3)",- "View (Share / Touch)", "Menu (Options)"-];--const keyList = [- {id: 0, name: "(Nenhuma)"},- {id: 87, name: "W"}, {id: 65, name: "A"}, {id: 83, name: "S"}, {id: 68, name: "D"},- {id: 81, name: "Q"}, {id: 69, name: "E"}, {id: 82, name: "R"}, {id: 70, name: "F"},- {id: 67, name: "C"}, {id: 86, name: "V"}, {id: 90, name: "Z"}, {id: 88, name: "X"},- {id: 66, name: "B"}, {id: 71, name: "G"}, {id: 84, name: "T"}, {id: 89, name: "Y"},- {id: 72, name: "H"}, {id: 74, name: "J"}, {id: 75, name: "K"}, {id: 76, name: "L"},- {id: 77, name: "M"}, {id: 78, name: "N"}, {id: 79, name: "O"}, {id: 80, name: "P"},- {id: 85, name: "U"}, {id: 73, name: "I"},- {id: 48, name: "0"}, {id: 49, name: "1"}, {id: 50, name: "2"}, {id: 51, name: "3"},- {id: 52, name: "4"}, {id: 53, name: "5"}, {id: 54, name: "6"}, {id: 55, name: "7"},- {id: 56, name: "8"}, {id: 57, name: "9"},- {id: 32, name: "Espaço (Space)"},- {id: 16, name: "Shift"}, {id: 17, name: "Ctrl"}, {id: 18, name: "Alt"},- {id: 9, name: "Tab"}, {id: 27, name: "Esc"}, {id: 13, name: "Enter"}, {id: 8, name: "Backspace"},- {id: 38, name: "Seta Cima"}, {id: 40, name: "Seta Baixo"},- {id: 37, name: "Seta Esquerda"}, {id: 39, name: "Seta Direita"},- {id: 241, name: "Mouse L (Esq)"}, {id: 242, name: "Mouse R (Dir)"},- {id: 243, name: "Mouse M (Meio)"}, {id: 244, name: "Mouse 4"}, {id: 245, name: "Mouse 5"}-];--const defaultKeyMap = [- 87, 0, 83, 0, 65, 0, 68, 0,- 38, 0, 40, 0, 37, 0, 39, 0,- 32, 0, 67, 0, 82, 0, 69, 0,- 81, 0, 70, 0, 242, 0, 241, 0,- 16, 0, 86, 243, 9, 0, 27, 0-];--let currentSettings = {- padMap: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],- keyMap: [...defaultKeyMap],- touchpadShortcuts: {...defaultTouchpadShortcuts}-};-let lastSettingsVersion = 0;--let currentSearchTab = 'gamepass';-let currentFilters = {- plan: 0,- consoleGP: 0,- consoleLib: 0,- modeGP: 0,- modeLib: 0,- langGP: 0,- langLib: 0,- mouseGP: false,- mouseLib: false,- wishlist: false,- free: false,- cheapest: false-};--function switchTab(name) {- document.querySelectorAll('.tab-pane').forEach(el => {- el.style.display = 'none';- el.classList.remove('active');- });- document.querySelectorAll('.nav-tab').forEach(el => el.classList.remove('active'));- const pane = document.getElementById('tab-' + name);- if (pane) {- pane.style.display = 'block';- pane.classList.add('active');- }- const tabBtn = document.getElementById('navTab-' + name);- if (tabBtn) tabBtn.classList.add('active');- if (name === 'search') pollStreamingState();- if (name === 'gamepad') {- sendPadState(true);- updateGamepadScale();- setTimeout(updateGamepadScale, 10);- }- if (name === 'stream') {- loadStreamMenuState();- pollStats();- }-}--function switchRemapSub(mode) {- document.getElementById('subRemapPad').style.display = mode === 'pad' ? 'block' : 'none';- document.getElementById('subRemapKey').style.display = mode === 'key' ? 'block' : 'none';- const subTouch = document.getElementById('subRemapTouch');- if (subTouch) subTouch.style.display = mode === 'touch' ? 'block' : 'none';- document.getElementById('btnSubPad').classList.toggle('active', mode === 'pad');- document.getElementById('btnSubKey').classList.toggle('active', mode === 'key');- const btnTouch = document.getElementById('btnSubTouch');- if (btnTouch) btnTouch.classList.toggle('active', mode === 'touch');-}--function showToast(msg) {- const t = document.getElementById('toast');- t.textContent = msg;- t.classList.add('show');- setTimeout(() => t.classList.remove('show'), 2500);-}--const searchInput = document.getElementById('searchInput');-let searchDebounce = null;--function applySearchTabUI(tab) {- currentSearchTab = tab;- document.getElementById('tabBtnGamePass').classList.toggle('active', tab === 'gamepass');- document.getElementById('tabBtnLibrary').classList.toggle('active', tab === 'library');- document.getElementById('filtersGamePass').style.display = tab === 'gamepass' ? 'flex' : 'none';- document.getElementById('filtersLibrary').style.display = tab === 'library' ? 'flex' : 'none';-}--function setSearchTab(tab) {- applySearchTabUI(tab);- sendSearch(true);-}--function toggleChip(id) {- const el = document.getElementById(id);- el.classList.toggle('active');- const active = el.classList.contains('active');- if (id === 'chipWishlist') currentFilters.wishlist = active;- if (id === 'chipFree') currentFilters.free = active;- if (id === 'chipCheapest') currentFilters.cheapest = active;- if (id === 'chipMouseGP') currentFilters.mouseGP = active;- if (id === 'chipMouseLib') currentFilters.mouseLib = active;- sendSearch(true);-}--function onFilterChange() {- currentFilters.plan = parseInt(document.getElementById('filterPlan').value, 10);- currentFilters.consoleGP = parseInt(document.getElementById('filterConsoleGP').value, 10);- currentFilters.consoleLib = parseInt(document.getElementById('filterConsoleLib').value, 10);- currentFilters.modeGP = parseInt(document.getElementById('filterModeGP').value, 10);- currentFilters.modeLib = parseInt(document.getElementById('filterModeLib').value, 10);- currentFilters.langGP = parseInt(document.getElementById('filterLangGP').value, 10);- currentFilters.langLib = parseInt(document.getElementById('filterLangLib').value, 10);-- document.getElementById('chipSelectPlan').classList.toggle('active', currentFilters.plan > 0);- document.getElementById('chipSelectConsoleGP').classList.toggle('active', currentFilters.consoleGP > 0);- document.getElementById('chipSelectConsoleLib').classList.toggle('active', currentFilters.consoleLib > 0);- document.getElementById('chipSelectModeGP').classList.toggle('active', currentFilters.modeGP > 0);- document.getElementById('chipSelectModeLib').classList.toggle('active', currentFilters.modeLib > 0);- document.getElementById('chipSelectLangGP').classList.toggle('active', currentFilters.langGP > 0);- document.getElementById('chipSelectLangLib').classList.toggle('active', currentFilters.langLib > 0);- sendSearch(true);-}--function updateSearchStatusText() {- const q = searchInput.value;- const isLib = currentSearchTab === 'library';- let status = isLib ? 'Meus jogos' : 'Game Pass';- if (q) status += ' • "' + q + '"';- const filterNames = [];- if (isLib) {- if (currentFilters.wishlist) filterNames.push('Lista de desejos');- if (currentFilters.free) filterNames.push('Grátis');- if (currentFilters.cheapest) filterNames.push('Menor preço');- if (currentFilters.mouseLib) filterNames.push('Teclado e mouse');- if (currentFilters.consoleLib > 0) {- const cNames = ['Todos', 'Series X|S', 'Xbox One', 'Xbox 360'];- filterNames.push(cNames[currentFilters.consoleLib]);- }- if (currentFilters.modeLib > 0) {- const mNames = ['Todos', 'Um jogador', 'Multijogador online', 'Cooperativo online', 'Multijogador local'];- filterNames.push(mNames[currentFilters.modeLib]);- }- if (currentFilters.langLib > 0) {- const lNames = ['Qualquer', 'Legendas', 'Dublado'];- filterNames.push(lNames[currentFilters.langLib]);- }- } else {- if (currentFilters.plan > 0) {- const pNames = ['Meu plano', 'Ultimate', 'Premium', 'Essential', 'Todos os planos'];- filterNames.push(pNames[currentFilters.plan]);- }- if (currentFilters.mouseGP) filterNames.push('Teclado e mouse');- if (currentFilters.consoleGP > 0) {- const cNames = ['Todos', 'Series X|S', 'Xbox One', 'Xbox 360'];- filterNames.push(cNames[currentFilters.consoleGP]);- }- if (currentFilters.modeGP > 0) {- const mNames = ['Todos', 'Um jogador', 'Multijogador online', 'Cooperativo online', 'Multijogador local'];- filterNames.push(mNames[currentFilters.modeGP]);- }- if (currentFilters.langGP > 0) {- const lNames = ['Qualquer', 'Legendas', 'Dublado'];- filterNames.push(lNames[currentFilters.langGP]);- }- }- if (filterNames.length > 0) {- status += ' [' + filterNames.join(', ') + ']';- }- document.getElementById('searchStatus').textContent = status;-}--function sendSearch(immediate = false) {- clearTimeout(searchDebounce);- const doFetch = () => {- const q = searchInput.value;- const isLib = currentSearchTab === 'library';- const activeFilters = {- plan: isLib ? 0 : currentFilters.plan,- console: isLib ? currentFilters.consoleLib : currentFilters.consoleGP,- mode: isLib ? currentFilters.modeLib : currentFilters.modeGP,- language: isLib ? currentFilters.langLib : currentFilters.langGP,- mouseKeyboard: isLib ? currentFilters.mouseLib : currentFilters.mouseGP,- wishlist: isLib ? currentFilters.wishlist : false,- free: isLib ? currentFilters.free : false,- cheapest: isLib ? currentFilters.cheapest : false- };-- updateSearchStatusText();-- fetch('/api/search', {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({- query: q,- tab: currentSearchTab,- filters: activeFilters- })- }).catch(e => console.error(e));- };-- if (immediate) {- doFetch();- } else {- searchDebounce = setTimeout(doFetch, 120);- }-}--searchInput.addEventListener('input', () => {- sendSearch(false);-});--function clearSearch() {- searchInput.value = '';- sendSearch(true);-}--function renderTouchpadShortcutsGrid(containerId, idPrefix, tsObj, onChangeFn) {- const grid = document.getElementById(containerId);- if (!grid) return;- grid.innerHTML = '';- const ts = Object.assign({}, defaultTouchpadShortcuts, tsObj || {});- touchpadTriggers.forEach(trig => {- const item = document.createElement('div');- item.className = 'map-item';- const label = document.createElement('label');- label.textContent = trig.label;- const select = document.createElement('select');- select.id = idPrefix + '_' + trig.key;- touchpadActions.forEach((act, idx) => {- const opt = document.createElement('option');- opt.value = act.id;- opt.textContent = act.name;- if (ts[trig.key] === act.id || ts[trig.key] === idx) opt.selected = true;- select.appendChild(opt);- });- select.addEventListener('change', () => {- currentSettings.touchpadShortcuts = currentSettings.touchpadShortcuts || {...defaultTouchpadShortcuts};- currentSettings.touchpadShortcuts[trig.key] = select.value;- syncTouchpadSelects(trig.key, select.value);- if (onChangeFn) onChangeFn(trig.key, select.value);- });- item.appendChild(label);- item.appendChild(select);- grid.appendChild(item);- });-}--function syncTouchpadSelects(trigKey, val) {- ['tp_remap_'].forEach(prefix => {- const el = document.getElementById(prefix + trigKey);- if (el && el.value !== String(val)) el.value = val;- });-}--function readTouchpadShortcutsFromPrefix(prefix) {- const out = {...defaultTouchpadShortcuts};- touchpadTriggers.forEach(trig => {- const el = document.getElementById(prefix + '_' + trig.key);- if (el) out[trig.key] = el.value;- });- return out;-}--function renderAllTouchpadGrids(tsObj) {- const ts = Object.assign({}, defaultTouchpadShortcuts, tsObj || currentSettings.touchpadShortcuts || {});- currentSettings.touchpadShortcuts = ts;- renderTouchpadShortcutsGrid('remapTouchpadShortcutsGrid', 'tp_remap', ts, null);-}--function resetTouchpadShortcuts() {- currentSettings.touchpadShortcuts = {...defaultTouchpadShortcuts};- renderAllTouchpadGrids(currentSettings.touchpadShortcuts);- saveSettings();-}--function renderPadMap() {- const grid = document.getElementById('padGrid');- grid.innerHTML = '';- const map = Array.isArray(currentSettings.padMap) ? currentSettings.padMap- : (currentSettings.padMap && Array.isArray(currentSettings.padMap.map)) ? currentSettings.padMap.map- : [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];- padFunctions.forEach((fnName, idx) => {- const item = document.createElement('div');- item.className = 'map-item';- const label = document.createElement('label');- label.textContent = fnName;- const select = document.createElement('select');- select.id = 'pad_fn_' + idx;- padSources.forEach(s => {- const opt = document.createElement('option');- opt.value = s.id;- opt.textContent = s.name;- if (map[idx] === s.id) opt.selected = true;- select.appendChild(opt);- });- item.appendChild(label);- item.appendChild(select);- grid.appendChild(item);- });-}--function renderKeyMap() {- const grid = document.getElementById('keyGrid');- grid.innerHTML = '';- const kmap = (currentSettings.keyMap && currentSettings.keyMap.length === 40) ? currentSettings.keyMap : defaultKeyMap;- keyActionNames.forEach((actName, idx) => {- const item = document.createElement('div');- item.className = 'map-item';- const label = document.createElement('label');- label.textContent = actName;- const selectsWrap = document.createElement('div');- selectsWrap.className = 'selects-wrap';- for (let slot = 0; slot < 2; slot++) {- const select = document.createElement('select');- select.id = 'key_act_' + idx + '_' + slot;- const code = kmap[idx * 2 + slot];- let hasMatch = false;- keyList.forEach(k => {- const opt = document.createElement('option');- opt.value = k.id;- opt.textContent = k.name;- if (code === k.id) { opt.selected = true; hasMatch = true; }- select.appendChild(opt);- });- if (!hasMatch && code > 0) {- const opt = document.createElement('option');- opt.value = code;- opt.textContent = "Key #" + code;- opt.selected = true;- select.appendChild(opt);- }- selectsWrap.appendChild(select);- }- item.appendChild(label);- item.appendChild(selectsWrap);- grid.appendChild(item);- });-}--function resetPadMap() {- currentSettings.padMap = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];- renderPadMap();- saveSettings();-}--function resetKeyMap() {- currentSettings.keyMap = [...defaultKeyMap];- renderKeyMap();- saveSettings();-}--function saveSettings() {- const padMap = [];- for (let i = 0; i < 16; i++) {- const sel = document.getElementById('pad_fn_' + i);- padMap.push(sel ? parseInt(sel.value, 10) : i);- }- const keyMap = [];- for (let i = 0; i < 20; i++) {- const s0 = document.getElementById('key_act_' + i + '_0');- const s1 = document.getElementById('key_act_' + i + '_1');- keyMap.push(s0 ? parseInt(s0.value, 10) : 0);- keyMap.push(s1 ? parseInt(s1.value, 10) : 0);- }- const touchpadShortcuts = readTouchpadShortcutsFromPrefix('tp_remap');- fetch('/api/settings', {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({ padMap: padMap, keyMap: keyMap, touchpadShortcuts: touchpadShortcuts })- }).then(r => r.json()).then(res => {- if (res.ok) {- showToast('Configurações salvas no console!');- }- }).catch(e => showToast('Erro ao salvar configurações'));-}--function onBitrateInput(val) {- const v = parseInt(val, 10);- const el = document.getElementById('valBitrate');- if (el) el.textContent = (v === 0) ? 'Auto' : v + ' Mbps';-}--function onLightBarModeChange() {- const sel = document.getElementById('selectLightBarMode');- const colorInput = document.getElementById('inputLightBarColor');- if (sel && colorInput) {- colorInput.style.display = (sel.value === '1') ? 'inline-block' : 'none';- }-}--function markSettingsChanged() {-}--function saveGeneralSettings() {- const payload = {- maxBitrateMbps: parseInt(document.getElementById('inputBitrate').value, 10),- highRefresh: document.getElementById('check120Hz').checked,- deadzoneLeft: parseInt(document.getElementById('inputDeadzoneL').value, 10),- deadzoneRight: parseInt(document.getElementById('inputDeadzoneR').value, 10),- triggerStrength: parseInt(document.getElementById('inputTriggerStrength').value, 10),- lightBarMode: parseInt(document.getElementById('selectLightBarMode').value, 10),- lightBarColour: document.getElementById('inputLightBarColor').value,- queueReadyAlert: document.getElementById('checkQueueAlert').checked,- videoDecoder: parseInt(document.getElementById('selectVideoDecoder').value, 10),- voiceRouting: parseInt(document.getElementById('selectVoiceRouting').value, 10)- };- fetch('/api/settings', {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify(payload)- }).then(r => r.json()).then(res => {- if (res.ok) {- showToast('Configurações salvas no console!');- } else {- showToast('Erro ao salvar configurações');- }- }).catch(() => showToast('Erro ao salvar configurações'));-}--function updateCasLabel(val) {- const labels = ['Desativada', 'Baixa', 'Média', 'Alta'];- const el = document.getElementById('valCas');- if (el) el.textContent = labels[val] !== undefined ? labels[val] : 'Média';-}--function sendStreamParam(param, val) {- const body = {};- body[param] = val;- fetch('/api/stream', {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify(body)- }).then(r => r.json()).then(res => {- if (res && res.ok) showToast('Aplicado na transmissão!');- }).catch(() => {});-}--function sendStreamAction(action) {- fetch('/api/stream', {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({ action: action })- }).then(r => r.json()).then(res => {- if (action === 'xbox_guide') showToast('Guia Xbox acionado');- if (action === 'end_session') showToast('Sessão encerrada');- }).catch(() => {});-}--function loadStreamMenuState() {- fetch('/api/stream').then(r => r.json()).then(s => {- if (s.sharpness !== undefined) {- const el = document.getElementById('inputCas');- if (el) { el.value = s.sharpness; updateCasLabel(s.sharpness); }- }- if (s.upscaler !== undefined) {- const el = document.getElementById('selectUpscaler');- if (el) el.value = s.upscaler;- }- if (s.deband !== undefined) {- const el = document.getElementById('selectDeband');- if (el) el.value = s.deband;- }- if (s.padSpeakerVolume !== undefined) {- const el = document.getElementById('inputPadSpeaker');- if (el) el.value = s.padSpeakerVolume;- const vlbl = document.getElementById('valPadSpeaker');- if (vlbl) vlbl.textContent = s.padSpeakerVolume + '%';- }- if (s.triggerProfile !== undefined) {- const el = document.getElementById('selectSmartTriggers');- if (el) el.value = s.triggerProfile;- }- if (s.touchpadShortcuts) {- renderAllTouchpadGrids(s.touchpadShortcuts);- }- }).catch(() => {});-}--function renderTelemetry(data) {- if (!data) return;- if (data.fps !== undefined) document.getElementById('telFps').textContent = data.fps;- if (data.rttMs !== undefined) document.getElementById('telRtt').textContent = data.rttMs + ' ms';- if (data.mbps !== undefined) document.getElementById('telMbps').textContent = (typeof data.mbps === 'number' ? data.mbps.toFixed(1) : data.mbps) + ' Mbps';- if (data.lossPct !== undefined) document.getElementById('telLoss').textContent = (typeof data.lossPct === 'number' ? data.lossPct.toFixed(1) : data.lossPct) + '%';- if (data.qp !== undefined) document.getElementById('telQp').textContent = data.qp;- if (data.decodeMs !== undefined) document.getElementById('telDec').textContent = (typeof data.decodeMs === 'number' ? data.decodeMs.toFixed(1) : data.decodeMs) + ' ms';-}--let ws = null;-function initWs() {- try {- const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';- ws = new WebSocket(proto + '//' + location.host + '/ws');- ws.onmessage = (ev) => {- try {- const msg = JSON.parse(ev.data);- if (msg.type === 'telemetry' && msg.stats) {- renderTelemetry(msg.stats);- } else if (msg.fps !== undefined) {- renderTelemetry(msg);- }- } catch (_) {}- };- ws.onclose = () => {- ws = null;- setTimeout(initWs, 2000);- };- ws.onerror = () => {- try { ws.close(); } catch(_) {}- };- } catch (_) {- ws = null;- }-}-initWs();--function pollStats() {- if (ws && ws.readyState === WebSocket.OPEN) return;- const streamTab = document.getElementById('tab-stream');- if (!streamTab || streamTab.style.display === 'none') return;- fetch('/api/stats').then(r => r.json()).then(renderTelemetry).catch(() => {});-}-setInterval(pollStats, 1000);--function loadLogPreview() {- const p = document.getElementById('logPreview');- p.textContent = 'Carregando log...';- fetch('/api/log').then(r => r.text()).then(text => {- const lines = text.split('\n');- p.textContent = lines.slice(-50).join('\n') || 'Log vazio.';- }).catch(e => {- p.textContent = 'Erro ao carregar log: ' + e;- });-}--function getReportParams() {- const title = (document.getElementById('reportTitle')?.value || '').trim();- const what = (document.getElementById('reportWhat')?.value || '').trim();- return { title, what };-}--function openGitHubReport() {- const { title, what } = getReportParams();- const btn = document.getElementById('btnOpenReport');- btn.disabled = true;- btn.textContent = 'Gerando link...';- fetch('/api/report-issue', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ title, what })- }).then(r => r.json()).then(data => {- btn.disabled = false;- btn.textContent = '🚀 Abrir Relatório no GitHub';- if (data && data.url) {- window.open(data.url, '_blank');- showToast('Formulário do GitHub aberto em nova aba!');- } else {- showToast('Erro ao obter link do relatório.');- }- }).catch(e => {- btn.disabled = false;- btn.textContent = '🚀 Abrir Relatório no GitHub';- showToast('Falha na requisição: ' + e);- });-}--function fallbackCopyText(text) {- return new Promise((resolve, reject) => {- try {- const ta = document.createElement('textarea');- ta.value = text;- ta.style.position = 'fixed';- ta.style.top = '0';- ta.style.left = '0';- ta.style.width = '2em';- ta.style.height = '2em';- ta.style.padding = '0';- ta.style.border = 'none';- ta.style.outline = 'none';- ta.style.boxShadow = 'none';- ta.style.background = 'transparent';- ta.style.opacity = '0.01';- document.body.appendChild(ta);- ta.focus();- ta.select();- if (typeof ta.setSelectionRange === 'function') {- ta.setSelectionRange(0, text.length);- }- let ok = false;- try {- ok = document.execCommand('copy');- } catch (_) {- ok = false;- }- document.body.removeChild(ta);- if (ok) resolve(); else reject(new Error('execCommand copy failed'));- } catch (e) { reject(e); }- });-}--function copyTextToClipboard(text) {- if (navigator.clipboard && window.isSecureContext && navigator.clipboard.writeText) {- return navigator.clipboard.writeText(text).catch(() => fallbackCopyText(text));- }- return fallbackCopyText(text);-}--function copySanitizedReport() {- const { title, what } = getReportParams();- const btn = document.getElementById('btnCopyReport');- btn.disabled = true;- fetch('/api/report-issue', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ title, what })- }).then(r => r.json()).then(data => {- btn.disabled = false;- if (data && data.excerpt) {- const markdown = `### ${data.title || 'Relatório de Erro'}\n\n**Plataforma:** ${data.platform || 'PlayStation 5 (PPSA99810)'}\n**Versão:** v${data.release || ')html" XC_APP_VERSION R"html('}\n**Firmware:** ${data.firmware || 'N/A'}\n\n**O que aconteceu:**\n${what || 'Relatório enviado via WebUI'}\n\n\`\`\`\n${data.excerpt}\n\`\`\``;- copyTextToClipboard(markdown).then(() => {- showToast('Relatório copiado para a área de transferência!');- }).catch(() => {- const p = document.getElementById('logPreview');- if (p) {- p.textContent = markdown;- p.scrollIntoView({ behavior: 'smooth', block: 'nearest' });- }- try {- window.prompt('Copie o relatório abaixo (Ctrl+C / Toque longo):', markdown);- showToast('Relatório preparado!');- } catch (_) {- showToast('Relatório preparado no campo abaixo para cópia!');- }- });- } else {- showToast('Erro ao gerar relatório.');- }- }).catch(e => {- btn.disabled = false;- showToast('Falha ao copiar: ' + e);- });-}--function previewReport() {- const { title, what } = getReportParams();- const p = document.getElementById('logPreview');- p.textContent = 'Carregando resumo do relatório sanitizado...';- fetch('/api/report-issue', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ title, what })- }).then(r => r.json()).then(data => {- if (data && data.excerpt) {- p.textContent = `=== RELATÓRIO PREPARADO ===\nTítulo: ${data.title}\nPlataforma: ${data.platform}\nVersão: v${data.release}\nFirmware: ${data.firmware}\n\n${data.excerpt}`;- } else {- p.textContent = 'Nenhum dado retornado.';- }- }).catch(e => {- p.textContent = 'Erro ao carregar pré-visualização: ' + e;- });-}--function applyLoadedSettings(s) {- currentSettings = Object.assign(currentSettings, s);- if (s.settingsVersion !== undefined) lastSettingsVersion = s.settingsVersion;- if (s.query !== undefined && document.activeElement !== searchInput) searchInput.value = s.query;- if (s.tab) {- currentSearchTab = s.tab;- }- if (s.filters) {- if (s.filters.wishlist !== undefined) {- currentFilters.wishlist = !!s.filters.wishlist;- const el = document.getElementById('chipWishlist');- if (el) el.classList.toggle('active', currentFilters.wishlist);- }- if (s.filters.free !== undefined) {- currentFilters.free = !!s.filters.free;- const el = document.getElementById('chipFree');- if (el) el.classList.toggle('active', currentFilters.free);- }- if (s.filters.cheapest !== undefined) {- currentFilters.cheapest = !!s.filters.cheapest;- const el = document.getElementById('chipCheapest');- if (el) el.classList.toggle('active', currentFilters.cheapest);- }- if (s.filters.mouseKeyboard !== undefined) {- currentFilters.mouseGP = !!s.filters.mouseKeyboard;- currentFilters.mouseLib = !!s.filters.mouseKeyboard;- const elGP = document.getElementById('chipMouseGP');- if (elGP) elGP.classList.toggle('active', currentFilters.mouseGP);- const elLib = document.getElementById('chipMouseLib');- if (elLib) elLib.classList.toggle('active', currentFilters.mouseLib);- }- if (s.filters.plan !== undefined) {- currentFilters.plan = s.filters.plan;- const sel = document.getElementById('filterPlan');- if (sel) sel.value = s.filters.plan;- const wrap = document.getElementById('chipSelectPlan');- if (wrap) wrap.classList.toggle('active', s.filters.plan > 0);- }- if (s.filters.console !== undefined) {- currentFilters.consoleGP = s.filters.console;- currentFilters.consoleLib = s.filters.console;- const selGP = document.getElementById('filterConsoleGP');- if (selGP) selGP.value = s.filters.console;- const selLib = document.getElementById('filterConsoleLib');- if (selLib) selLib.value = s.filters.console;- const wrapGP = document.getElementById('chipSelectConsoleGP');- if (wrapGP) wrapGP.classList.toggle('active', s.filters.console > 0);- const wrapLib = document.getElementById('chipSelectConsoleLib');- if (wrapLib) wrapLib.classList.toggle('active', s.filters.console > 0);- }- if (s.filters.mode !== undefined) {- currentFilters.modeGP = s.filters.mode;- currentFilters.modeLib = s.filters.mode;- const selGP = document.getElementById('filterModeGP');- if (selGP) selGP.value = s.filters.mode;- const selLib = document.getElementById('filterModeLib');- if (selLib) selLib.value = s.filters.mode;- const wrapGP = document.getElementById('chipSelectModeGP');- if (wrapGP) wrapGP.classList.toggle('active', s.filters.mode > 0);- const wrapLib = document.getElementById('chipSelectModeLib');- if (wrapLib) wrapLib.classList.toggle('active', s.filters.mode > 0);- }- if (s.filters.language !== undefined) {- currentFilters.langGP = s.filters.language;- currentFilters.langLib = s.filters.language;- const selGP = document.getElementById('filterLangGP');- if (selGP) selGP.value = s.filters.language;- const selLib = document.getElementById('filterLangLib');- if (selLib) selLib.value = s.filters.language;- const wrapGP = document.getElementById('chipSelectLangGP');- if (wrapGP) wrapGP.classList.toggle('active', s.filters.language > 0);- const wrapLib = document.getElementById('chipSelectLangLib');- if (wrapLib) wrapLib.classList.toggle('active', s.filters.language > 0);- }- }- if (s.maxBitrateMbps !== undefined) {- const el = document.getElementById('inputBitrate');- if (el) { el.value = s.maxBitrateMbps; onBitrateInput(s.maxBitrateMbps); }- }- if (s.highRefresh !== undefined) {- const el = document.getElementById('check120Hz');- if (el) el.checked = !!s.highRefresh;- }- if (s.deadzoneLeft !== undefined) {- const el = document.getElementById('inputDeadzoneL');- if (el) { el.value = s.deadzoneLeft; document.getElementById('valDeadzoneL').textContent = s.deadzoneLeft + '%'; }- }- if (s.deadzoneRight !== undefined) {- const el = document.getElementById('inputDeadzoneR');- if (el) { el.value = s.deadzoneRight; document.getElementById('valDeadzoneR').textContent = s.deadzoneRight + '%'; }- }- if (s.triggerStrength !== undefined) {- const el = document.getElementById('inputTriggerStrength');- if (el) { el.value = s.triggerStrength; document.getElementById('valTriggerStrength').textContent = s.triggerStrength; }- }- if (s.lightBarMode !== undefined) {- const el = document.getElementById('selectLightBarMode');- if (el) el.value = s.lightBarMode;- onLightBarModeChange();- }- if (s.lightBarColour) {- const el = document.getElementById('inputLightBarColor');- if (el) el.value = s.lightBarColour;- }- if (s.queueReadyAlert !== undefined) {- const el = document.getElementById('checkQueueAlert');- if (el) el.checked = !!s.queueReadyAlert;- }- if (s.videoDecoder !== undefined) {- const el = document.getElementById('selectVideoDecoder');- if (el) el.value = s.videoDecoder;- }- if (s.voiceRouting !== undefined) {- const el = document.getElementById('selectVoiceRouting');- if (el) el.value = s.voiceRouting;- }- applySearchTabUI(currentSearchTab);- updateSearchStatusText();- renderPadMap();- renderKeyMap();- renderAllTouchpadGrids(s.touchpadShortcuts);-}--function loadAllSettingsFromServer() {- fetch('/api/settings').then(r => r.json()).then(applyLoadedSettings).catch(() => {- renderPadMap();- renderKeyMap();- renderAllTouchpadGrids(currentSettings.touchpadShortcuts);- });-}-loadAllSettingsFromServer();--// --- Virtual Gamepad & Streaming Polling ----let activePlayer = 1;-const padState = {- btnA: false, btnB: false, btnX: false, btnY: false,- dpadUp: false, dpadDown: false, dpadLeft: false, dpadRight: false,- btnL1: false, btnR1: false, btnL3: false, btnR3: false,- btnView: false, btnMenu: false, btnNexus: false,- triggerL2: 0.0, triggerR2: 0.0,- leftStickX: 0.0, leftStickY: 0.0,- rightStickX: 0.0, rightStickY: 0.0-};-let padSendScheduled = false;--function setVirtualPlayer(p) {- const prev = activePlayer;- activePlayer = p;- for (let i = 1; i <= 4; i++) {- const btn = document.getElementById('btnPlayer' + i);- if (btn) btn.classList.toggle('active', p === i);- }- const statusEl = document.getElementById('gamepadStatus');- if (statusEl) {- statusEl.textContent = 'Controle ativo para Jogador ' + p + (p === 1 ? ' (Principal)' : ' (Co-op Local)');- }- sendPadState(true, prev);-}--function toggleGamepadFullscreen() {- const card = document.getElementById('gamepadCard');- if (!card) return;- const isFs = card.classList.contains('gamepad-fullscreen') || document.fullscreenElement === card || document.webkitFullscreenElement === card;- if (!isFs) {- card.classList.add('gamepad-fullscreen');- if (card.requestFullscreen) {- card.requestFullscreen().catch(() => {});- } else if (card.webkitRequestFullscreen) {- try { card.webkitRequestFullscreen(); } catch (_) {}- }- if (screen.orientation && screen.orientation.lock) {- screen.orientation.lock('landscape').catch(() => {});- }- } else {- card.classList.remove('gamepad-fullscreen');- if (document.fullscreenElement || document.webkitFullscreenElement) {- if (document.exitFullscreen) document.exitFullscreen().catch(() => {});- else if (document.webkitExitFullscreen) {- try { document.webkitExitFullscreen(); } catch (_) {}- }- }- if (screen.orientation && screen.orientation.unlock) {- try { screen.orientation.unlock(); } catch (_) {}- }- }- setTimeout(updateGamepadScale, 20);- setTimeout(updateGamepadScale, 150);-}--document.addEventListener('fullscreenchange', () => {- const card = document.getElementById('gamepadCard');- if (card && !document.fullscreenElement && !document.webkitFullscreenElement) {- card.classList.remove('gamepad-fullscreen');- }- setTimeout(updateGamepadScale, 30);-});-document.addEventListener('webkitfullscreenchange', () => {- const card = document.getElementById('gamepadCard');- if (card && !document.fullscreenElement && !document.webkitFullscreenElement) {- card.classList.remove('gamepad-fullscreen');- }- setTimeout(updateGamepadScale, 30);-});--function sendPadState(activeSwitch = false, prevPlayer = 0) {- const payload = { player: activePlayer, prevPlayer: prevPlayer, activeSwitch: !!activeSwitch, ...padState };- if (ws && ws.readyState === WebSocket.OPEN) {- ws.send(JSON.stringify(payload));- } else {- fetch('/api/gamepad', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload)- }).catch(() => {});- }-}--function schedulePadSend() {- if (padSendScheduled) return;- padSendScheduled = true;- requestAnimationFrame(() => {- padSendScheduled = false;- sendPadState(false);- });-}--function bindPadButtons() {- document.querySelectorAll('[data-btn]').forEach(el => {- const key = el.getAttribute('data-btn');- const isTrigger = key === 'triggerL2' || key === 'triggerR2';- const activeTouches = new Set();-- const setDown = () => {- if (isTrigger) padState[key] = 1.0;- else padState[key] = true;- el.classList.add('pressed');- if (navigator.vibrate) {- try { navigator.vibrate(14); } catch (_) {}- }- sendPadState(false);- };-- const setUp = () => {- if (isTrigger) padState[key] = 0.0;- else padState[key] = false;- el.classList.remove('pressed');- sendPadState(false);- };-- el.addEventListener('touchstart', (e) => {- e.preventDefault();- for (let i = 0; i < e.changedTouches.length; i++) {- activeTouches.add(e.changedTouches[i].identifier);- }- setDown();- }, { passive: false });-- const onTouchEnd = (e) => {- e.preventDefault();- for (let i = 0; i < e.changedTouches.length; i++) {- activeTouches.delete(e.changedTouches[i].identifier);- }- if (activeTouches.size === 0) setUp();- };-- el.addEventListener('touchend', onTouchEnd, { passive: false });- el.addEventListener('touchcancel', onTouchEnd, { passive: false });- el.addEventListener('mousedown', (e) => { e.preventDefault(); setDown(); });- el.addEventListener('mouseup', (e) => { e.preventDefault(); setUp(); });- el.addEventListener('mouseleave', () => { if (activeTouches.size === 0 && el.classList.contains('pressed')) setUp(); });- });-}--function setupStick(zoneId, headId, stickKeyX, stickKeyY) {- const zone = document.getElementById(zoneId);- const head = document.getElementById(headId);- if (!zone || !head) return;-- let activeTouchId = null;-- function updateStick(clientX, clientY) {- const rect = zone.getBoundingClientRect();- const maxR = Math.max(28, (rect.width - head.offsetWidth) / 2);- const cx = rect.left + rect.width / 2;- const cy = rect.top + rect.height / 2;- let dx = clientX - cx;- let dy = clientY - cy;- const dist = Math.hypot(dx, dy);- if (dist > maxR) {- dx = (dx / dist) * maxR;- dy = (dy / dist) * maxR;- }- head.style.transform = `translate(${dx}px, ${dy}px)`;- padState[stickKeyX] = Math.round((dx / maxR) * 100) / 100;- padState[stickKeyY] = Math.round((dy / maxR) * 100) / 100;- schedulePadSend();- }-- function resetStick() {- head.style.transform = 'translate(0px, 0px)';- padState[stickKeyX] = 0.0;- padState[stickKeyY] = 0.0;- activeTouchId = null;- sendPadState(false);- }-- zone.addEventListener('touchstart', (e) => {- e.preventDefault();- if (activeTouchId === null && e.changedTouches.length > 0) {- activeTouchId = e.changedTouches[0].identifier;- updateStick(e.changedTouches[0].clientX, e.changedTouches[0].clientY);- }- }, { passive: false });-- zone.addEventListener('touchmove', (e) => {- e.preventDefault();- for (let i = 0; i < e.changedTouches.length; i++) {- if (e.changedTouches[i].identifier === activeTouchId) {- updateStick(e.changedTouches[i].clientX, e.changedTouches[i].clientY);- break;- }- }- }, { passive: false });-- const onTouchEnd = (e) => {- for (let i = 0; i < e.changedTouches.length; i++) {- if (e.changedTouches[i].identifier === activeTouchId) {- resetStick();- break;- }- }- };- zone.addEventListener('touchend', onTouchEnd, { passive: false });- zone.addEventListener('touchcancel', onTouchEnd, { passive: false });-- // Mouse fallback- let isMouseDown = false;- zone.addEventListener('mousedown', (e) => {- isMouseDown = true;- updateStick(e.clientX, e.clientY);- });- window.addEventListener('mousemove', (e) => {- if (isMouseDown) updateStick(e.clientX, e.clientY);- });- window.addEventListener('mouseup', () => {- if (isMouseDown) {- isMouseDown = false;- resetStick();- }- });-}--bindPadButtons();-setupStick('leftStickZone', 'leftStickHead', 'leftStickX', 'leftStickY');-setupStick('rightStickZone', 'rightStickHead', 'rightStickX', 'rightStickY');--// Periodic streaming state poll and PS5 <-> WebUI settings version sync-let isCurrentlyStreaming = false;-function pollStreamingState() {- fetch('/api/status').then(r => r.json()).then(data => {- const streaming = !!data.streaming;- if (streaming !== isCurrentlyStreaming) {- isCurrentlyStreaming = streaming;- const overlay = document.getElementById('searchOverlay');- if (overlay) overlay.style.display = streaming ? 'flex' : 'none';- if (searchInput) searchInput.disabled = streaming;- }- if (data.settingsVersion !== undefined && data.settingsVersion !== lastSettingsVersion) {- lastSettingsVersion = data.settingsVersion;- applyLoadedSettings(data);- loadStreamMenuState();- }- }).catch(() => {});-}-setInterval(pollStreamingState, 1500);-pollStreamingState();--// Gamepad keepalive while gamepad tab is open (300ms ensures held buttons never drop)-setInterval(() => {- const gpPane = document.getElementById('tab-gamepad');- if (gpPane && gpPane.style.display !== 'none') {- sendPadState(false);- }-}, 300);--function updateGamepadScale() {- const container = document.getElementById('gamepadScaleContainer');- const card = document.getElementById('gamepadCard');- if (!container || !card) return;- const isFs = card.classList.contains('gamepad-fullscreen') || document.fullscreenElement === card || document.webkitFullscreenElement === card;- const isLandscape = window.innerWidth > window.innerHeight;-- if (isFs) {- const w = window.innerWidth;- const h = window.innerHeight;- const availW = container.clientWidth ? Math.max(200, container.clientWidth - 8) : (w - 28);- const availH = container.clientHeight ? Math.max(150, container.clientHeight - 8) : (h - 20);- const scale = Math.min(1.2, Math.max(0.4, Math.min(availW / 915, availH / 412)));- document.documentElement.style.setProperty('--gp-fs-scale', scale.toFixed(3));- document.documentElement.style.setProperty('--gp-scale', scale.toFixed(3));- return;- }-- let availW = container.clientWidth;- if (!availW) {- const padding = window.innerWidth <= 600 ? 16 : 32;- availW = Math.max(0, window.innerWidth - padding);- }-- if (!isLandscape) {- const targetW = Math.max(0, availW - 16);- const scale = Math.min(1, Math.max(0.4, targetW / 412));- document.documentElement.style.setProperty('--gp-scale', scale.toFixed(3));- } else {- const targetW = Math.max(0, availW - 16);- const availH = window.innerHeight;- const targetH = Math.max(120, availH - 78);- const scale = Math.min(1, Math.max(0.35, Math.min(targetW / 915, targetH / 412)));- document.documentElement.style.setProperty('--gp-scale', scale.toFixed(3));- }-}-window.addEventListener('resize', updateGamepadScale);-window.addEventListener('orientationchange', () => setTimeout(updateGamepadScale, 50));-window.addEventListener('DOMContentLoaded', updateGamepadScale);-if (window.ResizeObserver) {- const ro = new ResizeObserver(() => updateGamepadScale());- const cardEl = document.getElementById('gamepadCard');- if (cardEl) ro.observe(cardEl);-}--// Hash & route navigation support: #gamepad, #gamepad-fs, #logs, #settings, /boost, /gamepad, etc.-function checkHashNav() {- const p = (location.pathname || '').toLowerCase();- if (p.includes('/boost') || p.includes('/gamepad')) {- switchTab('gamepad');- }- const h = (location.hash || '').replace('#', '');- if (!h) return;- if (h === 'gamepad-fs') {- switchTab('gamepad');- const card = document.getElementById('gamepadCard');- if (card && !card.classList.contains('gamepad-fullscreen')) {- toggleGamepadFullscreen();- }- } else if (document.getElementById('tab-' + h)) {- switchTab(h);- }-}-window.addEventListener('hashchange', checkHashNav);-checkHashNav();-</script>-</body>-</html>)html";-std::string extractJsonField(const std::string& body, const std::string& field) {auto j = json::parse(body);if (j && j->isObject()) {@@ -2459,252 +118,6 @@ bool WebServer::start(uint16_t port) {return true;}-namespace ws {--std::string computeAccept(const std::string& key) {- std::string trimmed = key;- while (!trimmed.empty() && (trimmed.front() == ' ' || trimmed.front() == '\t' || trimmed.front() == '\r' || trimmed.front() == '\n')) {- trimmed.erase(trimmed.begin());- }- while (!trimmed.empty() && (trimmed.back() == ' ' || trimmed.back() == '\t' || trimmed.back() == '\r' || trimmed.back() == '\n')) {- trimmed.pop_back();- }- trimmed += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";- unsigned char sha[20];- mbedtls_sha1(reinterpret_cast<const unsigned char*>(trimmed.data()), trimmed.size(), sha);- unsigned char b64[64];- size_t olen = 0;- mbedtls_base64_encode(b64, sizeof(b64), &olen, sha, sizeof(sha));- return std::string(reinterpret_cast<char*>(b64), olen);-}--std::vector<uint8_t> makeFrame(Opcode opcode, const uint8_t* data, size_t len, bool fin) {- std::vector<uint8_t> frame;- uint8_t b0 = (fin ? 0x80 : 0x00) | (static_cast<uint8_t>(opcode) & 0x0F);- frame.push_back(b0);- if (len < 126) {- frame.push_back(static_cast<uint8_t>(len));- } else if (len <= 0xFFFF) {- frame.push_back(126);- frame.push_back(static_cast<uint8_t>((len >> 8) & 0xFF));- frame.push_back(static_cast<uint8_t>(len & 0xFF));- } else {- frame.push_back(127);- for (int i = 7; i >= 0; --i) {- frame.push_back(static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF));- }- }- if (data && len > 0) {- frame.insert(frame.end(), data, data + len);- }- return frame;-}--std::vector<uint8_t> makeTextFrame(const std::string& text) {- return makeFrame(Opcode::Text, reinterpret_cast<const uint8_t*>(text.data()), text.size());-}--std::vector<uint8_t> makeBinaryFrame(const uint8_t* data, size_t len) {- return makeFrame(Opcode::Binary, data, len);-}--std::vector<uint8_t> makePongFrame(const std::vector<uint8_t>& pingPayload) {- return makeFrame(Opcode::Pong, pingPayload.data(), pingPayload.size());-}--std::vector<uint8_t> makeCloseFrame(uint16_t code) {- uint8_t payload[2];- payload[0] = static_cast<uint8_t>((code >> 8) & 0xFF);- payload[1] = static_cast<uint8_t>(code & 0xFF);- return makeFrame(Opcode::Close, payload, sizeof(payload));-}--bool parseFrame(const uint8_t* data, size_t len, Frame& outFrame, size_t& bytesConsumed) {- if (!data || len < 2) return false;- bool fin = (data[0] & 0x80) != 0;- Opcode opcode = static_cast<Opcode>(data[0] & 0x0F);- bool masked = (data[1] & 0x80) != 0;- uint8_t lenField = data[1] & 0x7F;-- size_t headerSize = 2;- uint64_t payloadLen = 0;- if (lenField < 126) {- payloadLen = lenField;- } else if (lenField == 126) {- if (len < headerSize + 2) return false;- payloadLen = (static_cast<uint64_t>(data[2]) << 8) | data[3];- headerSize += 2;- } else {- if (len < headerSize + 8) return false;- payloadLen = 0;- for (int i = 0; i < 8; ++i) {- payloadLen = (payloadLen << 8) | data[headerSize + i];- }- headerSize += 8;- }- if (payloadLen > 1048576) return false;-- uint8_t maskKey[4] = {0, 0, 0, 0};- if (masked) {- if (len < headerSize + 4) return false;- std::memcpy(maskKey, data + headerSize, 4);- headerSize += 4;- }-- if (len < headerSize + payloadLen) return false;-- outFrame.fin = fin;- outFrame.opcode = opcode;- outFrame.payload.resize(static_cast<size_t>(payloadLen));- for (size_t i = 0; i < payloadLen; ++i) {- uint8_t b = data[headerSize + i];- if (masked) b ^= maskKey[i % 4];- outFrame.payload[i] = b;- }- bytesConsumed = headerSize + static_cast<size_t>(payloadLen);- return true;-}--} // namespace ws--bool parseGamepadJson(const json::Value& val, int& outSlot, input::ControllerState& outState) {- if (!val.isObject()) return false;- int slot = 0;- if (val.has("playerIndex")) {- slot = static_cast<int>(val["playerIndex"].asInt(0));- } else if (val.has("player")) {- int p = static_cast<int>(val["player"].asInt(1));- slot = p - 1;- }- slot = std::clamp(slot, 0, 3);- outSlot = slot;-- outState = input::ControllerState{};- outState.connected = true;-- auto readButton = [](const json::Value& b) -> bool {- if (b.isBool()) return b.asBool();- if (b.isNumber()) return b.asNumber() > 0.5;- if (b.isObject()) {- if (b.has("pressed")) return b["pressed"].asBool();- if (b.has("value")) return b["value"].asNumber() > 0.5;- }- return false;- };-- auto readTrigger = [](const json::Value& b) -> float {- if (b.isNumber()) return static_cast<float>(b.asNumber(0.0));- if (b.isBool()) return b.asBool() ? 1.0f : 0.0f;- if (b.isObject() && b.has("value")) return static_cast<float>(b["value"].asNumber(0.0));- if (b.isObject() && b.has("pressed")) return b["pressed"].asBool() ? 1.0f : 0.0f;- return 0.0f;- };-- // 1. W3C Gamepad API standard arrays- if (val.has("buttons") && val["buttons"].isArray()) {- const auto& arr = val["buttons"];- size_t n = arr.size();- if (n > 0) outState.btnA = readButton(arr[0]);- if (n > 1) outState.btnB = readButton(arr[1]);- if (n > 2) outState.btnX = readButton(arr[2]);- if (n > 3) outState.btnY = readButton(arr[3]);- if (n > 4) outState.btnL1 = readButton(arr[4]);- if (n > 5) outState.btnR1 = readButton(arr[5]);- if (n > 6) outState.triggerL2 = readTrigger(arr[6]);- if (n > 7) outState.triggerR2 = readTrigger(arr[7]);- if (n > 8) outState.btnTouchpad = readButton(arr[8]); // Select / View- if (n > 9) outState.btnOptions = readButton(arr[9]); // Start / Menu- if (n > 10) outState.btnL3 = readButton(arr[10]);- if (n > 11) outState.btnR3 = readButton(arr[11]);- if (n > 12) outState.dpadUp = readButton(arr[12]);- if (n > 13) outState.dpadDown = readButton(arr[13]);- if (n > 14) outState.dpadLeft = readButton(arr[14]);- if (n > 15) outState.dpadRight = readButton(arr[15]);- if (n > 16) outState.btnNexus = readButton(arr[16]); // Xbox / Guide- }-- if (val.has("axes") && val["axes"].isArray()) {- const auto& arr = val["axes"];- size_t n = arr.size();- if (n > 0) outState.leftStickX = static_cast<float>(arr[0].asNumber(0.0));- if (n > 1) outState.leftStickY = static_cast<float>(arr[1].asNumber(0.0));- if (n > 2) outState.rightStickX = static_cast<float>(arr[2].asNumber(0.0));- if (n > 3) outState.rightStickY = static_cast<float>(arr[3].asNumber(0.0));- }-- // 2. Named / object mappings and flat fields- auto getBool = [&](const char* k1, const char* k2 = nullptr, const char* k3 = nullptr) -> bool {- if (val.has(k1)) return val[k1].asBool(false);- if (k2 && val.has(k2)) return val[k2].asBool(false);- if (k3 && val.has(k3)) return val[k3].asBool(false);- if (val.has("buttons") && val["buttons"].isObject()) {- const auto& b = val["buttons"];- if (b.has(k1)) return b[k1].asBool(false);- if (k2 && b.has(k2)) return b[k2].asBool(false);- if (k3 && b.has(k3)) return b[k3].asBool(false);- }- return false;- };-- auto getFloat = [&](const char* k1, const char* k2 = nullptr) -> float {- if (val.has(k1)) return static_cast<float>(val[k1].asNumber(0.0));- if (k2 && val.has(k2)) return static_cast<float>(val[k2].asNumber(0.0));- if (val.has("axes") && val["axes"].isObject()) {- const auto& a = val["axes"];- if (a.has(k1)) return static_cast<float>(a[k1].asNumber(0.0));- if (k2 && a.has(k2)) return static_cast<float>(a[k2].asNumber(0.0));- }- return 0.0f;- };-- if (getBool("btnA", "a")) outState.btnA = true;- if (getBool("btnB", "b")) outState.btnB = true;- if (getBool("btnX", "x")) outState.btnX = true;- if (getBool("btnY", "y")) outState.btnY = true;-- if (getBool("dpadUp", "dpad_up", "up")) outState.dpadUp = true;- if (getBool("dpadDown", "dpad_down", "down")) outState.dpadDown = true;- if (getBool("dpadLeft", "dpad_left", "left")) outState.dpadLeft = true;- if (getBool("dpadRight", "dpad_right", "right")) outState.dpadRight = true;-- if (getBool("btnL1", "lb", "l1")) outState.btnL1 = true;- if (getBool("btnR1", "rb", "r1")) outState.btnR1 = true;- if (getBool("btnL3", "ls", "l3")) outState.btnL3 = true;- if (getBool("btnR3", "rs", "r3")) outState.btnR3 = true;-- if (getBool("btnTouchpad", "btnView", "view")) outState.btnTouchpad = true;- if (getBool("btnOptions", "btnMenu", "menu")) outState.btnOptions = true;- if (getBool("btnNexus", "xbox", "guide")) outState.btnNexus = true;-- float tL = getFloat("triggerL2", "lt");- if (tL > 0.0f) outState.triggerL2 = tL;- float tR = getFloat("triggerR2", "rt");- if (tR > 0.0f) outState.triggerR2 = tR;-- if (val.has("leftStickX") || val.has("lx") || (val.has("axes") && val["axes"].isObject())) {- float lx = getFloat("leftStickX", "lx");- if (std::abs(lx) > 0.001f) outState.leftStickX = lx;- }- if (val.has("leftStickY") || val.has("ly") || (val.has("axes") && val["axes"].isObject())) {- float ly = getFloat("leftStickY", "ly");- if (std::abs(ly) > 0.001f) outState.leftStickY = ly;- }- if (val.has("rightStickX") || val.has("rx") || (val.has("axes") && val["axes"].isObject())) {- float rx = getFloat("rightStickX", "rx");- if (std::abs(rx) > 0.001f) outState.rightStickX = rx;- }- if (val.has("rightStickY") || val.has("ry") || (val.has("axes") && val["axes"].isObject())) {- float ry = getFloat("rightStickY", "ry");- if (std::abs(ry) > 0.001f) outState.rightStickY = ry;- }-- outState.rawLeftX = outState.leftStickX;- outState.rawLeftY = outState.leftStickY;- outState.rawRightX = outState.rightStickX;- outState.rawRightY = outState.rightStickY;- return true;-}-void WebServer::stop() {if (!running_.exchange(false)) return;if (listenFd_ >= 0) {@@ -2995,92 +408,6 @@ done:}}-namespace {-struct VirtualGamepadSlot {- input::ControllerState state{};- uint64_t lastSeenMs = 0;- uint64_t lastInputMs = 0;-};-std::mutex s_vpadMutex;-VirtualGamepadSlot s_virtualPads[4];--bool hasGamepadInput(const input::ControllerState& s) {- return s.btnA || s.btnB || s.btnX || s.btnY ||- s.dpadUp || s.dpadDown || s.dpadLeft || s.dpadRight ||- s.btnL1 || s.btnR1 || s.btnL3 || s.btnR3 ||- s.btnTouchpad || s.btnOptions || s.btnNexus ||- s.triggerL2 > 0.05f || s.triggerR2 > 0.05f ||- std::abs(s.leftStickX) > 0.08f || std::abs(s.leftStickY) > 0.08f ||- std::abs(s.rightStickX) > 0.08f || std::abs(s.rightStickY) > 0.08f;-}-} // namespace--bool virtualGamepadState(int playerIndex, input::ControllerState& outState, bool& isConnected) {- if (playerIndex < 0 || playerIndex >= 4) {- isConnected = false;- outState = {};- return false;- }- std::lock_guard<std::mutex> lock(s_vpadMutex);- uint64_t now = platform::nowMs();- uint64_t diff = now > s_virtualPads[playerIndex].lastSeenMs ? now - s_virtualPads[playerIndex].lastSeenMs : 0;- isConnected = (s_virtualPads[playerIndex].lastSeenMs > 0 && diff < 4000);- if (diff < 2000) {- outState = s_virtualPads[playerIndex].state;- } else {- outState = {};- }- return isConnected;-}--void setVirtualGamepad(int playerIndex, const input::ControllerState& state) {- if (playerIndex < 0 || playerIndex >= 4) return;- std::lock_guard<std::mutex> lock(s_vpadMutex);- uint64_t now = platform::nowMs();- bool firstSeen = (s_virtualPads[playerIndex].lastSeenMs == 0);- s_virtualPads[playerIndex].state = state;- s_virtualPads[playerIndex].lastSeenMs = now;- if (firstSeen || hasGamepadInput(state)) {- s_virtualPads[playerIndex].lastInputMs = now;- }-}--void touchVirtualGamepad(int playerIndex) {- if (playerIndex < 0 || playerIndex >= 4) return;- std::lock_guard<std::mutex> lock(s_vpadMutex);- uint64_t now = platform::nowMs();- s_virtualPads[playerIndex].lastSeenMs = now;- s_virtualPads[playerIndex].lastInputMs = now;-}--void switchVirtualGamepadSlot(int newSlot) {- if (newSlot < 0 || newSlot >= 4) return;- std::lock_guard<std::mutex> lock(s_vpadMutex);- for (int i = 0; i < 4; ++i) {- if (i != newSlot) {- s_virtualPads[i] = {};- }- }- uint64_t now = platform::nowMs();- s_virtualPads[newSlot].lastSeenMs = now;- s_virtualPads[newSlot].lastInputMs = now;-}--uint64_t virtualGamepadActiveAt(int playerIndex) {- if (playerIndex < 0 || playerIndex >= 4) return 0;- std::lock_guard<std::mutex> lock(s_vpadMutex);- return s_virtualPads[playerIndex].lastInputMs;-}--void resetVirtualGamepads() {- std::lock_guard<std::mutex> lock(s_vpadMutex);- for (auto& slot : s_virtualPads) slot = {};-}--const char* webServerIndexHtml() {- return kIndexHtml;-}-void setWebServerHooks(WebServerHooks hooks) {s_hooks = std::move(hooks);}@@ -3093,7 +420,7 @@ WebServer::HttpResponse WebServer::handleRequest(const std::string& method, consif (method == "GET" || method == "HEAD") {if (path == "/" || path == "/index.html" || path == "/boost" || path == "/boost/" || path == "/gamepad" || path == "/gamepad/") {- return {200, "text/html; charset=utf-8", "", kIndexHtml};+ return {200, "text/html; charset=utf-8", "", webServerIndexHtml()};}if (path == "/api/settings" || path == "/api/status" || path == "/api/state") {json::Value root = json::Value::object();diff --git a/src/app/web_server_gamepad.cpp b/src/app/web_server_gamepad.cppnew file mode 100644index 0000000..da4882f--- /dev/null+++ b/src/app/web_server_gamepad.cpp@@ -0,0 +1,343 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/web_server.h"+#include "platform/platform.h"++#include <algorithm>+#include <cmath>+#include <cstring>+#include <mbedtls/base64.h>+#include <mbedtls/sha1.h>+#include <mutex>++namespace xc::app {++namespace ws {++std::string computeAccept(const std::string& key) {+ std::string trimmed = key;+ while (!trimmed.empty() && (trimmed.front() == ' ' || trimmed.front() == '\t' || trimmed.front() == '\r' || trimmed.front() == '\n')) {+ trimmed.erase(trimmed.begin());+ }+ while (!trimmed.empty() && (trimmed.back() == ' ' || trimmed.back() == '\t' || trimmed.back() == '\r' || trimmed.back() == '\n')) {+ trimmed.pop_back();+ }+ trimmed += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";+ unsigned char sha[20];+ mbedtls_sha1(reinterpret_cast<const unsigned char*>(trimmed.data()), trimmed.size(), sha);+ unsigned char b64[64];+ size_t olen = 0;+ mbedtls_base64_encode(b64, sizeof(b64), &olen, sha, sizeof(sha));+ return std::string(reinterpret_cast<char*>(b64), olen);+}++std::vector<uint8_t> makeFrame(Opcode opcode, const uint8_t* data, size_t len, bool fin) {+ std::vector<uint8_t> frame;+ uint8_t b0 = (fin ? 0x80 : 0x00) | (static_cast<uint8_t>(opcode) & 0x0F);+ frame.push_back(b0);+ if (len < 126) {+ frame.push_back(static_cast<uint8_t>(len));+ } else if (len <= 0xFFFF) {+ frame.push_back(126);+ frame.push_back(static_cast<uint8_t>((len >> 8) & 0xFF));+ frame.push_back(static_cast<uint8_t>(len & 0xFF));+ } else {+ frame.push_back(127);+ for (int i = 7; i >= 0; --i) {+ frame.push_back(static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF));+ }+ }+ if (data && len > 0) {+ frame.insert(frame.end(), data, data + len);+ }+ return frame;+}++std::vector<uint8_t> makeTextFrame(const std::string& text) {+ return makeFrame(Opcode::Text, reinterpret_cast<const uint8_t*>(text.data()), text.size());+}++std::vector<uint8_t> makeBinaryFrame(const uint8_t* data, size_t len) {+ return makeFrame(Opcode::Binary, data, len);+}++std::vector<uint8_t> makePongFrame(const std::vector<uint8_t>& pingPayload) {+ return makeFrame(Opcode::Pong, pingPayload.data(), pingPayload.size());+}++std::vector<uint8_t> makeCloseFrame(uint16_t code) {+ uint8_t payload[2];+ payload[0] = static_cast<uint8_t>((code >> 8) & 0xFF);+ payload[1] = static_cast<uint8_t>(code & 0xFF);+ return makeFrame(Opcode::Close, payload, sizeof(payload));+}++bool parseFrame(const uint8_t* data, size_t len, Frame& outFrame, size_t& bytesConsumed) {+ if (!data || len < 2) return false;+ bool fin = (data[0] & 0x80) != 0;+ Opcode opcode = static_cast<Opcode>(data[0] & 0x0F);+ bool masked = (data[1] & 0x80) != 0;+ uint8_t lenField = data[1] & 0x7F;++ size_t headerSize = 2;+ uint64_t payloadLen = 0;+ if (lenField < 126) {+ payloadLen = lenField;+ } else if (lenField == 126) {+ if (len < headerSize + 2) return false;+ payloadLen = (static_cast<uint64_t>(data[2]) << 8) | data[3];+ headerSize += 2;+ } else {+ if (len < headerSize + 8) return false;+ payloadLen = 0;+ for (int i = 0; i < 8; ++i) {+ payloadLen = (payloadLen << 8) | data[headerSize + i];+ }+ headerSize += 8;+ }+ if (payloadLen > 1048576) return false;++ uint8_t maskKey[4] = {0, 0, 0, 0};+ if (masked) {+ if (len < headerSize + 4) return false;+ std::memcpy(maskKey, data + headerSize, 4);+ headerSize += 4;+ }++ if (len < headerSize + payloadLen) return false;++ outFrame.fin = fin;+ outFrame.opcode = opcode;+ outFrame.payload.resize(static_cast<size_t>(payloadLen));+ for (size_t i = 0; i < payloadLen; ++i) {+ uint8_t b = data[headerSize + i];+ if (masked) b ^= maskKey[i % 4];+ outFrame.payload[i] = b;+ }+ bytesConsumed = headerSize + static_cast<size_t>(payloadLen);+ return true;+}++} // namespace ws++bool parseGamepadJson(const json::Value& val, int& outSlot, input::ControllerState& outState) {+ if (!val.isObject()) return false;+ int slot = 0;+ if (val.has("playerIndex")) {+ slot = static_cast<int>(val["playerIndex"].asInt(0));+ } else if (val.has("player")) {+ int p = static_cast<int>(val["player"].asInt(1));+ slot = p - 1;+ }+ slot = std::clamp(slot, 0, 3);+ outSlot = slot;++ outState = input::ControllerState{};+ outState.connected = true;++ auto readButton = [](const json::Value& b) -> bool {+ if (b.isBool()) return b.asBool();+ if (b.isNumber()) return b.asNumber() > 0.5;+ if (b.isObject()) {+ if (b.has("pressed")) return b["pressed"].asBool();+ if (b.has("value")) return b["value"].asNumber() > 0.5;+ }+ return false;+ };++ auto readTrigger = [](const json::Value& b) -> float {+ if (b.isNumber()) return static_cast<float>(b.asNumber(0.0));+ if (b.isBool()) return b.asBool() ? 1.0f : 0.0f;+ if (b.isObject() && b.has("value")) return static_cast<float>(b["value"].asNumber(0.0));+ if (b.isObject() && b.has("pressed")) return b["pressed"].asBool() ? 1.0f : 0.0f;+ return 0.0f;+ };++ // 1. W3C Gamepad API standard arrays+ if (val.has("buttons") && val["buttons"].isArray()) {+ const auto& arr = val["buttons"];+ size_t n = arr.size();+ if (n > 0) outState.btnA = readButton(arr[0]);+ if (n > 1) outState.btnB = readButton(arr[1]);+ if (n > 2) outState.btnX = readButton(arr[2]);+ if (n > 3) outState.btnY = readButton(arr[3]);+ if (n > 4) outState.btnL1 = readButton(arr[4]);+ if (n > 5) outState.btnR1 = readButton(arr[5]);+ if (n > 6) outState.triggerL2 = readTrigger(arr[6]);+ if (n > 7) outState.triggerR2 = readTrigger(arr[7]);+ if (n > 8) outState.btnTouchpad = readButton(arr[8]); // Select / View+ if (n > 9) outState.btnOptions = readButton(arr[9]); // Start / Menu+ if (n > 10) outState.btnL3 = readButton(arr[10]);+ if (n > 11) outState.btnR3 = readButton(arr[11]);+ if (n > 12) outState.dpadUp = readButton(arr[12]);+ if (n > 13) outState.dpadDown = readButton(arr[13]);+ if (n > 14) outState.dpadLeft = readButton(arr[14]);+ if (n > 15) outState.dpadRight = readButton(arr[15]);+ if (n > 16) outState.btnNexus = readButton(arr[16]); // Xbox / Guide+ }++ if (val.has("axes") && val["axes"].isArray()) {+ const auto& arr = val["axes"];+ size_t n = arr.size();+ if (n > 0) outState.leftStickX = static_cast<float>(arr[0].asNumber(0.0));+ if (n > 1) outState.leftStickY = static_cast<float>(arr[1].asNumber(0.0));+ if (n > 2) outState.rightStickX = static_cast<float>(arr[2].asNumber(0.0));+ if (n > 3) outState.rightStickY = static_cast<float>(arr[3].asNumber(0.0));+ }++ // 2. Named / object mappings and flat fields+ auto getBool = [&](const char* k1, const char* k2 = nullptr, const char* k3 = nullptr) -> bool {+ if (val.has(k1)) return val[k1].asBool(false);+ if (k2 && val.has(k2)) return val[k2].asBool(false);+ if (k3 && val.has(k3)) return val[k3].asBool(false);+ if (val.has("buttons") && val["buttons"].isObject()) {+ const auto& b = val["buttons"];+ if (b.has(k1)) return b[k1].asBool(false);+ if (k2 && b.has(k2)) return b[k2].asBool(false);+ if (k3 && b.has(k3)) return b[k3].asBool(false);+ }+ return false;+ };++ auto getFloat = [&](const char* k1, const char* k2 = nullptr) -> float {+ if (val.has(k1)) return static_cast<float>(val[k1].asNumber(0.0));+ if (k2 && val.has(k2)) return static_cast<float>(val[k2].asNumber(0.0));+ if (val.has("axes") && val["axes"].isObject()) {+ const auto& a = val["axes"];+ if (a.has(k1)) return static_cast<float>(a[k1].asNumber(0.0));+ if (k2 && a.has(k2)) return static_cast<float>(a[k2].asNumber(0.0));+ }+ return 0.0f;+ };++ if (getBool("btnA", "a")) outState.btnA = true;+ if (getBool("btnB", "b")) outState.btnB = true;+ if (getBool("btnX", "x")) outState.btnX = true;+ if (getBool("btnY", "y")) outState.btnY = true;++ if (getBool("dpadUp", "dpad_up", "up")) outState.dpadUp = true;+ if (getBool("dpadDown", "dpad_down", "down")) outState.dpadDown = true;+ if (getBool("dpadLeft", "dpad_left", "left")) outState.dpadLeft = true;+ if (getBool("dpadRight", "dpad_right", "right")) outState.dpadRight = true;++ if (getBool("btnL1", "lb", "l1")) outState.btnL1 = true;+ if (getBool("btnR1", "rb", "r1")) outState.btnR1 = true;+ if (getBool("btnL3", "ls", "l3")) outState.btnL3 = true;+ if (getBool("btnR3", "rs", "r3")) outState.btnR3 = true;++ if (getBool("btnTouchpad", "btnView", "view")) outState.btnTouchpad = true;+ if (getBool("btnOptions", "btnMenu", "menu")) outState.btnOptions = true;+ if (getBool("btnNexus", "xbox", "guide")) outState.btnNexus = true;++ float tL = getFloat("triggerL2", "lt");+ if (tL > 0.0f) outState.triggerL2 = tL;+ float tR = getFloat("triggerR2", "rt");+ if (tR > 0.0f) outState.triggerR2 = tR;++ if (val.has("leftStickX") || val.has("lx") || (val.has("axes") && val["axes"].isObject())) {+ float lx = getFloat("leftStickX", "lx");+ if (std::abs(lx) > 0.001f) outState.leftStickX = lx;+ }+ if (val.has("leftStickY") || val.has("ly") || (val.has("axes") && val["axes"].isObject())) {+ float ly = getFloat("leftStickY", "ly");+ if (std::abs(ly) > 0.001f) outState.leftStickY = ly;+ }+ if (val.has("rightStickX") || val.has("rx") || (val.has("axes") && val["axes"].isObject())) {+ float rx = getFloat("rightStickX", "rx");+ if (std::abs(rx) > 0.001f) outState.rightStickX = rx;+ }+ if (val.has("rightStickY") || val.has("ry") || (val.has("axes") && val["axes"].isObject())) {+ float ry = getFloat("rightStickY", "ry");+ if (std::abs(ry) > 0.001f) outState.rightStickY = ry;+ }++ outState.rawLeftX = outState.leftStickX;+ outState.rawLeftY = outState.leftStickY;+ outState.rawRightX = outState.rightStickX;+ outState.rawRightY = outState.rightStickY;+ return true;+}++namespace {+struct VirtualGamepadSlot {+ input::ControllerState state{};+ uint64_t lastSeenMs = 0;+ uint64_t lastInputMs = 0;+};+std::mutex s_vpadMutex;+VirtualGamepadSlot s_virtualPads[4];++bool hasGamepadInput(const input::ControllerState& s) {+ return s.btnA || s.btnB || s.btnX || s.btnY ||+ s.dpadUp || s.dpadDown || s.dpadLeft || s.dpadRight ||+ s.btnL1 || s.btnR1 || s.btnL3 || s.btnR3 ||+ s.btnTouchpad || s.btnOptions || s.btnNexus ||+ s.triggerL2 > 0.05f || s.triggerR2 > 0.05f ||+ std::abs(s.leftStickX) > 0.08f || std::abs(s.leftStickY) > 0.08f ||+ std::abs(s.rightStickX) > 0.08f || std::abs(s.rightStickY) > 0.08f;+}+} // namespace++bool virtualGamepadState(int playerIndex, input::ControllerState& outState, bool& isConnected) {+ if (playerIndex < 0 || playerIndex >= 4) {+ isConnected = false;+ outState = {};+ return false;+ }+ std::lock_guard<std::mutex> lock(s_vpadMutex);+ uint64_t now = platform::nowMs();+ uint64_t diff = now > s_virtualPads[playerIndex].lastSeenMs ? now - s_virtualPads[playerIndex].lastSeenMs : 0;+ isConnected = (s_virtualPads[playerIndex].lastSeenMs > 0 && diff < 4000);+ if (diff < 2000) {+ outState = s_virtualPads[playerIndex].state;+ } else {+ outState = {};+ }+ return isConnected;+}++void setVirtualGamepad(int playerIndex, const input::ControllerState& state) {+ if (playerIndex < 0 || playerIndex >= 4) return;+ std::lock_guard<std::mutex> lock(s_vpadMutex);+ uint64_t now = platform::nowMs();+ bool firstSeen = (s_virtualPads[playerIndex].lastSeenMs == 0);+ s_virtualPads[playerIndex].state = state;+ s_virtualPads[playerIndex].lastSeenMs = now;+ if (firstSeen || hasGamepadInput(state)) {+ s_virtualPads[playerIndex].lastInputMs = now;+ }+}++void touchVirtualGamepad(int playerIndex) {+ if (playerIndex < 0 || playerIndex >= 4) return;+ std::lock_guard<std::mutex> lock(s_vpadMutex);+ uint64_t now = platform::nowMs();+ s_virtualPads[playerIndex].lastSeenMs = now;+ s_virtualPads[playerIndex].lastInputMs = now;+}++void switchVirtualGamepadSlot(int newSlot) {+ if (newSlot < 0 || newSlot >= 4) return;+ std::lock_guard<std::mutex> lock(s_vpadMutex);+ for (int i = 0; i < 4; ++i) {+ if (i != newSlot) {+ s_virtualPads[i] = {};+ }+ }+ uint64_t now = platform::nowMs();+ s_virtualPads[newSlot].lastSeenMs = now;+ s_virtualPads[newSlot].lastInputMs = now;+}++uint64_t virtualGamepadActiveAt(int playerIndex) {+ if (playerIndex < 0 || playerIndex >= 4) return 0;+ std::lock_guard<std::mutex> lock(s_vpadMutex);+ return s_virtualPads[playerIndex].lastInputMs;+}++void resetVirtualGamepads() {+ std::lock_guard<std::mutex> lock(s_vpadMutex);+ for (auto& slot : s_virtualPads) slot = {};+}++} // namespace xc::appdiff --git a/src/app/web_server_html.cpp b/src/app/web_server_html.cppnew file mode 100644index 0000000..b7de86f--- /dev/null+++ b/src/app/web_server_html.cpp@@ -0,0 +1,2356 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/web_server.h"++namespace xc::app {++namespace {++const char* kIndexHtml = R"html(<!DOCTYPE html>+<html lang="pt-BR">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">+<title>PSBox Cloud Gaming - Smartglass WebUI</title>+<script>+(function() {+ function applyInitScale() {+ var w = window.innerWidth || (document.documentElement ? document.documentElement.clientWidth : 360);+ var h = window.innerHeight || (document.documentElement ? document.documentElement.clientHeight : 640);+ var isLand = w > h;+ var pScale = Math.min(1, Math.max(0.4, (w - 28) / 412));+ var lsScale = Math.min(1, Math.max(0.35, Math.min((w - 24) / 915, (h - 78) / 412)));+ var fsScale = Math.min(1.2, Math.max(0.4, Math.min((w - 28) / 915, (h - 20) / 412)));+ document.documentElement.style.setProperty('--gp-scale', (isLand ? lsScale : pScale).toFixed(3));+ document.documentElement.style.setProperty('--gp-fs-scale', fsScale.toFixed(3));+ }+ applyInitScale();+ window.addEventListener('resize', applyInitScale);+})();+</script>+<style>+:root {+ --bg: #0b0d13;+ --surface: #141722;+ --surface-alt: #1c2130;+ --border: #282f44;+ --primary: #107C41;+ --primary-hover: #169c53;+ --accent: #0070d8;+ --text: #f0f3f8;+ --text-dim: #9aa4b8;+ --danger: #d93838;+}+* { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }+html { width: 100%; max-width: 100%; background: var(--bg); }+body { width: 100%; max-width: 100%; margin: 0; padding: 0; overflow-x: hidden; overflow-y: auto; background: var(--bg); color: var(--text); -webkit-overflow-scrolling: touch; overscroll-behavior-y: none; }+header { box-sizing: border-box; background: var(--surface); border-bottom: 1px solid var(--border); padding-top: max(18px, env(safe-area-inset-top, 18px)); padding-bottom: 12px; padding-left: max(16px, env(safe-area-inset-left, 16px)); padding-right: max(16px, env(safe-area-inset-right, 16px)); display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; max-width: 100%; overflow-x: hidden; }+.brand { display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1 1 auto; }+.logo-icon { flex-shrink: 0; width: 32px; height: 32px; border-radius: 50%; box-shadow: 0 0 10px rgba(16, 124, 65, 0.45); }+.brand-text { min-width: 0; flex: 1 1 auto; }+.brand-text h1 { font-size: clamp(0.76rem, 3.6vw, 0.96rem); font-weight: 700; letter-spacing: 0.5px; color: #fff; text-transform: uppercase; line-height: 1.2; white-space: nowrap; }+.brand-subtitle { font-size: 0.70rem; color: var(--text-dim); display: block; font-weight: 500; white-space: nowrap; }+header .badge { background: var(--primary); color: #fff; font-size: 0.70rem; padding: 3px 7px; border-radius: 12px; font-weight: 600; text-transform: uppercase; flex-shrink: 0; }+.nav-tabs { display: grid; grid-template-columns: repeat(3, 1fr); background: var(--surface); border-bottom: 1px solid var(--border); width: 100%; max-width: 100%; overflow: hidden; }+.nav-tab { min-width: 0; text-align: center; padding: 11px 4px; min-height: 44px; display: flex; align-items: center; justify-content: center; font-size: clamp(0.74rem, 2.8vw, 0.86rem); font-weight: 600; color: var(--text-dim); border-bottom: 2px solid transparent; border-right: 1px solid rgba(40, 47, 68, 0.45); border-top: 1px solid rgba(40, 47, 68, 0.45); cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; user-select: none; -webkit-user-select: none; touch-action: manipulation; -webkit-tap-highlight-color: transparent; }+.nav-tab.active { color: #fff; border-bottom-color: var(--primary); background: var(--surface-alt); }+.tab-pane { display: none !important; height: 0 !important; max-height: 0 !important; overflow: hidden !important; width: 100%; }+.tab-pane.active { display: block !important; height: auto !important; max-height: none !important; overflow: visible !important; }+.content { max-width: 680px; width: 100%; margin: 12px auto 0 auto; padding: 0 12px 20px 12px; overflow-x: hidden; }+.subnav { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; width: 100%; max-width: 100%; }+.subnav .btn { flex: 1 1 120px; }+.subnav .btn.active { background: var(--primary); border-color: var(--primary); }+.card { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 14px; margin-bottom: 14px; width: 100%; max-width: 100%; overflow-x: hidden; }+.card:last-child { margin-bottom: 0 !important; }+.card h2 { font-size: 1.0rem; margin-bottom: 8px; font-weight: 600; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+.card p { font-size: 0.82rem; color: var(--text-dim); margin-bottom: 12px; line-height: 1.4; word-break: break-word; }++/* Search tabs & chips */+.search-tabs { display: flex; gap: 8px; margin-bottom: 12px; width: 100%; max-width: 100%; }+.search-tab { flex: 1 1 0; min-width: 0; padding: 10px 8px; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; color: var(--text-dim); font-size: clamp(0.82rem, 3.4vw, 0.88rem); font-weight: 600; cursor: pointer; transition: all 0.2s; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; outline: none; }+.search-tab:hover { border-color: var(--primary); color: #fff; }+.search-tab.active { background: var(--primary); border-color: var(--primary); color: #fff; box-shadow: 0 2px 8px rgba(16, 124, 65, 0.4); }+.filter-section { margin-top: 12px; margin-bottom: 12px; width: 100%; max-width: 100%; }+.filter-label { font-size: 0.76rem; font-weight: 600; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }+.filter-chips { display: flex; flex-wrap: wrap; gap: 8px; width: 100%; max-width: 100%; }+.chip { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 6px 11px; border-radius: 20px; font-size: 0.80rem; font-weight: 600; background: var(--surface-alt); border: 1px solid var(--border); color: var(--text-dim); cursor: pointer; transition: all 0.2s; user-select: none; max-width: 100%; outline: none; white-space: nowrap; }+.chip:hover { border-color: var(--primary-hover); color: var(--text); }+.chip.active { background: rgba(16, 124, 65, 0.28); border-color: var(--primary); color: #4ade80; }+.chip-select { display: inline-flex; align-items: center; gap: 5px; padding: 4px 9px; border-radius: 20px; background: var(--surface-alt); border: 1px solid var(--border); font-size: 0.80rem; color: var(--text-dim); font-weight: 600; max-width: 100%; }+.chip-select.active { border-color: var(--primary); background: rgba(16, 124, 65, 0.28); color: #4ade80; }+.chip-select select { background: transparent; border: none; color: #fff; font-size: 0.80rem; font-weight: 600; outline: none; cursor: pointer; padding: 2px 0; max-width: 100%; }+.chip-select select option { background: var(--surface); color: #fff; }++.input-group { display: flex; gap: 8px; margin-bottom: 12px; width: 100%; max-width: 100%; }+input[type="text"] { flex: 1 1 auto; min-width: 0; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; font-size: 0.92rem; color: #fff; outline: none; transition: border-color 0.2s; }+input[type="text"]:focus { border-color: var(--primary); }+.btn { display: inline-flex; align-items: center; justify-content: center; background: var(--surface-alt); color: #fff; border: 1px solid var(--border); border-radius: 10px; padding: 10px 14px; min-height: 44px; font-size: 0.86rem; font-weight: 600; cursor: pointer; text-decoration: none; transition: background 0.15s, border-color 0.15s; max-width: 100%; white-space: normal; text-align: center; touch-action: manipulation; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; }+.btn:hover { background: var(--border); }+.btn-primary { background: var(--primary); border-color: var(--primary); color: #fff; }+.btn-primary:hover { background: var(--primary-hover); }+.status-pill { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 20px; font-size: 0.80rem; background: rgba(16, 124, 65, 0.2); color: #4ade80; border: 1px solid rgba(16, 124, 65, 0.4); margin-top: 4px; max-width: 100%; word-break: break-word; }+.status-dot { width: 8px; height: 8px; border-radius: 50%; background: #4ade80; flex-shrink: 0; }+.grid-map { display: grid; grid-template-columns: 1fr; gap: 8px; margin-top: 12px; width: 100%; max-width: 100%; }+@media (min-width: 580px) {+ .grid-map { grid-template-columns: repeat(2, 1fr); }+}+.map-item { background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 9px 11px; display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%; max-width: 100%; min-width: 0; flex-wrap: wrap; }+.map-item label { font-size: 0.84rem; font-weight: 600; flex: 1 1 110px; min-width: 0; word-break: break-word; }+.selects-wrap { display: flex; gap: 6px; flex-wrap: wrap; flex: 1 1 180px; min-width: 0; justify-content: flex-end; }+.selects-wrap select { flex: 1 1 calc(50% - 4px); min-width: 85px; max-width: 100%; }+.map-item > select { flex: 0 1 auto; max-width: 100%; min-width: 0; }+select { background: var(--surface); color: #fff; border: 1px solid var(--border); border-radius: 8px; padding: 7px 9px; font-size: 0.80rem; outline: none; min-width: 0; }+.btn-row { margin-top: 16px; display: flex; gap: 8px; flex-wrap: wrap; width: 100%; max-width: 100%; }+.btn-row .btn { flex: 1 1 130px; }+pre { background: #07080b; border: 1px solid var(--border); border-radius: 10px; padding: 12px; font-family: monospace; font-size: 0.78rem; color: #c4ccdc; overflow-x: auto; max-height: 380px; white-space: pre-wrap; word-break: break-all; max-width: 100%; }+.toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: #169c53; color: #fff; padding: 10px 20px; border-radius: 24px; font-size: 0.88rem; font-weight: 600; box-shadow: 0 4px 16px rgba(0,0,0,0.5); opacity: 0; pointer-events: none; transition: opacity 0.3s; z-index: 10000; max-width: 90%; text-align: center; }+.toast.show { opacity: 1; }++/* Telemetry & interactive controls */+.telemetry-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 14px; width: 100%; }+.tel-item { background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 9px 6px; text-align: center; }+.tel-val { font-size: 1.10rem; font-weight: 700; color: #4ade80; }+.tel-lbl { font-size: 0.70rem; color: var(--text-dim); text-transform: uppercase; margin-top: 3px; }+.slider-group { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; width: 100%; }+.slider-header { display: flex; justify-content: space-between; font-size: 0.84rem; font-weight: 600; }+.slider-val { color: #4ade80; }+input[type="range"] { width: 100%; accent-color: var(--primary); margin: 6px 0; }+.toggle-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--border); }+.toggle-label { font-size: 0.86rem; font-weight: 600; }+.switch { position: relative; display: inline-block; width: 44px; height: 24px; flex-shrink: 0; }+.switch input { opacity: 0; width: 0; height: 0; }+.slider-sw { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--surface-alt); border: 1px solid var(--border); border-radius: 24px; transition: .25s; }+.slider-sw:before { position: absolute; content: ""; height: 16px; width: 16px; left: 3px; bottom: 3px; background-color: white; border-radius: 50%; transition: .25s; }+input:checked + .slider-sw { background-color: var(--primary); border-color: var(--primary); }+input:checked + .slider-sw:before { transform: translateX(20px); }+.btn-danger { background: var(--danger); border-color: var(--danger); color: #fff; }+.btn-danger:hover { background: #b82626; }+.section-sub { font-size: 0.86rem; font-weight: 700; color: #4ade80; margin: 14px 0 6px 0; display: flex; align-items: center; justify-content: space-between; }++/* Search overlay when streaming */+.search-disabled-overlay {+ position: absolute;+ top: 0; left: 0; right: 0; bottom: 0;+ background: rgba(11, 13, 19, 0.85);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ display: none;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ border-radius: 14px;+ z-index: 50;+ color: #fff;+ text-align: center;+ padding: 20px;+}+.search-disabled-overlay .msg {+ font-size: 0.95rem;+ font-weight: 700;+ letter-spacing: 0.6px;+ background: rgba(20, 23, 34, 0.95);+ border: 1px solid var(--border);+ padding: 12px 22px;+ border-radius: 20px;+ box-shadow: 0 4px 16px rgba(0,0,0,0.6);+ display: inline-flex;+ align-items: center;+ gap: 8px;+}++/* Virtual Gamepad */+.gamepad-toolbar {+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: flex-end;+ flex-wrap: wrap;+ margin-bottom: 8px;+}+.gamepad-container {+ user-select: none;+ -webkit-user-select: none;+ touch-action: none;+ width: 100%;+ max-width: 100%;+ display: flex;+ flex-direction: column;+ gap: 12px;+}+.player-select-row {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 6px;+ width: 100%;+ margin-bottom: 6px;+}+.player-btn {+ padding: 8px 6px;+ min-height: 42px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 10px;+ border: 1px solid var(--border);+ background: var(--surface-alt);+ color: var(--text-dim);+ font-size: clamp(0.74rem, 2.8vw, 0.84rem);+ font-weight: 700;+ cursor: pointer;+ text-align: center;+ transition: all 0.15s;+ touch-action: manipulation;+ user-select: none;+ -webkit-user-select: none;+ -webkit-tap-highlight-color: transparent;+}+.player-btn.active {+ background: var(--primary);+ border-color: var(--primary);+ color: #fff;+ box-shadow: 0 2px 8px rgba(16, 124, 65, 0.4);+}+/* Virtual Gamepad Viewport & Modules (Exact Layout Studio Match) */+:root {+ --gp-scale: 1;+ --gp-fs-scale: 1;+}+#tab-gamepad #gamepadCard {+ padding-left: 4px;+ padding-right: 4px;+}++.gamepad-viewport-wrapper {+ width: 100%;+ display: flex;+ justify-content: center;+ align-items: flex-start;+ overflow: hidden;+}+.gamepad-container {+ position: relative;+ background: transparent;+ user-select: none;+ -webkit-user-select: none;+ touch-action: none !important;+}+.gamepad-module {+ position: absolute;+ transform-origin: center center;+ display: flex;+ align-items: center;+ justify-content: center;+ touch-action: none !important;+ box-sizing: border-box;+}++/* Stick Styling (Matching Layout Studio) */+.stick-base {+ position: relative;+ width: 146px;+ height: 146px;+ border-radius: 50%;+ background: radial-gradient(circle at 50% 50%, #1a2233 0%, #0d121c 100%);+ border: 2px solid #334155;+ box-shadow: inset 0 3px 10px rgba(0,0,0,0.8), 0 3px 8px rgba(0,0,0,0.5);+ display: flex;+ align-items: center;+ justify-content: center;+ touch-action: none;+}+.stick-head {+ width: 62px;+ height: 62px;+ border-radius: 50%;+ background: radial-gradient(circle at 35% 35%, #475569, #1e293b);+ border: 2px solid #64748b;+ box-shadow: 0 4px 12px rgba(0,0,0,0.7);+ pointer-events: none;+ transform: translate(0px, 0px);+ display: flex;+ align-items: center;+ justify-content: center;+}+.stick-head::after {+ content: '';+ width: 45%;+ height: 45%;+ border-radius: 50%;+ border: 1.5px solid rgba(255, 255, 255, 0.2);+ background: radial-gradient(circle, #1e293b 0%, #334155 100%);+ box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.7);+}++/* D-Pad Styling (Matching Layout Studio) */+.dpad-container {+ position: relative;+ width: 150px;+ height: 150px;+}+.dpad-arm {+ position: absolute;+ border-radius: 10px;+ background: #1e2538;+ border: 1.5px solid #3e4d70;+ color: #94a3b8;+ font-weight: 900;+ display: flex;+ align-items: center;+ justify-content: center;+ box-shadow: 0 3px 6px rgba(0,0,0,0.4);+ transition: transform 0.06s, background 0.06s;+ cursor: pointer;+ touch-action: none;+ user-select: none;+}+.dpad-arm:active, .dpad-arm.pressed {+ transform: scale(0.92);+ background: #107c41 !important;+ color: #fff !important;+ border-color: #4ade80 !important;+ box-shadow: 0 0 12px rgba(16, 124, 65, 0.8) !important;+}+.dpad-arm-up { top: 0; left: 33.33%; width: 33.33%; height: 35%; }+.dpad-arm-down { bottom: 0; left: 33.33%; width: 33.33%; height: 35%; }+.dpad-arm-left { top: 33.33%; left: 0; width: 35%; height: 33.33%; }+.dpad-arm-right { top: 33.33%; right: 0; width: 35%; height: 33.33%; }+.dpad-mid {+ position: absolute;+ top: 33.33%; left: 33.33%;+ width: 33.33%; height: 33.33%;+ background: #151a27;+ border-radius: 4px;+ pointer-events: none;+}++/* ABXY Styling (Matching Layout Studio) */+.abxy-container {+ position: relative;+ width: 156px;+ height: 156px;+}+.abxy-key {+ position: absolute;+ width: 52px;+ height: 52px;+ border-radius: 50%;+ font-weight: 900;+ font-size: 1.3rem;+ color: #fff;+ display: flex;+ align-items: center;+ justify-content: center;+ border-width: 2px;+ box-shadow: 0 3px 8px rgba(0,0,0,0.5);+ transition: filter 0.06s, box-shadow 0.06s;+ cursor: pointer;+ touch-action: none;+ user-select: none;+ -webkit-user-select: none;+ -webkit-tap-highlight-color: transparent;+}+.abxy-key:active, .abxy-key.pressed {+ box-shadow: 0 0 16px rgba(255,255,255,0.85) !important;+ filter: brightness(1.35) !important;+}+.btn-y { top: 0; left: 52px; background: #c68900; border-color: #ffd000; }+.btn-a { bottom: 0; left: 52px; background: #0e6b37; border-color: #22c55e; }+.btn-x { top: 52px; left: 0; background: #006eb8; border-color: #38bdf8; }+.btn-b { top: 52px; right: 0; background: #b80d1b; border-color: #f87171; }++/* Buttons & System Styling */+.pad-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: #1e2538;+ border: 1.5px solid #3e4d70;+ border-radius: 10px;+ color: #fff;+ font-weight: 700;+ box-shadow: 0 2px 6px rgba(0,0,0,0.3);+ transition: transform 0.06s, background 0.06s;+ cursor: pointer;+ touch-action: none;+ user-select: none;+ width: 100%;+ height: 100%;+}+.pad-btn:active, .pad-btn.pressed {+ transform: scale(0.92);+ background: #107c41 !important;+ border-color: #4ade80 !important;+ box-shadow: 0 0 12px rgba(16, 124, 65, 0.7) !important;+}+.pad-btn-trigger {+ font-weight: 800;+ font-size: 1.05rem;+ background: linear-gradient(180deg, #2e3a54, #182030);+ border: 1.5px solid #4a5c82;+ border-radius: 12px;+}+.pad-btn-bumper {+ font-weight: 700;+ font-size: 0.92rem;+ border-radius: 10px;+}+.pad-btn-stick-click {+ font-size: 0.82rem;+ color: #94a3b8;+ border-radius: 8px;+}+.center-sys-container {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ width: 100%;+ height: 100%;+}+.pad-btn-sys {+ padding: 4px 10px;+ font-size: 11px;+ font-weight: 800;+ height: 36px;+ border-radius: 8px;+}+.pad-btn-nexus-btn {+ width: 38px;+ height: 38px;+ border-radius: 50%;+ background: #107c41;+ border: 2px solid #ffffff;+ font-weight: 900;+ font-size: 12px;+ color: #ffffff;+ box-shadow: 0 4px 10px rgba(0,0,0,0.6);+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ touch-action: none;+ flex-shrink: 0;+}+.pad-btn-nexus-btn:active, .pad-btn-nexus-btn.pressed {+ transform: scale(0.92);+ filter: brightness(1.2);+}++/* Player Bar Styling (Clean minimalist capsule matching studio) */+.player-bar-container {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 5px;+ background: rgba(15, 23, 42, 0.9);+ padding: 3px 6px;+ border-radius: 12px;+ border: 1px solid #1e293b;+ width: 100%;+ height: 100%;+}+.player-pill {+ padding: 3px 8px;+ font-size: 11px;+ font-weight: 800;+ border-radius: 8px;+ background: transparent;+ color: #94a3b8;+ border: none;+ cursor: pointer;+ transition: all 0.1s;+}+.player-pill.active {+ background: #107c41;+ color: #ffffff;+ box-shadow: 0 0 8px rgba(16, 124, 65, 0.6);+}+.fs-only-exit { display: none; }++/* Portrait Layout Positions (Exact Layout Studio Alignment) */+#gamepadArea {+ width: 412px !important;+ min-width: 412px !important;+ max-width: 412px !important;+ flex-shrink: 0 !important;+ height: 680px;+}+#gamepadArea #mod_player_bar { left: 130px; top: 10px; width: 152px !important; height: 44px; transform: scale(1.0); }+#gamepadArea #mod_center_sys { left: 115px; top: 62px; width: 182px; height: 56px; transform: scale(1.0); }+#gamepadArea #mod_btn_ls { left: 16px; top: 132px; width: 56px; height: 52px; transform: scale(1.25); }+#gamepadArea #mod_btn_rs { left: 340px; top: 132px; width: 56px; height: 52px; transform: scale(1.25); }+#gamepadArea #mod_btn_lt { left: 10px; top: 206px; width: 98px; height: 56px; transform: scale(1.0); }+#gamepadArea #mod_btn_lb { left: 116px; top: 207px; width: 78px; height: 52px; transform: scale(1.0); }+#gamepadArea #mod_btn_rb { left: 218px; top: 207px; width: 78px; height: 52px; transform: scale(1.0); }+#gamepadArea #mod_btn_rt { left: 304px; top: 206px; width: 98px; height: 56px; transform: scale(1.0); }+#gamepadArea #mod_stick_left { left: 21px; top: 282px; width: 166px; height: 166px; transform: scale(1.15); }+#gamepadArea #mod_abxy { left: 218px; top: 282px; width: 176px; height: 176px; transform: scale(1.15); }+#gamepadArea #mod_dpad { left: 19px; top: 488px; width: 160px !important; height: 160px; transform: scale(1.0); }+#gamepadArea #mod_stick_right { left: 225px; top: 490px; width: 166px; height: 166px; transform: scale(1.0); }++/* Responsive scale wrapper for Portrait */+@media (orientation: portrait), (max-width: 600px) and (orientation: portrait) {+ .gamepad-viewport-wrapper {+ height: calc(680px * var(--gp-scale, 0.82));+ }+ #gamepadArea {+ transform: scale(var(--gp-scale, 0.82));+ transform-origin: top center;+ }+}++/* Landscape Layout Positions (Exact Layout Studio Alignment) */+@media (orientation: landscape), (max-height: 520px) {+ .gamepad-status-bar {+ display: none !important;+ }+ .gamepad-viewport-wrapper {+ height: calc(412px * var(--gp-scale, 0.8));+ min-height: calc(412px * var(--gp-scale, 0.8));+ display: flex;+ justify-content: center;+ align-items: flex-start;+ overflow: hidden;+ }+ #gamepadArea {+ width: 915px !important;+ min-width: 915px !important;+ max-width: 915px !important;+ flex-shrink: 0 !important;+ height: 412px !important;+ transform: scale(var(--gp-scale, 0.8));+ transform-origin: top center !important;+ }+ #gamepadArea #mod_btn_lt { left: 10px; top: 10px; width: 94px; height: 54px; transform: scale(1.0); }+ #gamepadArea #mod_btn_lb { left: 110px; top: 11px; width: 76px; height: 52px; transform: scale(1.0); }+ #gamepadArea #mod_btn_ls { left: 192px; top: 11px; width: 54px; height: 52px; transform: scale(1.0); }+ #gamepadArea #mod_player_bar { left: 381px; top: 12px; width: 152px !important; height: 44px; transform: scale(1.0); }+ #gamepadArea #mod_center_sys { left: 342px; top: 66px; width: 230px; height: 56px; transform: scale(1.0); }+ #gamepadArea #mod_btn_rs { left: 669px; top: 11px; width: 54px; height: 52px; transform: scale(1.0); }+ #gamepadArea #mod_btn_rb { left: 729px; top: 11px; width: 76px; height: 52px; transform: scale(1.0); }+ #gamepadArea #mod_btn_rt { left: 811px; top: 10px; width: 94px; height: 54px; transform: scale(1.0); }+ #gamepadArea #mod_stick_left { left: 32px; top: 97px; width: 166px; height: 166px; transform: scale(1.3); }+ #gamepadArea #mod_abxy { left: 712px; top: 97px; width: 176px; height: 176px; transform: scale(1.3); }+ #gamepadArea #mod_dpad { left: 205px; top: 242px; width: 160px !important; height: 160px; transform: scale(1.05); }+ #gamepadArea #mod_stick_right { left: 545px; top: 240px; width: 166px; height: 166px; transform: scale(1.2); }+}++/* Fullscreen Mode (Landscape) */+#gamepadCard.gamepad-fullscreen, #gamepadCard:fullscreen, #gamepadCard:-webkit-full-screen {+ position: fixed !important;+ inset: 0 !important;+ width: 100vw !important;+ height: 100dvh !important;+ max-width: 100vw !important;+ margin: 0 !important;+ border-radius: 0 !important;+ border: none !important;+ z-index: 9999 !important;+ background: radial-gradient(circle at 50% 35%, #161c2c 0%, #090b11 100%) !important;+ padding: env(safe-area-inset-top, 0) env(safe-area-inset-right, 14px) env(safe-area-inset-bottom, 8px) env(safe-area-inset-left, 14px) !important;+ display: flex !important;+ align-items: center !important;+ justify-content: center !important;+ overflow: hidden !important;+}+#gamepadCard.gamepad-fullscreen .gamepad-intro,+#gamepadCard:fullscreen .gamepad-intro,+#gamepadCard:-webkit-full-screen .gamepad-intro,+#gamepadCard.gamepad-fullscreen .gamepad-status-bar,+#gamepadCard:fullscreen .gamepad-status-bar,+#gamepadCard:-webkit-full-screen .gamepad-status-bar {+ display: none !important;+}+#gamepadCard.gamepad-fullscreen .fs-only-exit,+#gamepadCard:fullscreen .fs-only-exit,+#gamepadCard:-webkit-full-screen .fs-only-exit {+ display: inline-flex !important;+}+#gamepadCard.gamepad-fullscreen .gamepad-viewport-wrapper,+#gamepadCard:fullscreen .gamepad-viewport-wrapper,+#gamepadCard:-webkit-full-screen .gamepad-viewport-wrapper {+ width: calc(915px * var(--gp-fs-scale, 0.85)) !important;+ height: calc(412px * var(--gp-fs-scale, 0.85)) !important;+ max-width: 100% !important;+ max-height: 100% !important;+ display: flex !important;+ align-items: flex-start !important;+ justify-content: center !important;+ overflow: hidden !important;+ position: relative !important;+}+#gamepadCard.gamepad-fullscreen #gamepadArea,+#gamepadCard:fullscreen #gamepadArea,+#gamepadCard:-webkit-full-screen #gamepadArea {+ width: 915px !important;+ min-width: 915px !important;+ max-width: 915px !important;+ flex-shrink: 0 !important;+ height: 412px !important;+ transform: scale(var(--gp-fs-scale, 0.85)) !important;+ transform-origin: top center !important;+}+#gamepadCard.gamepad-fullscreen #mod_btn_lt { left: 10px !important; top: 10px !important; width: 94px !important; height: 54px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_btn_lb { left: 110px !important; top: 11px !important; width: 76px !important; height: 52px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_btn_ls { left: 192px !important; top: 11px !important; width: 54px !important; height: 52px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_player_bar { left: 381px !important; top: 12px !important; width: 152px !important; height: 44px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_center_sys { left: 342px !important; top: 66px !important; width: 230px !important; height: 56px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_btn_rs { left: 669px !important; top: 11px !important; width: 54px !important; height: 52px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_btn_rb { left: 729px !important; top: 11px !important; width: 76px !important; height: 52px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_btn_rt { left: 811px !important; top: 10px !important; width: 94px !important; height: 54px !important; transform: scale(1.0) !important; }+#gamepadCard.gamepad-fullscreen #mod_stick_left { left: 32px !important; top: 97px !important; width: 166px !important; height: 166px !important; transform: scale(1.3) !important; }+#gamepadCard.gamepad-fullscreen #mod_abxy { left: 712px !important; top: 97px !important; width: 176px !important; height: 176px !important; transform: scale(1.3) !important; }+#gamepadCard.gamepad-fullscreen #mod_dpad { left: 205px !important; top: 242px !important; width: 160px !important; height: 160px !important; transform: scale(1.05) !important; }+#gamepadCard.gamepad-fullscreen #mod_stick_right { left: 545px !important; top: 240px !important; width: 166px !important; height: 166px !important; transform: scale(1.2) !important; }++@media (max-width: 600px) {+ .nav-tabs { grid-template-columns: repeat(3, 1fr); }+ .nav-tab { padding: 9px 4px; font-size: 0.74rem; }+ .telemetry-grid { grid-template-columns: repeat(2, 1fr); }+ .content { padding-left: 6px; padding-right: 6px; }+ #tab-gamepad #gamepadCard { padding-left: 2px; padding-right: 2px; }+}++@media (orientation: landscape), (max-height: 520px) {+ .nav-tabs {+ grid-template-columns: repeat(6, 1fr);+ gap: 4px;+ }+ .nav-tab {+ min-height: 36px;+ padding: 5px 2px;+ font-size: 0.72rem;+ }+ header {+ display: none !important;+ }+ .content {+ max-width: 960px;+ margin: 2px auto 0 auto;+ padding: 0 4px 6px 4px;+ }+ .card {+ padding: 4px 8px;+ margin-bottom: 0 !important;+ }+ .card h2 {+ font-size: 0.88rem;+ margin-bottom: 4px;+ }+ .card p {+ font-size: 0.76rem;+ margin-bottom: 6px;+ }+ .gamepad-intro {+ display: block;+ margin-bottom: 2px;+ }+ .gamepad-toolbar {+ margin-bottom: 2px;+ justify-content: flex-end;+ }+ .gamepad-status-bar {+ display: none !important;+ }+}+</style>+</head>+<body>+<header>+ <div class="brand">+ <svg class="logo-icon" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">+ <circle cx="50" cy="50" r="50" fill="#ffffff"/>+ <path fill="#107C41" d="M 50.00 40.10 s 0.12 0.00 0.00 0.00 c 15.07 11.46 40.60 39.60 32.88 47.57 -8.84 7.72 -20.30 12.33 -32.88 12.33 s -24.16 -4.61 -32.88 -12.33 c -7.85 -7.97 17.81 -36.11 32.75 -47.45 0.00 -0.12 0.12 -0.12 0.12 -0.12 z m 26.03 -32.75 C 68.43 2.74 60.09 0.00 50.00 0.00 s -18.43 2.74 -26.03 7.35 c -0.12 0.00 -0.12 0.12 -0.12 0.25 s 0.12 0.12 0.25 0.12 c 9.71 -2.12 24.41 6.23 25.78 7.10 h 0.25 c 1.37 -0.87 16.06 -9.22 25.78 -7.10 0.12 0.00 0.25 0.00 0.25 -0.12 s 0.00 -0.25 -0.12 -0.25 z M 15.01 14.32 c -0.12 0.00 -0.12 0.12 -0.25 0.12 -9.09 9.09 -14.69 21.67 -14.69 35.49 0.00 11.33 3.86 21.92 10.21 30.26 0.00 0.12 0.12 0.12 0.25 0.12 s 0.12 -0.12 0.00 -0.25 c -3.86 -11.83 15.69 -40.35 25.78 -52.30 l 0.12 -0.12 c 0.00 -0.12 0.00 -0.12 -0.12 -0.12 -15.32 -15.19 -20.42 -13.57 -21.30 -13.20 z m 48.69 13.08 l -0.12 0.12 s 0.00 0.12 0.12 0.12 c 10.09 11.96 29.51 40.47 25.78 52.30 v 0.25 c 0.12 0.00 0.25 0.00 0.25 -0.12 6.35 -8.34 10.21 -18.93 10.21 -30.26 0.00 -13.82 -5.60 -26.40 -14.82 -35.49 -0.12 -0.12 -0.12 -0.12 -0.25 -0.12 -0.75 -0.25 -5.85 -1.87 -21.17 13.20 z"/>+ </svg>+ <div class="brand-text">+ <h1>PSBOX CLOUD GAMING</h1>+ <span class="brand-subtitle">Smartglass WebUI</span>+ </div>+ </div>+ <span class="badge">v)html" XC_APP_VERSION R"html(</span>+</header>++<div class="nav-tabs">+ <div class="nav-tab active" id="navTab-search" onclick="switchTab('search')">🔍 Busca</div>+ <div class="nav-tab" id="navTab-settings" onclick="switchTab('settings')">⚙️ Configurações</div>+ <div class="nav-tab" id="navTab-stream" onclick="switchTab('stream')">📺 Jogo Atual</div>+ <div class="nav-tab" id="navTab-remap" onclick="switchTab('remap')">🎮 Mapeamento</div>+ <div class="nav-tab" id="navTab-gamepad" onclick="switchTab('gamepad')">🕹️ Controle</div>+ <div class="nav-tab" id="navTab-logs" onclick="switchTab('logs')">📋 Logs</div>+</div>++<div class="content">+ <!-- TAB: SETTINGS -->+ <div id="tab-settings" class="tab-pane" style="display:none;">+ <div class="card">+ <h2>⚙️ Configurações Gerais</h2>+ <p>Ajuste opções gráficas, de controle e comportamento do aplicativo.</p>++ <div class="slider-group">+ <div class="slider-header">+ <span>Bitrate Máximo</span>+ <span class="slider-val" id="valBitrate">Auto</span>+ </div>+ <input type="range" id="inputBitrate" min="0" max="50" step="5" value="0" oninput="onBitrateInput(this.value)">+ </div>++ <div class="toggle-row">+ <span class="toggle-label">Modo 120 Hz (High Refresh / VRR)</span>+ <label class="switch">+ <input type="checkbox" id="check120Hz" onchange="markSettingsChanged()">+ <span class="slider-sw"></span>+ </label>+ </div>++ <div class="slider-group" style="margin-top: 10px;">+ <div class="slider-header">+ <span>Zona Morta - Analógico Esquerdo (L)</span>+ <span class="slider-val" id="valDeadzoneL">15%</span>+ </div>+ <input type="range" id="inputDeadzoneL" min="0" max="50" step="1" value="15" oninput="document.getElementById('valDeadzoneL').textContent=this.value+'%'; markSettingsChanged()">+ </div>++ <div class="slider-group">+ <div class="slider-header">+ <span>Zona Morta - Analógico Direito (R)</span>+ <span class="slider-val" id="valDeadzoneR">15%</span>+ </div>+ <input type="range" id="inputDeadzoneR" min="0" max="50" step="1" value="15" oninput="document.getElementById('valDeadzoneR').textContent=this.value+'%'; markSettingsChanged()">+ </div>++ <div class="slider-group">+ <div class="slider-header">+ <span>Vibração dos Gatilhos</span>+ <span class="slider-val" id="valTriggerStrength">2</span>+ </div>+ <input type="range" id="inputTriggerStrength" min="0" max="4" step="1" value="2" oninput="document.getElementById('valTriggerStrength').textContent=this.value; markSettingsChanged()">+ </div>++ <div class="map-item" style="margin-bottom: 10px;">+ <label>Barra de Luz DualSense</label>+ <select id="selectLightBarMode" onchange="onLightBarModeChange()">+ <option value="0">Cor do Jogo</option>+ <option value="1">Cor Personalizada</option>+ <option value="2">Desativada</option>+ </select>+ <input type="color" id="inputLightBarColor" value="#0070dc" style="margin-left: 8px; height: 32px; width: 44px; border: none; border-radius: 6px; cursor: pointer; display: none;" onchange="markSettingsChanged()">+ </div>++ <div class="toggle-row">+ <span class="toggle-label">Aviso Sonoro de Fila (Queue Chime)</span>+ <label class="switch">+ <input type="checkbox" id="checkQueueAlert" onchange="markSettingsChanged()">+ <span class="slider-sw"></span>+ </label>+ </div>++ <div class="map-item" style="margin-top: 10px;">+ <label>Decodificador de Vídeo</label>+ <select id="selectVideoDecoder" onchange="markSettingsChanged()">+ <option value="0">Hardware (libSceVideodec2 / HWAccel)</option>+ <option value="1">Software (FFmpeg CPU)</option>+ </select>+ </div>++ <div class="map-item" style="margin-top: 10px;">+ <label>Saída do Chat de Voz</label>+ <select id="selectVoiceRouting" onchange="markSettingsChanged()">+ <option value="0">Automático (Alto-falante DualSense se disponível)</option>+ <option value="1">Sempre TV / Headset Principal</option>+ </select>+ </div>++ <div class="btn-row" style="margin-top: 16px;">+ <button class="btn btn-primary" onclick="saveGeneralSettings()">Salvar Configurações</button>+ </div>+ </div>+ </div>++ <!-- TAB: STREAM (JOGO ATUAL) -->+ <div id="tab-stream" class="tab-pane" style="display:none;">+ <div class="card">+ <h2>📺 Jogo Atual & Telemetria</h2>+ <p>Métricas de transmissão em tempo real e ajustes do menu de jogo (StreamMenu).</p>++ <div class="telemetry-grid">+ <div class="tel-item"><div class="tel-val" id="telFps">--</div><div class="tel-lbl">FPS</div></div>+ <div class="tel-item"><div class="tel-val" id="telRtt">-- ms</div><div class="tel-lbl">RTT (Ping)</div></div>+ <div class="tel-item"><div class="tel-val" id="telMbps">-- Mbps</div><div class="tel-lbl">Bitrate</div></div>+ <div class="tel-item"><div class="tel-val" id="telLoss">0.0%</div><div class="tel-lbl">Perda Pkts</div></div>+ <div class="tel-item"><div class="tel-val" id="telQp">--</div><div class="tel-lbl">QP (Qualidade)</div></div>+ <div class="tel-item"><div class="tel-val" id="telDec">-- ms</div><div class="tel-lbl">Decodificação</div></div>+ </div>++ <div class="slider-group" style="margin-top: 10px;">+ <div class="slider-header">+ <span>Nitidez CAS (FidelityFX RCAS)</span>+ <span class="slider-val" id="valCas">Média</span>+ </div>+ <input type="range" id="inputCas" min="0" max="3" step="1" value="2" oninput="sendStreamParam('sharpness', parseInt(this.value)); updateCasLabel(this.value);">+ </div>++ <div class="map-item" style="margin-bottom: 10px;">+ <label>Upscaler de Imagem</label>+ <select id="selectUpscaler" onchange="sendStreamParam('upscaler', parseInt(this.value))">+ <option value="0">FSR 1.0</option>+ <option value="1">Anime4K</option>+ <option value="2">FSR 1.0 + Clean-up</option>+ <option value="3">Anime4K + Clean-up</option>+ </select>+ </div>++ <div class="map-item" style="margin-bottom: 10px;">+ <label>Suavização de Blocos (Deband)</label>+ <select id="selectDeband" onchange="sendStreamParam('deband', parseInt(this.value))">+ <option value="0">Desativada</option>+ <option value="1">Baixa</option>+ <option value="2">Alta</option>+ <option value="3">Automática (Bitrate-adaptive)</option>+ </select>+ </div>++ <div class="slider-group">+ <div class="slider-header">+ <span>Volume Alto-falante DualSense</span>+ <span class="slider-val" id="valPadSpeaker">100%</span>+ </div>+ <input type="range" id="inputPadSpeaker" min="0" max="100" step="5" value="100" oninput="document.getElementById('valPadSpeaker').textContent=this.value+'%'; sendStreamParam('padSpeakerVolume', parseInt(this.value));">+ </div>++ <div class="map-item" style="margin-bottom: 14px;">+ <label>Perfis de Gatilho Inteligente</label>+ <select id="selectSmartTriggers" onchange="sendStreamParam('triggerProfile', parseInt(this.value))">+ <option value="0">Padrão (Standard Haptics)</option>+ <option value="1">Tiro (Shooter - Hair Trigger)</option>+ <option value="2">Corrida (Racing - Progressive Resistance)</option>+ </select>+ </div>++ <div class="btn-row">+ <button class="btn btn-primary" onclick="sendStreamAction('xbox_guide')">Abrir Guia Xbox</button>+ <button class="btn btn-danger" onclick="sendStreamAction('end_session')">Encerrar Sessão</button>+ </div>+ </div>+ </div>++ <!-- TAB: SEARCH -->+ <div id="tab-search" class="tab-pane active">+ <div class="card" id="searchCard" style="position: relative;">+ <div id="searchOverlay" class="search-disabled-overlay" style="display: none;">+ <div class="msg">🔒 Desativado enquanto jogando</div>+ </div>+ <h2>🔍 Teclado Remoto para Busca</h2>+ <p>Digite no celular para atualizar a pesquisa ativa na TV em tempo real sem precisar do controle.</p>++ <!-- Search destination tabs -->+ <div class="search-tabs">+ <button class="search-tab active" id="tabBtnGamePass" type="button" onclick="setSearchTab('gamepass')">🎮 Game Pass</button>+ <button class="search-tab" id="tabBtnLibrary" type="button" onclick="setSearchTab('library')">📚 Meus jogos</button>+ </div>++ <div class="input-group">+ <input type="text" id="searchInput" placeholder="Digite o nome de um jogo..." autocomplete="off">+ <button class="btn" onclick="clearSearch()">Limpar</button>+ </div>++ <!-- Search filters -->+ <div class="filter-section">+ <div class="filter-label">Filtros da pesquisa:</div>++ <!-- Game Pass filters -->+ <div id="filtersGamePass" class="filter-chips">+ <div class="chip-select" id="chipSelectPlan">+ <label for="filterPlan">👑 Plano:</label>+ <select id="filterPlan" onchange="onFilterChange()">+ <option value="0">Meu plano</option>+ <option value="1">Ultimate</option>+ <option value="2">Premium</option>+ <option value="3">Essential</option>+ <option value="4">Todos os planos</option>+ </select>+ </div>+ <div class="chip-select" id="chipSelectConsoleGP">+ <label for="filterConsoleGP">🎮 Console:</label>+ <select id="filterConsoleGP" onchange="onFilterChange()">+ <option value="0">Todos</option>+ <option value="1">Series X|S</option>+ <option value="2">Xbox One</option>+ <option value="3">Xbox 360</option>+ </select>+ </div>+ <button class="chip" id="chipMouseGP" type="button" onclick="toggleChip('chipMouseGP')">+ ⌨️🖱️ Teclado e mouse+ </button>+ <div class="chip-select" id="chipSelectModeGP">+ <label for="filterModeGP">👤 Modo:</label>+ <select id="filterModeGP" onchange="onFilterChange()">+ <option value="0">Todos</option>+ <option value="1">Um jogador</option>+ <option value="2">Multijogador online</option>+ <option value="3">Cooperativo online</option>+ <option value="4">Multijogador local</option>+ </select>+ </div>+ <div class="chip-select" id="chipSelectLangGP">+ <label for="filterLangGP">🌐 Idioma:</label>+ <select id="filterLangGP" onchange="onFilterChange()">+ <option value="0">Qualquer</option>+ <option value="1">Legendas</option>+ <option value="2">Dublado</option>+ </select>+ </div>+ </div>++ <!-- Meus Jogos (Library) filters -->+ <div id="filtersLibrary" class="filter-chips" style="display:none;">+ <button class="chip" id="chipWishlist" type="button" onclick="toggleChip('chipWishlist')">+ 💖 Lista de desejos+ </button>+ <button class="chip" id="chipFree" type="button" onclick="toggleChip('chipFree')">+ 🎁 Grátis+ </button>+ <button class="chip" id="chipCheapest" type="button" onclick="toggleChip('chipCheapest')">+ 🏷️ Menor preço+ </button>+ <div class="chip-select" id="chipSelectConsoleLib">+ <label for="filterConsoleLib">🎮 Console:</label>+ <select id="filterConsoleLib" onchange="onFilterChange()">+ <option value="0">Todos</option>+ <option value="1">Series X|S</option>+ <option value="2">Xbox One</option>+ <option value="3">Xbox 360</option>+ </select>+ </div>+ <button class="chip" id="chipMouseLib" type="button" onclick="toggleChip('chipMouseLib')">+ ⌨️🖱️ Teclado e mouse+ </button>+ <div class="chip-select" id="chipSelectModeLib">+ <label for="filterModeLib">👤 Modo:</label>+ <select id="filterModeLib" onchange="onFilterChange()">+ <option value="0">Todos</option>+ <option value="1">Um jogador</option>+ <option value="2">Multijogador online</option>+ <option value="3">Cooperativo online</option>+ <option value="4">Multijogador local</option>+ </select>+ </div>+ <div class="chip-select" id="chipSelectLangLib">+ <label for="filterLangLib">🌐 Idioma:</label>+ <select id="filterLangLib" onchange="onFilterChange()">+ <option value="0">Qualquer</option>+ <option value="1">Legendas</option>+ <option value="2">Dublado</option>+ </select>+ </div>+ </div>+ </div>++ <div class="status-pill">+ <div class="status-dot"></div>+ <span id="searchStatus">Pronto para pesquisar</span>+ </div>+ </div>+ </div>++ <!-- TAB: REMAP -->+ <div id="tab-remap" class="tab-pane" style="display:none;">+ <div class="subnav">+ <button class="btn active" id="btnSubPad" onclick="switchRemapSub('pad')">🎮 DualSense</button>+ <button class="btn" id="btnSubKey" onclick="switchRemapSub('key')">⌨️ Teclado</button>+ <button class="btn" id="btnSubTouch" onclick="switchRemapSub('touch')">👆 Touchpad</button>+ </div>++ <div id="subRemapPad">+ <div class="card">+ <h2>🎮 Remapeamento de Botões (DualSense)</h2>+ <p>Ajuste os botões do controle para o jogo na nuvem. Suas alterações são sincronizadas e salvas automaticamente.</p>+ <div class="grid-map" id="padGrid"></div>+ <div class="btn-row">+ <button class="btn btn-primary" onclick="saveSettings()">Salvar no Console</button>+ <button class="btn" onclick="resetPadMap()">Restaurar Controle Padrão</button>+ </div>+ </div>+ </div>++ <div id="subRemapKey" style="display:none;">+ <div class="card">+ <h2>⌨️ Remapeamento de Teclado (WASD / Teclas)</h2>+ <p>Mapeie teclas e botões do mouse para os comandos do Xbox na nuvem. Cada ação possui tecla Primária e Secundária.</p>+ <div class="grid-map" id="keyGrid"></div>+ <div class="btn-row">+ <button class="btn btn-primary" onclick="saveSettings()">Salvar no Console</button>+ <button class="btn" onclick="resetKeyMap()">Restaurar Teclado Padrão</button>+ </div>+ </div>+ </div>++ <div id="subRemapTouch" style="display:none;">+ <div class="card">+ <h2>👆 Atalhos do Touchpad (DualSense)</h2>+ <p>Configure o que cada gesto (deslizar) ou clique físico (lado esquerdo/direito) no touchpad faz durante o streaming. <strong>Touchpad + Options</strong> permanece sempre fixo para abrir o Menu do Jogo.</p>+ <div class="grid-map" id="remapTouchpadShortcutsGrid"></div>+ <div class="btn-row">+ <button class="btn btn-primary" onclick="saveSettings()">Salvar no Console</button>+ <button class="btn" onclick="resetTouchpadShortcuts()">Restaurar Touchpad Padrão</button>+ </div>+ </div>+ </div>+ </div>++ <!-- TAB: GAMEPAD (CONTROLE VIRTUAL) -->+ <div id="tab-gamepad" class="tab-pane" style="display:none;">+ <div class="card" id="gamepadCard">+ <div class="gamepad-intro">+ <div class="gamepad-toolbar">+ <button type="button" class="btn btn-primary" id="btnFullscreenPad" onclick="toggleGamepadFullscreen()" style="padding: 6px 12px; font-size: 0.78rem;">+ ⛶ Tela Cheia+ </button>+ </div>+ </div>++ <div class="gamepad-viewport-wrapper" id="gamepadScaleContainer">+ <div class="gamepad-container" id="gamepadArea">++ <!-- MODULE 1: Left Stick -->+ <div id="mod_stick_left" class="gamepad-module">+ <div class="stick-base" id="leftStickZone">+ <div class="stick-head" id="leftStickHead"></div>+ </div>+ </div>++ <!-- MODULE 2: D-Pad -->+ <div id="mod_dpad" class="gamepad-module">+ <div class="dpad-container" id="box_dpad">+ <div class="dpad-arm dpad-arm-up" data-btn="dpadUp">▲</div>+ <div class="dpad-arm dpad-arm-left" data-btn="dpadLeft">◀</div>+ <div class="dpad-mid"></div>+ <div class="dpad-arm dpad-arm-right" data-btn="dpadRight">▶</div>+ <div class="dpad-arm dpad-arm-down" data-btn="dpadDown">▼</div>+ </div>+ </div>++ <!-- MODULE 3: ABXY Diamond -->+ <div id="mod_abxy" class="gamepad-module">+ <div class="abxy-container" id="box_abxy">+ <div class="abxy-key btn-y" data-btn="btnY">Y</div>+ <div class="abxy-key btn-x" data-btn="btnX">X</div>+ <div class="abxy-key btn-b" data-btn="btnB">B</div>+ <div class="abxy-key btn-a" data-btn="btnA">A</div>+ </div>+ </div>++ <!-- MODULE 4: Right Stick -->+ <div id="mod_stick_right" class="gamepad-module">+ <div class="stick-base" id="rightStickZone">+ <div class="stick-head" id="rightStickHead"></div>+ </div>+ </div>++ <!-- INDIVIDUAL SHOULDER & TRIGGER BUTTONS -->+ <!-- MODULE 5: LT Trigger -->+ <div id="mod_btn_lt" class="gamepad-module pad-bumper-left">+ <button type="button" class="pad-btn pad-btn-trigger" id="btn_lt" data-btn="triggerL2">LT</button>+ </div>++ <!-- MODULE 6: LB Bumper -->+ <div id="mod_btn_lb" class="gamepad-module pad-bumper-left">+ <button type="button" class="pad-btn pad-btn-bumper" id="btn_lb" data-btn="btnL1">LB</button>+ </div>++ <!-- MODULE 7: LS Button -->+ <div id="mod_btn_ls" class="gamepad-module pad-bumper-left">+ <button type="button" class="pad-btn pad-btn-stick-click pad-btn-stick-btn" id="btn_ls" data-btn="btnL3">LS</button>+ </div>++ <!-- MODULE 8: RS Button -->+ <div id="mod_btn_rs" class="gamepad-module pad-bumper-right">+ <button type="button" class="pad-btn pad-btn-stick-click pad-btn-stick-btn" id="btn_rs" data-btn="btnR3">RS</button>+ </div>++ <!-- MODULE 9: RB Bumper -->+ <div id="mod_btn_rb" class="gamepad-module pad-bumper-right">+ <button type="button" class="pad-btn pad-btn-bumper" id="btn_rb" data-btn="btnR1">RB</button>+ </div>++ <!-- MODULE 10: RT Trigger -->+ <div id="mod_btn_rt" class="gamepad-module pad-bumper-right">+ <button type="button" class="pad-btn pad-btn-trigger" id="btn_rt" data-btn="triggerR2">RT</button>+ </div>++ <!-- MODULE 11: Center System Buttons (VIEW, X, MENU) -->+ <div id="mod_center_sys" class="gamepad-module">+ <div class="center-sys-container">+ <button type="button" class="pad-btn pad-btn-sys" id="btn_view" data-btn="btnView">VIEW</button>+ <button type="button" class="pad-btn-nexus-btn" id="btn_nexus" data-btn="btnNexus" aria-label="Xbox Guide" title="Xbox Guide">+ <svg viewBox="0 0 100 100" width="22" height="22" style="pointer-events:none;display:block;">+ <circle cx="50" cy="50" r="48" fill="#ffffff"/>+ <path fill="#107C41" d="M 50.00 40.10 s 0.12 0.00 0.00 0.00 c 15.07 11.46 40.60 39.60 32.88 47.57 -8.84 7.72 -20.30 12.33 -32.88 12.33 s -24.16 -4.61 -32.88 -12.33 c -7.85 -7.97 17.81 -36.11 32.75 -47.45 0.00 -0.12 0.12 -0.12 0.12 -0.12 z m 26.03 -32.75 C 68.43 2.74 60.09 0.00 50.00 0.00 s -18.43 2.74 -26.03 7.35 c -0.12 0.00 -0.12 0.12 -0.12 0.25 s 0.12 0.12 0.25 0.12 c 9.71 -2.12 24.41 6.23 25.78 7.10 h 0.25 c 1.37 -0.87 16.06 -9.22 25.78 -7.10 0.12 0.00 0.25 0.00 0.25 -0.12 s 0.00 -0.25 -0.12 -0.25 z M 15.01 14.32 c -0.12 0.00 -0.12 0.12 -0.25 0.12 -9.09 9.09 -14.69 21.67 -14.69 35.49 0.00 11.33 3.86 21.92 10.21 30.26 0.00 0.12 0.12 0.12 0.25 0.12 s 0.12 -0.12 0.00 -0.25 c -3.86 -11.83 15.69 -40.35 25.78 -52.30 l 0.12 -0.12 c 0.00 -0.12 0.00 -0.12 -0.12 -0.12 -15.32 -15.19 -20.42 -13.57 -21.30 -13.20 z m 48.69 13.08 l -0.12 0.12 s 0.00 0.12 0.12 0.12 c 10.09 11.96 29.51 40.47 25.78 52.30 v 0.25 c 0.12 0.00 0.25 0.00 0.25 -0.12 6.35 -8.34 10.21 -18.93 10.21 -30.26 0.00 -13.82 -5.60 -26.40 -14.82 -35.49 -0.12 -0.12 -0.12 -0.12 -0.25 -0.12 -0.75 -0.25 -5.85 -1.87 -21.17 13.20 z"/>+ </svg>+ </button>+ <button type="button" class="pad-btn pad-btn-sys" id="btn_menu" data-btn="btnMenu">MENU</button>+ <button type="button" class="pad-btn pad-btn-sys fs-only-exit" id="btn_exit_fs" onclick="toggleGamepadFullscreen()" style="background:#451a1a;border-color:#b91c1c;color:#fca5a5;">✕ Sair</button>+ </div>+ </div>++ <!-- MODULE 12: Player Selector (P1..P4) -->+ <div id="mod_player_bar" class="gamepad-module">+ <div class="player-bar-container">+ <button type="button" class="player-pill active" id="btnPlayer1" onclick="setVirtualPlayer(1)">P1</button>+ <button type="button" class="player-pill" id="btnPlayer2" onclick="setVirtualPlayer(2)">P2</button>+ <button type="button" class="player-pill" id="btnPlayer3" onclick="setVirtualPlayer(3)">P3</button>+ <button type="button" class="player-pill" id="btnPlayer4" onclick="setVirtualPlayer(4)">P4</button>+ </div>+ </div>++ </div>+ </div>++ <div class="status-pill gamepad-status-bar" style="margin-top: 10px;">+ <div class="status-dot"></div>+ <span id="gamepadStatus">Controle ativo para Jogador 1 (Principal)</span>+ </div>+ </div>+ </div>++ <!-- TAB: LOGS -->+ <div id="tab-logs" class="tab-pane" style="display:none;">+ <div class="card">+ <h2>🐛 Enviar Relatório de Erro (GitHub)</h2>+ <p>Gere um relatório completo da sessão atual com logs sanitizados (sem dados privados, e-mails ou tokens) formatado automaticamente para o repositório oficial no GitHub.</p>++ <div class="form-group" style="margin-bottom: 10px;">+ <label for="reportTitle" style="font-weight: 600; font-size: 0.82rem; display: block; margin-bottom: 4px;">Título do Problema (Opcional):</label>+ <input type="text" id="reportTitle" class="form-control" placeholder="Ex: Queda de transmissão ou erro de áudio" style="width: 100%; box-sizing: border-box; padding: 8px 10px; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 8px; color: #fff; font-size: 0.85rem;">+ </div>++ <div class="form-group" style="margin-bottom: 12px;">+ <label for="reportWhat" style="font-weight: 600; font-size: 0.82rem; display: block; margin-bottom: 4px;">O que aconteceu? (Opcional):</label>+ <textarea id="reportWhat" class="form-control" rows="2" placeholder="Descreva brevemente o que você estava fazendo quando o erro ocorreu..." style="width: 100%; box-sizing: border-box; padding: 8px 10px; background: var(--surface-alt); border: 1px solid var(--border); border-radius: 8px; color: #fff; font-size: 0.85rem; resize: vertical;"></textarea>+ </div>++ <div class="btn-row" style="margin-top: 0; margin-bottom: 8px; gap: 8px; display: flex; flex-wrap: wrap;">+ <button type="button" class="btn btn-primary" onclick="openGitHubReport()" id="btnOpenReport">🚀 Abrir Relatório no GitHub</button>+ <button type="button" class="btn" onclick="copySanitizedReport()" id="btnCopyReport">📋 Copiar Relatório</button>+ <button type="button" class="btn" onclick="previewReport()" id="btnPreviewReport">🔍 Pré-visualizar</button>+ </div>+ </div>++ <div class="card">+ <h2>📋 Download de Logs Cru</h2>+ <p>Baixe o arquivo <code>xcloud.log</code> sanitizado (sem tokens ou dados privados) para inspeção local ou envio manual.</p>+ <div class="btn-row" style="margin-top: 0; margin-bottom: 14px; gap: 8px; display: flex; flex-wrap: wrap;">+ <a href="/api/log" download="xcloud.log" class="btn btn-primary">⬇️ Baixar xcloud.log</a>+ <button type="button" class="btn" onclick="loadLogPreview()">Visualizar Últimas Linhas</button>+ </div>+ <pre id="logPreview">Clique em "Visualizar Últimas Linhas" ou "Pré-visualizar" para inspecionar os dados...</pre>+ </div>+ </div>+</div>++<div id="toast" class="toast">Alterações salvas com sucesso!</div>++<script>+const padFunctions = [+ "A (Sul / Cruz)", "B (Leste / Círculo)", "X (Oeste / Quadrado)", "Y (Norte / Triângulo)",+ "LB (L1)", "RB (R1)", "LT (L2)", "RT (R2)", "LS (L3)", "RS (R3)",+ "View (Touchpad / Share)", "Menu (Options)", "D-pad Cima", "D-pad Baixo", "D-pad Esquerda", "D-pad Direita"+];+const padSources = [+ {id: 0, name: "Cruz (South)"}, {id: 1, name: "Círculo (East)"}, {id: 2, name: "Quadrado (West)"}, {id: 3, name: "Triângulo (North)"},+ {id: 4, name: "L1 (LB)"}, {id: 5, name: "R1 (RB)"}, {id: 6, name: "L2 (LT)"}, {id: 7, name: "R2 (RT)"},+ {id: 8, name: "L3 (LS)"}, {id: 9, name: "R3 (RS)"}, {id: 10, name: "Touchpad (View)"}, {id: 11, name: "Options (Menu)"},+ {id: 12, name: "D-pad Cima"}, {id: 13, name: "D-pad Baixo"}, {id: 14, name: "D-pad Esquerda"}, {id: 15, name: "D-pad Direita"}+];++const touchpadTriggers = [+ {key: "swipeUp", label: "Deslizar ↑ (Cima)"},+ {key: "swipeDown", label: "Deslizar ↓ (Baixo)"},+ {key: "swipeLeft", label: "Deslizar ← (Esquerda)"},+ {key: "swipeRight", label: "Deslizar → (Direita)"},+ {key: "clickLeft", label: "Clique Esquerdo"},+ {key: "clickRight", label: "Clique Direito"}+];++const touchpadActions = [+ {id: "none", name: "Desativado"},+ {id: "game_menu", name: "Menu do Jogo"},+ {id: "xbox_button", name: "Botão Xbox (Guia)"},+ {id: "toggle_stats", name: "Alternar Telemetria"},+ {id: "toggle_mic_mute", name: "Silenciar Microfone"},+ {id: "cycle_gyro", name: "Alternar Giroscópio"},+ {id: "cycle_trigger_profile", name: "Alternar Perfil de Gatilho"},+ {id: "view", name: "View"},+ {id: "menu", name: "Menu"},+ {id: "l3", name: "LS (L3)"},+ {id: "r3", name: "RS (R3)"},+ {id: "a", name: "A (Cruz)"},+ {id: "b", name: "B (Círculo)"},+ {id: "x", name: "X (Quadrado)"},+ {id: "y", name: "Y (Triângulo)"},+ {id: "lb", name: "LB (L1)"},+ {id: "rb", name: "RB (R1)"},+ {id: "dpad_up", name: "D-pad Cima"},+ {id: "dpad_down", name: "D-pad Baixo"},+ {id: "dpad_left", name: "D-pad Esquerda"},+ {id: "dpad_right", name: "D-pad Direita"}+];++const defaultTouchpadShortcuts = {+ swipeUp: "xbox_button",+ swipeDown: "game_menu",+ swipeLeft: "game_menu",+ swipeRight: "xbox_button",+ clickLeft: "view",+ clickRight: "view"+};++const keyActionNames = [+ "Analógico Esq. Cima", "Analógico Esq. Baixo", "Analógico Esq. Esquerda", "Analógico Esq. Direita",+ "D-pad Cima", "D-pad Baixo", "D-pad Esquerda", "D-pad Direita",+ "A (Cruz)", "B (Círculo)", "X (Quadrado)", "Y (Triângulo)",+ "LB (L1)", "RB (R1)", "LT (L2)", "RT (R2)", "LS (L3)", "RS (R3)",+ "View (Share / Touch)", "Menu (Options)"+];++const keyList = [+ {id: 0, name: "(Nenhuma)"},+ {id: 87, name: "W"}, {id: 65, name: "A"}, {id: 83, name: "S"}, {id: 68, name: "D"},+ {id: 81, name: "Q"}, {id: 69, name: "E"}, {id: 82, name: "R"}, {id: 70, name: "F"},+ {id: 67, name: "C"}, {id: 86, name: "V"}, {id: 90, name: "Z"}, {id: 88, name: "X"},+ {id: 66, name: "B"}, {id: 71, name: "G"}, {id: 84, name: "T"}, {id: 89, name: "Y"},+ {id: 72, name: "H"}, {id: 74, name: "J"}, {id: 75, name: "K"}, {id: 76, name: "L"},+ {id: 77, name: "M"}, {id: 78, name: "N"}, {id: 79, name: "O"}, {id: 80, name: "P"},+ {id: 85, name: "U"}, {id: 73, name: "I"},+ {id: 48, name: "0"}, {id: 49, name: "1"}, {id: 50, name: "2"}, {id: 51, name: "3"},+ {id: 52, name: "4"}, {id: 53, name: "5"}, {id: 54, name: "6"}, {id: 55, name: "7"},+ {id: 56, name: "8"}, {id: 57, name: "9"},+ {id: 32, name: "Espaço (Space)"},+ {id: 16, name: "Shift"}, {id: 17, name: "Ctrl"}, {id: 18, name: "Alt"},+ {id: 9, name: "Tab"}, {id: 27, name: "Esc"}, {id: 13, name: "Enter"}, {id: 8, name: "Backspace"},+ {id: 38, name: "Seta Cima"}, {id: 40, name: "Seta Baixo"},+ {id: 37, name: "Seta Esquerda"}, {id: 39, name: "Seta Direita"},+ {id: 241, name: "Mouse L (Esq)"}, {id: 242, name: "Mouse R (Dir)"},+ {id: 243, name: "Mouse M (Meio)"}, {id: 244, name: "Mouse 4"}, {id: 245, name: "Mouse 5"}+];++const defaultKeyMap = [+ 87, 0, 83, 0, 65, 0, 68, 0,+ 38, 0, 40, 0, 37, 0, 39, 0,+ 32, 0, 67, 0, 82, 0, 69, 0,+ 81, 0, 70, 0, 242, 0, 241, 0,+ 16, 0, 86, 243, 9, 0, 27, 0+];++let currentSettings = {+ padMap: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],+ keyMap: [...defaultKeyMap],+ touchpadShortcuts: {...defaultTouchpadShortcuts}+};+let lastSettingsVersion = 0;++let currentSearchTab = 'gamepass';+let currentFilters = {+ plan: 0,+ consoleGP: 0,+ consoleLib: 0,+ modeGP: 0,+ modeLib: 0,+ langGP: 0,+ langLib: 0,+ mouseGP: false,+ mouseLib: false,+ wishlist: false,+ free: false,+ cheapest: false+};++function switchTab(name) {+ document.querySelectorAll('.tab-pane').forEach(el => {+ el.style.display = 'none';+ el.classList.remove('active');+ });+ document.querySelectorAll('.nav-tab').forEach(el => el.classList.remove('active'));+ const pane = document.getElementById('tab-' + name);+ if (pane) {+ pane.style.display = 'block';+ pane.classList.add('active');+ }+ const tabBtn = document.getElementById('navTab-' + name);+ if (tabBtn) tabBtn.classList.add('active');+ if (name === 'search') pollStreamingState();+ if (name === 'gamepad') {+ sendPadState(true);+ updateGamepadScale();+ setTimeout(updateGamepadScale, 10);+ }+ if (name === 'stream') {+ loadStreamMenuState();+ pollStats();+ }+}++function switchRemapSub(mode) {+ document.getElementById('subRemapPad').style.display = mode === 'pad' ? 'block' : 'none';+ document.getElementById('subRemapKey').style.display = mode === 'key' ? 'block' : 'none';+ const subTouch = document.getElementById('subRemapTouch');+ if (subTouch) subTouch.style.display = mode === 'touch' ? 'block' : 'none';+ document.getElementById('btnSubPad').classList.toggle('active', mode === 'pad');+ document.getElementById('btnSubKey').classList.toggle('active', mode === 'key');+ const btnTouch = document.getElementById('btnSubTouch');+ if (btnTouch) btnTouch.classList.toggle('active', mode === 'touch');+}++function showToast(msg) {+ const t = document.getElementById('toast');+ t.textContent = msg;+ t.classList.add('show');+ setTimeout(() => t.classList.remove('show'), 2500);+}++const searchInput = document.getElementById('searchInput');+let searchDebounce = null;++function applySearchTabUI(tab) {+ currentSearchTab = tab;+ document.getElementById('tabBtnGamePass').classList.toggle('active', tab === 'gamepass');+ document.getElementById('tabBtnLibrary').classList.toggle('active', tab === 'library');+ document.getElementById('filtersGamePass').style.display = tab === 'gamepass' ? 'flex' : 'none';+ document.getElementById('filtersLibrary').style.display = tab === 'library' ? 'flex' : 'none';+}++function setSearchTab(tab) {+ applySearchTabUI(tab);+ sendSearch(true);+}++function toggleChip(id) {+ const el = document.getElementById(id);+ el.classList.toggle('active');+ const active = el.classList.contains('active');+ if (id === 'chipWishlist') currentFilters.wishlist = active;+ if (id === 'chipFree') currentFilters.free = active;+ if (id === 'chipCheapest') currentFilters.cheapest = active;+ if (id === 'chipMouseGP') currentFilters.mouseGP = active;+ if (id === 'chipMouseLib') currentFilters.mouseLib = active;+ sendSearch(true);+}++function onFilterChange() {+ currentFilters.plan = parseInt(document.getElementById('filterPlan').value, 10);+ currentFilters.consoleGP = parseInt(document.getElementById('filterConsoleGP').value, 10);+ currentFilters.consoleLib = parseInt(document.getElementById('filterConsoleLib').value, 10);+ currentFilters.modeGP = parseInt(document.getElementById('filterModeGP').value, 10);+ currentFilters.modeLib = parseInt(document.getElementById('filterModeLib').value, 10);+ currentFilters.langGP = parseInt(document.getElementById('filterLangGP').value, 10);+ currentFilters.langLib = parseInt(document.getElementById('filterLangLib').value, 10);++ document.getElementById('chipSelectPlan').classList.toggle('active', currentFilters.plan > 0);+ document.getElementById('chipSelectConsoleGP').classList.toggle('active', currentFilters.consoleGP > 0);+ document.getElementById('chipSelectConsoleLib').classList.toggle('active', currentFilters.consoleLib > 0);+ document.getElementById('chipSelectModeGP').classList.toggle('active', currentFilters.modeGP > 0);+ document.getElementById('chipSelectModeLib').classList.toggle('active', currentFilters.modeLib > 0);+ document.getElementById('chipSelectLangGP').classList.toggle('active', currentFilters.langGP > 0);+ document.getElementById('chipSelectLangLib').classList.toggle('active', currentFilters.langLib > 0);+ sendSearch(true);+}++function updateSearchStatusText() {+ const q = searchInput.value;+ const isLib = currentSearchTab === 'library';+ let status = isLib ? 'Meus jogos' : 'Game Pass';+ if (q) status += ' • "' + q + '"';+ const filterNames = [];+ if (isLib) {+ if (currentFilters.wishlist) filterNames.push('Lista de desejos');+ if (currentFilters.free) filterNames.push('Grátis');+ if (currentFilters.cheapest) filterNames.push('Menor preço');+ if (currentFilters.mouseLib) filterNames.push('Teclado e mouse');+ if (currentFilters.consoleLib > 0) {+ const cNames = ['Todos', 'Series X|S', 'Xbox One', 'Xbox 360'];+ filterNames.push(cNames[currentFilters.consoleLib]);+ }+ if (currentFilters.modeLib > 0) {+ const mNames = ['Todos', 'Um jogador', 'Multijogador online', 'Cooperativo online', 'Multijogador local'];+ filterNames.push(mNames[currentFilters.modeLib]);+ }+ if (currentFilters.langLib > 0) {+ const lNames = ['Qualquer', 'Legendas', 'Dublado'];+ filterNames.push(lNames[currentFilters.langLib]);+ }+ } else {+ if (currentFilters.plan > 0) {+ const pNames = ['Meu plano', 'Ultimate', 'Premium', 'Essential', 'Todos os planos'];+ filterNames.push(pNames[currentFilters.plan]);+ }+ if (currentFilters.mouseGP) filterNames.push('Teclado e mouse');+ if (currentFilters.consoleGP > 0) {+ const cNames = ['Todos', 'Series X|S', 'Xbox One', 'Xbox 360'];+ filterNames.push(cNames[currentFilters.consoleGP]);+ }+ if (currentFilters.modeGP > 0) {+ const mNames = ['Todos', 'Um jogador', 'Multijogador online', 'Cooperativo online', 'Multijogador local'];+ filterNames.push(mNames[currentFilters.modeGP]);+ }+ if (currentFilters.langGP > 0) {+ const lNames = ['Qualquer', 'Legendas', 'Dublado'];+ filterNames.push(lNames[currentFilters.langGP]);+ }+ }+ if (filterNames.length > 0) {+ status += ' [' + filterNames.join(', ') + ']';+ }+ document.getElementById('searchStatus').textContent = status;+}++function sendSearch(immediate = false) {+ clearTimeout(searchDebounce);+ const doFetch = () => {+ const q = searchInput.value;+ const isLib = currentSearchTab === 'library';+ const activeFilters = {+ plan: isLib ? 0 : currentFilters.plan,+ console: isLib ? currentFilters.consoleLib : currentFilters.consoleGP,+ mode: isLib ? currentFilters.modeLib : currentFilters.modeGP,+ language: isLib ? currentFilters.langLib : currentFilters.langGP,+ mouseKeyboard: isLib ? currentFilters.mouseLib : currentFilters.mouseGP,+ wishlist: isLib ? currentFilters.wishlist : false,+ free: isLib ? currentFilters.free : false,+ cheapest: isLib ? currentFilters.cheapest : false+ };++ updateSearchStatusText();++ fetch('/api/search', {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({+ query: q,+ tab: currentSearchTab,+ filters: activeFilters+ })+ }).catch(e => console.error(e));+ };++ if (immediate) {+ doFetch();+ } else {+ searchDebounce = setTimeout(doFetch, 120);+ }+}++searchInput.addEventListener('input', () => {+ sendSearch(false);+});++function clearSearch() {+ searchInput.value = '';+ sendSearch(true);+}++function renderTouchpadShortcutsGrid(containerId, idPrefix, tsObj, onChangeFn) {+ const grid = document.getElementById(containerId);+ if (!grid) return;+ grid.innerHTML = '';+ const ts = Object.assign({}, defaultTouchpadShortcuts, tsObj || {});+ touchpadTriggers.forEach(trig => {+ const item = document.createElement('div');+ item.className = 'map-item';+ const label = document.createElement('label');+ label.textContent = trig.label;+ const select = document.createElement('select');+ select.id = idPrefix + '_' + trig.key;+ touchpadActions.forEach((act, idx) => {+ const opt = document.createElement('option');+ opt.value = act.id;+ opt.textContent = act.name;+ if (ts[trig.key] === act.id || ts[trig.key] === idx) opt.selected = true;+ select.appendChild(opt);+ });+ select.addEventListener('change', () => {+ currentSettings.touchpadShortcuts = currentSettings.touchpadShortcuts || {...defaultTouchpadShortcuts};+ currentSettings.touchpadShortcuts[trig.key] = select.value;+ syncTouchpadSelects(trig.key, select.value);+ if (onChangeFn) onChangeFn(trig.key, select.value);+ });+ item.appendChild(label);+ item.appendChild(select);+ grid.appendChild(item);+ });+}++function syncTouchpadSelects(trigKey, val) {+ ['tp_remap_'].forEach(prefix => {+ const el = document.getElementById(prefix + trigKey);+ if (el && el.value !== String(val)) el.value = val;+ });+}++function readTouchpadShortcutsFromPrefix(prefix) {+ const out = {...defaultTouchpadShortcuts};+ touchpadTriggers.forEach(trig => {+ const el = document.getElementById(prefix + '_' + trig.key);+ if (el) out[trig.key] = el.value;+ });+ return out;+}++function renderAllTouchpadGrids(tsObj) {+ const ts = Object.assign({}, defaultTouchpadShortcuts, tsObj || currentSettings.touchpadShortcuts || {});+ currentSettings.touchpadShortcuts = ts;+ renderTouchpadShortcutsGrid('remapTouchpadShortcutsGrid', 'tp_remap', ts, null);+}++function resetTouchpadShortcuts() {+ currentSettings.touchpadShortcuts = {...defaultTouchpadShortcuts};+ renderAllTouchpadGrids(currentSettings.touchpadShortcuts);+ saveSettings();+}++function renderPadMap() {+ const grid = document.getElementById('padGrid');+ grid.innerHTML = '';+ const map = Array.isArray(currentSettings.padMap) ? currentSettings.padMap+ : (currentSettings.padMap && Array.isArray(currentSettings.padMap.map)) ? currentSettings.padMap.map+ : [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];+ padFunctions.forEach((fnName, idx) => {+ const item = document.createElement('div');+ item.className = 'map-item';+ const label = document.createElement('label');+ label.textContent = fnName;+ const select = document.createElement('select');+ select.id = 'pad_fn_' + idx;+ padSources.forEach(s => {+ const opt = document.createElement('option');+ opt.value = s.id;+ opt.textContent = s.name;+ if (map[idx] === s.id) opt.selected = true;+ select.appendChild(opt);+ });+ item.appendChild(label);+ item.appendChild(select);+ grid.appendChild(item);+ });+}++function renderKeyMap() {+ const grid = document.getElementById('keyGrid');+ grid.innerHTML = '';+ const kmap = (currentSettings.keyMap && currentSettings.keyMap.length === 40) ? currentSettings.keyMap : defaultKeyMap;+ keyActionNames.forEach((actName, idx) => {+ const item = document.createElement('div');+ item.className = 'map-item';+ const label = document.createElement('label');+ label.textContent = actName;+ const selectsWrap = document.createElement('div');+ selectsWrap.className = 'selects-wrap';+ for (let slot = 0; slot < 2; slot++) {+ const select = document.createElement('select');+ select.id = 'key_act_' + idx + '_' + slot;+ const code = kmap[idx * 2 + slot];+ let hasMatch = false;+ keyList.forEach(k => {+ const opt = document.createElement('option');+ opt.value = k.id;+ opt.textContent = k.name;+ if (code === k.id) { opt.selected = true; hasMatch = true; }+ select.appendChild(opt);+ });+ if (!hasMatch && code > 0) {+ const opt = document.createElement('option');+ opt.value = code;+ opt.textContent = "Key #" + code;+ opt.selected = true;+ select.appendChild(opt);+ }+ selectsWrap.appendChild(select);+ }+ item.appendChild(label);+ item.appendChild(selectsWrap);+ grid.appendChild(item);+ });+}++function resetPadMap() {+ currentSettings.padMap = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];+ renderPadMap();+ saveSettings();+}++function resetKeyMap() {+ currentSettings.keyMap = [...defaultKeyMap];+ renderKeyMap();+ saveSettings();+}++function saveSettings() {+ const padMap = [];+ for (let i = 0; i < 16; i++) {+ const sel = document.getElementById('pad_fn_' + i);+ padMap.push(sel ? parseInt(sel.value, 10) : i);+ }+ const keyMap = [];+ for (let i = 0; i < 20; i++) {+ const s0 = document.getElementById('key_act_' + i + '_0');+ const s1 = document.getElementById('key_act_' + i + '_1');+ keyMap.push(s0 ? parseInt(s0.value, 10) : 0);+ keyMap.push(s1 ? parseInt(s1.value, 10) : 0);+ }+ const touchpadShortcuts = readTouchpadShortcutsFromPrefix('tp_remap');+ fetch('/api/settings', {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({ padMap: padMap, keyMap: keyMap, touchpadShortcuts: touchpadShortcuts })+ }).then(r => r.json()).then(res => {+ if (res.ok) {+ showToast('Configurações salvas no console!');+ }+ }).catch(e => showToast('Erro ao salvar configurações'));+}++function onBitrateInput(val) {+ const v = parseInt(val, 10);+ const el = document.getElementById('valBitrate');+ if (el) el.textContent = (v === 0) ? 'Auto' : v + ' Mbps';+}++function onLightBarModeChange() {+ const sel = document.getElementById('selectLightBarMode');+ const colorInput = document.getElementById('inputLightBarColor');+ if (sel && colorInput) {+ colorInput.style.display = (sel.value === '1') ? 'inline-block' : 'none';+ }+}++function markSettingsChanged() {+}++function saveGeneralSettings() {+ const payload = {+ maxBitrateMbps: parseInt(document.getElementById('inputBitrate').value, 10),+ highRefresh: document.getElementById('check120Hz').checked,+ deadzoneLeft: parseInt(document.getElementById('inputDeadzoneL').value, 10),+ deadzoneRight: parseInt(document.getElementById('inputDeadzoneR').value, 10),+ triggerStrength: parseInt(document.getElementById('inputTriggerStrength').value, 10),+ lightBarMode: parseInt(document.getElementById('selectLightBarMode').value, 10),+ lightBarColour: document.getElementById('inputLightBarColor').value,+ queueReadyAlert: document.getElementById('checkQueueAlert').checked,+ videoDecoder: parseInt(document.getElementById('selectVideoDecoder').value, 10),+ voiceRouting: parseInt(document.getElementById('selectVoiceRouting').value, 10)+ };+ fetch('/api/settings', {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify(payload)+ }).then(r => r.json()).then(res => {+ if (res.ok) {+ showToast('Configurações salvas no console!');+ } else {+ showToast('Erro ao salvar configurações');+ }+ }).catch(() => showToast('Erro ao salvar configurações'));+}++function updateCasLabel(val) {+ const labels = ['Desativada', 'Baixa', 'Média', 'Alta'];+ const el = document.getElementById('valCas');+ if (el) el.textContent = labels[val] !== undefined ? labels[val] : 'Média';+}++function sendStreamParam(param, val) {+ const body = {};+ body[param] = val;+ fetch('/api/stream', {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify(body)+ }).then(r => r.json()).then(res => {+ if (res && res.ok) showToast('Aplicado na transmissão!');+ }).catch(() => {});+}++function sendStreamAction(action) {+ fetch('/api/stream', {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({ action: action })+ }).then(r => r.json()).then(res => {+ if (action === 'xbox_guide') showToast('Guia Xbox acionado');+ if (action === 'end_session') showToast('Sessão encerrada');+ }).catch(() => {});+}++function loadStreamMenuState() {+ fetch('/api/stream').then(r => r.json()).then(s => {+ if (s.sharpness !== undefined) {+ const el = document.getElementById('inputCas');+ if (el) { el.value = s.sharpness; updateCasLabel(s.sharpness); }+ }+ if (s.upscaler !== undefined) {+ const el = document.getElementById('selectUpscaler');+ if (el) el.value = s.upscaler;+ }+ if (s.deband !== undefined) {+ const el = document.getElementById('selectDeband');+ if (el) el.value = s.deband;+ }+ if (s.padSpeakerVolume !== undefined) {+ const el = document.getElementById('inputPadSpeaker');+ if (el) el.value = s.padSpeakerVolume;+ const vlbl = document.getElementById('valPadSpeaker');+ if (vlbl) vlbl.textContent = s.padSpeakerVolume + '%';+ }+ if (s.triggerProfile !== undefined) {+ const el = document.getElementById('selectSmartTriggers');+ if (el) el.value = s.triggerProfile;+ }+ if (s.touchpadShortcuts) {+ renderAllTouchpadGrids(s.touchpadShortcuts);+ }+ }).catch(() => {});+}++function renderTelemetry(data) {+ if (!data) return;+ if (data.fps !== undefined) document.getElementById('telFps').textContent = data.fps;+ if (data.rttMs !== undefined) document.getElementById('telRtt').textContent = data.rttMs + ' ms';+ if (data.mbps !== undefined) document.getElementById('telMbps').textContent = (typeof data.mbps === 'number' ? data.mbps.toFixed(1) : data.mbps) + ' Mbps';+ if (data.lossPct !== undefined) document.getElementById('telLoss').textContent = (typeof data.lossPct === 'number' ? data.lossPct.toFixed(1) : data.lossPct) + '%';+ if (data.qp !== undefined) document.getElementById('telQp').textContent = data.qp;+ if (data.decodeMs !== undefined) document.getElementById('telDec').textContent = (typeof data.decodeMs === 'number' ? data.decodeMs.toFixed(1) : data.decodeMs) + ' ms';+}++let ws = null;+function initWs() {+ try {+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';+ ws = new WebSocket(proto + '//' + location.host + '/ws');+ ws.onmessage = (ev) => {+ try {+ const msg = JSON.parse(ev.data);+ if (msg.type === 'telemetry' && msg.stats) {+ renderTelemetry(msg.stats);+ } else if (msg.fps !== undefined) {+ renderTelemetry(msg);+ }+ } catch (_) {}+ };+ ws.onclose = () => {+ ws = null;+ setTimeout(initWs, 2000);+ };+ ws.onerror = () => {+ try { ws.close(); } catch(_) {}+ };+ } catch (_) {+ ws = null;+ }+}+initWs();++function pollStats() {+ if (ws && ws.readyState === WebSocket.OPEN) return;+ const streamTab = document.getElementById('tab-stream');+ if (!streamTab || streamTab.style.display === 'none') return;+ fetch('/api/stats').then(r => r.json()).then(renderTelemetry).catch(() => {});+}+setInterval(pollStats, 1000);++function loadLogPreview() {+ const p = document.getElementById('logPreview');+ p.textContent = 'Carregando log...';+ fetch('/api/log').then(r => r.text()).then(text => {+ const lines = text.split('\n');+ p.textContent = lines.slice(-50).join('\n') || 'Log vazio.';+ }).catch(e => {+ p.textContent = 'Erro ao carregar log: ' + e;+ });+}++function getReportParams() {+ const title = (document.getElementById('reportTitle')?.value || '').trim();+ const what = (document.getElementById('reportWhat')?.value || '').trim();+ return { title, what };+}++function openGitHubReport() {+ const { title, what } = getReportParams();+ const btn = document.getElementById('btnOpenReport');+ btn.disabled = true;+ btn.textContent = 'Gerando link...';+ fetch('/api/report-issue', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ title, what })+ }).then(r => r.json()).then(data => {+ btn.disabled = false;+ btn.textContent = '🚀 Abrir Relatório no GitHub';+ if (data && data.url) {+ window.open(data.url, '_blank');+ showToast('Formulário do GitHub aberto em nova aba!');+ } else {+ showToast('Erro ao obter link do relatório.');+ }+ }).catch(e => {+ btn.disabled = false;+ btn.textContent = '🚀 Abrir Relatório no GitHub';+ showToast('Falha na requisição: ' + e);+ });+}++function fallbackCopyText(text) {+ return new Promise((resolve, reject) => {+ try {+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.style.position = 'fixed';+ ta.style.top = '0';+ ta.style.left = '0';+ ta.style.width = '2em';+ ta.style.height = '2em';+ ta.style.padding = '0';+ ta.style.border = 'none';+ ta.style.outline = 'none';+ ta.style.boxShadow = 'none';+ ta.style.background = 'transparent';+ ta.style.opacity = '0.01';+ document.body.appendChild(ta);+ ta.focus();+ ta.select();+ if (typeof ta.setSelectionRange === 'function') {+ ta.setSelectionRange(0, text.length);+ }+ let ok = false;+ try {+ ok = document.execCommand('copy');+ } catch (_) {+ ok = false;+ }+ document.body.removeChild(ta);+ if (ok) resolve(); else reject(new Error('execCommand copy failed'));+ } catch (e) { reject(e); }+ });+}++function copyTextToClipboard(text) {+ if (navigator.clipboard && window.isSecureContext && navigator.clipboard.writeText) {+ return navigator.clipboard.writeText(text).catch(() => fallbackCopyText(text));+ }+ return fallbackCopyText(text);+}++function copySanitizedReport() {+ const { title, what } = getReportParams();+ const btn = document.getElementById('btnCopyReport');+ btn.disabled = true;+ fetch('/api/report-issue', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ title, what })+ }).then(r => r.json()).then(data => {+ btn.disabled = false;+ if (data && data.excerpt) {+ const markdown = `### ${data.title || 'Relatório de Erro'}\n\n**Plataforma:** ${data.platform || 'PlayStation 5 (PPSA99810)'}\n**Versão:** v${data.release || ')html" XC_APP_VERSION R"html('}\n**Firmware:** ${data.firmware || 'N/A'}\n\n**O que aconteceu:**\n${what || 'Relatório enviado via WebUI'}\n\n\`\`\`\n${data.excerpt}\n\`\`\``;+ copyTextToClipboard(markdown).then(() => {+ showToast('Relatório copiado para a área de transferência!');+ }).catch(() => {+ const p = document.getElementById('logPreview');+ if (p) {+ p.textContent = markdown;+ p.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ }+ try {+ window.prompt('Copie o relatório abaixo (Ctrl+C / Toque longo):', markdown);+ showToast('Relatório preparado!');+ } catch (_) {+ showToast('Relatório preparado no campo abaixo para cópia!');+ }+ });+ } else {+ showToast('Erro ao gerar relatório.');+ }+ }).catch(e => {+ btn.disabled = false;+ showToast('Falha ao copiar: ' + e);+ });+}++function previewReport() {+ const { title, what } = getReportParams();+ const p = document.getElementById('logPreview');+ p.textContent = 'Carregando resumo do relatório sanitizado...';+ fetch('/api/report-issue', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ title, what })+ }).then(r => r.json()).then(data => {+ if (data && data.excerpt) {+ p.textContent = `=== RELATÓRIO PREPARADO ===\nTítulo: ${data.title}\nPlataforma: ${data.platform}\nVersão: v${data.release}\nFirmware: ${data.firmware}\n\n${data.excerpt}`;+ } else {+ p.textContent = 'Nenhum dado retornado.';+ }+ }).catch(e => {+ p.textContent = 'Erro ao carregar pré-visualização: ' + e;+ });+}++function applyLoadedSettings(s) {+ currentSettings = Object.assign(currentSettings, s);+ if (s.settingsVersion !== undefined) lastSettingsVersion = s.settingsVersion;+ if (s.query !== undefined && document.activeElement !== searchInput) searchInput.value = s.query;+ if (s.tab) {+ currentSearchTab = s.tab;+ }+ if (s.filters) {+ if (s.filters.wishlist !== undefined) {+ currentFilters.wishlist = !!s.filters.wishlist;+ const el = document.getElementById('chipWishlist');+ if (el) el.classList.toggle('active', currentFilters.wishlist);+ }+ if (s.filters.free !== undefined) {+ currentFilters.free = !!s.filters.free;+ const el = document.getElementById('chipFree');+ if (el) el.classList.toggle('active', currentFilters.free);+ }+ if (s.filters.cheapest !== undefined) {+ currentFilters.cheapest = !!s.filters.cheapest;+ const el = document.getElementById('chipCheapest');+ if (el) el.classList.toggle('active', currentFilters.cheapest);+ }+ if (s.filters.mouseKeyboard !== undefined) {+ currentFilters.mouseGP = !!s.filters.mouseKeyboard;+ currentFilters.mouseLib = !!s.filters.mouseKeyboard;+ const elGP = document.getElementById('chipMouseGP');+ if (elGP) elGP.classList.toggle('active', currentFilters.mouseGP);+ const elLib = document.getElementById('chipMouseLib');+ if (elLib) elLib.classList.toggle('active', currentFilters.mouseLib);+ }+ if (s.filters.plan !== undefined) {+ currentFilters.plan = s.filters.plan;+ const sel = document.getElementById('filterPlan');+ if (sel) sel.value = s.filters.plan;+ const wrap = document.getElementById('chipSelectPlan');+ if (wrap) wrap.classList.toggle('active', s.filters.plan > 0);+ }+ if (s.filters.console !== undefined) {+ currentFilters.consoleGP = s.filters.console;+ currentFilters.consoleLib = s.filters.console;+ const selGP = document.getElementById('filterConsoleGP');+ if (selGP) selGP.value = s.filters.console;+ const selLib = document.getElementById('filterConsoleLib');+ if (selLib) selLib.value = s.filters.console;+ const wrapGP = document.getElementById('chipSelectConsoleGP');+ if (wrapGP) wrapGP.classList.toggle('active', s.filters.console > 0);+ const wrapLib = document.getElementById('chipSelectConsoleLib');+ if (wrapLib) wrapLib.classList.toggle('active', s.filters.console > 0);+ }+ if (s.filters.mode !== undefined) {+ currentFilters.modeGP = s.filters.mode;+ currentFilters.modeLib = s.filters.mode;+ const selGP = document.getElementById('filterModeGP');+ if (selGP) selGP.value = s.filters.mode;+ const selLib = document.getElementById('filterModeLib');+ if (selLib) selLib.value = s.filters.mode;+ const wrapGP = document.getElementById('chipSelectModeGP');+ if (wrapGP) wrapGP.classList.toggle('active', s.filters.mode > 0);+ const wrapLib = document.getElementById('chipSelectModeLib');+ if (wrapLib) wrapLib.classList.toggle('active', s.filters.mode > 0);+ }+ if (s.filters.language !== undefined) {+ currentFilters.langGP = s.filters.language;+ currentFilters.langLib = s.filters.language;+ const selGP = document.getElementById('filterLangGP');+ if (selGP) selGP.value = s.filters.language;+ const selLib = document.getElementById('filterLangLib');+ if (selLib) selLib.value = s.filters.language;+ const wrapGP = document.getElementById('chipSelectLangGP');+ if (wrapGP) wrapGP.classList.toggle('active', s.filters.language > 0);+ const wrapLib = document.getElementById('chipSelectLangLib');+ if (wrapLib) wrapLib.classList.toggle('active', s.filters.language > 0);+ }+ }+ if (s.maxBitrateMbps !== undefined) {+ const el = document.getElementById('inputBitrate');+ if (el) { el.value = s.maxBitrateMbps; onBitrateInput(s.maxBitrateMbps); }+ }+ if (s.highRefresh !== undefined) {+ const el = document.getElementById('check120Hz');+ if (el) el.checked = !!s.highRefresh;+ }+ if (s.deadzoneLeft !== undefined) {+ const el = document.getElementById('inputDeadzoneL');+ if (el) { el.value = s.deadzoneLeft; document.getElementById('valDeadzoneL').textContent = s.deadzoneLeft + '%'; }+ }+ if (s.deadzoneRight !== undefined) {+ const el = document.getElementById('inputDeadzoneR');+ if (el) { el.value = s.deadzoneRight; document.getElementById('valDeadzoneR').textContent = s.deadzoneRight + '%'; }+ }+ if (s.triggerStrength !== undefined) {+ const el = document.getElementById('inputTriggerStrength');+ if (el) { el.value = s.triggerStrength; document.getElementById('valTriggerStrength').textContent = s.triggerStrength; }+ }+ if (s.lightBarMode !== undefined) {+ const el = document.getElementById('selectLightBarMode');+ if (el) el.value = s.lightBarMode;+ onLightBarModeChange();+ }+ if (s.lightBarColour) {+ const el = document.getElementById('inputLightBarColor');+ if (el) el.value = s.lightBarColour;+ }+ if (s.queueReadyAlert !== undefined) {+ const el = document.getElementById('checkQueueAlert');+ if (el) el.checked = !!s.queueReadyAlert;+ }+ if (s.videoDecoder !== undefined) {+ const el = document.getElementById('selectVideoDecoder');+ if (el) el.value = s.videoDecoder;+ }+ if (s.voiceRouting !== undefined) {+ const el = document.getElementById('selectVoiceRouting');+ if (el) el.value = s.voiceRouting;+ }+ applySearchTabUI(currentSearchTab);+ updateSearchStatusText();+ renderPadMap();+ renderKeyMap();+ renderAllTouchpadGrids(s.touchpadShortcuts);+}++function loadAllSettingsFromServer() {+ fetch('/api/settings').then(r => r.json()).then(applyLoadedSettings).catch(() => {+ renderPadMap();+ renderKeyMap();+ renderAllTouchpadGrids(currentSettings.touchpadShortcuts);+ });+}+loadAllSettingsFromServer();++// --- Virtual Gamepad & Streaming Polling ---+let activePlayer = 1;+const padState = {+ btnA: false, btnB: false, btnX: false, btnY: false,+ dpadUp: false, dpadDown: false, dpadLeft: false, dpadRight: false,+ btnL1: false, btnR1: false, btnL3: false, btnR3: false,+ btnView: false, btnMenu: false, btnNexus: false,+ triggerL2: 0.0, triggerR2: 0.0,+ leftStickX: 0.0, leftStickY: 0.0,+ rightStickX: 0.0, rightStickY: 0.0+};+let padSendScheduled = false;++function setVirtualPlayer(p) {+ const prev = activePlayer;+ activePlayer = p;+ for (let i = 1; i <= 4; i++) {+ const btn = document.getElementById('btnPlayer' + i);+ if (btn) btn.classList.toggle('active', p === i);+ }+ const statusEl = document.getElementById('gamepadStatus');+ if (statusEl) {+ statusEl.textContent = 'Controle ativo para Jogador ' + p + (p === 1 ? ' (Principal)' : ' (Co-op Local)');+ }+ sendPadState(true, prev);+}++function toggleGamepadFullscreen() {+ const card = document.getElementById('gamepadCard');+ if (!card) return;+ const isFs = card.classList.contains('gamepad-fullscreen') || document.fullscreenElement === card || document.webkitFullscreenElement === card;+ if (!isFs) {+ card.classList.add('gamepad-fullscreen');+ if (card.requestFullscreen) {+ card.requestFullscreen().catch(() => {});+ } else if (card.webkitRequestFullscreen) {+ try { card.webkitRequestFullscreen(); } catch (_) {}+ }+ if (screen.orientation && screen.orientation.lock) {+ screen.orientation.lock('landscape').catch(() => {});+ }+ } else {+ card.classList.remove('gamepad-fullscreen');+ if (document.fullscreenElement || document.webkitFullscreenElement) {+ if (document.exitFullscreen) document.exitFullscreen().catch(() => {});+ else if (document.webkitExitFullscreen) {+ try { document.webkitExitFullscreen(); } catch (_) {}+ }+ }+ if (screen.orientation && screen.orientation.unlock) {+ try { screen.orientation.unlock(); } catch (_) {}+ }+ }+ setTimeout(updateGamepadScale, 20);+ setTimeout(updateGamepadScale, 150);+}++document.addEventListener('fullscreenchange', () => {+ const card = document.getElementById('gamepadCard');+ if (card && !document.fullscreenElement && !document.webkitFullscreenElement) {+ card.classList.remove('gamepad-fullscreen');+ }+ setTimeout(updateGamepadScale, 30);+});+document.addEventListener('webkitfullscreenchange', () => {+ const card = document.getElementById('gamepadCard');+ if (card && !document.fullscreenElement && !document.webkitFullscreenElement) {+ card.classList.remove('gamepad-fullscreen');+ }+ setTimeout(updateGamepadScale, 30);+});++function sendPadState(activeSwitch = false, prevPlayer = 0) {+ const payload = { player: activePlayer, prevPlayer: prevPlayer, activeSwitch: !!activeSwitch, ...padState };+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify(payload));+ } else {+ fetch('/api/gamepad', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)+ }).catch(() => {});+ }+}++function schedulePadSend() {+ if (padSendScheduled) return;+ padSendScheduled = true;+ requestAnimationFrame(() => {+ padSendScheduled = false;+ sendPadState(false);+ });+}++function bindPadButtons() {+ document.querySelectorAll('[data-btn]').forEach(el => {+ const key = el.getAttribute('data-btn');+ const isTrigger = key === 'triggerL2' || key === 'triggerR2';+ const activeTouches = new Set();++ const setDown = () => {+ if (isTrigger) padState[key] = 1.0;+ else padState[key] = true;+ el.classList.add('pressed');+ if (navigator.vibrate) {+ try { navigator.vibrate(14); } catch (_) {}+ }+ sendPadState(false);+ };++ const setUp = () => {+ if (isTrigger) padState[key] = 0.0;+ else padState[key] = false;+ el.classList.remove('pressed');+ sendPadState(false);+ };++ el.addEventListener('touchstart', (e) => {+ e.preventDefault();+ for (let i = 0; i < e.changedTouches.length; i++) {+ activeTouches.add(e.changedTouches[i].identifier);+ }+ setDown();+ }, { passive: false });++ const onTouchEnd = (e) => {+ e.preventDefault();+ for (let i = 0; i < e.changedTouches.length; i++) {+ activeTouches.delete(e.changedTouches[i].identifier);+ }+ if (activeTouches.size === 0) setUp();+ };++ el.addEventListener('touchend', onTouchEnd, { passive: false });+ el.addEventListener('touchcancel', onTouchEnd, { passive: false });+ el.addEventListener('mousedown', (e) => { e.preventDefault(); setDown(); });+ el.addEventListener('mouseup', (e) => { e.preventDefault(); setUp(); });+ el.addEventListener('mouseleave', () => { if (activeTouches.size === 0 && el.classList.contains('pressed')) setUp(); });+ });+}++function setupStick(zoneId, headId, stickKeyX, stickKeyY) {+ const zone = document.getElementById(zoneId);+ const head = document.getElementById(headId);+ if (!zone || !head) return;++ let activeTouchId = null;++ function updateStick(clientX, clientY) {+ const rect = zone.getBoundingClientRect();+ const maxR = Math.max(28, (rect.width - head.offsetWidth) / 2);+ const cx = rect.left + rect.width / 2;+ const cy = rect.top + rect.height / 2;+ let dx = clientX - cx;+ let dy = clientY - cy;+ const dist = Math.hypot(dx, dy);+ if (dist > maxR) {+ dx = (dx / dist) * maxR;+ dy = (dy / dist) * maxR;+ }+ head.style.transform = `translate(${dx}px, ${dy}px)`;+ padState[stickKeyX] = Math.round((dx / maxR) * 100) / 100;+ padState[stickKeyY] = Math.round((dy / maxR) * 100) / 100;+ schedulePadSend();+ }++ function resetStick() {+ head.style.transform = 'translate(0px, 0px)';+ padState[stickKeyX] = 0.0;+ padState[stickKeyY] = 0.0;+ activeTouchId = null;+ sendPadState(false);+ }++ zone.addEventListener('touchstart', (e) => {+ e.preventDefault();+ if (activeTouchId === null && e.changedTouches.length > 0) {+ activeTouchId = e.changedTouches[0].identifier;+ updateStick(e.changedTouches[0].clientX, e.changedTouches[0].clientY);+ }+ }, { passive: false });++ zone.addEventListener('touchmove', (e) => {+ e.preventDefault();+ for (let i = 0; i < e.changedTouches.length; i++) {+ if (e.changedTouches[i].identifier === activeTouchId) {+ updateStick(e.changedTouches[i].clientX, e.changedTouches[i].clientY);+ break;+ }+ }+ }, { passive: false });++ const onTouchEnd = (e) => {+ for (let i = 0; i < e.changedTouches.length; i++) {+ if (e.changedTouches[i].identifier === activeTouchId) {+ resetStick();+ break;+ }+ }+ };+ zone.addEventListener('touchend', onTouchEnd, { passive: false });+ zone.addEventListener('touchcancel', onTouchEnd, { passive: false });++ // Mouse fallback+ let isMouseDown = false;+ zone.addEventListener('mousedown', (e) => {+ isMouseDown = true;+ updateStick(e.clientX, e.clientY);+ });+ window.addEventListener('mousemove', (e) => {+ if (isMouseDown) updateStick(e.clientX, e.clientY);+ });+ window.addEventListener('mouseup', () => {+ if (isMouseDown) {+ isMouseDown = false;+ resetStick();+ }+ });+}++bindPadButtons();+setupStick('leftStickZone', 'leftStickHead', 'leftStickX', 'leftStickY');+setupStick('rightStickZone', 'rightStickHead', 'rightStickX', 'rightStickY');++// Periodic streaming state poll and PS5 <-> WebUI settings version sync+let isCurrentlyStreaming = false;+function pollStreamingState() {+ fetch('/api/status').then(r => r.json()).then(data => {+ const streaming = !!data.streaming;+ if (streaming !== isCurrentlyStreaming) {+ isCurrentlyStreaming = streaming;+ const overlay = document.getElementById('searchOverlay');+ if (overlay) overlay.style.display = streaming ? 'flex' : 'none';+ if (searchInput) searchInput.disabled = streaming;+ }+ if (data.settingsVersion !== undefined && data.settingsVersion !== lastSettingsVersion) {+ lastSettingsVersion = data.settingsVersion;+ applyLoadedSettings(data);+ loadStreamMenuState();+ }+ }).catch(() => {});+}+setInterval(pollStreamingState, 1500);+pollStreamingState();++// Gamepad keepalive while gamepad tab is open (300ms ensures held buttons never drop)+setInterval(() => {+ const gpPane = document.getElementById('tab-gamepad');+ if (gpPane && gpPane.style.display !== 'none') {+ sendPadState(false);+ }+}, 300);++function updateGamepadScale() {+ const container = document.getElementById('gamepadScaleContainer');+ const card = document.getElementById('gamepadCard');+ if (!container || !card) return;+ const isFs = card.classList.contains('gamepad-fullscreen') || document.fullscreenElement === card || document.webkitFullscreenElement === card;+ const isLandscape = window.innerWidth > window.innerHeight;++ if (isFs) {+ const w = window.innerWidth;+ const h = window.innerHeight;+ const availW = container.clientWidth ? Math.max(200, container.clientWidth - 8) : (w - 28);+ const availH = container.clientHeight ? Math.max(150, container.clientHeight - 8) : (h - 20);+ const scale = Math.min(1.2, Math.max(0.4, Math.min(availW / 915, availH / 412)));+ document.documentElement.style.setProperty('--gp-fs-scale', scale.toFixed(3));+ document.documentElement.style.setProperty('--gp-scale', scale.toFixed(3));+ return;+ }++ let availW = container.clientWidth;+ if (!availW) {+ const padding = window.innerWidth <= 600 ? 16 : 32;+ availW = Math.max(0, window.innerWidth - padding);+ }++ if (!isLandscape) {+ const targetW = Math.max(0, availW - 16);+ const scale = Math.min(1, Math.max(0.4, targetW / 412));+ document.documentElement.style.setProperty('--gp-scale', scale.toFixed(3));+ } else {+ const targetW = Math.max(0, availW - 16);+ const availH = window.innerHeight;+ const targetH = Math.max(120, availH - 78);+ const scale = Math.min(1, Math.max(0.35, Math.min(targetW / 915, targetH / 412)));+ document.documentElement.style.setProperty('--gp-scale', scale.toFixed(3));+ }+}+window.addEventListener('resize', updateGamepadScale);+window.addEventListener('orientationchange', () => setTimeout(updateGamepadScale, 50));+window.addEventListener('DOMContentLoaded', updateGamepadScale);+if (window.ResizeObserver) {+ const ro = new ResizeObserver(() => updateGamepadScale());+ const cardEl = document.getElementById('gamepadCard');+ if (cardEl) ro.observe(cardEl);+}++// Hash & route navigation support: #gamepad, #gamepad-fs, #logs, #settings, /boost, /gamepad, etc.+function checkHashNav() {+ const p = (location.pathname || '').toLowerCase();+ if (p.includes('/boost') || p.includes('/gamepad')) {+ switchTab('gamepad');+ }+ const h = (location.hash || '').replace('#', '');+ if (!h) return;+ if (h === 'gamepad-fs') {+ switchTab('gamepad');+ const card = document.getElementById('gamepadCard');+ if (card && !card.classList.contains('gamepad-fullscreen')) {+ toggleGamepadFullscreen();+ }+ } else if (document.getElementById('tab-' + h)) {+ switchTab(h);+ }+}+window.addEventListener('hashchange', checkHashNav);+checkHashNav();+</script>+</body>+</html>)html";++} // namespace++const char* webServerIndexHtml() {+ return kIndexHtml;+}++} // namespace xc::appdiff --git a/src/app/worker.cpp b/src/app/worker.cppindex cbfed30..50b7929 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -3,46 +3,31 @@// The worker thread: sign-in, the library, the account's consoles, and// playing a title (queue -> /connect -> Provisioned -> StreamPlayer). It// owns AuthManager and the GssvClients and does all the network work.-#include "app/app_state.h"+#include "app/worker_internal.h"+#include "app/autoplay.h"#include "app/crash_guard.h"-#include "app/library.h"#include "app/shell.h"#include "app/stream_player.h"-#include "app/update_check.h"-#include "app/updater.h"-#include "auth/auth_manager.h"-#include "input/controller.h"-#include "media/audio_out.h"-#include "media/audio_queue.h"#include "net/http.h"#include "platform/platform.h"#include "ui/strings.h"#include "util/log.h"#include "xcloud/catalog.h"-#include "xcloud/gssv.h"-#include "xcloud/regions.h"#include "xcloud/purchase.h"--#include <cmath>+#include "xcloud/regions.h"#include <algorithm>#include <chrono>#include <condition_variable>#include <cstdlib>-#include <cstring>#include <map>-#include <fcntl.h>-#include <netdb.h>-#include <poll.h>-#include <sys/socket.h>-#include <unistd.h>#include <memory>#include <thread>+#include <unistd.h>#include <vector>namespace xc::app {-namespace {// Background catalog hydration (hero art, descriptions).std::atomic<bool> g_stopHydration{false};@@ -58,12 +43,6 @@ void stopHydration() {bool g_probing = false;std::string g_afterProbeAlias;-std::string formatWait(int seconds) {- if (seconds < 0) return "...";- if (seconds < 60) return std::to_string(seconds) + " s";- return std::to_string((seconds + 59) / 60) + " min";-}-// Set by stream(): the game quit on the server before its first frame.bool g_gameClosedOnServer = false;// Titles that would not start in the automatic region, and where they did@@ -76,52 +55,6 @@ std::mutex s_libraryMutex;// based on playtime telemetry, as Microsoft does not enforce client-side blocking.int64_t s_playtimeRemainingSeconds = -1;-} // namespace--void playQueueReadyAlert(bool notifyToast) {- // 1. DualSense rumble pulse- input::setRumble(180, 180, 500, 0);-- // 2. Synthesize a pleasant 3-tone harmonic chime (E5 -> G#5 -> B5, E Major triad)- constexpr int kRate = 48000;- constexpr float kPi = 3.14159265358979323846f;- struct Tone {- float freq;- int ms;- };- const Tone tones[3] = {- {659.25f, 100}, // E5- {830.61f, 100}, // G#5- {987.77f, 220} // B5- };-- std::vector<float> pcm;- pcm.reserve(kRate * 2);- for (int t = 0; t < 3; ++t) {- int frames = (kRate * tones[t].ms) / 1000;- float freq = tones[t].freq;- float decayRate = (t == 2) ? 6.0f : 4.0f;- for (int i = 0; i < frames; ++i) {- float sec = static_cast<float>(i) / static_cast<float>(kRate);- float attack = std::min(1.0f, sec / 0.005f);- float decay = std::exp(-decayRate * sec);- float env = attack * decay * 0.70f;- float s = std::sin(2.0f * kPi * freq * sec) + 0.25f * std::sin(4.0f * kPi * freq * sec);- float sample = s * env;- pcm.push_back(sample); // Left- pcm.push_back(sample); // Right- }- }-- // Play directly through the DualSense controller speaker (falls back to main audio)- media::playPadSpeakerAudio(pcm.data(), pcm.size() / 2);-- // 3. System notification toast (only when stream queue actually finishes)- if (notifyToast) {- platform::notify(ui::tr(ui::Str::QueueReadyAlert));- }-}-void updateLibraryFavorites(const std::vector<std::string>& favorites) {std::shared_ptr<app::Library> lib;{@@ -156,293 +89,6 @@ std::shared_ptr<Library> currentLibrary() {return s_library;}-namespace {--// Streams until the player ends or the user leaves; returns a status line.-// The cloud title being played, for crash markers (set by play()).-std::string g_stageTitle;-std::string g_stageProduct;--std::string stream(xcloud::GssvClient& gssv) {- crash::setStage(gssv.isHome() ? "streaming own Xbox" : ("streaming " + g_stageTitle).c_str());- g_gameClosedOnServer = false;- app::StreamPlayer player(gssv);- if (g_autoplay.dump) player.dumpVideo(platform::dataDir() + "/stream.aus", g_autoplay.seconds + 15);- player.setDecodeThreads(g_autoplay.decodeThreads);- player.setSimulatedLoss(g_autoplay.videoLoss);- player.setHwDecodeProbe(g_autoplay.hwDecode);- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- bool hasCustom = false;- GameProfile prof = g_settings.profileForGame(g_stageProduct, g_stageTitle, &hasCustom);- bool preferHw = true;- if (g_autoplay.swDecode) {- preferHw = false;- } else if (g_autoplay.preferHwDecode) {- preferHw = (hasCustom ? (prof.videoDecoder == 0) : (g_settings.videoDecoder == 0));- } else {- preferHw = false;- }- player.setPreferHwDecode(preferHw);- XC_LOGI("stream: video decoder %s", preferHw ? "hardware preferred" : "software (CPU)");- player.setMicGain(g_settings.micGainFactor());- player.setMicEnabled(g_settings.micEnabled);- int cap = g_autoplay.bitrateMbps > 0 ? g_autoplay.bitrateMbps : g_settings.maxBitrateMbps;- player.setMaxBitrate(cap);- media::audioSetVolume(g_settings.gameVolume / 100.0f);- XC_LOGI("stream: bitrate cap %s, game volume %d%%",- cap ? (std::to_string(cap) + " Mbps").c_str() : "automatic",- g_settings.gameVolume);- media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));- media::audioSetVoiceRouting(g_settings.voiceRouting);- int hapticLvl = hasCustom ? prof.audioHaptics : g_settings.audioHaptics;- media::setAudioHapticsLevel(hapticLvl);- }- std::string err;- if (!player.start(err)) return "ERROR: " + ui::trf(ui::Str::StreamFailed, err);- {- std::lock_guard<std::mutex> lock(g_playerMutex);- g_player = &player;- }- g_ui->showStreaming();- {- // The touchpad's gestures, in the first three streams only.- std::lock_guard<std::mutex> lock(g_settingsMutex);- if (g_settings.gestureHints < 3) {- ++g_settings.gestureHints;- g_settings.save(settingsPath());- // (Without a touchpad: the buttons and keys that do the same.)- platform::notify(ui::tr(g_ui->caps().touchpad ? ui::Str::GestureHint : ui::Str::GestureHintButtons));- }- }-- const uint64_t started = platform::nowMs();- uint64_t nextTick = started;- bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;- bool autoplayDone = false;- int bestRtt = -1; // lowest round trip seen: the region's latency- int tallest = 0; // the tallest picture seen (the probe's measure)- // The connection's state for the warning and the end-of-session summary:- // a second is bad when the jitter buffer dropped a frame (lost for good),- // no video arrived at all, or the round trip went far above the best seen.- // Not the frame rate: games send fewer frames in some scenes.- uint64_t degradedUntil = 0, lastTickAt = 0;- bool degradedLogged = false;- uint32_t reconnectsSeen = 0;- struct {- uint64_t seconds = 0, badSeconds = 0, kbps = 0, rttSum = 0, rttCount = 0;- } session;- uint64_t prevPlaytime = 0;- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- prevPlaytime = g_settings.playtimeForGame(g_stageProduct, g_stageTitle);- }- bool probeDone = !g_probing;- auto recordProbe = [&] {- probeDone = true;- if (tallest <= 0) return;- std::lock_guard<std::mutex> lock(g_settingsMutex);- (gssv.isHome() ? g_settings.maxHeightHome : g_settings.maxHeightCloud) = tallest;- (gssv.isHome() ? g_settings.probedHome : g_settings.probedCloud) = auth::unixNow();- g_settings.save(settingsPath());- g_ui->setAllow1440(allow1440Locked());- XC_LOGI("resolution probe (%s): %dp at most", gssv.isHome() ? "own Xbox" : "cloud", tallest);- };- app::StreamPlayer::Stats last{};- while (player.running() && !g_cancel) {- uint64_t elapsed = platform::nowMs() - started;- if (!g_autoplay.title.empty()) {- if (elapsed >= static_cast<uint64_t>(g_autoplay.seconds) * 1000u) {- autoplayDone = true;- break;- }- if (!snapshot1 && elapsed >= 10000) {- snapshot1 = true;- player.requestSnapshot(platform::dataDir() + "/frame.ppm");- }- bool press = !g_autoplay.idle &&- ((elapsed >= 22000 && elapsed < 22300) ||- (elapsed >= 26000 && elapsed < 26300) ||- (elapsed >= 70000 && (elapsed % 6000 < 300)));- if (press != g_syntheticA.exchange(press)) XC_LOGI("autoplay: A %s", press ? "down" : "up");- static bool dropped = false;- if (g_autoplay.dropTest && !dropped && elapsed >= 20000) {- dropped = true;- player.simulateDrop();- }- if (!snapshot2 && elapsed >= 28000) {- snapshot2 = true;- player.requestSnapshot(platform::dataDir() + "/frame2.ppm");- }- if (!snapshot3 && elapsed >= 70000) {- snapshot3 = true;- player.requestSnapshot(platform::dataDir() + "/frame3.ppm");- }- if (!snapshot4 && elapsed >= 110000) {- snapshot4 = true;- player.requestSnapshot(platform::dataDir() + "/frame4.ppm");- }- }- if (platform::nowMs() >= nextTick) {- uint64_t tickNow = platform::nowMs();- double dt = lastTickAt ? (tickNow - lastTickAt) / 1000.0 : 1.0;- nextTick = tickNow + 1000;- player.tick();- 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 (%s), draw %.1f/%.1f ms, %llu late; "- "rtt %d ms; %dx%d; on screen %.1f/%.1f ms after arrival; qp %.1f",- 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),- static_cast<unsigned long long>(st.queued), static_cast<unsigned long long>(st.audioPackets),- static_cast<unsigned long long>(st.rtpPackets), static_cast<unsigned long long>(st.rtpLost),- static_cast<unsigned long long>(st.rtpRecovered), static_cast<unsigned long long>(st.rtpNacks),- 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.isHwDecode ? "HW" : "SW",- st.drawAvgUs / 1000.0, st.drawMaxUs / 1000.0,- static_cast<unsigned long long>(st.lateFrames), st.rttMs, st.width, st.height,- st.displayAvgUs / 1000.0, st.displayMaxUs / 1000.0, st.qpAvg);- if (st.rttMs > 0 && (bestRtt < 0 || st.rttMs < bestRtt)) bestRtt = st.rttMs;- tallest = std::max(tallest, st.height);- if (!probeDone && platform::nowMs() - started >= 20000) {- recordProbe();- if (!g_afterProbeAlias.empty() && !g_tierPicked) player.requestResolution(g_afterProbeAlias);- }- {- ui::StreamInfo info;- info.region = ui::prettyRegion(gssv.region().name);- info.rttMs = st.rttMs;- info.fps = dt > 0.05- ? std::max(0.0, static_cast<double>(st.decodedFrames - last.decodedFrames -- (st.droppedFrames - last.droppedFrames)) /- dt)- : 60.0;- info.mbps = st.rtpKbps / 1000.0;- uint64_t lost = st.rtpLost - last.rtpLost, got = st.rtpPackets - last.rtpPackets;- info.lossPct = got + lost ? 100.0 * lost / (got + lost) : 0;- info.decodeMs = st.decodeAvgUs / 1000.0;- info.isHwDecode = st.isHwDecode;- info.onScreenMs = st.displayAvgUs / 1000.0;- info.width = st.width;- info.height = st.height;- info.qp = st.qpAvg;- if (last.decodedFrames > 0) { // once the picture is running- uint64_t dropped = st.rtpDroppedFrames - last.rtpDroppedFrames;- uint64_t now = platform::nowMs();- // No video for a second; or the loop itself held up (a- // reconnection blocks it) / a new session after a drop.- bool stalled = st.videoFrames == last.videoFrames || (lastTickAt && now - lastTickAt > 2500) ||- player.reconnects() != reconnectsSeen;- reconnectsSeen = player.reconnects();- bool slow = st.rttMs > 0 && bestRtt > 0 && st.rttMs > bestRtt + 60;- if (dropped || stalled || slow) {- if (!degradedLogged) // once per episode- XC_LOGW("connection degraded: %llu frame(s) lost, %s, rtt %d ms (best %d)",- static_cast<unsigned long long>(dropped), stalled ? "no video for a second" : "video arriving",- st.rttMs, bestRtt);- degradedLogged = true;- degradedUntil = now + 3000;- ++session.badSeconds;- } else if (now >= degradedUntil) {- degradedLogged = false;- }- info.degraded = now < degradedUntil;- lastTickAt = tickNow;- ++session.seconds;- session.kbps += st.rtpKbps;- if (st.rttMs > 0) session.rttSum += static_cast<uint64_t>(st.rttMs), ++session.rttCount;- }- if (s_playtimeRemainingSeconds >= 0) {- info.playtimeHours = static_cast<int>((s_playtimeRemainingSeconds + 3599) / 3600);- }- info.playtimeSeconds = prevPlaytime + session.seconds;- player.getRecentFrametimes(info.frametimes);- std::lock_guard<std::mutex> lock(g_infoMutex);- g_streamInfo = info;- ++g_infoSeq;- }- last = st;- }- platform::sleepMs(100);- }- {- std::lock_guard<std::mutex> lock(g_playerMutex);- g_player = nullptr;- }- if (!probeDone && player.stats().decodedFrames > 0) recordProbe(); // a short stream still measured- std::string reason = g_cancel ? "left the game" : autoplayDone ? "autoplay finished" : player.endReason();- player.stop();- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- media::setAudioHapticsLevel(g_settings.audioHaptics);- }- if (session.seconds >= 5 && (!g_stageTitle.empty() || !g_stageProduct.empty())) {- std::lock_guard<std::mutex> lock(g_settingsMutex);- uint64_t newTotal = prevPlaytime + session.seconds;- if (!g_stageTitle.empty()) g_settings.titlePlaytime[g_stageTitle] = newTotal;- if (!g_stageProduct.empty()) g_settings.titlePlaytime[g_stageProduct] = newTotal;- g_settings.save(settingsPath());- if (g_ui) g_ui->setSettings(ui::choiceFromSettings(g_settings));- XC_LOGI("playtime: updated for %s (%s) to %llu seconds (%s)", g_stageTitle.c_str(),- g_stageProduct.c_str(), static_cast<unsigned long long>(newTotal),- ui::formatPlaytime(newTotal).c_str());-- std::shared_ptr<app::Library> lib;- {- std::lock_guard<std::mutex> lockLib(s_libraryMutex);- lib = s_library;- }- if (lib) {- if (!g_stageProduct.empty()) lib->recordRecent(g_stageProduct);- else if (!g_stageTitle.empty()) lib->recordRecent(g_stageTitle);- lib->setPlaytime(g_settings.titlePlaytime);- g_ui->setRows(lib->rows());- g_ui->setOwned(lib->owned(), lib->purchasable(), lib->ownedKnown());- }- }- 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();- if (session.seconds >= 10) {- // The session in one line: the log (and so a report) and a notification.- double lossPct = st.rtpPackets + st.rtpLost ? 100.0 * (st.rtpLost - std::min(st.rtpRecovered, st.rtpLost)) /- static_cast<double>(st.rtpPackets + st.rtpLost)- : 0;- char details[160];- std::snprintf(details, sizeof details, "%llu min, %dp, %.1f Mbps, %.2f%% lost, %d ms",- static_cast<unsigned long long>((session.seconds + 30) / 60), tallest,- session.kbps / 1000.0 / static_cast<double>(session.seconds), lossPct,- session.rttCount ? static_cast<int>(session.rttSum / session.rttCount) : -1);- XC_LOGI("session summary: %s; %llu s with a degraded connection, %llu frames lost, %llu recovered packets",- details, static_cast<unsigned long long>(session.badSeconds),- static_cast<unsigned long long>(st.rtpDroppedFrames), static_cast<unsigned long long>(st.rtpRecovered));- }- // Ended before a single frame: the game never started (e.g. it closed on- // the server); say so on the error screen instead of going back quietly.- if (st.decodedFrames == 0 && !g_cancel && !autoplayDone) {- g_gameClosedOnServer = reason.rfind("the game closed on the server", 0) == 0;- return "ERROR: " + ui::trf(ui::Str::StreamFailed, reason);- }- return "Stream ended (" + reason + "), " + std::to_string(st.decodedFrames) + " frames shown";-}--// Queue -> /connect -> Provisioned -> stream. Returns a status line; sets-// `failed` when the user should see an error rather than the home screen.-// `regionName` overrides the settings' region (empty: as set).-// Profile token for titlehub (memory only).std::string g_xblAuth;std::string g_xuid;@@ -450,7 +96,7 @@ std::string g_xuid;// `force`: a request was refused), before the xCloud calls. What other// threads hold follows a renewal: titlehub's token, and the copy of the// cloud client the queue estimates use.-bool keepSignedIn(auth::AuthManager& am, xcloud::GssvClient& gssv, std::string& err, bool force = false) {+bool keepSignedIn(auth::AuthManager& am, xcloud::GssvClient& gssv, std::string& err, bool force) {bool renewed = false;if (!am.ensureFresh(&gssv, err, force, &renewed)) return false;if (renewed) {@@ -465,277 +111,6 @@ bool keepSignedIn(auth::AuthManager& am, xcloud::GssvClient& gssv, std::string&return true;}-std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::GameTile& game, bool& failed,- const std::string& regionName = {}) {- failed = true;- // A home session's id is the console's: only its start in the log.- XC_LOGI("starting %s (%s)", gssv.isHome() ? "own Xbox" : game.name.c_str(), // not the console's name- gssv.isHome() ? (game.titleId.substr(0, 4) + "...").c_str() : game.titleId.c_str());- g_ui->showLaunching(game, regionName.empty() ? ui::tr(ui::Str::Connecting)- : ui::trf(ui::Str::TryingRegion, ui::prettyRegion(regionName)));- std::string err;- // A login about to expire is renewed first (its region kept); if that- // fails the start is tried all the same.- if (!keepSignedIn(am, gssv, err)) XC_LOGW("sign-in renewal: %s", err.c_str());- err.clear();- std::string streamLocale = ui::gameLocale();- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- bool hasCustom = false;- GameProfile prof = g_settings.profileForGame(game.productId, game.titleId, &hasCustom);- if (!prof.locale.empty()) streamLocale = prof.locale;- std::string res;- if (!g_autoplay.resolution.empty()) {- res = g_autoplay.resolution;- } else if (hasCustom) {- res = prof.resolution == 1 ? "720p" : prof.resolution == 2 ? "best" : "1080p";- } else {- res = g_settings.resolution;- }- bool isBest = (res == "best" || res == "1440p");- // "Best" asks for the top tier every time, nothing measured or- // remembered: the service gives what the plan and the game allow- // (1440p where it can, else 1080p). The user's own Xbox always gets- // the top tier (it sends 1080p either way, at ~16 Mbps instead of ~9.5).- bool home = gssv.isHome();- g_probing = false;- g_afterProbeAlias.clear();- g_tierPicked = false;- xcloud::Resolution tier;- if (!g_autoplay.resolution.empty())- tier = res == "720p" ? xcloud::Resolution::P720- : res == "1440p" ? xcloud::Resolution::P1440- : res == "1080p-hq" ? xcloud::Resolution::P1080HQ- : isBest ? (allow1440Locked() ? xcloud::Resolution::P1440 : xcloud::Resolution::P1080HQ)- : xcloud::Resolution::P1080HQ;- else if (res == "720p")- tier = xcloud::Resolution::P720;- else if (home)- tier = xcloud::Resolution::P1440;- else if (res == "1440p" || (isBest && allow1440Locked()))- tier = xcloud::Resolution::P1440;- else- tier = xcloud::Resolution::P1080HQ;- gssv.setResolution(tier);- const xcloud::Region* region = gssv.session().defaultRegion();- const std::string& wanted = regionName.empty() ? g_settings.region : regionName;- for (const auto& r : gssv.session().regions)- if (r.name == wanted) region = &r;- if (region) gssv.setRegion(*region);- XC_LOGI("stream settings: %s%s, region %s, locale %s", res.c_str(),- hasCustom ? " (per-game)" : "", region ? region->name.c_str() : "?", streamLocale.c_str());- }- // For a crash marker: what is being started (a console's id stays out).- g_stageTitle = game.titleId;- g_stageProduct = game.productId;- crash::setStage(gssv.isHome() ? "starting own Xbox" : ("starting " + game.titleId).c_str());- int status = 0;- bool started = gssv.startSession(game.titleId, streamLocale, err, &status);- if (!started && status == 401 && !g_cancel) {- // The token refused before its time: renewed once, asked again.- XC_LOGW("%s; renewing the sign-in and asking again", err.c_str());- std::string renewErr;- if (keepSignedIn(am, gssv, renewErr, true)) started = gssv.startSession(game.titleId, streamLocale, err, &status);- else XC_LOGW("sign-in renewal: %s", renewErr.c_str());- }- if (!started) {- if (err.find("0x87DD043A") != std::string::npos || err.find("MonthlyLimitExceeded") != std::string::npos) {- return std::string(ui::tr(ui::Str::MonthlyLimitExceeded));- }- return err;- }- if (game.heroUrl.empty() && !game.productId.empty()) {- // Picked before the background hydration reached it: fetch the hero- // art for the loading screen while the session queues.- std::map<std::string, xcloud::Product> full;- std::string e;- if (xcloud::fetchProducts({game.productId}, gssv.session().market.empty() ? "US" : gssv.session().market,- ui::catalogLanguage(), full, e, true) &&- full.count(game.productId)) {- ui::GameTile withArt = game;- withArt.heroUrl = full[game.productId].heroUrl;- XC_LOGI("launch art: %s", withArt.heroUrl.empty() ? "(none)" : withArt.heroUrl.c_str());- g_ui->showLaunching(withArt, ui::tr(ui::Str::Connecting));- }- }- bool connected = false;- bool wasInQueue = false;- std::string result = "timed out waiting for the session";- // A console that is off for good (not asleep) never comes out of- // Provisioning: give up after a minute (the cloud's queue may take long).- const uint64_t provisioningSince = platform::nowMs();- int pollErrors = 0;- // The queue's estimate: the title's (the service has no per-session one),- // asked every 15 s and counted down in between; -1 unknown.- int queueSeconds = -1;- uint64_t queueAskedAt = 0;- for (int i = 0; i < 900 && !g_cancel; ++i) {- if (gssv.isHome() && platform::nowMs() - provisioningSince > 60000) {- result = "ConsoleDidNotWake: no answer in 60 s";- break;- }- xcloud::SessionStatus st;- if (!gssv.sessionState(st, err)) {- // A network hiccup (a TLS timeout) is asked again; three in a row end it.- if (++pollErrors < 3) {- XC_LOGW("%s (asking again)", err.c_str());- platform::sleepMs(1000);- continue;- }- result = err;- break;- }- pollErrors = 0;- XC_LOGI("session state: %s", st.raw.c_str());- if (st.state == xcloud::SessionState::WaitingForResources) {- wasInQueue = true;- uint64_t now = platform::nowMs();- if (!queueAskedAt || now - queueAskedAt >= 15000) {- int s = gssv.titleWaitSeconds(game.titleId);- XC_LOGI("queue: estimated %d s", s);- if (s >= 0 || queueSeconds < 0) queueSeconds = s;- queueAskedAt = now;- }- int left = queueSeconds < 0 ? -1 : std::max(0, queueSeconds - static_cast<int>((now - queueAskedAt) / 1000));- g_ui->setLaunchStatus(left < 0 ? std::string(ui::tr(ui::Str::InQueueNoEstimate))- : ui::trf(ui::Str::InQueue, formatWait(left)));- }- if (st.state == xcloud::SessionState::Provisioning && gssv.isHome())- g_ui->setLaunchStatus(ui::tr(ui::Str::WakingConsole)); // a sleeping Xbox takes ~10 s- if (st.state == xcloud::SessionState::Failed) {- if (st.errorCode == "0x87DD043A" || st.errorCode == "MonthlyLimitExceeded" ||- st.raw.find("0x87DD043A") != std::string::npos || st.raw.find("MonthlyLimitExceeded") != std::string::npos) {- result = ui::tr(ui::Str::MonthlyLimitExceeded);- } else {- result = "the session failed: " + st.errorCode + " " + st.errorMessage;- }- break;- }- if (st.state == xcloud::SessionState::ReadyToConnect && !connected) {- std::string transfer;- if (!am.consoleTransferToken(transfer, err) || !gssv.connect(transfer, err)) {- result = err;- break;- }- connected = true;- }- if (st.state == xcloud::SessionState::Provisioned) {- bool alertOn = false;- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- alertOn = g_settings.queueReadyAlert;- }- if (alertOn && (wasInQueue || (platform::nowMs() - provisioningSince >= 2000))) {- XC_LOGI("session: queue completed and provisioned; triggering queue-ready chime and rumble on DualSense");- playQueueReadyAlert(true);- }- g_ui->setLaunchStatus(ui::tr(ui::Str::StartingStream));- result = stream(gssv);- failed = result.rfind("ERROR", 0) == 0;- break;- }- platform::sleepMs(1000);- }- if (g_cancel && failed) {- result = "cancelled";- failed = false;- }- gssv.stopSession();- return result;-}--void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefresh = false);--// --- Updates ---------------------------------------------------------------------// The newer release found at start (empty tag: none).-std::mutex g_releaseMutex;-Release g_release;--// Asks for the latest release; a newer one with a signed package is offered-// (the pop-up, unless the user said "Not now" to it) and shown in Settings.-void checkForUpdate() {- g_ui->setUpdateState(XC_APP_VERSION, {}, true);- Release r;- std::string err;- bool found = findLatestRelease(r, err, g_autoplay.updateFeed);- XC_LOGI("latest release: %s (this is %s)", found ? r.tag.c_str() : err.c_str(), XC_APP_VERSION);- bool newer = found && isNewerVersion(r.tag, XC_APP_VERSION);- bool offer = newer && !r.zipUrl.empty() && !r.sigUrl.empty();- if (newer && !offer) XC_LOGW("%s has no signed package", r.tag.c_str());- const bool selfUpdate = shell::canSelfUpdate();- if (newer && !selfUpdate) {- // This build doesn't install updates itself (only the PS5's does):- // Settings names the new version and opens its page instead.- XC_LOGI("%s is out: this build doesn't update itself", r.tag.c_str());- offer = false;- }- {- std::lock_guard<std::mutex> lock(g_releaseMutex);- g_release = offer ? r : Release{};- }- g_ui->setUpdateState(XC_APP_VERSION, offer || (newer && !selfUpdate) ? r.tag : std::string(), false, r.notes);- bool skipped;- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- skipped = g_settings.skippedUpdate == r.tag;- }- if (offer && !skipped) g_ui->offerUpdate(r.notes);-}--// The update itself, then the restart into the new version. A failure-// changes nothing and goes back to the home screen.-void runUpdate() {- Release r;- {- std::lock_guard<std::mutex> lock(g_releaseMutex);- r = g_release;- }- if (r.tag.empty()) return;- XC_LOGI("update to %s: starting", r.tag.c_str());- g_ui->showUpdating(r.tag);- // Only where the app runs from: installed elsewhere, it would write next- // to the wrong eboot.bin.- std::string dir = platform::appDir(), err;- bool ok = shell::isInstalledCopy(dir);- if (!ok) err = "the app doesn't run from " + dir;- int lastPct = -1;- ok = ok && installRelease(r, dir, XC_APP_VERSION, [&](UpdateStep step, double f) {- if (step == UpdateStep::Downloading) {- int pct = f < 0 ? 0 : static_cast<int>(f * 100);- if (pct == lastPct) return;- lastPct = pct;- g_ui->setUpdateStatus(ui::trf(ui::Str::UpdateDownloading, std::to_string(pct) + " %"), static_cast<float>(f));- } else {- g_ui->setUpdateStatus(ui::tr(step == UpdateStep::Verifying ? ui::Str::UpdateVerifying : ui::Str::UpdateInstalling), -1);- }- }, err);- if (!ok) {- XC_LOGE("update to %s failed: %s", r.tag.c_str(), err.c_str());- g_ui->showHome(ui::tr(ui::Str::UpdateFailed));- if (!g_autoplay.title.empty()) XC_LOGI("AUTOPLAY END: update failed");- return;- }- g_ui->setUpdateStatus(ui::tr(ui::Str::UpdateRestarting), 1);- platform::sleepMs(1500);- XC_LOGI("update to %s: restarting", r.tag.c_str());- g_restartWanted = true;-}--} // namespace--void skipOfferedUpdate() {- std::string tag;- {- std::lock_guard<std::mutex> lock(g_releaseMutex);- tag = g_release.tag;- }- std::lock_guard<std::mutex> lock(g_settingsMutex);- g_settings.skippedUpdate = tag;- g_settings.save(settingsPath());- XC_LOGI("update %s: not now", tag.c_str());-}-namespace {// The note on the home screen after a stream: who ended it, when known.@@ -766,10 +141,12 @@ void loadConsoles(auth::AuthManager& am, xcloud::GssvClient& home) {g_ui->setConsoles(std::move(tiles), true);}-namespace {-std::string g_subscription;} // namespace+std::string g_subscription;++namespace {+bool isDnsOrSinkholeError(const std::string& err) {return err.find("DNS lookup failed") != std::string::npos ||err.find("0x8041013d") != std::string::npos ||@@ -791,11 +168,14 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {std::string err;auto onCode = [](const auth::DeviceCode& dc) { g_ui->showSignIn(dc.userCode, dc.verificationUri); };std::string country;+ bool preview = false;{std::lock_guard<std::mutex> lock(g_settingsMutex);country = g_settings.loginCountry;+ preview = g_settings.previewFeatures;}gssv.setLoginCountry(country);+ gssv.setPreviewFeatures(preview);if (!am.signIn(gssv, onCode, err, &g_cancel)) {XC_LOGE("sign-in failed: %s", err.c_str());if (g_ui->screen() == ui::Screen::Home) {@@ -875,6 +255,9 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {}if (!am.saved()) // the next start would ask for a code again: said now, not thenplatform::notify(ui::tr(ui::Str::SignInNotSaved), "the sign-in couldn't be saved (notification)");+ if (g_ui->screen() == ui::Screen::SignIn) {+ g_ui->showSplash(ui::tr(ui::Str::LoadingGames));+ }g_ui->setProfile(am.profile().gamertag, am.profile().gamerpicUrl, am.profile().gamerscore);g_subscription = am.profile().subscription;if (!g_subscription.empty()) g_ui->setSubscription(g_subscription);@@ -899,7 +282,13 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {loadLibrary(am, gssv);}+} // namespace+void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefresh) {+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ gssv.setPreviewFeatures(g_settings.previewFeatures);+ }std::string err;if (!keepSignedIn(am, gssv, err)) XC_LOGW("sign-in renewal: %s", err.c_str());err.clear();@@ -911,25 +300,27 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefr}if (!forceRefresh && existingLib && existingLib->ownedKnown()) {+ stopHydration();+ existingLib->setSubscription(g_subscription);{std::lock_guard<std::mutex> lock(g_settingsMutex);existingLib->setPlaytime(g_settings.titlePlaytime);}+ setPriceMarket(gssv.session().market.empty() ? "US" : gssv.session().market, ui::catalogLanguage());+ setQueueClient(&gssv);XC_LOGI("library: delta-sync against active library (forceRefresh=%d)", forceRefresh);- if (g_ui->screen() == ui::Screen::Splash) {+ if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {g_ui->showSplash(ui::tr(ui::Str::LoadingGames));} else {g_ui->setLoading(true, 0, 0);}auto publish = [](const app::Library& lib) {- g_ui->setRows(lib.rows());- g_ui->setOwned(lib.owned(), lib.purchasable(), lib.ownedKnown());- g_ui->setMembership(lib.gamePassMember());- g_ui->setSearchPools(lib.gamePassSearchPool(), lib.librarySearchPool());auto p = lib.progress();- g_ui->setLoading(p.active, p.done, p.total);+ g_ui->setCatalogState(lib.rows(), lib.owned(), lib.purchasable(), lib.ownedKnown(),+ lib.gamePassMember(), lib.gamePassSearchPool(), lib.librarySearchPool(),+ p.active, p.done, p.total);};- size_t newCount = existingLib->syncDelta(gssv, [&] { publish(*existingLib); }, err);+ size_t newCount = existingLib->syncDelta(gssv, [&] { publish(*existingLib); }, err, ui::catalogLanguage());g_ui->setLoading(false, 0, 0);publish(*existingLib);@@ -942,13 +333,48 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrif (!shell::caps().console) g_ui->showToast(msg);platform::notify(msg);}- if (g_ui->screen() == ui::Screen::Splash) {+ if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {g_ui->showHome();}++ std::vector<ui::GameRow> rows = existingLib->rows();+ g_stopHydration = false;+ std::string xblAuth;+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ xblAuth = g_xblAuth;+ }+ platform::startThread(g_hydrationThread, [existingLib, publish, xblAuth] {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_hydr");+ auto changed = [&] { publish(*existingLib); };+ existingLib->loadFirstScreen(xblAuth, changed, &g_stopHydration);+ existingLib->loadFriends(xblAuth, changed, &g_stopHydration);+ existingLib->loadPlatforms(xblAuth, changed, &g_stopHydration);+ existingLib->hydrate(changed, &g_stopHydration);+ existingLib->loadFriends(xblAuth, changed, &g_stopHydration);+ g_ui->setLoading(false, 0, 0);+ });+ if (!g_autoplay.title.empty() && g_autoplay.title != "BENCH" && g_autoplay.title != "UPDATE" && g_autoplay.title != "AUTOTEST" &&+ !g_autoplay.detailTest && !g_autoplay.libraryTest &&+ !g_autoplay.consolesTab && !g_autoplay.settingsTest && !g_autoplay.keysTest && !g_autoplay.padMapTest &&+ !g_autoplay.imeTest && !g_autoplay.vibeTest && !g_autoplay.searchTest && !g_autoplay.quickTest && !g_autoplay.crashTest && !g_autoplay.scrollTest &&+ !g_autoplay.gridTest && !g_autoplay.gameSettingsTest && !g_autoplay.publisherTest && !g_autoplay.friendsTest &&+ !g_autoplay.regionTest && !g_autoplay.mw4Test && !g_autoplay.v150Test && !g_autoplay.claimTest) {+ platform::sleepMs(6000);+ ui::GameTile tile;+ tile.titleId = g_autoplay.title;+ tile.name = g_autoplay.title;+ for (const auto& row : rows)+ for (const auto& t : row.tiles)+ if ((t.titleId == g_autoplay.title || t.productId == g_autoplay.title || t.name == g_autoplay.title) && tile.productId.empty()) tile = t;+ std::lock_guard<std::mutex> lock(g_argMutex);+ g_playTile = tile;+ g_command = kPlay;+ }return;}- bool onSplash = (g_ui->screen() == ui::Screen::Splash);+ bool onSplash = (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn);if (onSplash) {g_ui->showSplash(ui::tr(ui::Str::LoadingGames));} else {@@ -974,21 +400,19 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrsetPriceMarket(gssv.session().market.empty() ? "US" : gssv.session().market, ui::catalogLanguage());setQueueClient(&gssv);bool shown = !onSplash;- // Hands the library's current state to the UI (copies).+ // Hands the library's current state to the UI (coalesced into a single rebuild).auto publish = [](const app::Library& lib) {- g_ui->setRows(lib.rows());- g_ui->setOwned(lib.owned(), lib.purchasable(), lib.ownedKnown());- g_ui->setMembership(lib.gamePassMember());- g_ui->setSearchPools(lib.gamePassSearchPool(), lib.librarySearchPool());auto p = lib.progress();- g_ui->setLoading(p.active, p.done, p.total);+ g_ui->setCatalogState(lib.rows(), lib.owned(), lib.purchasable(), lib.ownedKnown(),+ lib.gamePassMember(), lib.gamePassSearchPool(), lib.librarySearchPool(),+ p.active, p.done, p.total);};bool ok = library->load(gssv, ui::catalogLanguage(),[&] {publish(*library);if (!shown) {shown = true;- if (g_ui->screen() == ui::Screen::Splash) {+ if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {g_ui->showHome();}}@@ -998,7 +422,7 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrif (!ok) {ui::GameTile dummy;if (g_ui->screen() == ui::Screen::Home || g_ui->firstTile(dummy)) {- if (g_ui->screen() == ui::Screen::Splash) {+ if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {g_ui->showHome();}platform::notify("Offline mode: using cached library");@@ -1017,6 +441,9 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrif (!shell::caps().console) g_ui->showToast(msg);platform::notify(msg);}+ if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {+ g_ui->showHome();+ }std::vector<ui::GameRow> rows = library->rows();{std::set<std::string> wishSet;@@ -1074,8 +501,6 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefr}}-} // namespace-namespace {// The worker's life, for closing: 0 not started, 1 running, 2 left its loop.@@ -1091,263 +516,6 @@ void setWorkerState(int state) {g_workerStateCv.notify_all();}-void runSignInCheck(auth::AuthManager& am, xcloud::GssvClient& gssv) {- ui::SignInCheckState st;- st.running = true;- st.stages = {- {"1. Account Storage", false, true, "Checking..."},- {"2. Microsoft OAuth (MSA)", false, true, "Waiting..."},- {"3. Xbox Live User Token", false, true, "Waiting..."},- {"4. XSTS Security Token", false, true, "Waiting..."},- {"5. xCloud Offering (xgpuweb)", false, true, "Waiting..."},- };- g_ui->setSignInCheckState(st);-- bool writable = platform::dataDirWritable();- bool hasAccount = am.hasStoredAccount();- st.stages[0].pending = false;- st.stages[0].ok = writable && hasAccount;- st.stages[0].detail = !writable ? "Storage read-only" : (hasAccount ? "OK (account.json saved)" : "No saved account");- XC_LOGI("sign-in check: stage 1 (%s) -> %s: %s", st.stages[0].name.c_str(),- st.stages[0].ok ? "OK" : "FAIL", st.stages[0].detail.c_str());- if (!hasAccount) {- for (size_t i = 1; i < st.stages.size(); ++i) {- st.stages[i].pending = false;- st.stages[i].ok = false;- st.stages[i].detail = "Skipped (not signed in)";- }- st.running = false;- g_ui->setSignInCheckState(st);- return;- }- g_ui->setSignInCheckState(st);-- std::string err;- uint64_t t0 = platform::nowMs();- bool ok = am.ensureFresh(&gssv, err, true);- uint64_t elapsedMs = platform::nowMs() - t0;-- int failedStage = -1;- if (!ok) {- if (err.find("token refresh") != std::string::npos || err.find("not signed in") != std::string::npos) {- failedStage = 1;- } else if (err.find("Xbox user authentication") != std::string::npos) {- failedStage = 2;- } else if (err.find("XSTS authorization") != std::string::npos) {- failedStage = 3;- } else {- failedStage = 4;- }- }-- for (int i = 1; i <= 4; ++i) {- auto& s = st.stages[static_cast<size_t>(i)];- s.pending = false;- if (ok || i < failedStage) {- s.ok = true;- if (i == 1) s.detail = "OK";- else if (i == 2) s.detail = "OK";- else if (i == 3) s.detail = am.profile().gamertag.empty() ? "OK" : ("OK (" + am.profile().gamertag + ")");- else if (i == 4)- s.detail = "OK (" + (gssv.session().market.empty() ? std::string("cloud") : gssv.session().market) +- ", " + std::to_string(gssv.session().regions.size()) + " regions, " +- std::to_string(elapsedMs) + " ms)";- } else if (i == failedStage) {- s.ok = false;- s.detail = err;- } else {- s.ok = false;- s.detail = "Skipped";- }- XC_LOGI("sign-in check: stage %d (%s) -> %s: %s", i + 1, s.name.c_str(), s.ok ? "OK" : "FAIL", s.detail.c_str());- }- st.running = false;- g_ui->setSignInCheckState(st);-}--std::string probeStunUdp() {- addrinfo hints{};- hints.ai_family = AF_INET;- hints.ai_socktype = SOCK_DGRAM;- addrinfo* res = nullptr;- if (::getaddrinfo("stun.l.google.com", "19302", &hints, &res) != 0 || !res) {- return "DNS / UDP Unavailable";- }- int fd = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);- if (fd < 0) {- ::freeaddrinfo(res);- return "UDP Socket Error";- }- // RFC 5389 STUN Binding Request (20 bytes)- uint8_t req[20] = {- 0x00, 0x01, 0x00, 0x00, // Binding Request, length 0- 0x21, 0x12, 0xA4, 0x42, // Magic cookie- 0x63, 0x87, 0x11, 0x42, 0x99, 0x10, // Transaction ID (12 bytes)- 0x24, 0x55, 0x7A, 0xBC, 0xDE, 0xF0,- };- uint64_t t0 = platform::nowMs();- ssize_t sent = ::sendto(fd, req, sizeof(req), 0, res->ai_addr, res->ai_addrlen);- ::freeaddrinfo(res);- if (sent != static_cast<ssize_t>(sizeof(req))) {- ::close(fd);- return "UDP Blocked";- }- pollfd pfd{};- pfd.fd = fd;- pfd.events = POLLIN;- int pr = ::poll(&pfd, 1, 900);- if (pr <= 0) {- ::close(fd);- return "UDP Filtered / Timeout";- }- uint8_t resp[128];- ssize_t got = ::recv(fd, resp, sizeof(resp), 0);- ::close(fd);- int rtt = static_cast<int>(platform::nowMs() - t0);- if (got >= 20 && resp[0] == 0x01 && resp[1] == 0x01) {- return "UDP Reachable (" + std::to_string(rtt) + " ms)";- }- return "UDP Invalid Response";-}--int probeTcpConnect(const char* host, const char* port, int timeoutMs) {- addrinfo hints{};- hints.ai_family = AF_INET;- hints.ai_socktype = SOCK_STREAM;- addrinfo* res = nullptr;- if (::getaddrinfo(host, port, &hints, &res) != 0 || !res) {- return -1;- }- int fd = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);- if (fd < 0) {- ::freeaddrinfo(res);- return -1;- }- int flags = ::fcntl(fd, F_GETFL, 0);- if (flags >= 0) ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);-- uint64_t t0 = platform::nowMs();- int rc = ::connect(fd, res->ai_addr, res->ai_addrlen);- int rtt = -1;- if (rc == 0) {- rtt = static_cast<int>(platform::nowMs() - t0);- } else if (errno == EINPROGRESS) {- pollfd pfd{};- pfd.fd = fd;- pfd.events = POLLOUT;- int pr = ::poll(&pfd, 1, timeoutMs);- if (pr > 0) {- int err = 0;- socklen_t len = sizeof(err);- if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) == 0 && err == 0) {- rtt = static_cast<int>(platform::nowMs() - t0);- }- }- }- ::close(fd);- ::freeaddrinfo(res);- return rtt;-}--void runNetworkTest(xcloud::GssvClient& gssv) {- ui::NetworkTestState state;- state.running = true;- state.natStatus = "Probing UDP STUN...";- auto regions = gssv.session().regions;- if (regions.empty()) {- regions = {- {"BRAZILSOUTH", "https://brazilsouth.core.gssv-play-prod.xboxlive.com", true},- {"EASTUS", "https://eastus.core.gssv-play-prod.xboxlive.com", false},- {"EASTUS2", "https://eastus2.core.gssv-play-prod.xboxlive.com", false},- {"SOUTHCENTRALUS", "https://southcentralus.core.gssv-play-prod.xboxlive.com", false},- {"WESTUS2", "https://westus2.core.gssv-play-prod.xboxlive.com", false},- {"WESTEUROPE", "https://westeurope.core.gssv-play-prod.xboxlive.com", false},- };- }- for (const auto& r : regions) {- state.regions.push_back({r.name, -1, -1});- }- g_ui->setNetworkTestState(state);-- state.natStatus = probeStunUdp();- XC_LOGI("network test: NAT/STUN -> %s", state.natStatus.c_str());- g_ui->setNetworkTestState(state);-- std::map<std::string, int> measured;- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- measured = g_settings.regionRtt;- }-- std::string defaultRegion;- if (const auto* def = gssv.session().defaultRegion()) defaultRegion = def->name;- if (defaultRegion.empty()) defaultRegion = gssv.region().name;- if (defaultRegion.empty()) defaultRegion = "BRAZILSOUTH";-- // Measure raw base edge RTT to the closest Anycast/Geo-DNS entrypoint- std::vector<int> edgeSamples;- for (int s = 0; s < 3 && !g_cancel && !g_quit; ++s) {- int dt = probeTcpConnect("xgpuweb.gssv-play-prod.xboxlive.com", "443", 1500);- if (dt >= 0) edgeSamples.push_back(dt);- if (s < 2) platform::sleepMs(30);- }- int baseRtt = 15, baseJitter = 1;- if (!edgeSamples.empty()) {- auto [minIt, maxIt] = std::minmax_element(edgeSamples.begin(), edgeSamples.end());- baseRtt = *minIt;- baseJitter = *maxIt - *minIt;- }- XC_LOGI("network test: edge TCP connect base RTT=%d ms, jitter=%d ms (default=%s)",- baseRtt, baseJitter, defaultRegion.c_str());-- for (size_t i = 0; i < regions.size() && !g_cancel && !g_quit; ++i) {- const auto& r = regions[i];- int rtt = -1, jitter = -1;- bool isDefault = (r.name == defaultRegion) || r.isDefault;- if (isDefault) {- rtt = baseRtt;- jitter = baseJitter;- } else {- auto m = measured.find(r.name);- double distKm = xcloud::regionDistanceKm(defaultRegion, r.name);- int estRtt = (distKm >= 0) ? (baseRtt + static_cast<int>(std::round(distKm / 100.0))) : 120;- if (m != measured.end() && m->second > 0) {- rtt = m->second;- jitter = std::max(1, baseJitter + 2);- } else {- rtt = estRtt;- jitter = std::max(1, baseJitter + (distKm > 4000 ? 3 : 1));- }- }- measured[r.name] = rtt;- for (auto& entry : state.regions) {- if (entry.name == r.name) {- entry.rttMs = rtt;- entry.jitterMs = jitter;- break;- }- }- XC_LOGI("network test: region %s -> rtt=%d ms, jitter=%d ms", r.name.c_str(), rtt, jitter);- g_ui->setNetworkTestState(state);- platform::sleepMs(20);- }-- std::sort(state.regions.begin(), state.regions.end(), [](const ui::RegionNetStat& a, const ui::RegionNetStat& b) {- if ((a.rttMs >= 0) != (b.rttMs >= 0)) return a.rttMs >= 0;- if (a.rttMs != b.rttMs) return a.rttMs < b.rttMs;- return a.name < b.name;- });- state.running = false;- g_ui->setNetworkTestState(state);- if (!measured.empty()) {- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- g_settings.regionRtt = measured;- }- g_ui->setRegionLatency(measured);- }-}-} // namespacevoid startWorker() {@@ -1523,13 +691,29 @@ void worker() {if (!failed) g_regionFallback[tile.titleId] = next;}}- if (failed && result.find("NoEntitlement") != std::string::npos) {- // Not on the account: a free game not got yet in the- // store (it can be, on the phone, and tried again here),- // or one outside the subscription.- g_ui->showPlayError(ui::trf(tile.freeInStore ? ui::Str::NoEntitlementFree : ui::Str::NoEntitlement,- tile.name),- tile);+ bool isEntitlementErr = result.find("NoEntitlement") != std::string::npos ||+ result.find("NotEntitled") != std::string::npos ||+ result.find("PurchasableProductRequired") != std::string::npos ||+ result.find("LicenseRequired") != std::string::npos;+ if (failed && isEntitlementErr) {+ bool isFreeUser = g_ui->isFreeAccount();+ bool isF2P = g_ui->isFreeGame(tile) || tile.freeInStore;+ bool previewActive = false;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ previewActive = g_settings.previewFeatures;+ }+ if (isFreeUser && isF2P) {+ if (!previewActive) {+ g_ui->showPlayError(ui::tr(ui::Str::F2pPreviewRequiredDesc), tile, "https://www.xbox.com/play");+ } else {+ g_ui->showPlayError(ui::tr(ui::Str::F2pPreviewAccountNeededDesc), tile, "https://www.xbox.com/play");+ }+ } else {+ g_ui->showPlayError(ui::trf(tile.freeInStore ? ui::Str::NoEntitlementFree : ui::Str::NoEntitlement,+ tile.name),+ tile);+ }} else if (failed) {if (net::lastTlsProblem() == net::TlsProblem::Clock) {g_ui->showError(ui::trf(shell::caps().console ? ui::Str::ClockWrong : ui::Str::ClockWrongPc, net::todayText()));@@ -1548,6 +732,7 @@ void worker() {break;}case kClaimFree: {+ stopHydration();ui::GameTile tile;{std::lock_guard<std::mutex> lock(g_argMutex);@@ -1576,6 +761,16 @@ void worker() {if (!offer.isFree) {XC_LOGW("claim refused: product %s is not free (list=%.2f, msrp=%.2f)",tile.productId.c_str(), offer.listPrice, offer.msrp);+ std::shared_ptr<app::Library> lib;+ {+ std::lock_guard<std::mutex> lock(s_libraryMutex);+ lib = s_library;+ }+ if (lib) {+ lib->markUnclaimable(tile.productId);+ }+ g_ui->markUnclaimable(tile.productId);+ tile.freeInStore = false;g_ui->showPlayError(ui::tr(ui::Str::ProductNotFree), tile);break;}@@ -1611,17 +806,18 @@ void worker() {// Re-sync owned titles in backgroundlib->loadOwned(gssv, [lib]() {- g_ui->setRows(lib->rows());- g_ui->setOwned(lib->owned(), lib->purchasable(), lib->ownedKnown());auto p = lib->progress();- g_ui->setLoading(p.active, p.done, p.total);+ g_ui->setCatalogState(lib->rows(), lib->owned(), lib->purchasable(), lib->ownedKnown(),+ lib->gamePassMember(), lib->gamePassSearchPool(), lib->librarySearchPool(),+ p.active, p.done, p.total);});g_ui->setLoading(false, 0, 0);}tile.playable = true;tile.purchasable = false;- tile.freeInStore = false;- g_ui->showDetails(tile);+ if (g_ui->screen() == ui::Screen::Details || g_ui->screen() == ui::Screen::Error) {+ g_ui->showDetails(tile);+ }break;}default: {diff --git a/src/app/worker_diagnostics.cpp b/src/app/worker_diagnostics.cppnew file mode 100644index 0000000..1714088--- /dev/null+++ b/src/app/worker_diagnostics.cpp@@ -0,0 +1,394 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/worker_internal.h"++#include "app/autoplay.h"+#include "app/shell.h"+#include "app/update_check.h"+#include "app/updater.h"+#include "platform/platform.h"+#include "ui/strings.h"+#include "util/log.h"+#include "xcloud/regions.h"++#include <algorithm>+#include <cerrno>+#include <cmath>+#include <fcntl.h>+#include <map>+#include <netdb.h>+#include <poll.h>+#include <sys/socket.h>+#include <unistd.h>+#include <vector>++namespace xc::app {++namespace {++// The newer release found at start (empty tag: none).+std::mutex g_releaseMutex;+Release g_release;+++} // namespace++// Asks for the latest release; a newer one with a signed package is offered+// (the pop-up, unless the user said "Not now" to it) and shown in Settings.+void checkForUpdate() {+ g_ui->setUpdateState(XC_APP_VERSION, {}, true);+ Release r;+ std::string err;+ bool found = findLatestRelease(r, err, g_autoplay.updateFeed);+ XC_LOGI("latest release: %s (this is %s)", found ? r.tag.c_str() : err.c_str(), XC_APP_VERSION);+ bool newer = found && isNewerVersion(r.tag, XC_APP_VERSION);+ bool offer = newer && !r.zipUrl.empty() && !r.sigUrl.empty();+ if (newer && !offer) XC_LOGW("%s has no signed package", r.tag.c_str());+ const bool selfUpdate = shell::canSelfUpdate();+ if (newer && !selfUpdate) {+ // This build doesn't install updates itself (only the PS5's does):+ // Settings names the new version and opens its page instead.+ XC_LOGI("%s is out: this build doesn't update itself", r.tag.c_str());+ offer = false;+ }+ {+ std::lock_guard<std::mutex> lock(g_releaseMutex);+ g_release = offer ? r : Release{};+ }+ g_ui->setUpdateState(XC_APP_VERSION, offer || (newer && !selfUpdate) ? r.tag : std::string(), false, r.notes);+ bool skipped;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ skipped = g_settings.skippedUpdate == r.tag;+ }+ if (offer && !skipped) g_ui->offerUpdate(r.notes);+}++// The update itself, then the restart into the new version. A failure+// changes nothing and goes back to the home screen.+void runUpdate() {+ Release r;+ {+ std::lock_guard<std::mutex> lock(g_releaseMutex);+ r = g_release;+ }+ if (r.tag.empty()) return;+ XC_LOGI("update to %s: starting", r.tag.c_str());+ g_ui->showUpdating(r.tag);+ // Only where the app runs from: installed elsewhere, it would write next+ // to the wrong eboot.bin.+ std::string dir = platform::appDir(), err;+ bool ok = shell::isInstalledCopy(dir);+ if (!ok) err = "the app doesn't run from " + dir;+ int lastPct = -1;+ ok = ok && installRelease(r, dir, XC_APP_VERSION, [&](UpdateStep step, double f) {+ if (step == UpdateStep::Downloading) {+ int pct = f < 0 ? 0 : static_cast<int>(f * 100);+ if (pct == lastPct) return;+ lastPct = pct;+ g_ui->setUpdateStatus(ui::trf(ui::Str::UpdateDownloading, std::to_string(pct) + " %"), static_cast<float>(f));+ } else {+ g_ui->setUpdateStatus(ui::tr(step == UpdateStep::Verifying ? ui::Str::UpdateVerifying : ui::Str::UpdateInstalling), -1);+ }+ }, err);+ if (!ok) {+ XC_LOGE("update to %s failed: %s", r.tag.c_str(), err.c_str());+ g_ui->showHome(ui::tr(ui::Str::UpdateFailed));+ if (!g_autoplay.title.empty()) XC_LOGI("AUTOPLAY END: update failed");+ return;+ }+ g_ui->setUpdateStatus(ui::tr(ui::Str::UpdateRestarting), 1);+ platform::sleepMs(1500);+ XC_LOGI("update to %s: restarting", r.tag.c_str());+ g_restartWanted = true;+}+++void skipOfferedUpdate() {+ std::string tag;+ {+ std::lock_guard<std::mutex> lock(g_releaseMutex);+ tag = g_release.tag;+ }+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ g_settings.skippedUpdate = tag;+ g_settings.save(settingsPath());+ XC_LOGI("update %s: not now", tag.c_str());+}++void runSignInCheck(auth::AuthManager& am, xcloud::GssvClient& gssv) {+ ui::SignInCheckState st;+ st.running = true;+ st.stages = {+ {"1. Account Storage", false, true, "Checking..."},+ {"2. Microsoft OAuth (MSA)", false, true, "Waiting..."},+ {"3. Xbox Live User Token", false, true, "Waiting..."},+ {"4. XSTS Security Token", false, true, "Waiting..."},+ {"5. xCloud Offering (xgpuweb)", false, true, "Waiting..."},+ {"6. Recursos Preview (xCloud & Ads)", false, true, "Waiting..."},+ };+ g_ui->setSignInCheckState(st);++ bool writable = platform::dataDirWritable();+ bool hasAccount = am.hasStoredAccount();+ st.stages[0].pending = false;+ st.stages[0].ok = writable && hasAccount;+ st.stages[0].detail = !writable ? "Storage read-only" : (hasAccount ? "OK (account.json saved)" : "No saved account");+ XC_LOGI("sign-in check: stage 1 (%s) -> %s: %s", st.stages[0].name.c_str(),+ st.stages[0].ok ? "OK" : "FAIL", st.stages[0].detail.c_str());+ if (!hasAccount) {+ for (size_t i = 1; i < st.stages.size(); ++i) {+ st.stages[i].pending = false;+ st.stages[i].ok = false;+ st.stages[i].detail = "Skipped (not signed in)";+ }+ st.running = false;+ g_ui->setSignInCheckState(st);+ return;+ }+ g_ui->setSignInCheckState(st);++ std::string err;+ uint64_t t0 = platform::nowMs();+ bool ok = am.ensureFresh(&gssv, err, true);+ uint64_t elapsedMs = platform::nowMs() - t0;++ int failedStage = -1;+ if (!ok) {+ if (err.find("token refresh") != std::string::npos || err.find("not signed in") != std::string::npos) {+ failedStage = 1;+ } else if (err.find("Xbox user authentication") != std::string::npos) {+ failedStage = 2;+ } else if (err.find("XSTS authorization") != std::string::npos) {+ failedStage = 3;+ } else {+ failedStage = 4;+ }+ }++ for (int i = 1; i <= 4; ++i) {+ auto& s = st.stages[static_cast<size_t>(i)];+ s.pending = false;+ if (ok || i < failedStage) {+ s.ok = true;+ if (i == 1) s.detail = "OK";+ else if (i == 2) s.detail = "OK";+ else if (i == 3) s.detail = am.profile().gamertag.empty() ? "OK" : ("OK (" + am.profile().gamertag + ")");+ else if (i == 4)+ s.detail = "OK (" + (gssv.session().market.empty() ? std::string("cloud") : gssv.session().market) ++ ", " + std::to_string(gssv.session().regions.size()) + " regions, " ++ std::to_string(elapsedMs) + " ms)";+ } else if (i == failedStage) {+ s.ok = false;+ s.detail = err;+ } else {+ s.ok = false;+ s.detail = "Skipped";+ }+ XC_LOGI("sign-in check: stage %d (%s) -> %s: %s", i + 1, s.name.c_str(), s.ok ? "OK" : "FAIL", s.detail.c_str());+ }++ bool previewActive = false;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ previewActive = g_settings.previewFeatures;+ }+ auto& s5 = st.stages[5];+ s5.pending = false;+ s5.ok = previewActive;+ s5.detail = previewActive ? "OK (Ativo - Streaming de F2P habilitado)" : "Desativado (Requer ativação nas opções)";+ XC_LOGI("sign-in check: stage 6 (%s) -> %s: %s", s5.name.c_str(), s5.ok ? "OK" : "FAIL", s5.detail.c_str());++ st.running = false;+ g_ui->setSignInCheckState(st);+}+++namespace {++std::string probeStunUdp() {+ addrinfo hints{};+ hints.ai_family = AF_INET;+ hints.ai_socktype = SOCK_DGRAM;+ addrinfo* res = nullptr;+ if (::getaddrinfo("stun.l.google.com", "19302", &hints, &res) != 0 || !res) {+ return "DNS / UDP Unavailable";+ }+ int fd = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);+ if (fd < 0) {+ ::freeaddrinfo(res);+ return "UDP Socket Error";+ }+ // RFC 5389 STUN Binding Request (20 bytes)+ uint8_t req[20] = {+ 0x00, 0x01, 0x00, 0x00, // Binding Request, length 0+ 0x21, 0x12, 0xA4, 0x42, // Magic cookie+ 0x63, 0x87, 0x11, 0x42, 0x99, 0x10, // Transaction ID (12 bytes)+ 0x24, 0x55, 0x7A, 0xBC, 0xDE, 0xF0,+ };+ uint64_t t0 = platform::nowMs();+ ssize_t sent = ::sendto(fd, req, sizeof(req), 0, res->ai_addr, res->ai_addrlen);+ ::freeaddrinfo(res);+ if (sent != static_cast<ssize_t>(sizeof(req))) {+ ::close(fd);+ return "UDP Blocked";+ }+ pollfd pfd{};+ pfd.fd = fd;+ pfd.events = POLLIN;+ int pr = ::poll(&pfd, 1, 900);+ if (pr <= 0) {+ ::close(fd);+ return "UDP Filtered / Timeout";+ }+ uint8_t resp[128];+ ssize_t got = ::recv(fd, resp, sizeof(resp), 0);+ ::close(fd);+ int rtt = static_cast<int>(platform::nowMs() - t0);+ if (got >= 20 && resp[0] == 0x01 && resp[1] == 0x01) {+ return "UDP Reachable (" + std::to_string(rtt) + " ms)";+ }+ return "UDP Invalid Response";+}++int probeTcpConnect(const char* host, const char* port, int timeoutMs) {+ addrinfo hints{};+ hints.ai_family = AF_INET;+ hints.ai_socktype = SOCK_STREAM;+ addrinfo* res = nullptr;+ if (::getaddrinfo(host, port, &hints, &res) != 0 || !res) {+ return -1;+ }+ int fd = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);+ if (fd < 0) {+ ::freeaddrinfo(res);+ return -1;+ }+ int flags = ::fcntl(fd, F_GETFL, 0);+ if (flags >= 0) ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);++ uint64_t t0 = platform::nowMs();+ int rc = ::connect(fd, res->ai_addr, res->ai_addrlen);+ int rtt = -1;+ if (rc == 0) {+ rtt = static_cast<int>(platform::nowMs() - t0);+ } else if (errno == EINPROGRESS) {+ pollfd pfd{};+ pfd.fd = fd;+ pfd.events = POLLOUT;+ int pr = ::poll(&pfd, 1, timeoutMs);+ if (pr > 0) {+ int err = 0;+ socklen_t len = sizeof(err);+ if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) == 0 && err == 0) {+ rtt = static_cast<int>(platform::nowMs() - t0);+ }+ }+ }+ ::close(fd);+ ::freeaddrinfo(res);+ return rtt;+}++} // namespace++void runNetworkTest(xcloud::GssvClient& gssv) {+ ui::NetworkTestState state;+ state.running = true;+ state.natStatus = "Probing UDP STUN...";+ auto regions = gssv.session().regions;+ if (regions.empty()) {+ regions = {+ {"BRAZILSOUTH", "https://brazilsouth.core.gssv-play-prod.xboxlive.com", true},+ {"EASTUS", "https://eastus.core.gssv-play-prod.xboxlive.com", false},+ {"EASTUS2", "https://eastus2.core.gssv-play-prod.xboxlive.com", false},+ {"SOUTHCENTRALUS", "https://southcentralus.core.gssv-play-prod.xboxlive.com", false},+ {"WESTUS2", "https://westus2.core.gssv-play-prod.xboxlive.com", false},+ {"WESTEUROPE", "https://westeurope.core.gssv-play-prod.xboxlive.com", false},+ };+ }+ for (const auto& r : regions) {+ state.regions.push_back({r.name, -1, -1});+ }+ g_ui->setNetworkTestState(state);++ state.natStatus = probeStunUdp();+ XC_LOGI("network test: NAT/STUN -> %s", state.natStatus.c_str());+ g_ui->setNetworkTestState(state);++ std::map<std::string, int> measured;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ measured = g_settings.regionRtt;+ }++ std::string defaultRegion;+ if (const auto* def = gssv.session().defaultRegion()) defaultRegion = def->name;+ if (defaultRegion.empty()) defaultRegion = gssv.region().name;+ if (defaultRegion.empty()) defaultRegion = "BRAZILSOUTH";++ // Measure raw base edge RTT to the closest Anycast/Geo-DNS entrypoint+ std::vector<int> edgeSamples;+ for (int s = 0; s < 3 && !g_cancel && !g_quit; ++s) {+ int dt = probeTcpConnect("xgpuweb.gssv-play-prod.xboxlive.com", "443", 1500);+ if (dt >= 0) edgeSamples.push_back(dt);+ if (s < 2) platform::sleepMs(30);+ }+ int baseRtt = 15, baseJitter = 1;+ if (!edgeSamples.empty()) {+ auto [minIt, maxIt] = std::minmax_element(edgeSamples.begin(), edgeSamples.end());+ baseRtt = *minIt;+ baseJitter = *maxIt - *minIt;+ }+ XC_LOGI("network test: edge TCP connect base RTT=%d ms, jitter=%d ms (default=%s)",+ baseRtt, baseJitter, defaultRegion.c_str());++ for (size_t i = 0; i < regions.size() && !g_cancel && !g_quit; ++i) {+ const auto& r = regions[i];+ int rtt = -1, jitter = -1;+ bool isDefault = (r.name == defaultRegion) || r.isDefault;+ if (isDefault) {+ rtt = baseRtt;+ jitter = baseJitter;+ } else {+ auto m = measured.find(r.name);+ double distKm = xcloud::regionDistanceKm(defaultRegion, r.name);+ int estRtt = (distKm >= 0) ? (baseRtt + static_cast<int>(std::round(distKm / 100.0))) : 120;+ if (m != measured.end() && m->second > 0) {+ rtt = m->second;+ jitter = std::max(1, baseJitter + 2);+ } else {+ rtt = estRtt;+ jitter = std::max(1, baseJitter + (distKm > 4000 ? 3 : 1));+ }+ }+ measured[r.name] = rtt;+ for (auto& entry : state.regions) {+ if (entry.name == r.name) {+ entry.rttMs = rtt;+ entry.jitterMs = jitter;+ break;+ }+ }+ XC_LOGI("network test: region %s -> rtt=%d ms, jitter=%d ms", r.name.c_str(), rtt, jitter);+ g_ui->setNetworkTestState(state);+ platform::sleepMs(20);+ }++ std::sort(state.regions.begin(), state.regions.end(), [](const ui::RegionNetStat& a, const ui::RegionNetStat& b) {+ if ((a.rttMs >= 0) != (b.rttMs >= 0)) return a.rttMs >= 0;+ if (a.rttMs != b.rttMs) return a.rttMs < b.rttMs;+ return a.name < b.name;+ });+ state.running = false;+ g_ui->setNetworkTestState(state);+ if (!measured.empty()) {+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ g_settings.regionRtt = measured;+ }+ g_ui->setRegionLatency(measured);+ }+}++} // namespace xc::appdiff --git a/src/app/worker_internal.h b/src/app/worker_internal.hnew file mode 100644index 0000000..be5d2d2--- /dev/null+++ b/src/app/worker_internal.h@@ -0,0 +1,45 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "app/app_state.h"+#include "app/library.h"+#include "auth/auth_manager.h"+#include "platform/platform.h"+#include "xcloud/gssv.h"++#include <atomic>+#include <cstdint>+#include <map>+#include <memory>+#include <mutex>+#include <string>++namespace xc::app {++extern std::atomic<bool> g_stopHydration;+extern platform::Thread g_hydrationThread;+void stopHydration();++extern bool g_probing;+extern std::string g_afterProbeAlias;+extern bool g_gameClosedOnServer;+extern std::map<std::string, std::string> g_regionFallback;+extern std::shared_ptr<app::Library> s_library;+extern std::mutex s_libraryMutex;+extern int64_t s_playtimeRemainingSeconds;+extern std::string g_xblAuth;+extern std::string g_xuid;+extern std::string g_subscription;++bool keepSignedIn(auth::AuthManager& am, xcloud::GssvClient& gssv, std::string& err, bool force = false);+std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::GameTile& game, bool& failed,+ const std::string& overrideRegion = {});+void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefresh = false);+void checkForUpdate();+void runUpdate();+void skipOfferedUpdate();+void runSignInCheck(auth::AuthManager& am, xcloud::GssvClient& gssv);+void runNetworkTest(xcloud::GssvClient& gssv);++} // namespace xc::appdiff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cppnew file mode 100644index 0000000..0f0e409--- /dev/null+++ b/src/app/worker_stream.cpp@@ -0,0 +1,555 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/worker_internal.h"++#include "app/autoplay.h"+#include "app/crash_guard.h"+#include "app/shell.h"+#include "app/stream_player.h"+#include "input/controller.h"+#include "media/audio_out.h"+#include "media/audio_queue.h"+#include "platform/platform.h"+#include "ui/strings.h"+#include "util/log.h"+#include "xcloud/catalog.h"+#include "xcloud/regions.h"++#include <algorithm>+#include <cmath>+#include <cstdlib>+#include <vector>++namespace xc::app {++namespace {++std::string formatWait(int seconds) {+ if (seconds < 0) return "...";+ if (seconds < 60) return std::to_string(seconds) + " s";+ return std::to_string((seconds + 59) / 60) + " min";+}++} // namespace++void playQueueReadyAlert(bool notifyToast) {+ // 1. DualSense rumble pulse+ input::setRumble(180, 180, 500, 0);++ // 2. Synthesize a pleasant 3-tone harmonic chime (E5 -> G#5 -> B5, E Major triad)+ constexpr int kRate = 48000;+ constexpr float kPi = 3.14159265358979323846f;+ struct Tone {+ float freq;+ int ms;+ };+ const Tone tones[3] = {+ {659.25f, 100}, // E5+ {830.61f, 100}, // G#5+ {987.77f, 220} // B5+ };++ std::vector<float> pcm;+ pcm.reserve(kRate * 2);+ for (int t = 0; t < 3; ++t) {+ int frames = (kRate * tones[t].ms) / 1000;+ float freq = tones[t].freq;+ float decayRate = (t == 2) ? 6.0f : 4.0f;+ for (int i = 0; i < frames; ++i) {+ float sec = static_cast<float>(i) / static_cast<float>(kRate);+ float attack = std::min(1.0f, sec / 0.005f);+ float decay = std::exp(-decayRate * sec);+ float env = attack * decay * 0.70f;+ float s = std::sin(2.0f * kPi * freq * sec) + 0.25f * std::sin(4.0f * kPi * freq * sec);+ float sample = s * env;+ pcm.push_back(sample); // Left+ pcm.push_back(sample); // Right+ }+ }++ // Play directly through the DualSense controller speaker (falls back to main audio)+ media::playPadSpeakerAudio(pcm.data(), pcm.size() / 2);++ // 3. System notification toast (only when stream queue actually finishes)+ if (notifyToast) {+ platform::notify(ui::tr(ui::Str::QueueReadyAlert));+ }+}++namespace {++// Streams until the player ends or the user leaves; returns a status line.+// The cloud title being played, for crash markers (set by play()).+std::string g_stageTitle;+std::string g_stageProduct;++std::string stream(xcloud::GssvClient& gssv) {+ crash::setStage(gssv.isHome() ? "streaming own Xbox" : ("streaming " + g_stageTitle).c_str());+ g_gameClosedOnServer = false;+ app::StreamPlayer player(gssv);+ if (g_autoplay.dump) player.dumpVideo(platform::dataDir() + "/stream.aus", g_autoplay.seconds + 15);+ player.setDecodeThreads(g_autoplay.decodeThreads);+ player.setSimulatedLoss(g_autoplay.videoLoss);+ player.setHwDecodeProbe(g_autoplay.hwDecode);+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ bool hasCustom = false;+ GameProfile prof = g_settings.profileForGame(g_stageProduct, g_stageTitle, &hasCustom);+ bool preferHw = true;+ if (g_autoplay.swDecode) {+ preferHw = false;+ } else if (g_autoplay.preferHwDecode) {+ preferHw = (hasCustom ? (prof.videoDecoder == 0) : (g_settings.videoDecoder == 0));+ } else {+ preferHw = false;+ }+ player.setPreferHwDecode(preferHw);+ XC_LOGI("stream: video decoder %s", preferHw ? "hardware preferred" : "software (CPU)");+ player.setMicGain(g_settings.micGainFactor());+ player.setMicEnabled(g_settings.micEnabled);+ int cap = g_autoplay.bitrateMbps > 0 ? g_autoplay.bitrateMbps : g_settings.maxBitrateMbps;+ player.setMaxBitrate(cap);+ media::audioSetVolume(g_settings.gameVolume / 100.0f);+ XC_LOGI("stream: bitrate cap %s, game volume %d%%",+ cap ? (std::to_string(cap) + " Mbps").c_str() : "automatic",+ g_settings.gameVolume);+ media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));+ media::audioSetVoiceRouting(g_settings.voiceRouting);+ int hapticLvl = hasCustom ? prof.audioHaptics : g_settings.audioHaptics;+ media::setAudioHapticsLevel(hapticLvl);+ }+ std::string err;+ if (!player.start(err)) return "ERROR: " + ui::trf(ui::Str::StreamFailed, err);+ {+ std::lock_guard<std::mutex> lock(g_playerMutex);+ g_player = &player;+ }+ g_ui->showStreaming();+ {+ // The touchpad's gestures, in the first three streams only.+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ if (g_settings.gestureHints < 3) {+ ++g_settings.gestureHints;+ g_settings.save(settingsPath());+ // (Without a touchpad: the buttons and keys that do the same.)+ platform::notify(ui::tr(g_ui->caps().touchpad ? ui::Str::GestureHint : ui::Str::GestureHintButtons));+ }+ }++ const uint64_t started = platform::nowMs();+ uint64_t nextTick = started;+ bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;+ bool autoplayDone = false;+ int bestRtt = -1; // lowest round trip seen: the region's latency+ int tallest = 0; // the tallest picture seen (the probe's measure)+ // The connection's state for the warning and the end-of-session summary:+ // a second is bad when the jitter buffer dropped a frame (lost for good),+ // no video arrived at all, or the round trip went far above the best seen.+ // Not the frame rate: games send fewer frames in some scenes.+ uint64_t degradedUntil = 0, lastTickAt = 0;+ bool degradedLogged = false;+ uint32_t reconnectsSeen = 0;+ struct {+ uint64_t seconds = 0, badSeconds = 0, kbps = 0, rttSum = 0, rttCount = 0;+ } session;+ uint64_t prevPlaytime = 0;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ prevPlaytime = g_settings.playtimeForGame(g_stageProduct, g_stageTitle);+ }+ bool probeDone = !g_probing;+ auto recordProbe = [&] {+ probeDone = true;+ if (tallest <= 0) return;+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ (gssv.isHome() ? g_settings.maxHeightHome : g_settings.maxHeightCloud) = tallest;+ (gssv.isHome() ? g_settings.probedHome : g_settings.probedCloud) = auth::unixNow();+ g_settings.save(settingsPath());+ g_ui->setAllow1440(allow1440Locked());+ XC_LOGI("resolution probe (%s): %dp at most", gssv.isHome() ? "own Xbox" : "cloud", tallest);+ };+ app::StreamPlayer::Stats last{};+ while (player.running() && !g_cancel) {+ uint64_t elapsed = platform::nowMs() - started;+ if (!g_autoplay.title.empty()) {+ if (elapsed >= static_cast<uint64_t>(g_autoplay.seconds) * 1000u) {+ autoplayDone = true;+ break;+ }+ if (!snapshot1 && elapsed >= 10000) {+ snapshot1 = true;+ player.requestSnapshot(platform::dataDir() + "/frame.ppm");+ }+ bool press = !g_autoplay.idle &&+ ((elapsed >= 22000 && elapsed < 22300) ||+ (elapsed >= 26000 && elapsed < 26300) ||+ (elapsed >= 70000 && (elapsed % 6000 < 300)));+ if (press != g_syntheticA.exchange(press)) XC_LOGI("autoplay: A %s", press ? "down" : "up");+ static bool dropped = false;+ if (g_autoplay.dropTest && !dropped && elapsed >= 20000) {+ dropped = true;+ player.simulateDrop();+ }+ if (!snapshot2 && elapsed >= 28000) {+ snapshot2 = true;+ player.requestSnapshot(platform::dataDir() + "/frame2.ppm");+ }+ if (!snapshot3 && elapsed >= 70000) {+ snapshot3 = true;+ player.requestSnapshot(platform::dataDir() + "/frame3.ppm");+ }+ if (!snapshot4 && elapsed >= 110000) {+ snapshot4 = true;+ player.requestSnapshot(platform::dataDir() + "/frame4.ppm");+ }+ }+ if (platform::nowMs() >= nextTick) {+ uint64_t tickNow = platform::nowMs();+ double dt = lastTickAt ? (tickNow - lastTickAt) / 1000.0 : 1.0;+ nextTick = tickNow + 1000;+ player.tick();+ 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 (%s), draw %.1f/%.1f ms, %llu late; "+ "rtt %d ms; %dx%d; on screen %.1f/%.1f ms after arrival; qp %.1f",+ 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),+ static_cast<unsigned long long>(st.queued), static_cast<unsigned long long>(st.audioPackets),+ static_cast<unsigned long long>(st.rtpPackets), static_cast<unsigned long long>(st.rtpLost),+ static_cast<unsigned long long>(st.rtpRecovered), static_cast<unsigned long long>(st.rtpNacks),+ 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.isHwDecode ? "HW" : "SW",+ st.drawAvgUs / 1000.0, st.drawMaxUs / 1000.0,+ static_cast<unsigned long long>(st.lateFrames), st.rttMs, st.width, st.height,+ st.displayAvgUs / 1000.0, st.displayMaxUs / 1000.0, st.qpAvg);+ if (st.rttMs > 0 && (bestRtt < 0 || st.rttMs < bestRtt)) bestRtt = st.rttMs;+ tallest = std::max(tallest, st.height);+ if (!probeDone && platform::nowMs() - started >= 20000) {+ recordProbe();+ if (!g_afterProbeAlias.empty() && !g_tierPicked) player.requestResolution(g_afterProbeAlias);+ }+ {+ ui::StreamInfo info;+ info.region = ui::prettyRegion(gssv.region().name);+ info.rttMs = st.rttMs;+ info.fps = dt > 0.05+ ? std::max(0.0, static_cast<double>(st.decodedFrames - last.decodedFrames -+ (st.droppedFrames - last.droppedFrames)) /+ dt)+ : 60.0;+ info.mbps = st.rtpKbps / 1000.0;+ uint64_t lost = st.rtpLost - last.rtpLost, got = st.rtpPackets - last.rtpPackets;+ info.lossPct = got + lost ? 100.0 * lost / (got + lost) : 0;+ info.decodeMs = st.decodeAvgUs / 1000.0;+ info.isHwDecode = st.isHwDecode;+ info.onScreenMs = st.displayAvgUs / 1000.0;+ info.width = st.width;+ info.height = st.height;+ info.qp = st.qpAvg;+ if (last.decodedFrames > 0) { // once the picture is running+ uint64_t dropped = st.rtpDroppedFrames - last.rtpDroppedFrames;+ uint64_t now = platform::nowMs();+ // No video for a second; or the loop itself held up (a+ // reconnection blocks it) / a new session after a drop.+ bool stalled = st.videoFrames == last.videoFrames || (lastTickAt && now - lastTickAt > 2500) ||+ player.reconnects() != reconnectsSeen;+ reconnectsSeen = player.reconnects();+ bool slow = st.rttMs > 0 && bestRtt > 0 && st.rttMs > bestRtt + 60;+ if (dropped || stalled || slow) {+ if (!degradedLogged) // once per episode+ XC_LOGW("connection degraded: %llu frame(s) lost, %s, rtt %d ms (best %d)",+ static_cast<unsigned long long>(dropped), stalled ? "no video for a second" : "video arriving",+ st.rttMs, bestRtt);+ degradedLogged = true;+ degradedUntil = now + 3000;+ ++session.badSeconds;+ } else if (now >= degradedUntil) {+ degradedLogged = false;+ }+ info.degraded = now < degradedUntil;+ lastTickAt = tickNow;+ ++session.seconds;+ session.kbps += st.rtpKbps;+ if (st.rttMs > 0) session.rttSum += static_cast<uint64_t>(st.rttMs), ++session.rttCount;+ }+ if (s_playtimeRemainingSeconds >= 0) {+ info.playtimeHours = static_cast<int>((s_playtimeRemainingSeconds + 3599) / 3600);+ }+ info.playtimeSeconds = prevPlaytime + session.seconds;+ player.getRecentFrametimes(info.frametimes);+ std::lock_guard<std::mutex> lock(g_infoMutex);+ g_streamInfo = info;+ ++g_infoSeq;+ }+ last = st;+ }+ platform::sleepMs(100);+ }+ {+ std::lock_guard<std::mutex> lock(g_playerMutex);+ g_player = nullptr;+ }+ if (!probeDone && player.stats().decodedFrames > 0) recordProbe(); // a short stream still measured+ std::string reason = g_cancel ? "left the game" : autoplayDone ? "autoplay finished" : player.endReason();+ player.stop();+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ media::setAudioHapticsLevel(g_settings.audioHaptics);+ }+ if (session.seconds >= 5 && (!g_stageTitle.empty() || !g_stageProduct.empty())) {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ uint64_t newTotal = prevPlaytime + session.seconds;+ if (!g_stageTitle.empty()) g_settings.titlePlaytime[g_stageTitle] = newTotal;+ if (!g_stageProduct.empty()) g_settings.titlePlaytime[g_stageProduct] = newTotal;+ g_settings.save(settingsPath());+ if (g_ui) g_ui->setSettings(ui::choiceFromSettings(g_settings));+ XC_LOGI("playtime: updated for %s (%s) to %llu seconds (%s)", g_stageTitle.c_str(),+ g_stageProduct.c_str(), static_cast<unsigned long long>(newTotal),+ ui::formatPlaytime(newTotal).c_str());++ std::shared_ptr<app::Library> lib;+ {+ std::lock_guard<std::mutex> lockLib(s_libraryMutex);+ lib = s_library;+ }+ if (lib) {+ if (!g_stageProduct.empty()) lib->recordRecent(g_stageProduct);+ else if (!g_stageTitle.empty()) lib->recordRecent(g_stageTitle);+ lib->setPlaytime(g_settings.titlePlaytime);+ g_ui->setRows(lib->rows());+ g_ui->setOwned(lib->owned(), lib->purchasable(), lib->ownedKnown());+ }+ }+ 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();+ if (session.seconds >= 10) {+ // The session in one line: the log (and so a report) and a notification.+ double lossPct = st.rtpPackets + st.rtpLost ? 100.0 * (st.rtpLost - std::min(st.rtpRecovered, st.rtpLost)) /+ static_cast<double>(st.rtpPackets + st.rtpLost)+ : 0;+ char details[160];+ std::snprintf(details, sizeof details, "%llu min, %dp, %.1f Mbps, %.2f%% lost, %d ms",+ static_cast<unsigned long long>((session.seconds + 30) / 60), tallest,+ session.kbps / 1000.0 / static_cast<double>(session.seconds), lossPct,+ session.rttCount ? static_cast<int>(session.rttSum / session.rttCount) : -1);+ XC_LOGI("session summary: %s; %llu s with a degraded connection, %llu frames lost, %llu recovered packets",+ details, static_cast<unsigned long long>(session.badSeconds),+ static_cast<unsigned long long>(st.rtpDroppedFrames), static_cast<unsigned long long>(st.rtpRecovered));+ }+ // Ended before a single frame: the game never started (e.g. it closed on+ // the server); say so on the error screen instead of going back quietly.+ if (st.decodedFrames == 0 && !g_cancel && !autoplayDone) {+ g_gameClosedOnServer = reason.rfind("the game closed on the server", 0) == 0;+ return "ERROR: " + ui::trf(ui::Str::StreamFailed, reason);+ }+ return "Stream ended (" + reason + "), " + std::to_string(st.decodedFrames) + " frames shown";+}++// Queue -> /connect -> Provisioned -> stream. Returns a status line; sets+// `failed` when the user should see an error rather than the home screen.+// `regionName` overrides the settings' region (empty: as set).++} // namespace++std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::GameTile& game, bool& failed,+ const std::string& regionName) {+ failed = true;+ // A home session's id is the console's: only its start in the log.+ XC_LOGI("starting %s (%s)", gssv.isHome() ? "own Xbox" : game.name.c_str(), // not the console's name+ gssv.isHome() ? (game.titleId.substr(0, 4) + "...").c_str() : game.titleId.c_str());+ g_ui->showLaunching(game, regionName.empty() ? ui::tr(ui::Str::Connecting)+ : ui::trf(ui::Str::TryingRegion, ui::prettyRegion(regionName)));+ std::string err;+ // A login about to expire is renewed first (its region kept); if that+ // fails the start is tried all the same.+ if (!keepSignedIn(am, gssv, err)) XC_LOGW("sign-in renewal: %s", err.c_str());+ err.clear();+ std::string streamLocale = ui::gameLocale();+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ bool hasCustom = false;+ GameProfile prof = g_settings.profileForGame(game.productId, game.titleId, &hasCustom);+ if (!prof.locale.empty()) streamLocale = prof.locale;+ std::string res;+ if (!g_autoplay.resolution.empty()) {+ res = g_autoplay.resolution;+ } else if (hasCustom) {+ res = prof.resolution == 1 ? "720p" : prof.resolution == 2 ? "best" : "1080p";+ } else {+ res = g_settings.resolution;+ }+ bool isBest = (res == "best" || res == "1440p");+ // "Best" asks for the top tier every time, nothing measured or+ // remembered: the service gives what the plan and the game allow+ // (1440p where it can, else 1080p). The user's own Xbox always gets+ // the top tier (it sends 1080p either way, at ~16 Mbps instead of ~9.5).+ bool home = gssv.isHome();+ g_probing = false;+ g_afterProbeAlias.clear();+ g_tierPicked = false;+ xcloud::Resolution tier;+ if (!g_autoplay.resolution.empty())+ tier = res == "720p" ? xcloud::Resolution::P720+ : res == "1440p" ? xcloud::Resolution::P1440+ : res == "1080p-hq" ? xcloud::Resolution::P1080HQ+ : isBest ? (allow1440Locked() ? xcloud::Resolution::P1440 : xcloud::Resolution::P1080HQ)+ : xcloud::Resolution::P1080HQ;+ else if (res == "720p")+ tier = xcloud::Resolution::P720;+ else if (home)+ tier = xcloud::Resolution::P1440;+ else if (res == "1440p" || (isBest && allow1440Locked()))+ tier = xcloud::Resolution::P1440;+ else+ tier = xcloud::Resolution::P1080HQ;+ gssv.setResolution(tier);+ gssv.setPreviewFeatures(g_settings.previewFeatures);+ const xcloud::Region* region = gssv.session().defaultRegion();+ const std::string& wanted = regionName.empty() ? g_settings.region : regionName;+ for (const auto& r : gssv.session().regions)+ if (r.name == wanted) region = &r;+ if (region) gssv.setRegion(*region);+ XC_LOGI("stream settings: %s%s, region %s, locale %s", res.c_str(),+ hasCustom ? " (per-game)" : "", region ? region->name.c_str() : "?", streamLocale.c_str());+ }+ // For a crash marker: what is being started (a console's id stays out).+ g_stageTitle = game.titleId;+ g_stageProduct = game.productId;+ crash::setStage(gssv.isHome() ? "starting own Xbox" : ("starting " + game.titleId).c_str());+ int status = 0;+ bool started = gssv.startSession(game.titleId, streamLocale, err, &status);+ if (!started && status == 401 && !g_cancel) {+ // The token refused before its time: renewed once, asked again.+ XC_LOGW("%s; renewing the sign-in and asking again", err.c_str());+ std::string renewErr;+ if (keepSignedIn(am, gssv, renewErr, true)) started = gssv.startSession(game.titleId, streamLocale, err, &status);+ else XC_LOGW("sign-in renewal: %s", renewErr.c_str());+ }+ if (!started) {+ if (err.find("0x87DD043A") != std::string::npos || err.find("MonthlyLimitExceeded") != std::string::npos) {+ return std::string(ui::tr(ui::Str::MonthlyLimitExceeded));+ }+ return err;+ }+ if (game.heroUrl.empty() && !game.productId.empty()) {+ // Picked before the background hydration reached it: fetch the hero+ // art for the loading screen while the session queues.+ std::map<std::string, xcloud::Product> full;+ std::string e;+ if (xcloud::fetchProducts({game.productId}, gssv.session().market.empty() ? "US" : gssv.session().market,+ ui::catalogLanguage(), full, e, true) &&+ full.count(game.productId)) {+ ui::GameTile withArt = game;+ withArt.heroUrl = full[game.productId].heroUrl;+ XC_LOGI("launch art: %s", withArt.heroUrl.empty() ? "(none)" : withArt.heroUrl.c_str());+ g_ui->showLaunching(withArt, ui::tr(ui::Str::Connecting));+ }+ }+ bool connected = false;+ bool wasInQueue = false;+ std::string result = "timed out waiting for the session";+ // A console that is off for good (not asleep) never comes out of+ // Provisioning: give up after a minute (the cloud's queue may take long).+ const uint64_t provisioningSince = platform::nowMs();+ int pollErrors = 0;+ // The queue's estimate: the title's (the service has no per-session one),+ // asked every 15 s and counted down in between; -1 unknown.+ int queueSeconds = -1;+ uint64_t queueAskedAt = 0;+ uint64_t queueStartedAt = 0;+ for (int i = 0; i < 900 && !g_cancel; ++i) {+ if (gssv.isHome() && platform::nowMs() - provisioningSince > 60000) {+ result = "ConsoleDidNotWake: no answer in 60 s";+ break;+ }+ xcloud::SessionStatus st;+ if (!gssv.sessionState(st, err)) {+ // A network hiccup (a TLS timeout) is asked again; three in a row end it.+ if (++pollErrors < 3) {+ XC_LOGW("%s (asking again)", err.c_str());+ platform::sleepMs(1000);+ continue;+ }+ result = err;+ break;+ }+ pollErrors = 0;+ XC_LOGI("session state: %s", st.raw.c_str());+ if (st.state == xcloud::SessionState::WaitingForResources) {+ wasInQueue = true;+ uint64_t now = platform::nowMs();+ if (!queueStartedAt) queueStartedAt = now;+ int elapsedSec = static_cast<int>((now - queueStartedAt) / 1000);+ if (!queueAskedAt || now - queueAskedAt >= 15000) {+ int s = gssv.titleWaitSeconds(game.titleId);+ XC_LOGI("queue: estimated %d s (elapsed %d s)", s, elapsedSec);+ if (s >= 0 || queueSeconds < 0) queueSeconds = s;+ queueAskedAt = now;+ }+ bool indeterminate = (queueSeconds < 0) || (queueSeconds <= 15 && elapsedSec >= 15);+ if (indeterminate) {+ g_ui->setLaunchStatus(ui::trf(ui::Str::InQueueIndeterminate, formatWait(elapsedSec)));+ } else {+ int left = std::max(0, queueSeconds - static_cast<int>((now - queueAskedAt) / 1000));+ g_ui->setLaunchStatus(ui::trf(ui::Str::InQueueEstimated, formatWait(left), formatWait(elapsedSec)));+ }+ }+ if (st.state == xcloud::SessionState::Provisioning && gssv.isHome())+ g_ui->setLaunchStatus(ui::tr(ui::Str::WakingConsole)); // a sleeping Xbox takes ~10 s+ if (st.state == xcloud::SessionState::Failed) {+ if (st.errorCode == "0x87DD043A" || st.errorCode == "MonthlyLimitExceeded" ||+ st.raw.find("0x87DD043A") != std::string::npos || st.raw.find("MonthlyLimitExceeded") != std::string::npos) {+ result = ui::tr(ui::Str::MonthlyLimitExceeded);+ } else {+ result = "the session failed: " + st.errorCode + " " + st.errorMessage;+ }+ break;+ }+ if (st.state == xcloud::SessionState::ReadyToConnect && !connected) {+ std::string transfer;+ if (!am.consoleTransferToken(transfer, err) || !gssv.connect(transfer, err)) {+ result = err;+ break;+ }+ connected = true;+ }+ if (st.state == xcloud::SessionState::Provisioned) {+ bool alertOn = false;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ alertOn = g_settings.queueReadyAlert;+ }+ if (alertOn && (wasInQueue || (platform::nowMs() - provisioningSince >= 2000))) {+ XC_LOGI("session: queue completed and provisioned; triggering queue-ready chime and rumble on DualSense");+ playQueueReadyAlert(true);+ }+ g_ui->setLaunchStatus(ui::tr(ui::Str::StartingStream));+ result = stream(gssv);+ failed = result.rfind("ERROR", 0) == 0;+ break;+ }+ platform::sleepMs(1000);+ }+ if (g_cancel && failed) {+ result = "cancelled";+ failed = false;+ }+ gssv.stopSession();+ return result;+}++} // namespace xc::appdiff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 0ee7fcf..deed568 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -1,248 +1,9 @@// SPDX-License-Identifier: GPL-3.0-or-later// Copyright (C) 2026 RafaelNGP-#include "ui/app_ui.h"-#include "ui/input_mode.h"-#include "ui/pad_glyphs.h"--#include "input/tuning.h"-#include "xcloud/catalog.h"-#include "ui/accent_color.h"--#include "platform/platform.h"-#include "platform/toasts.h"-#include "ui/brand.h"-#include "ui/strings.h"-#include "ui/toast_view.h"-#include "app/update_check.h"--#include "qrcodegen.h"--#include <algorithm>-#include <cctype>-#include <cmath>-#include <map>+#include "ui/app_ui_internal.h"namespace xc::ui {-namespace {--// A padlock centred on (cx, cy), about 24x30 px: a game the account can't play.-void drawLock(Canvas& c, int cx, int cy) {- const Color white = rgba(255, 255, 255, 230);- c.strokeArc(static_cast<float>(cx), static_cast<float>(cy - 4), 8, 3.5f, 3.1416f, 3.1416f, white);- c.line(cx - 8.0f, cy - 4.0f, cx - 8.0f, cy + 1.0f, 3.5f, white);- c.line(cx + 8.0f, cy - 4.0f, cx + 8.0f, cy + 1.0f, 3.5f, white);- c.fillRect({cx - 12, cy, 24, 18}, white, 4);-}--constexpr int kW = 1920, kH = 1080;-constexpr int kMargin = 96;-constexpr int kCard = 240;-constexpr int kCardGap = 24;-constexpr int kCardPitch = kCard + kCardGap;-constexpr int kRowPitch = 340;-constexpr int kRowTop = 470; // y of the focused row's title-constexpr uint64_t kHeroFadeMs = 300;--constexpr Color kBg = rgba(14, 14, 14);-constexpr Color kWhite = rgba(255, 255, 255);-constexpr Color kGray = rgba(190, 190, 190);-constexpr Color kDim = rgba(140, 140, 140);-constexpr Color kGreen = rgba(16, 124, 16);-constexpr Color kPanel = rgba(36, 36, 36);-constexpr Color kPlaceholder = rgba(44, 44, 44);--enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle, kIconTouchpad, kIconSquare, kIconR3, kIconL3, kIconL2R2, kIconDpadLR, kIconL1R1 };--// The resolution list, lowest first: SettingsChoice::resolution value per-// position (0 = 1080p, 1 = 720p, 2 = 1440p, as saved).-constexpr int kResolutionOrder[3] = {1, 0, 2};-// Settings' rows on screen, alike ones together (the row ids stay what-// settingsRow_ and the helpers use): language, sign-in country, and sign-in check; the-// stream (resolution, a desktop's display mode, 120 Hz, bitrate, region, network test);-// the controller, keyboard and queue-ready alert; support and updates last. A group starts at each-// kSettingsGroupStart.-constexpr int kSettingsCount = 22;-constexpr int kSettingsOrder[kSettingsCount] = {0, 2, 8, 17, 18, 1, 20, 13, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 19, 7, 23};-constexpr bool kSettingsGroupStart[kSettingsCount] = {false, false, false, false, false, true, false, false, false, false,- true, false, false, false, false, false, false, false, false, true, false, true};-// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2-// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7-// confirm, 8 120 Hz, 9 keyboard keys, 10 back to the default, 11 controller-// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language, 15 video decoder, 16 audio-to-haptics).-constexpr int kGameRowCount = 17;-constexpr int kGameRowOrder[kGameRowCount] = {0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10};-constexpr bool kGameGroupStart[kGameRowCount] = {false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true};-// The keyboard keys' screen: two columns of inputs, then "Reset to default".-constexpr int kKeysPerColumn = input::kKeyActions / 2;-// Updates on a desktop: the newest release's page (the app doesn't install it there).-constexpr const char* kReleasesPage = "https://github.com/RafaelNGP/xbox-cloud-gaming-ps5/releases/latest";--// The rows of `order` that `shown` keeps. A group starts on screen where the-// row above belongs to another group (a hidden group leaves no gap).-template <size_t N, class Shown>-std::vector<SettingsRowPos> filterRows(const int (&order)[N], const bool (&groupStart)[N], Shown shown) {- std::vector<SettingsRowPos> out;- int group = 0, lastGroup = -1;- for (size_t pos = 0; pos < N; ++pos) {- if (groupStart[pos]) ++group;- if (!shown(order[pos])) continue;- out.push_back({order[pos], !out.empty() && group != lastGroup});- lastGroup = group;- }- return out;-}--// Where `row` is in `rows` (0 when it isn't there).-int posOf(const std::vector<SettingsRowPos>& rows, int row) {- for (size_t i = 0; i < rows.size(); ++i)- if (rows[i].row == row) return static_cast<int>(i);- return 0;-}--// Grids ("Your games", search results): cards with the name below.-constexpr int kGridPitchY = 300;-constexpr int kLibraryCols = 6;-constexpr int kResultCols = 4;-// Keeps the focused grid row on screen: scrolls once it passes the second row.-inline float gridTarget(int focus, int cols) { return static_cast<float>(std::max(0, focus / cols - 1) * kGridPitchY); }-constexpr int kGridTop = 236; // y of the first card row (search results)-constexpr int kLibraryTop = 160; // y where "Your games" starts (its first heading)-constexpr int kResultsX = 760;-constexpr int kSectionHeaderH = 96; // "Available to buy" heading in the grid-constexpr size_t kMaxResults = 60;-constexpr size_t kMaxFilterResults = 300; // filters with no words: lists, not lookups--// The search keyboard: 6 x 6 letters and digits, then Space / Delete / Clear.-constexpr const char* kKeys = "abcdefghijklmnopqrstuvwxyz0123456789";-constexpr int kKeyCols = 6, kKeyRows = 6; // + the row of wide keys-constexpr int kKeyW = 90, kKeyH = 62, kKeyGap = 10;-constexpr int kKeysY = 262;-constexpr int kWideCols[3] = {0, 3, 5}; // first column of Space, Delete, Clear-constexpr int kWideSpan[3] = {3, 2, 1};-constexpr int kKeysW = kKeyCols * (kKeyW + kKeyGap) - kKeyGap;-constexpr int kChipGap = 10;-int chipWidth(int count) { return (kKeysW - kChipGap * (count - 1)) / std::max(1, count); }--// Lower case, accents dropped (Latin-1 range), anything else a space: what-// the search compares.-std::string fold(const std::string& s) {- static const char kLatin1[] = "aaaaaaaceeeeiiiidnooooo ouuuuytsaaaaaaaceeeeiiiidnooooo ouuuuyty";- std::string out;- out.reserve(s.size());- for (size_t i = 0; i < s.size();) {- unsigned char c = static_cast<unsigned char>(s[i]);- uint32_t cp = ' ';- size_t n = 1;- if (c < 0x80) {- cp = c;- } else if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) {- cp = ((c & 0x1Fu) << 6) | (static_cast<unsigned char>(s[i + 1]) & 0x3Fu);- n = 2;- } else if ((c & 0xF0) == 0xE0) {- n = 3;- } else if ((c & 0xF8) == 0xF0) {- n = 4;- }- i += n;- char ch = ' ';- if (cp < 0x80 && std::isalnum(static_cast<int>(cp))) ch = static_cast<char>(std::tolower(static_cast<int>(cp)));- else if (cp >= 0xC0 && cp <= 0xFF) ch = kLatin1[cp - 0xC0];- out += ch;- }- return out;-}--// "164 games", "1 game".-std::string gamesCount(size_t n) { return n == 1 ? std::string(tr(Str::OneGame)) : trf(Str::GamesCount, std::to_string(n)); }--std::string withoutSpaces(std::string s) {- s.erase(std::remove(s.begin(), s.end(), ' '), s.end());- return s;-}--bool matchesPublisher(const std::string& rawPublisher, int filter) {- if (filter <= 0) return true;- std::string p = fold(rawPublisher);-- auto isXbox = [&]() {- return p.find("xbox game studios") != std::string::npos ||- p.find("microsoft") != std::string::npos ||- p.find("bethesda") != std::string::npos ||- p.find("mojang") != std::string::npos ||- p.find("activision") != std::string::npos ||- p.find("blizzard") != std::string::npos ||- p.find("zenimax") != std::string::npos ||- p.find("id software") != std::string::npos ||- p.find("obsidian") != std::string::npos ||- p.find("ninja theory") != std::string::npos ||- p.find("double fine") != std::string::npos;- };- auto isEA = [&]() {- return p.find("electronic arts") != std::string::npos ||- p.find("ea swiss") != std::string::npos ||- p.find("ea sports") != std::string::npos ||- p == "ea" || p.find("ea ") == 0 ||- p.find(" ea ") != std::string::npos;- };- auto isUbisoft = [&]() { return p.find("ubisoft") != std::string::npos; };- auto isSquareEnix = [&]() { return p.find("square enix") != std::string::npos; };- auto isWarner = [&]() { return p.find("warner") != std::string::npos || p.find("wb games") != std::string::npos; };- auto is2K = [&]() {- return p.find("2k") != std::string::npos ||- p.find("take-two") != std::string::npos ||- p.find("take two") != std::string::npos ||- p.find("rockstar") != std::string::npos ||- p.find("private division") != std::string::npos;- };- auto isCapcom = [&]() { return p.find("capcom") != std::string::npos; };- auto isSega = [&]() { return p.find("sega") != std::string::npos || p.find("atlus") != std::string::npos; };- auto isBandai = [&]() {- return p.find("bandai namco") != std::string::npos ||- p.find("namco bandai") != std::string::npos ||- p.find("bandai") != std::string::npos;- };- auto isTHQ = [&]() {- return p.find("thq nordic") != std::string::npos ||- p.find("plaion") != std::string::npos ||- p.find("deep silver") != std::string::npos ||- p.find("koch media") != std::string::npos ||- p.find("handygames") != std::string::npos ||- p.find("embracer") != std::string::npos;- };- auto isFocus = [&]() { return p.find("focus entertainment") != std::string::npos || p.find("focus home") != std::string::npos || p == "focus"; };- auto isDevolver = [&]() { return p.find("devolver") != std::string::npos; };- auto isAnnapurna = [&]() { return p.find("annapurna") != std::string::npos; };- auto isTeam17 = [&]() { return p.find("team17") != std::string::npos || p.find("team 17") != std::string::npos; };-- switch (filter) {- case 1: return isXbox();- case 2: return isEA();- case 3: return isUbisoft();- case 4: return isSquareEnix();- case 5: return isWarner();- case 6: return is2K();- case 7: return isCapcom();- case 8: return isSega();- case 9: return isBandai();- case 10: return isTHQ();- case 11: return isFocus();- case 12: return isDevolver();- case 13: return isAnnapurna();- case 14: return isTeam17();- case 15: // Indies & Outras- return !isXbox() && !isEA() && !isUbisoft() && !isSquareEnix() &&- !isWarner() && !is2K() && !isCapcom() && !isSega() &&- !isBandai() && !isTHQ() && !isFocus() && !isDevolver() &&- !isAnnapurna() && !isTeam17();- default: return true;- }-}--constexpr uint64_t kSignOutHoldMs = 5000;--} // namespace-std::vector<SettingsRowPos> visibleSettingsRows(const UiCaps& caps) {return filterRows(kSettingsOrder, kSettingsGroupStart, [&](int row) {switch (row) {@@ -281,14 +42,6 @@ std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool cus});}-std::string loginCountryName(const std::string& country) {- static const std::pair<const char*, Str> kNames[] = {- {"br", Str::CountryBR}, {"jp", Str::CountryJP}, {"kr", Str::CountryKR}, {"pl", Str::CountryPL}, {"us", Str::CountryUS}};- for (const auto& [code, name] : kNames)- if (country == code) return tr(name);- return {};-}-std::string prettyRegion(const std::string& name) {// Longer words first where one starts another (SOUTHEAST before SOUTH).static const char* kWords[] = {"SOUTHEAST", "NORTHEAST", "SWITZERLAND", "CENTRAL", "AUSTRALIA", "GERMANY",@@ -411,6 +164,26 @@ void AppUi::setMembership(bool member) {dirty_ = true;}+bool AppUi::isFreeAccountLocked() const {+ return subscription_.empty() || (subscription_ != "GamePass" && xcloud::planTier(subscription_) == 0);+}++bool AppUi::isFreeAccount() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return isFreeAccountLocked();+}++bool AppUi::isEffectivePlayableLocked(const GameTile& t) const {+ if (!t.playable) return false;+ if (!isFreeAccountLocked()) return true;+ return isFreeGame(t) || isAcquired(t);+}++bool AppUi::isEffectivePlayable(const GameTile& t) const {+ std::lock_guard<std::mutex> lock(mutex_);+ return isEffectivePlayableLocked(t);+}+void AppUi::setRows(std::vector<GameRow> rows) {std::lock_guard<std::mutex> lock(mutex_);allRows_ = std::move(rows);@@ -420,6 +193,7 @@ void AppUi::setRows(std::vector<GameRow> rows) {void AppUi::setRowsLocked(std::vector<GameRow> rows) {// Caller holds mutex_. Remember, per row title, which game had the focus// and the scroll.+ libLayoutValid_ = false;struct Kept {std::string productId;Anim scroll;@@ -466,16 +240,28 @@ void AppUi::setOwned(std::vector<GameTile> owned, std::vector<GameTile> purchasarebuild(true);}-namespace {--int consoleRank(const std::string& platform) {- return platform == "XS" ? 0 : platform == "ONE" ? 1 : platform == "360" ? 2 : 3;+void AppUi::setCatalogState(std::vector<GameRow> rows, std::vector<GameTile> owned, std::vector<GameTile> purchasable,+ bool ownedKnown, bool member, std::vector<GameTile> gpPool, std::vector<GameTile> libPool,+ bool loadingActive, size_t loadingDone, size_t loadingTotal) {+ std::lock_guard<std::mutex> lock(mutex_);+ allRows_ = std::move(rows);+ allOwned_ = std::move(owned);+ allPurchasable_ = std::move(purchasable);+ ownedKnown_ = ownedKnown;+ if (subscription_.empty() || subscription_ == "GamePass") {+ subscription_ = member ? "GamePass" : "";+ }+ gamePassPool_ = std::move(gpPool);+ libraryPool_ = std::move(libPool);+ loading_ = loadingActive;+ loadingDone_ = loadingDone;+ loadingTotal_ = loadingTotal;+ rebuild(true);}-} // namespace-void AppUi::rebuild(bool keepPosition) {// Caller holds mutex_.+ libLayoutValid_ = false;const GameTile* was = libraryTile(gridFocus_);std::string focused = was ? was->productId : "";// Where the cursor is: section of "Your games" and place in it; Game@@ -487,32 +273,70 @@ void AppUi::rebuild(bool keepPosition) {int oldCol = focusRow_ < static_cast<int>(focusCol_.size()) ? focusCol_[static_cast<size_t>(focusRow_)] : 0;auto visible = [&](const std::vector<GameTile>& in) {std::vector<GameTile> out;+ out.reserve(in.size());for (const auto& t : in)if (!hidden_.count(t.productId)) out.push_back(t);return out;};+ auto sortByName = [](std::vector<GameTile>& v) {+ if (v.size() <= 1) return;+ struct Keyed {+ std::string key;+ size_t idx;+ };+ std::vector<Keyed> keys(v.size());+ for (size_t i = 0; i < v.size(); ++i) keys[i] = {fold(v[i].name), i};+ std::stable_sort(keys.begin(), keys.end(), [](const Keyed& a, const Keyed& b) { return a.key < b.key; });+ std::vector<GameTile> out;+ out.reserve(v.size());+ for (const auto& k : keys) out.push_back(std::move(v[k.idx]));+ v = std::move(out);+ };// "Recent" keeps the order received: recently played first for the// account's games, most popular first for the games to buy.- auto byName = [](const GameTile& a, const GameTile& b) { return fold(a.name) < fold(b.name); };auto sorted = [&](std::vector<GameTile> v) {if (librarySort_ == LibrarySort::AZ) {- std::stable_sort(v.begin(), v.end(), byName);- } else if (librarySort_ == LibrarySort::Console) {- std::stable_sort(v.begin(), v.end(), [&](const GameTile& a, const GameTile& b) {- int ra = consoleRank(a.platform), rb = consoleRank(b.platform);- return ra != rb ? ra < rb : byName(a, b);+ sortByName(v);+ } else if (librarySort_ == LibrarySort::Console && v.size() > 1) {+ struct Keyed {+ int rank;+ std::string key;+ size_t idx;+ };+ std::vector<Keyed> keys(v.size());+ for (size_t i = 0; i < v.size(); ++i) keys[i] = {consoleRank(v[i].platform), fold(v[i].name), i};+ std::stable_sort(keys.begin(), keys.end(), [](const Keyed& a, const Keyed& b) {+ return a.rank != b.rank ? a.rank < b.rank : a.key < b.key;});+ std::vector<GameTile> out;+ out.reserve(v.size());+ for (const auto& k : keys) out.push_back(std::move(v[k.idx]));+ v = std::move(out);}return v;};- for (auto it = wishlist_.begin(); it != wishlist_.end(); ) {- GameTile checkTile;- checkTile.productId = *it;+ if (!wishlist_.empty()) {+ std::unordered_set<std::string> ownedPids, ownedTids;+ ownedPids.reserve(allOwned_.size());+ ownedTids.reserve(allOwned_.size());+ for (const auto& o : allOwned_) {+ if (!o.productId.empty()) ownedPids.insert(o.productId);+ if (!o.titleId.empty()) ownedTids.insert(o.titleId);+ }+ std::unordered_map<std::string, std::string> purchTid;+ purchTid.reserve(allPurchasable_.size());for (const auto& p : allPurchasable_) {- if (p.productId == *it) { checkTile.titleId = p.titleId; break; }+ if (!p.productId.empty() && !p.titleId.empty()) purchTid.emplace(p.productId, p.titleId);+ }+ for (auto it = wishlist_.begin(); it != wishlist_.end(); ) {+ bool acq = ownedPids.count(*it) > 0;+ if (!acq) {+ auto pit = purchTid.find(*it);+ if (pit != purchTid.end() && ownedTids.count(pit->second) > 0) acq = true;+ }+ if (acq) it = wishlist_.erase(it);+ else ++it;}- if (isAcquired(checkTile)) it = wishlist_.erase(it);- else ++it;}owned_ = sorted(visible(allOwned_));purchasable_ = sorted(visible(allPurchasable_));@@ -529,14 +353,14 @@ void AppUi::rebuild(bool keepPosition) {hiddenTiles_.clear();for (const auto* list : {&allOwned_, &allPurchasable_})for (const auto& t : *list) collect(hiddenTiles_, t);- std::stable_sort(hiddenTiles_.begin(), hiddenTiles_.end(), byName);+ sortByName(hiddenTiles_);GameRow hiddenRow;hiddenRow.title = tr(Str::HiddenSection);hiddenRow.gamePassBadges = true;for (const auto& row : allRows_)for (const auto& t : row.tiles) collect(hiddenRow.tiles, t);for (const auto& t : gamePassPool_) collect(hiddenRow.tiles, t);- std::stable_sort(hiddenRow.tiles.begin(), hiddenRow.tiles.end(), byName);+ sortByName(hiddenRow.tiles);std::vector<GameRow> rows;for (const auto& row : allRows_) {@@ -752,7 +576,7 @@ std::vector<std::string> AppUi::pricesWanted(size_t max, bool background) {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();+ const 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])];@@ -768,13 +592,38 @@ std::vector<std::string> AppUi::pricesWanted(size_t max, bool background) {std::string AppUi::detailWanted(uint64_t nowMs) {std::lock_guard<std::mutex> lock(mutex_);- if (screen_ != Screen::Details || detail_.productId.empty()) return {};- if (detailInfo_.find(detail_.productId) != detailInfo_.end()) return {};+ if (screen_ != Screen::Details) return {};+ std::string pid = detail_.productId;+ if (pid.empty() && !detail_.titleId.empty()) {+ for (const auto* list : {&gamePassPool_, &libraryPool_, &allOwned_, &allPurchasable_}) {+ for (const auto& t : *list) {+ if (!t.productId.empty() && t.titleId == detail_.titleId) {+ pid = t.productId;+ break;+ }+ }+ if (!pid.empty()) break;+ }+ if (pid.empty()) {+ for (const auto& row : allRows_) {+ for (const auto& t : row.tiles) {+ if (!t.productId.empty() && t.titleId == detail_.titleId) {+ pid = t.productId;+ break;+ }+ }+ if (!pid.empty()) break;+ }+ }+ if (!pid.empty()) detail_.productId = pid;+ }+ if (pid.empty()) return {};+ if (detailInfo_.find(pid) != detailInfo_.end()) return {};if (!detail_.description.empty() && !detail_.heroUrl.empty() && !detail_.ratingAge.empty()) return {};- if (detail_.productId == detailAskedFor_ && nowMs - detailAskedAt_ < 5000) return {};- detailAskedFor_ = detail_.productId;+ if (pid == detailAskedFor_ && nowMs - detailAskedAt_ < 5000) return {};+ detailAskedFor_ = pid;detailAskedAt_ = nowMs;- return detail_.productId;+ return pid;}std::string AppUi::heroWanted(uint64_t nowMs) {@@ -890,7 +739,7 @@ void AppUi::syncHeroToRowsLocked(const std::string& productId, const std::stringif (productId.empty() && titleId.empty()) return;auto updateTile = [&](GameTile& t) {bool match = (!productId.empty() && t.productId == productId) ||- (!titleId.empty() && t.titleId == titleId);+ (!titleId.empty() && t.titleId == titleId && (t.productId.empty() || productId.empty()));if (match) {if (t.productId.empty() && !productId.empty()) t.productId = productId;if (t.titleId.empty() && !titleId.empty()) t.titleId = titleId;@@ -932,7 +781,7 @@ void AppUi::setDetailInfo(const std::string& productId, const std::string& descrsyncHeroToRowsLocked(productId, matchingTitleId, heroUrl, description, publisher, categories);if (!ratingAge.empty() || !ratingSystem.empty() || !ratingDescriptors.empty()) {auto updateRating = [&](GameTile& t) {- if (t.productId == productId || (!matchingTitleId.empty() && t.titleId == matchingTitleId)) {+ if (t.productId == productId || (!matchingTitleId.empty() && t.titleId == matchingTitleId && t.productId.empty())) {if (!ratingAge.empty() && t.ratingAge.empty()) t.ratingAge = ratingAge;if (!ratingSystem.empty() && t.ratingSystem.empty()) t.ratingSystem = ratingSystem;if (!ratingDescriptors.empty() && t.ratingDescriptors.empty()) t.ratingDescriptors = ratingDescriptors;@@ -953,13 +802,16 @@ bool AppUi::findTile(const std::string& titleId, GameTile& out) const {std::vector<const GameTile*> all;for (const auto& row : rows_)for (const auto& t : row.tiles) all.push_back(&t);- for (const auto* list : {&owned_, &purchasable_})+ for (const auto& row : allRows_)+ for (const auto& t : row.tiles) all.push_back(&t);+ for (const auto* list : {&owned_, &purchasable_, &allOwned_, &allPurchasable_, &gamePassPool_, &libraryPool_})for (const auto& t : *list) all.push_back(&t);- for (const GameTile* t : all)- if (t->titleId == titleId) {+ for (const GameTile* t : all) {+ if (t->titleId == titleId || t->productId == titleId || t->name == titleId) {out = *t;return true;}+ }return false;}@@ -1062,7 +914,7 @@ std::string AppUi::focusDescription() const {return "Game Pass row " + std::to_string(focusRow_) + " card " +std::to_string(focusCol_.empty() ? 0 : focusCol_[static_cast<size_t>(focusRow_)]);if (tab_ == Tab::Library) {- LibraryLayout L = libraryLayout();+ const LibraryLayout& L = libraryLayout();int f = gridFocus_;if (f >= 0 && f < static_cast<int>(L.rowOf.size()))return "My games tile " + std::to_string(f) + " (row " + std::to_string(L.rowOf[static_cast<size_t>(f)]) + ")";@@ -1086,35 +938,99 @@ Tab AppUi::tab() const {void AppUi::openDetails(const GameTile& tile) {// Caller holds mutex_.detail_ = tile;+ if (detail_.productId.empty() && !detail_.titleId.empty()) {+ for (const auto* list : {&gamePassPool_, &libraryPool_, &allOwned_, &allPurchasable_}) {+ for (const auto& t : *list) {+ if (!t.productId.empty() && t.titleId == detail_.titleId) {+ detail_.productId = t.productId;+ break;+ }+ }+ if (!detail_.productId.empty()) break;+ }+ if (detail_.productId.empty()) {+ for (const auto& row : allRows_) {+ for (const auto& t : row.tiles) {+ if (!t.productId.empty() && t.titleId == detail_.titleId) {+ detail_.productId = t.productId;+ break;+ }+ }+ if (!detail_.productId.empty()) break;+ }+ }+ }gameSettingsOpen_ = false;tester_ = Tester::None;- auto info = detailInfo_.find(tile.productId);- if (info != detailInfo_.end()) {- if (detail_.description.empty()) detail_.description = info->second.description;- if (detail_.heroUrl.empty()) detail_.heroUrl = info->second.heroUrl;- if (detail_.publisher.empty()) detail_.publisher = info->second.publisher;- if (detail_.categories.empty()) detail_.categories = info->second.categories;- if (detail_.ratingAge.empty()) detail_.ratingAge = info->second.ratingAge;- if (detail_.ratingSystem.empty()) detail_.ratingSystem = info->second.ratingSystem;- if (detail_.ratingDescriptors.empty()) detail_.ratingDescriptors = info->second.ratingDescriptors;- }detailButtonFocus_ = 0;+ playRect_ = {};+ achRect_ = {};+ claimRect_ = {};screen_ = Screen::Details;+ refreshDetail();dirty_ = true;}void AppUi::refreshDetail() {// Caller holds mutex_. Hero art and descriptions arrive after the page opened.- if (screen_ != Screen::Details || detail_.productId.empty()) return;+ if (screen_ != Screen::Details || (detail_.productId.empty() && detail_.titleId.empty())) return;bool changed = false;+ if (!detail_.productId.empty()) {+ auto info = detailInfo_.find(detail_.productId);+ if (info != detailInfo_.end()) {+ if (detail_.description.empty() && !info->second.description.empty()) {+ detail_.description = info->second.description;+ changed = true;+ }+ if (detail_.heroUrl.empty() && !info->second.heroUrl.empty()) {+ detail_.heroUrl = info->second.heroUrl;+ changed = true;+ }+ if (detail_.publisher.empty() && !info->second.publisher.empty()) {+ detail_.publisher = info->second.publisher;+ changed = true;+ }+ if (detail_.categories.empty() && !info->second.categories.empty()) {+ detail_.categories = info->second.categories;+ changed = true;+ }+ if (detail_.ratingAge.empty() && !info->second.ratingAge.empty()) {+ detail_.ratingAge = info->second.ratingAge;+ detail_.ratingSystem = info->second.ratingSystem;+ detail_.ratingDescriptors = info->second.ratingDescriptors;+ changed = true;+ }+ }+ }auto take = [&](const GameTile& t) {- if (t.productId == detail_.productId) {- if (t.heroUrl.size() + t.description.size() >- detail_.heroUrl.size() + detail_.description.size()) {- detail_.heroUrl = t.heroUrl;+ bool match = (!detail_.productId.empty() && t.productId == detail_.productId) ||+ (!detail_.titleId.empty() && t.titleId == detail_.titleId && (detail_.productId.empty() || t.productId.empty()));+ if (match) {+ if (detail_.productId.empty() && !t.productId.empty()) {+ detail_.productId = t.productId;+ changed = true;+ }+ if (detail_.xboxTitleId.empty() && !t.xboxTitleId.empty()) {+ detail_.xboxTitleId = t.xboxTitleId;+ changed = true;+ }+ if (detail_.description.empty() && !t.description.empty()) {+ detail_.description = t.description;+ changed = true;+ } else if (!t.description.empty() && t.description.size() > detail_.description.size()) {detail_.description = t.description;- if (!t.publisher.empty()) detail_.publisher = t.publisher;- if (!t.categories.empty()) detail_.categories = t.categories;+ changed = true;+ }+ if (detail_.heroUrl.empty() && !t.heroUrl.empty()) {+ detail_.heroUrl = t.heroUrl;+ changed = true;+ }+ if (detail_.publisher.empty() && !t.publisher.empty()) {+ detail_.publisher = t.publisher;+ changed = true;+ }+ if (detail_.categories.empty() && !t.categories.empty()) {+ detail_.categories = t.categories;changed = true;}if (detail_.ratingAge.empty() && !t.ratingAge.empty()) {@@ -1127,214 +1043,13 @@ void AppUi::refreshDetail() {};for (const auto& row : rows_)for (const auto& t : row.tiles) take(t);- for (const auto* list : {&owned_, &purchasable_, &gamePassPool_, &libraryPool_})+ for (const auto& row : allRows_)+ for (const auto& t : row.tiles) take(t);+ for (const auto* list : {&owned_, &purchasable_, &allOwned_, &allPurchasable_, &gamePassPool_, &libraryPool_})for (const auto& t : *list) take(t);if (changed) dirty_ = true;}-static bool containsWordBoundary(const std::string& text, const std::string& token) {- size_t pos = 0;- while ((pos = text.find(token, pos)) != std::string::npos) {- bool startBound = (pos == 0 || !isalnum((unsigned char)text[pos - 1]));- bool endBound = (pos + token.size() >= text.size() || !isalnum((unsigned char)text[pos + token.size()]));- if (startBound && endBound) return true;- pos += token.size();- }- return false;-}--static bool matchSearchWord(const std::string& name, const std::string& word) {- if (name.find(word) != std::string::npos) return true;- static const std::pair<const char*, const char*> kRoman[] = {- {"1", "i"}, {"i", "1"},- {"2", "ii"}, {"ii", "2"},- {"3", "iii"}, {"iii", "3"},- {"4", "iv"}, {"iv", "4"},- {"4", "iiii"}, {"iiii", "4"},- {"5", "v"}, {"v", "5"},- {"6", "vi"}, {"vi", "6"},- };- for (const auto& [num, rom] : kRoman) {- if (word == num && containsWordBoundary(name, rom)) return true;- }- static const std::pair<const char*, const char*> kAcronyms[] = {- {"cod", "call of duty"},- {"cod4", "call of duty 4"},- {"codmw", "modern warfare"},- {"codmw4", "modern warfare 4"},- {"mw", "modern warfare"},- {"mw1", "modern warfare"},- {"mw2", "modern warfare ii"},- {"mwii", "modern warfare ii"},- {"mw3", "modern warfare iii"},- {"mwiii", "modern warfare iii"},- {"mw4", "modern warfare 4"},- {"mwiv", "modern warfare 4"},- {"bo", "black ops"},- {"bo1", "black ops"},- {"bo2", "black ops ii"},- {"bo3", "black ops iii"},- {"bo4", "black ops iiii"},- {"bo6", "black ops 6"},- {"bops", "black ops"},- {"gta", "grand theft auto"},- {"rdr", "red dead"},- {"re", "resident evil"},- {"ac", "assassin"},- {"gow", "gears of war"},- {"nfs", "need for speed"},- {"bf", "battlefield"},- };- for (const auto& [acro, full] : kAcronyms) {- if (word == acro && name.find(full) != std::string::npos) return true;- }- return false;-}--void AppUi::runSearch(bool keepPosition) {- // Caller holds mutex_. The typed words narrow by name; the filters by- // price and console. With filters and no words: every game that passes.- std::string focusedProductId;- std::string focusedTitleId;- int oldFocus = resultFocus_;- float oldScrollVal = resultScroll_.value;- if (keepPosition && resultFocus_ >= 0 && resultFocus_ < static_cast<int>(results_.size())) {- focusedProductId = results_[static_cast<size_t>(resultFocus_)].productId;- focusedTitleId = results_[static_cast<size_t>(resultFocus_)].titleId;- }-- results_.clear();- std::string q = fold(query_);- std::vector<std::string> words;- for (size_t i = 0; i < q.size();) {- size_t j = q.find(' ', i);- if (j == std::string::npos) j = q.size();- if (j > i) words.push_back(q.substr(i, j - i));- i = j + 1;- }- bool filtering = anyFilter();- if (words.empty() && !filtering) {- resultFocus_ = 0;- resultScroll_ = Anim{};- return;- }- std::string compact = withoutSpaces(q);- static const char* kConsoleCodes[] = {"", "XS", "ONE", "360"};- struct Hit {- int score;- double order; // the price now (with any discount), by the active order filter- double discount; // the bigger first among equal prices- const GameTile* tile;- };- std::vector<Hit> hits;- for (const auto& t : tab_ == Tab::GamePass ? gamePassPool_ : libraryPool_) {- if (hidden_.count(t.productId)) continue;- if (tab_ == Tab::GamePass && filterPlan_ != 4) {- if (filterPlan_ == 0) {- uint8_t myPlan = xcloud::planTier(subscription_);- bool inPlan = (myPlan > 0) ? xcloud::planIncludes(myPlan, t.plan, t.freeInStore) : true;- if (!t.freeInStore && !t.playable && !inPlan) continue;- } else {- uint8_t want = filterPlan_ == 1 ? xcloud::kPlanUltimate- : filterPlan_ == 2 ? xcloud::kPlanPremium- : xcloud::kPlanEssential;- if (!t.freeInStore && (want < xcloud::kPlanUltimate && t.plan == 0)) continue;- if (!xcloud::planIncludes(want, t.plan, t.freeInStore)) continue;- }- }- if (filterConsole_ && t.platform != kConsoleCodes[filterConsole_]) continue;- if (filterMouseKeyboard_ && !t.mouseKeyboard) continue;- // Play mode and language need the full details: a game without them- // yet comes in when they arrive.- static constexpr uint32_t kModeBits[] = {0, xcloud::kModeSingle, xcloud::kModeOnlineMulti, xcloud::kModeOnlineCoop,- xcloud::kModeLocal};- if (filterMode_ && !(t.modes & kModeBits[filterMode_])) continue;- if (filterLanguage_ == 1 && !(t.languages & (xcloud::kLangInterface | xcloud::kLangSubtitles))) continue;- if (filterLanguage_ == 2 && !(t.languages & xcloud::kLangAudio)) continue;- if (!filterGenre_.empty() && std::find(t.categories.begin(), t.categories.end(), filterGenre_) == t.categories.end())- continue;- if (filterPublisher_ && !matchesPublisher(t.publisher, filterPublisher_))- continue;- auto price = prices_.find(t.productId);- bool priced = price != prices_.end();- if (tab_ == Tab::Library) {- if (filterWishlist_ && !wishlist_.count(t.productId)) continue;- // Free-to-play: free in the store and no regular price. A paid- // game given away (price 0 now, regular price above 0) is a- // sale, not free-to-play.- bool zeroNow = t.purchasable && priced && price->second.list < 0.005;- bool freeToPlay = (t.freeInStore || (zeroNow && price->second.msrp < 0.005)) && !unclaimable_.count(t.productId);- if (filterFree_) {- if (!freeToPlay && !zeroNow) continue; // Free: both- if (t.playable || isAcquired(t)) continue; // Do not show games the user already owns on their account!- }- // Free-to-play games have their own filter: the price orders- // leave them out, unless Free is on too. Giveaways stay (first).- if (filterCheapest_ && freeToPlay && !filterFree_) continue;- // Price filters look at games to buy only.- if (filterCheapest_ && !t.purchasable) continue;- }- std::string name = fold(t.name);- int score = 0;- if (!words.empty()) {- bool all = true;- for (const auto& w : words)- if (!matchSearchWord(name, w)) all = false;- if (!all && withoutSpaces(name).find(compact) == std::string::npos) continue;- // Starts with the query or acronym, then a word starting with it, then the rest.- if (matchSearchWord(name, words[0])) {- score = name.rfind(words[0], 0) == 0 ? 0 : name.find(" " + words[0]) != std::string::npos ? 1 : 2;- if (words[0] == "cod" && name.find("call of duty") != std::string::npos) score = 0;- else if ((words[0] == "cod4" || words[0] == "mw4" || words[0] == "codmw4" ||- words[0] == "mwiv" || words[0] == "codmwiv") &&- (name.find("modern warfare 4") != std::string::npos || name.find("call of duty 4") != std::string::npos)) score = 0;- else if (words[0] == "codmw" && name.find("modern warfare") != std::string::npos) score = 0;- } else {- score = 2;- }- }- if (!t.playable) score += 3; // in "Your games": owned before games to buy- // Lowest price: by the price now (with any discount, not the regular- // one), lowest first; unknown prices last; the bigger discount first- // among equal prices.- double order = 0, discount = 0;- if (filterCheapest_) order = priced ? price->second.list : 1e12;- if (filterCheapest_ && priced && price->second.msrp > 0) discount = 1.0 - price->second.list / price->second.msrp;- hits.push_back({score, order, discount, &t});- }- bool byOrder = tab_ == Tab::Library && filterCheapest_;- std::stable_sort(hits.begin(), hits.end(), [&](const Hit& a, const Hit& b) {- if (byOrder && a.order != b.order) return a.order < b.order;- if (byOrder && a.discount != b.discount) return a.discount > b.discount;- if (a.score != b.score) return a.score < b.score;- return fold(a.tile->name) < fold(b.tile->name);- });- size_t max = words.empty() ? kMaxFilterResults : kMaxResults;- for (size_t i = 0; i < hits.size() && i < max; ++i) results_.push_back(*hits[i].tile);- if (keepPosition && !results_.empty()) {- int newFocus = -1;- if (!focusedProductId.empty() || !focusedTitleId.empty()) {- for (size_t i = 0; i < results_.size(); ++i) {- if ((!focusedProductId.empty() && results_[i].productId == focusedProductId) ||- (!focusedTitleId.empty() && results_[i].titleId == focusedTitleId)) {- newFocus = static_cast<int>(i);- break;- }- }- }- if (newFocus >= 0) {- resultFocus_ = newFocus;- } else {- resultFocus_ = std::min(oldFocus, static_cast<int>(results_.size()) - 1);- }- resultScroll_.target = gridTarget(resultFocus_, kResultCols);- resultScroll_.value = oldScrollVal;- } else {- resultFocus_ = 0;- resultScroll_ = Anim{};- }-}-void AppUi::showHome(const std::string& toast) {std::lock_guard<std::mutex> lock(mutex_);if (screen_ == Screen::Details) {@@ -1363,14 +1078,12 @@ void AppUi::markTileOwned(const std::string& productId, const std::string& titleif (detail_.productId == productId || (!titleId.empty() && detail_.titleId == titleId)) {detail_.playable = true;detail_.purchasable = false;- detail_.freeInStore = false;dirty_ = true;}auto updateTileFlags = [&](GameTile& t) {if ((!productId.empty() && t.productId == productId) || (!titleId.empty() && t.titleId == titleId)) {t.playable = true;t.purchasable = false;- t.freeInStore = false;}};for (auto& row : rows_) {@@ -1409,7 +1122,6 @@ void AppUi::markTileOwned(const std::string& productId, const std::string& titleif (!acquiredTile.productId.empty()) {acquiredTile.playable = true;acquiredTile.purchasable = false;- acquiredTile.freeInStore = false;for (auto it = allOwned_.begin(); it != allOwned_.end(); ++it) {if (it->productId == acquiredTile.productId || (!acquiredTile.titleId.empty() && it->titleId == acquiredTile.titleId)) {if (acquiredTile.name.empty()) acquiredTile.name = it->name;@@ -1431,8 +1143,18 @@ void AppUi::markUnclaimable(const std::string& productId) {unclaimable_.insert(productId);if (detail_.productId == productId) {detail_.freeInStore = false;- dirty_ = true;}+ auto clearFree = [&](GameTile& t) {+ if (!productId.empty() && t.productId == productId) {+ t.freeInStore = false;+ }+ };+ for (auto& row : rows_) for (auto& t : row.tiles) clearFree(t);+ for (auto& row : allRows_) for (auto& t : row.tiles) clearFree(t);+ for (auto* list : {&owned_, &purchasable_, &allOwned_, &allPurchasable_, &gamePassPool_, &libraryPool_, &results_}) {+ for (auto& t : *list) clearFree(t);+ }+ dirty_ = true;}void AppUi::showLaunching(const GameTile& game, const std::string& status) {@@ -1480,477 +1202,101 @@ void AppUi::showRegionRefused(const std::string& message) {dirty_ = true;}-void AppUi::showPlayError(const std::string& message, const GameTile& game) {+void AppUi::showPlayError(const std::string& message, const GameTile& game, const std::string& url) {std::lock_guard<std::mutex> lock(mutex_);screen_ = Screen::Error;error_ = message;- errorUrl_.clear();+ errorUrl_ = url;errorGame_ = game;loading_ = false;regionRefused_ = countryPickerOpen_ = false;dirty_ = true;}-namespace {--// Hue 0..1, saturation and value 0..1.-Color hsvColour(float h, float s, float v) {- h = (h - std::floor(h)) * 6.0f;- int i = static_cast<int>(h) % 6;- float f = h - std::floor(h), p = v * (1 - s), q = v * (1 - s * f), t = v * (1 - s * (1 - f));- float r = i == 0 || i == 5 ? v : i == 1 ? q : i == 2 || i == 3 ? p : t;- float g = i == 0 ? t : i == 1 || i == 2 ? v : i == 3 ? q : p;- float b = i == 2 ? t : i == 3 || i == 4 ? v : i == 5 ? q : p;- auto byte = [](float x) { return static_cast<uint8_t>(std::lround(std::clamp(x, 0.0f, 1.0f) * 255)); };- return rgba(byte(r), byte(g), byte(b));+void AppUi::setUpdateState(const std::string& current, const std::string& available, bool checking, const std::string& notes) {+ std::lock_guard<std::mutex> lock(mutex_);+ updateCurrent_ = current;+ updateAvailable_ = available;+ updateChecking_ = checking;+ if (!notes.empty()) {+ updateNotes_ = notes;+ formatUpdateNotes();+ }+ dirty_ = true;}-void colourHsv(Color c, float& h, float& s, float& v) {- float r = (c & 0xFF) / 255.0f, g = (c >> 8 & 0xFF) / 255.0f, b = (c >> 16 & 0xFF) / 255.0f;- float mx = std::max({r, g, b}), mn = std::min({r, g, b}), d = mx - mn;- v = mx;- s = mx > 0 ? d / mx : 0;- if (d <= 0) h = 0;- else if (mx == r) h = (g - b) / d / 6.0f;- else if (mx == g) h = ((b - r) / d + 2) / 6.0f;- else h = ((r - g) / d + 4) / 6.0f;- if (h < 0) h += 1;+void AppUi::setUpdateNotes(const std::string& notes) {+ std::lock_guard<std::mutex> lock(mutex_);+ updateNotes_ = notes;+ formatUpdateNotes();+ dirty_ = true;}-constexpr int kWheelR = 180;-constexpr float kMinValue = 0.2f; // darker turns the light bar all but off--} // namespace+void AppUi::setSignInCheckState(const SignInCheckState& state) {+ std::lock_guard<std::mutex> lock(mutex_);+ signInCheck_ = state;+ dirty_ = true;+}-bool AppUi::settingsLightBar(int& mode, Color& colour) const {+SignInCheckState AppUi::signInCheckState() const {std::lock_guard<std::mutex> lock(mutex_);- if (screen_ != Screen::Settings) return false;- mode = pickerOpen_ ? 1 : settings_.lightBarMode;- colour = pickerOpen_ ? pickerColour() : settings_.lightBarColour;- return true;+ return signInCheck_;}-bool AppUi::settingsTriggerFeel(int& strength, int& hzIndex, int& resistance, bool& pulses, int& profile) const {+void AppUi::setNetworkTestState(const NetworkTestState& state) {std::lock_guard<std::mutex> lock(mutex_);- if (screen_ != Screen::Settings && !gameSettingsOpen_) return false;- strength = settings_.triggerStrength;- hzIndex = settings_.triggerHz;- resistance = settings_.triggerResistance;- pulses = settings_.triggerPulses;- profile = settings_.triggerProfile;- return true;+ networkTest_ = state;+ dirty_ = true;}-bool AppUi::triggerTest(float& l2, float& r2) const {+NetworkTestState AppUi::networkTestState() const {std::lock_guard<std::mutex> lock(mutex_);- if ((screen_ != Screen::Settings && !gameSettingsOpen_) || tester_ != Tester::Triggers) return false;- l2 = testL2_;- r2 = testR2_;- return true;+ return networkTest_;}-void AppUi::openTester(Tester t) {- // Caller holds mutex_. Circle puts back what was there.- tester_ = t;- testerRow_ = 0;- testerStick_ = 0;- testerBackup_ = settings_;- keysRow_ = keysCol_ = 0;- captureSince_ = 0;- keyRefused_ = 0;+void AppUi::offerUpdate(const std::string& notes) {+ std::lock_guard<std::mutex> lock(mutex_);+ updatePrompt_ = true;+ showingUpdateNotes_ = false;+ updateNotesScroll_ = 0;+ promptFocus_ = 0;+ if (!notes.empty()) updateNotes_ = notes;+ formatUpdateNotes();dirty_ = true;}-bool AppUi::capturingKey() const {+bool AppUi::updateOffered() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return updatePrompt_ && screen_ == Screen::Home;+}++bool AppUi::showingUpdateNotes() const {std::lock_guard<std::mutex> lock(mutex_);- return tester_ == Tester::Keys && captureSince_ && (screen_ == Screen::Settings || gameSettingsOpen_);+ return updatePrompt_ && showingUpdateNotes_;}-void AppUi::captureKey(uint8_t code) {+void AppUi::showUpdateNotes(bool show) {std::lock_guard<std::mutex> lock(mutex_);- if (tester_ != Tester::Keys || !captureSince_ || keysRow_ >= kKeysPerColumn) return;+ showingUpdateNotes_ = show;+ updateNotesScroll_ = 0;+ if (show) formatUpdateNotes();dirty_ = true;- if (input::isReservedKey(code)) { // still waiting: another key- keyRefused_ = code;- return;- }- auto action = static_cast<input::KeyAction>((keysCol_ / 2) * kKeysPerColumn + keysRow_);- input::assignKey(settings_.keyMap, action, keysCol_ % 2, code);- captureSince_ = 0;- keyRefused_ = 0;}-void AppUi::handleKeysTester(const NavInput& in) {- // Caller holds mutex_. Each change applies at once; Circle goes back- // with them (as Settings itself), "Reset to default" puts the first back.- auto& map = settings_.keyMap;- if (captureSince_) {- // Waiting for a key (captureKey): Circle or 10 s give up.- if (in.back || (in.nowMs > captureSince_ && in.nowMs - captureSince_ > 10000))- captureSince_ = 0, keyRefused_ = 0, dirty_ = true;- return;- }- constexpr int kRows = kKeysPerColumn + 1;- if (in.up) keysRow_ = (keysRow_ + kRows - 1) % kRows, dirty_ = true;- if (in.down) keysRow_ = (keysRow_ + 1) % kRows, dirty_ = true;- if (keysRow_ < kKeysPerColumn) {- if (in.left && keysCol_ > 0) --keysCol_, dirty_ = true;- if (in.right && keysCol_ < 3) ++keysCol_, dirty_ = true;- }- size_t action = static_cast<size_t>((keysCol_ / 2) * kKeysPerColumn + keysRow_);- if (in.accept) {- if (keysRow_ == kKeysPerColumn)- map = input::defaultKeyMap();- else- captureSince_ = in.nowMs ? in.nowMs : 1;- keyRefused_ = 0;- dirty_ = true;- }- if (in.square && keysRow_ < kKeysPerColumn) map[action][static_cast<size_t>(keysCol_ % 2)] = 0, dirty_ = true;- if (in.back) {- if (gameSettingsOpen_) {- if (map != activeGameProfile_.keyMap) activeGameProfile_.keyMap = map, activeGameHasCustom_ = true;- settings_ = testerBackup_;- }- tester_ = Tester::None;- dirty_ = true;- }+void AppUi::showUpdating(const std::string& version) {+ std::lock_guard<std::mutex> lock(mutex_);+ screen_ = Screen::Updating;+ updatePrompt_ = false;+ updatingTo_ = version;+ updateStatus_.clear();+ updateFraction_ = -1;+ dirty_ = true;}-void AppUi::openPadTester() {- // Caller holds mutex_. A copy of the map and touchpad shortcuts in force- // (Settings', or the game's with its settings open) is what the screen edits.- tester_ = Tester::Pad;- padWork_ = gameSettingsOpen_ ? activeGameProfile_.padMap : settings_.padMap;- if (!input::padMapValid(padWork_)) padWork_ = input::defaultPadMap();- touchpadWork_ = gameSettingsOpen_ ? activeGameProfile_.touchpadShortcuts : settings_.touchpadShortcuts;- padRow_ = padCol_ = 0;- padCaptureSince_ = 0;- padTesterTab_ = 0;- touchpadRow_ = 0;- touchpadDropdownOpen_ = false;- touchpadDropdownIndex_ = 0;- touchpadDropdownTop_ = 0;- dirty_ = true;-}--void AppUi::handlePadTester(const NavInput& in) {- if (touchpadDropdownOpen_) {- constexpr int kMaxVisible = 8;- constexpr int n = input::kTouchpadActions;- if (in.up) {- touchpadDropdownIndex_ = (touchpadDropdownIndex_ + n - 1) % n;- if (touchpadDropdownIndex_ < touchpadDropdownTop_) touchpadDropdownTop_ = touchpadDropdownIndex_;- else if (touchpadDropdownIndex_ >= touchpadDropdownTop_ + kMaxVisible)- touchpadDropdownTop_ = touchpadDropdownIndex_ - kMaxVisible + 1;- dirty_ = true;- }- if (in.down) {- touchpadDropdownIndex_ = (touchpadDropdownIndex_ + 1) % n;- if (touchpadDropdownIndex_ < touchpadDropdownTop_) touchpadDropdownTop_ = touchpadDropdownIndex_;- else if (touchpadDropdownIndex_ >= touchpadDropdownTop_ + kMaxVisible)- touchpadDropdownTop_ = touchpadDropdownIndex_ - kMaxVisible + 1;- dirty_ = true;- }- if (in.accept) {- touchpadWork_.set(touchpadRow_, static_cast<input::TouchpadAction>(touchpadDropdownIndex_));- touchpadDropdownOpen_ = false;- dirty_ = true;- }- if (in.back) {- touchpadDropdownOpen_ = false;- dirty_ = true;- }- return;- }-- if (caps_.touchpad && (in.l1 || in.r1)) {- padTesterTab_ = 1 - padTesterTab_;- dirty_ = true;- return;- }-- if (padTesterTab_ == 1) {- constexpr int kRows = input::kTouchpadTriggers + 1; // 0..5 triggers, 6 Reset to default- if (in.up) touchpadRow_ = (touchpadRow_ + kRows - 1) % kRows, dirty_ = true;- if (in.down) touchpadRow_ = (touchpadRow_ + 1) % kRows, dirty_ = true;- if (touchpadRow_ < input::kTouchpadTriggers) {- if (in.accept) {- touchpadDropdownOpen_ = true;- touchpadDropdownIndex_ = static_cast<int>(touchpadWork_.get(touchpadRow_));- constexpr int kMaxVisible = 8;- touchpadDropdownTop_ = std::clamp(touchpadDropdownIndex_ - 3, 0, std::max(0, input::kTouchpadActions - kMaxVisible));- dirty_ = true;- }- if (in.square) {- touchpadWork_.set(touchpadRow_, input::defaultTouchpadShortcuts().get(touchpadRow_));- dirty_ = true;- }- } else if (in.accept) {- touchpadWork_ = input::defaultTouchpadShortcuts();- dirty_ = true;- }- if (in.back) {- dirty_ = true;- if (!input::padMapValid(padWork_)) {- padTesterTab_ = 0;- return;- }- if (gameSettingsOpen_) {- if (padWork_ != activeGameProfile_.padMap) activeGameProfile_.padMap = padWork_, activeGameHasCustom_ = true;- if (touchpadWork_ != activeGameProfile_.touchpadShortcuts) activeGameProfile_.touchpadShortcuts = touchpadWork_, activeGameHasCustom_ = true;- } else {- settings_.padMap = padWork_;- settings_.touchpadShortcuts = touchpadWork_;- }- tester_ = Tester::None;- }- return;- }-- const bool mapSwap = gameSettingsOpen_ ? activeGameProfile_.circleConfirms : settings_.circleConfirms;- constexpr int kPerColumn = input::kPadFns / 2, kButtonsRow = kPerColumn;- const auto fn = static_cast<input::PadFn>(padCol_ * kPerColumn + std::min(padRow_, kPerColumn - 1));- if (padCaptureSince_) {- if (in.padPressed) {- uint8_t slot = 0;- while (!(in.padPressed & (1u << slot))) ++slot;- const uint8_t onPad = input::physicalSource(slot, circleConfirms_);- input::assignPadSource(padWork_, fn, input::physicalSource(onPad, mapSwap));- padCaptureSince_ = 0;- dirty_ = true;- } else if (in.nowMs > padCaptureSince_ && in.nowMs - padCaptureSince_ > 5000) {- padCaptureSince_ = 0;- dirty_ = true;- }- return;- }- if (in.up) padRow_ = (padRow_ + kButtonsRow) % (kButtonsRow + 1), dirty_ = true;- if (in.down) padRow_ = (padRow_ + 1) % (kButtonsRow + 1), dirty_ = true;- if (in.left || in.right) padCol_ = 1 - padCol_, dirty_ = true;- if (in.accept) {- dirty_ = true;- if (padRow_ < kButtonsRow) {- padCaptureSince_ = in.nowMs ? in.nowMs : 1;- } else if (padCol_ == 0) {- padWork_ = input::defaultPadMap(); // Reset to default (kept on the way out)- } else {- tester_ = Tester::None; // Discard changes: what was saved stays- return;- }- }- if (in.square && padRow_ < kButtonsRow) input::assignPadSource(padWork_, fn, input::kPadNone), dirty_ = true;- if (in.back) {- dirty_ = true;- if (!input::padMapValid(padWork_)) return; // incomplete: the warning says what's missing- if (gameSettingsOpen_) {- if (padWork_ != activeGameProfile_.padMap) activeGameProfile_.padMap = padWork_, activeGameHasCustom_ = true;- if (touchpadWork_ != activeGameProfile_.touchpadShortcuts) activeGameProfile_.touchpadShortcuts = touchpadWork_, activeGameHasCustom_ = true;- } else {- settings_.padMap = padWork_;- settings_.touchpadShortcuts = touchpadWork_;- }- tester_ = Tester::None;- }-}--void AppUi::openTouchpadTester() {- openPadTester();- padTesterTab_ = 1;-}--void AppUi::handleTouchpadTester(const NavInput& in) {- handlePadTester(in);-}--void AppUi::handleTester(const NavInput& in) {- // Caller holds mutex_. Changes apply as they are made (the pad follows);- // Cross keeps them, Circle puts the old ones back.- if (tester_ == Tester::Keys) return handleKeysTester(in);- if (tester_ == Tester::Pad) return handlePadTester(in);- if (tester_ == Tester::Touchpad) return handleTouchpadTester(in);- if (tester_ == Tester::Sticks) {- // L1 / R1 pick the stick, the D-pad (only: the sticks are what is- // being tried) changes its dead zone.- if (in.l1 || in.r1) testerStick_ = in.r1 ? 1 : 0, dirty_ = true;- int& zone = settings_.deadzone[testerStick_];- int dz = std::clamp(zone + (in.dpadRight ? 1 : 0) - (in.dpadLeft ? 1 : 0), 0, kMaxDeadzone);- if (dz != zone) zone = dz, dirty_ = true;- const float now[4] = {in.rawLX, in.rawLY, in.rawRX, in.rawRY};- for (int i = 0; i < 4; ++i)- if (now[i] != testSticks_[i]) testSticks_[i] = now[i], dirty_ = true;- } else {- if (in.up && testerRow_ > 0) --testerRow_, dirty_ = true;- if (in.down && testerRow_ < triggerTesterRows() - 1) ++testerRow_, dirty_ = true;- int delta = (in.right ? 1 : 0) - (in.left ? 1 : 0);- if (delta && testerRow_ == 0)- settings_.triggerStrength = std::clamp(settings_.triggerStrength + delta, 0, input::kTriggerStrengths - 1);- if (delta && testerRow_ == 1) settings_.triggerHz = std::clamp(settings_.triggerHz + delta, 0, 2);- if (delta && testerRow_ == 2)- settings_.triggerResistance = std::clamp(settings_.triggerResistance + delta, 0, input::kTriggerResistances - 1);- if (delta && testerRow_ == 3) settings_.triggerPulses = !settings_.triggerPulses;- if (delta && testerRow_ == 4) settings_.triggerProfile = std::clamp(settings_.triggerProfile + delta, 0, input::kTriggerProfiles - 1);- if (delta) dirty_ = true;- if (in.l2Analog != testL2_ || in.r2Analog != testR2_) testL2_ = in.l2Analog, testR2_ = in.r2Analog, dirty_ = true;- }- if (in.back) {- settings_.deadzone[0] = testerBackup_.deadzone[0], settings_.deadzone[1] = testerBackup_.deadzone[1];- settings_.triggerStrength = testerBackup_.triggerStrength, settings_.triggerHz = testerBackup_.triggerHz;- settings_.triggerResistance = testerBackup_.triggerResistance, settings_.triggerPulses = testerBackup_.triggerPulses;- settings_.triggerProfile = testerBackup_.triggerProfile;- }- if (in.accept || in.back) {- if (gameSettingsOpen_) {- if (in.accept) {- activeGameProfile_.deadzoneLeft = settings_.deadzone[0];- activeGameProfile_.deadzoneRight = settings_.deadzone[1];- activeGameProfile_.triggerStrength = settings_.triggerStrength;- activeGameProfile_.triggerHz = settings_.triggerHz;- activeGameProfile_.triggerResistance = settings_.triggerResistance;- activeGameProfile_.triggerPulses = settings_.triggerPulses;- activeGameProfile_.triggerProfile = settings_.triggerProfile;- activeGameHasCustom_ = true;- }- settings_ = testerBackup_;- }- tester_ = Tester::None;- testL2_ = testR2_ = 0;- dirty_ = true;- }-}--void AppUi::openColourPicker(int previousMode) {- // Caller holds mutex_. Starts on the colour saved.- float h, s, v;- colourHsv(settings_.lightBarColour, h, s, v);- pickU_ = s * std::cos(h * 6.2832f);- pickV_ = s * std::sin(h * 6.2832f);- pickValue_ = std::max(kMinValue, v);- pickerPrevMode_ = previousMode;- pickerLastMs_ = 0;- pickerOpen_ = true;- dirty_ = true;-}--Color AppUi::pickerColour() const {- float h = std::atan2(pickV_, pickU_) / 6.2832f;- return hsvColour(h < 0 ? h + 1 : h, std::min(1.0f, std::hypot(pickU_, pickV_)), pickValue_);-}--void AppUi::handleColourPicker(const NavInput& in) {- // Caller holds mutex_. The stick moves the cursor smoothly, the D-pad a- // step at a time; L2 / R2 change the brightness.- float dt = pickerLastMs_ && in.nowMs > pickerLastMs_ ? std::min(0.1f, (in.nowMs - pickerLastMs_) / 1000.0f) : 0;- pickerLastMs_ = in.nowMs;- float u = pickU_, v = pickV_;- auto axis = [](float a) { return std::abs(a) < 0.2f ? 0.0f : a; };- u += axis(in.stickX) * 1.1f * dt;- v += axis(in.stickY) * 1.1f * dt;- constexpr float kStep = 0.05f;- if (in.left) u -= kStep;- if (in.right) u += kStep;- if (in.up) v -= kStep;- if (in.down) v += kStep;- if (float d = std::hypot(u, v); d > 1) u /= d, v /= d;- if (u != pickU_ || v != pickV_) pickU_ = u, pickV_ = v, dirty_ = true;- if (in.l2) pickValue_ = std::max(kMinValue, pickValue_ - 0.1f), dirty_ = true;- if (in.r2) pickValue_ = std::min(1.0f, pickValue_ + 0.1f), dirty_ = true;- if (in.accept) {- settings_.lightBarColour = pickerColour();- settings_.lightBarMode = 1;- pickerOpen_ = false;- dirty_ = true;- } else if (in.back) {- settings_.lightBarMode = pickerPrevMode_;- pickerOpen_ = false;- dirty_ = true;- }-}--void AppUi::setUpdateState(const std::string& current, const std::string& available, bool checking, const std::string& notes) {- std::lock_guard<std::mutex> lock(mutex_);- updateCurrent_ = current;- updateAvailable_ = available;- updateChecking_ = checking;- if (!notes.empty()) {- updateNotes_ = notes;- formatUpdateNotes();- }- dirty_ = true;-}--void AppUi::setUpdateNotes(const std::string& notes) {- std::lock_guard<std::mutex> lock(mutex_);- updateNotes_ = notes;- formatUpdateNotes();- dirty_ = true;-}--void AppUi::setSignInCheckState(const SignInCheckState& state) {- std::lock_guard<std::mutex> lock(mutex_);- signInCheck_ = state;- dirty_ = true;-}--SignInCheckState AppUi::signInCheckState() const {- std::lock_guard<std::mutex> lock(mutex_);- return signInCheck_;-}--void AppUi::setNetworkTestState(const NetworkTestState& state) {- std::lock_guard<std::mutex> lock(mutex_);- networkTest_ = state;- dirty_ = true;-}--NetworkTestState AppUi::networkTestState() const {- std::lock_guard<std::mutex> lock(mutex_);- return networkTest_;-}--void AppUi::offerUpdate(const std::string& notes) {- std::lock_guard<std::mutex> lock(mutex_);- updatePrompt_ = true;- showingUpdateNotes_ = false;- updateNotesScroll_ = 0;- promptFocus_ = 0;- if (!notes.empty()) updateNotes_ = notes;- formatUpdateNotes();- dirty_ = true;-}--bool AppUi::updateOffered() const {- std::lock_guard<std::mutex> lock(mutex_);- return updatePrompt_ && screen_ == Screen::Home;-}--bool AppUi::showingUpdateNotes() const {- std::lock_guard<std::mutex> lock(mutex_);- return updatePrompt_ && showingUpdateNotes_;-}--void AppUi::showUpdateNotes(bool show) {- std::lock_guard<std::mutex> lock(mutex_);- showingUpdateNotes_ = show;- updateNotesScroll_ = 0;- if (show) formatUpdateNotes();- dirty_ = true;-}--void AppUi::showUpdating(const std::string& version) {- std::lock_guard<std::mutex> lock(mutex_);- screen_ = Screen::Updating;- updatePrompt_ = false;- updatingTo_ = version;- updateStatus_.clear();- updateFraction_ = -1;- dirty_ = true;-}--void AppUi::setUpdateStatus(const std::string& status, float fraction) {- std::lock_guard<std::mutex> lock(mutex_);- updateStatus_ = status;- updateFraction_ = fraction;+void AppUi::setUpdateStatus(const std::string& status, float fraction) {+ std::lock_guard<std::mutex> lock(mutex_);+ updateStatus_ = status;+ updateFraction_ = fraction;dirty_ = true;}@@ -1990,123 +1336,6 @@ std::string AppUi::webUrl() const {return webUrl_;}-void AppUi::setSearchQuery(const std::string& query) {- std::lock_guard<std::mutex> lock(mutex_);- query_ = query;- if (screen_ == Screen::Home || screen_ == Screen::Details || screen_ == Screen::Settings || screen_ == Screen::Error) {- screen_ = Screen::Home;- searching_ = true;- searchOnKeys_ = true;- filterList_ = -1;- runSearch();- dirty_ = true;- }-}--std::string AppUi::searchQuery() const {- std::lock_guard<std::mutex> lock(mutex_);- return query_;-}--void AppUi::setSearchTab(Tab t) {- setSearchState(nullptr, &t, nullptr);-}--Tab AppUi::searchTab() const {- return tab();-}--void AppUi::setSearchState(const std::string* query, const Tab* tab,- const std::vector<std::pair<Filter, int>>* filters) {- std::lock_guard<std::mutex> lock(mutex_);- if (query) {- query_ = *query;- }- if (tab) {- tab_ = *tab;- }- if (filters) {- for (const auto& [f, val] : *filters) {- applyFilterLocked(f, val);- }- }- if (screen_ == Screen::Home || screen_ == Screen::Details || screen_ == Screen::Settings || screen_ == Screen::Error) {- screen_ = Screen::Home;- searching_ = true;- searchOnKeys_ = true;- filterList_ = -1;- runSearch();- dirty_ = true;- }-}--int AppUi::filterSelectedPublic(Filter f) const {- std::lock_guard<std::mutex> lock(mutex_);- if (f == Filter::Free) return filterFree_ ? 1 : 0;- if (f == Filter::Cheapest) return filterCheapest_ ? 1 : 0;- if (f == Filter::MouseKeyboard) return filterMouseKeyboard_ ? 1 : 0;- if (f == Filter::Wishlist) return filterWishlist_ ? 1 : 0;- return filterSelected(f);-}--bool AppUi::filterOnPublic(Filter f) const {- std::lock_guard<std::mutex> lock(mutex_);- return filterOn(f);-}--void AppUi::setGyroDefaults(int mode, int level) {- std::lock_guard<std::mutex> lock(mutex_);- gyroMode_ = mode;- gyroLevel_ = level;- settings_.gyroMode = mode;- settings_.gyroLevel = level;- dirty_ = true;-}--void AppUi::setPerGameSettings(const std::map<std::string, app::GameProfile>& perGame) {- std::lock_guard<std::mutex> lock(mutex_);- perGameSettings_ = perGame;- dirty_ = true;-}--void AppUi::openGameSettings() {- gameSettingsOpen_ = true;- gameSettingsRow_ = 0;- activeGameMouseSupported_ = detail_.mouseKeyboard;- std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);- auto it = perGameSettings_.find(key);- if (it != perGameSettings_.end()) {- activeGameHasCustom_ = true;- activeGameProfile_ = it->second;- } else {- activeGameHasCustom_ = false;- activeGameProfile_.sharpness = settings_.sharpness;- activeGameProfile_.deband = settings_.deband;- activeGameProfile_.upscaler = settings_.upscaler;- activeGameProfile_.resolution = settings_.resolution;- activeGameProfile_.deadzoneLeft = settings_.deadzone[0];- activeGameProfile_.deadzoneRight = settings_.deadzone[1];- activeGameProfile_.triggerStrength = settings_.triggerStrength;- activeGameProfile_.triggerHz = settings_.triggerHz;- activeGameProfile_.triggerResistance = settings_.triggerResistance;- activeGameProfile_.triggerPulses = settings_.triggerPulses;- activeGameProfile_.audioHaptics = settings_.audioHaptics;- activeGameProfile_.circleConfirms = settings_.circleConfirms;- activeGameProfile_.highRefresh = settings_.highRefresh;- activeGameProfile_.keyMap = settings_.keyMap;- activeGameProfile_.padMap = settings_.padMap;- activeGameProfile_.gyroMode = gyroMode_;- activeGameProfile_.gyroLevel = gyroLevel_;- activeGameProfile_.touchpadMouse = settings_.touchpadMouse;- activeGameProfile_.touchpadShortcuts = settings_.touchpadShortcuts;- }-}--void AppUi::closeGameSettings() {- gameSettingsOpen_ = false;- tester_ = Tester::None;-}-void AppUi::setCircleConfirms(bool on) {std::lock_guard<std::mutex> lock(mutex_);circleConfirms_ = on;@@ -2160,196 +1389,6 @@ bool AppUi::accentColor(Color& out) {return true;}-void AppUi::drawPads(Canvas& c) {- // Bottom left, on the line of the button hints (which are right-aligned).- drawPadRow(c, fonts_.bold, kMargin, kH - 26 - padIconHeight(48), 48, 16, pads_, kBg,- fonts_.hasIcons ? &fonts_.icons : nullptr);-}--void AppUi::setRegions(std::vector<std::string> regions, const std::string& defaultRegion) {- std::lock_guard<std::mutex> lock(mutex_);- regions_ = std::move(regions);- defaultRegion_ = defaultRegion;- dirty_ = true;-}--// Settings' bitrate caps (Mbps, after Automatic) and game volumes (percent).-constexpr int kBitrateCaps[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};-constexpr int kVolumes[] = {25, 50, 75, 100, 150};--std::vector<std::string> AppUi::settingOptions(int row) const {- // Caller holds mutex_.- std::vector<std::string> out;- auto withMs = [&](std::string label, const std::string& region) {- auto ms = regionMs_.find(region);- if (ms != regionMs_.end()) label += " \xE2\x80\xA2 " + std::to_string(ms->second) + " ms";- return label;- };- if (row == 0) {- for (int i = 0; i < static_cast<int>(Language::Count); ++i) out.push_back(languageName(static_cast<Language>(i)));- } else if (row == 1) {- out = {tr(Str::Res720), tr(Str::Res1080), tr(Str::ResBest)}; // kResolutionOrder- } else if (row == 3) {- // Left and right stick (the tester changes them).- out = {std::to_string(settings_.deadzone[0]) + " % \xC2\xB7 " + std::to_string(settings_.deadzone[1]) + " %"};- } else if (row == 4) {- out = {tr(Str::Deactivated), tr(Str::TriggerLight), tr(Str::TriggerMedium), tr(Str::TriggerStrong),- tr(Str::TriggerMax)};- } else if (row == 5) {- out = {"", ""}; // Cross, Circle: drawn as the buttons- } else if (row == 6) {- out = {tr(Str::LightBarGame), tr(Str::LightBarCustom), tr(Str::Deactivated)};- } else if (row == 7) {- // Updates: Cross acts, no list.- } else if (row == 9) {- out = {tr(Str::Deactivated), tr(Str::HighRefreshOn)};- } else if (row == 13) {- out = {tr(Str::DisplayWindow), tr(Str::DisplayFullscreen)};- } else if (row == 10) {- out.push_back(tr(Str::BitrateAuto));- for (int mbps : kBitrateCaps) out.push_back(std::to_string(mbps) + " Mbps");- } else if (row == 11) {- for (int v : kVolumes) out.push_back(std::to_string(v) + " %");- } else if (row == 16) {- out = {tr(Str::Deactivated), tr(Str::Activated)};- } else if (row == 12) {- // The keys' own screen changes them.- out = {tr(settings_.keyMap == input::defaultKeyMap() ? Str::ProfileDefault : Str::ProfileCustom)};- } else if (row == 14) {- // So do the controller buttons'.- out = {tr(settings_.padMap == input::defaultPadMap() ? Str::ProfileDefault : Str::ProfileCustom)};- } else if (row == 22) {- out = {tr(settings_.touchpadShortcuts == input::defaultTouchpadShortcuts() ? Str::ProfileDefault : Str::ProfileCustom)};- } else if (row == 15) {- out = {tr(Str::Off), tr(Str::GyroAlways), tr(Str::GyroAiming)};- } else if (row == 17) {- out = {tr(Str::RunCheck)};- } else if (row == 18) {- out = {tr(Str::RunTest)};- } else if (row == 19) {- out = {tr(Str::SupportKoFi)};- } else if (row == 20) {- out = {tr(Str::VideoDecoderHw), tr(Str::VideoDecoderSw)};- } else if (row == 21) {- out = {tr(Str::Off), tr(Str::SharpLow), tr(Str::SharpMedium), tr(Str::SharpHigh)};- } else if (row == 23) {- out = {tr(Str::ResetSettings)};- } else if (row == 8) {- out.push_back(loginCountryOffText());- for (const char* country : kLoginCountries) out.push_back(loginCountryName(country));- } else {- // Automatic first, then the regions in the login's order.- out.push_back(withMs(trf(Str::RegionAuto, defaultRegion_.empty() ? "-" : prettyRegion(defaultRegion_)),- defaultRegion_));- for (const auto& r : regions_) out.push_back(withMs(prettyRegion(r), r));- }- return out;-}--int AppUi::settingSelected(int row) const {- // Caller holds mutex_.- if (row == 0) return settings_.language;- if (row == 1) {- for (int i = 0; i < 3; ++i)- if (kResolutionOrder[i] == settings_.resolution) return i;- }- if (row == 3 || row == 12 || row == 14 || row == 17 || row == 18 || row == 19 || row == 22 || row == 23) return 0;- if (row == 4) return settings_.triggerStrength;- if (row == 5) return settings_.circleConfirms ? 1 : 0;- if (row == 6) return settings_.lightBarMode;- if (row == 7) return 0;- if (row == 9) return settings_.highRefresh ? 1 : 0;- if (row == 13) return settings_.fullscreen ? 1 : 0;- if (row == 15) return std::clamp(settings_.gyroMode, 0, 2);- if (row == 16) return settings_.queueReadyAlert ? 1 : 0;- if (row == 20) return std::clamp(settings_.videoDecoder, 0, 1);- if (row == 21) return std::clamp(settings_.audioHaptics, 0, 3);- if (row == 10) {- if (settings_.maxBitrateMbps <= 0) return 0;- int closest = 1;- int minDiff = 1000;- for (size_t i = 0; i < std::size(kBitrateCaps); ++i) {- int diff = std::abs(kBitrateCaps[i] - settings_.maxBitrateMbps);- if (diff < minDiff) {- minDiff = diff;- closest = static_cast<int>(i) + 1;- }- }- return closest;- }- if (row == 11) {- for (size_t i = 0; i < std::size(kVolumes); ++i)- if (kVolumes[i] == settings_.gameVolume) return static_cast<int>(i);- return 3; // 100 %- }- if (row == 8) {- for (size_t i = 0; i < std::size(kLoginCountries); ++i)- if (settings_.loginCountry == kLoginCountries[i]) return static_cast<int>(i) + 1;- return 0;- }- for (size_t i = 0; i < regions_.size(); ++i)- if (regions_[i] == settings_.region) return static_cast<int>(i) + 1;- return 0;-}--void AppUi::applySetting(int row, int index) {- // Caller holds mutex_.- if (row == 0) {- settings_.language = index;- setLanguage(static_cast<Language>(index)); // the UI switches right away- } else if (row == 1) {- settings_.resolution = kResolutionOrder[index];- } else if (row == 3 || row == 12 || row == 14 || row == 17 || row == 18 || row == 22 || row == 23) {- (void)index; // the tester sets each stick's, the keys', buttons' and touchpad's screens theirs- } else if (row == 4) {- settings_.triggerStrength = index;- } else if (row == 5) {- settings_.circleConfirms = index == 1;- circleConfirms_ = settings_.circleConfirms; // in force at once: the next press already uses it- } else if (row == 6) {- settings_.lightBarMode = index;- } else if (row == 7) {- } else if (row == 9) {- settings_.highRefresh = index == 1;- } else if (row == 13) {- // In force at once (handle() sends the settings): the window follows.- if (settings_.fullscreen != (index == 1)) displayModeChanged_ = true;- settings_.fullscreen = index == 1;- } else if (row == 15) {- settings_.gyroMode = index;- gyroMode_ = index;- } else if (row == 10) {- settings_.maxBitrateMbps = index == 0 ? 0 : kBitrateCaps[index - 1];- } else if (row == 11) {- settings_.gameVolume = kVolumes[index];- } else if (row == 16) {- settings_.queueReadyAlert = (index == 1);- } else if (row == 20) {- settings_.videoDecoder = index;- } else if (row == 21) {- settings_.audioHaptics = std::clamp(index, 0, 3);- } else if (row == 8) {- settings_.loginCountry = index == 0 ? std::string() : kLoginCountries[index - 1];- } else {- settings_.region = index == 0 ? std::string() : regions_[static_cast<size_t>(index - 1)];- }- dirty_ = true;-}--void AppUi::changeSetting(int delta) {- // Caller holds mutex_. Left / right: the previous / next choice.- int n = static_cast<int>(settingOptions(settingsRow_).size());- if (n <= 0) return;- if (settingsRow_ == 10) {- // Bitrate slider: clamp between 0 (Automatic) and n - 1 (50 Mbps)- int cur = settingSelected(10);- int next = std::clamp(cur + delta, 0, n - 1);- if (next != cur) applySetting(10, next);- return;- }- applySetting(settingsRow_, (settingSelected(settingsRow_) + delta + n) % n);-}-Screen AppUi::screen() const {std::lock_guard<std::mutex> lock(mutex_);return screen_;@@ -2432,28 +1471,15 @@ void AppUi::retarget() {}}-// --- Input -----------------------------------------------------------------------namespace {--// Moves `focus` in a grid of `count` items, `cols` wide. Returns true if it moved.-bool moveInGrid(int& focus, int count, int cols, const NavInput& in) {- int before = focus;- if (in.right && focus + 1 < count && (focus + 1) % cols != 0) ++focus;- if (in.left && focus % cols != 0) --focus;- if (in.down && focus + cols < count) focus += cols;- else if (in.down && focus / cols < (count - 1) / cols) focus = count - 1; // onto a short last row- if (in.up && focus >= cols) focus -= cols;- return focus != before;-}--} // namespace--AppUi::LibraryLayout AppUi::libraryLayout() const {+const AppUi::LibraryLayout& AppUi::libraryLayout() const {// Caller holds mutex_. The account's games, then (after headers) the// games to buy and the hidden games, all kLibraryCols wide.+ if (libLayoutValid_) return cachedLibLayout_;LibraryLayout L;L.cols = kLibraryCols;+ size_t totalTiles = owned_.size() + purchasable_.size() + hiddenTiles_.size();+ L.rowOf.reserve(totalTiles);+ L.colOf.reserve(totalTiles);int y = 0, row = 0, index = 0;for (int section = 0; section < 3; ++section) {const auto& list = section == 0 ? owned_ : section == 1 ? purchasable_ : hiddenTiles_;@@ -2473,4610 +1499,9 @@ AppUi::LibraryLayout AppUi::libraryLayout() const {}y = L.rowY.back() + kGridPitchY;}- return L;-}--void AppUi::handleHome(const NavInput& in, UiEvent& ev) {- // Caller holds mutex_.- if ((in.scrollRows || in.scrollCards) && !(searching_ && searchOnKeys_)) {- // Smooth scrolling: the rows and cards it moved by since the last- // pass, one step at a time (the view glides after the focus).- auto steps = [&](int n, bool vertical) {- NavInput step;- step.nowMs = in.nowMs;- (vertical ? (n > 0 ? step.down : step.up) : (n > 0 ? step.right : step.left)) = true;- for (int k = 0; k < std::abs(n); ++k) {- // In the search's results, sideways stops at the row's edge- // (left of it is the keyboard).- if (searching_ && !vertical && (n < 0 ? resultFocus_ % kResultCols == 0- : (resultFocus_ + 1) % kResultCols == 0))- break;- handleHome(step, ev);- }- };- if (in.scrollRows) steps(in.scrollRows, true);- if (in.scrollCards) steps(in.scrollCards, false);- return;- }- if (in.l1 || in.r1) {- // Game Pass, Your games, My consoles, round.- int n = static_cast<int>(tab_) + (in.r1 ? 1 : 2);- tab_ = static_cast<Tab>(n % 3);- searching_ = false;- dirty_ = true;- if (tab_ == Tab::Consoles) ev.action = Action::ConsolesShown;- return;- }- if (in.l3 && !searching_) {- ev.action = Action::RefreshLibrary;- return;- }- if (in.options) {- screen_ = Screen::Settings;- settingsRow_ = 0;- settingsFromError_ = false;- settingsCountry_ = settings_.loginCountry;- dropdownOpen_ = false;- filterList_ = -1;- dirty_ = true;- return;- }- if (in.triangle && !searching_ && tab_ != Tab::Consoles) { // search this tab- searching_ = true;- searchOnKeys_ = true;- query_.clear();- runSearch();- dirty_ = true;- return;- }- if (searching_) {- if (searchOnKeys_) {- if ((in.back || in.triangle) && filterList_ < 0) { // close the search (Circle closes an open list first)- 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::Consoles: {- int n = static_cast<int>(consoles_.size());- // Search again: Cross with none listed, Triangle otherwise.- if (consolesKnown_ && ((n == 0 && in.accept) || in.triangle)) {- if (n == 0) consolesKnown_ = false; // the spinner while it looks- ev.action = Action::ConsolesShown;- dirty_ = true;- break;- }- if (n == 0) break;- int before = consoleFocus_;- if (in.right && consoleFocus_ + 1 < n) ++consoleFocus_;- if (in.left && consoleFocus_ > 0) --consoleFocus_;- if (consoleFocus_ != before) dirty_ = true;- if (in.accept) {- const ConsoleTile& con = consoles_[static_cast<size_t>(consoleFocus_)];- ev.action = Action::Play;- ev.game.titleId = con.serverId;- ev.game.name = con.name.empty() ? "Xbox" : con.name;- ev.game.homeConsole = true;- }- break;- }- case Tab::GamePass: {- if (rows_.empty()) break;- int rows = static_cast<int>(rows_.size());- const GameRow& curRow = rows_[static_cast<size_t>(focusRow_)];- int& col = focusCol_[static_cast<size_t>(focusRow_)];- int count = static_cast<int>(curRow.tiles.size());-- if (curRow.isGrid) {- if (in.up && col < kLibraryCols) {- if (focusRow_ > 0) {- --focusRow_;- int upCols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());- focusCol_[static_cast<size_t>(focusRow_)] = std::clamp(focusCol_[static_cast<size_t>(focusRow_)], 0, upCols - 1);- }- } else if (in.down && col + kLibraryCols >= count && col / kLibraryCols == (count - 1) / kLibraryCols) {- if (focusRow_ + 1 < rows) {- ++focusRow_;- int downCols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());- focusCol_[static_cast<size_t>(focusRow_)] = std::clamp(focusCol_[static_cast<size_t>(focusRow_)], 0, downCols - 1);- }- } else {- moveInGrid(col, count, kLibraryCols, in);- }- } else {- if (in.down && focusRow_ + 1 < rows) {- ++focusRow_;- if (rows_[static_cast<size_t>(focusRow_)].isGrid) {- int gCols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());- int targetCol = std::min(col % kLibraryCols, gCols - 1);- focusCol_[static_cast<size_t>(focusRow_)] = std::max(0, targetCol);- }- }- if (in.up && focusRow_ > 0) --focusRow_;- if (in.right && col + 1 < count) ++col;- if (in.left && col > 0) --col;- }- if (in.up || in.down || in.left || in.right) {- retarget();- dirty_ = true;- }- if (in.accept && focusedTile()) openDetails(*focusedTile());- if (in.square && focusedTile()) toggleHidden(*focusedTile(), ev);- break;- }- 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 && libraryTile(f)) openDetails(*libraryTile(f));- if (in.square && libraryTile(f)) {- GameTile t = *libraryTile(f);- toggleHidden(t, ev);- }- if (in.l2 || in.r2) {- // Jump between sections: the account's games, games to buy,- // hidden games. L2 goes to the start of this section first.- int starts[3] = {0, static_cast<int>(owned_.size()),- static_cast<int>(owned_.size() + purchasable_.size())};- int total = starts[2] + static_cast<int>(hiddenTiles_.size());- int section = f >= starts[2] ? 2 : f >= starts[1] ? 1 : 0;- int target = f;- if (in.r2) {- for (int k = section + 1; k < 3; ++k)- if (starts[k] < total && (k == 2 ? !hiddenTiles_.empty() : starts[k] < starts[k + 1])) {- target = starts[k];- break;- }- } else if (f != starts[section]) {- target = starts[section];- } else {- for (int k = section - 1; k >= 0; --k)- if (starts[k] < starts[k + 1]) {- target = starts[k];- break;- }- }- if (target != f) {- gridFocus_ = target;- int section2 = target >= starts[2] ? 2 : target >= starts[1] ? 1 : 0;- gridScroll_.target = static_cast<float>(L.headerY[section2]); // its heading at the top- dirty_ = true;- }- }- if (in.r3) { // next sort order- librarySort_ = static_cast<LibrarySort>((static_cast<int>(librarySort_) + 1) %- static_cast<int>(LibrarySort::Count));- rebuild(true); // same place on screen, not back to the top- prefsEvent(ev);- }- break;- }- }-}--bool AppUi::anyFilter() const {- // Caller holds mutex_. Free and Lowest price only count in "Your games";- // Plan only in Game Pass.- bool library = tab_ == Tab::Library && (filterFree_ || filterCheapest_ || filterWishlist_);- bool gamePass = tab_ == Tab::GamePass && filterPlan_ > 0;- return library || gamePass || filterConsole_ || filterMouseKeyboard_ || filterMode_ || !filterGenre_.empty() ||- filterPublisher_ || filterLanguage_;-}--std::vector<AppUi::Filter> AppUi::filterRow(int row) const {- // Caller holds mutex_. Prices only matter in "Your games" (Game Pass- // games aren't bought).- if (tab_ == Tab::GamePass) {- if (row == 0) return {Filter::Plan, Filter::Console, Filter::MouseKeyboard};- if (row == 1) return {Filter::Mode, Filter::Genre, Filter::Publisher};- if (row == 2) return {Filter::Language};- return {};- }- if (row == 0) return {Filter::Wishlist, Filter::Free, Filter::Cheapest};- if (row == 1) return {Filter::Mode, Filter::Genre, Filter::Publisher};- if (row == 2) return {Filter::Console, Filter::Language, Filter::MouseKeyboard};- return {};-}--std::vector<std::string> AppUi::poolGenres() const {- // Caller holds mutex_.- std::map<std::string, int> count;- for (const auto& t : tab_ == Tab::GamePass ? gamePassPool_ : libraryPool_)- for (const auto& c : t.categories) ++count[c];- std::vector<std::pair<int, std::string>> order;- for (const auto& [g, n] : count) order.push_back({-n, g});- std::sort(order.begin(), order.end());- std::vector<std::string> out;- for (const auto& [n, g] : order) out.push_back(g);- return out;-}--std::vector<std::string> AppUi::filterOptions(Filter f) const {- // Caller holds mutex_. The first choice is always "all".- switch (f) {- case Filter::Plan: return {tr(Str::PlanMine), "Ultimate", "Premium", "Essential", tr(Str::PlanAll)};- case Filter::Console: return {tr(Str::FilterAllConsoles), "SERIES X|S", "XBOX ONE", "XBOX 360"};- case Filter::Mode:- return {tr(Str::ModeAll), tr(Str::ModeSingle), tr(Str::ModeOnlineMulti), tr(Str::ModeOnlineCoop), tr(Str::ModeLocal)};- case Filter::Genre: {- std::vector<std::string> out = {tr(Str::GenreAll)};- for (auto& g : poolGenres()) out.push_back(std::move(g));- return out;- }- case Filter::Publisher:- return {- tr(Str::PublisherAll),- "Xbox Game Studios / Bethesda",- "Electronic Arts",- "Ubisoft",- "Square Enix",- "Warner Bros. Games",- "2K / Take-Two",- "Capcom",- "SEGA / Atlus",- "Bandai Namco",- "THQ Nordic / Plaion",- "Focus Entertainment",- "Devolver Digital",- "Annapurna Interactive",- "Team17",- tr(Str::PublisherIndies)- };- case Filter::Language:- return {tr(Str::LanguageAll), trf(Str::LangSubtitles, tr(Str::LanguageNoun)), trf(Str::LangAudio, tr(Str::LanguageNoun))};- default: return {};- }-}--int AppUi::filterSelected(Filter f) const {- // Caller holds mutex_.- if (f == Filter::Plan) return filterPlan_;- if (f == Filter::Console) return filterConsole_;- if (f == Filter::Mode) return filterMode_;- if (f == Filter::Publisher) return filterPublisher_;- if (f == Filter::Language) return filterLanguage_;- if (f == Filter::Genre) {- auto genres = poolGenres();- for (size_t i = 0; i < genres.size(); ++i)- if (genres[i] == filterGenre_) return static_cast<int>(i) + 1;- }- return 0;-}--void AppUi::chooseFilter(Filter f, int index) {- std::lock_guard<std::mutex> lock(mutex_);- chooseFilterLocked(f, index);-}--void AppUi::applyFilterLocked(Filter f, int index) {- // Caller holds mutex_.- if (f == Filter::Plan) filterPlan_ = index;- if (f == Filter::Console) filterConsole_ = index;- if (f == Filter::Mode) filterMode_ = index;- if (f == Filter::Publisher) filterPublisher_ = index;- if (f == Filter::Language) filterLanguage_ = index;- if (f == Filter::Free) filterFree_ = index != 0;- if (f == Filter::Cheapest) filterCheapest_ = index != 0;- if (f == Filter::MouseKeyboard) filterMouseKeyboard_ = index != 0;- if (f == Filter::Wishlist) filterWishlist_ = index != 0;- if (f == Filter::Genre) {- auto genres = poolGenres();- filterGenre_ = index > 0 && index <= static_cast<int>(genres.size()) ? genres[static_cast<size_t>(index - 1)] : "";- }-}--void AppUi::chooseFilterLocked(Filter f, int index) {- // Caller holds mutex_.- applyFilterLocked(f, index);- filterList_ = -1;- runSearch();- dirty_ = true;-}--std::string AppUi::filterText(Filter f) const {- // Caller holds mutex_. A list shows its name until a choice is made.- if (f == Filter::Free) return tr(Str::FilterFree);- if (f == Filter::MouseKeyboard) return tr(Str::FilterMouseKeyboard);- if (f == Filter::Cheapest) return tr(Str::FilterCheapest);- if (f == Filter::Wishlist) return tr(Str::Wishlist);- int sel = filterSelected(f);- if (sel > 0 || f == Filter::Console) {- auto options = filterOptions(f);- if (sel < static_cast<int>(options.size())) return options[static_cast<size_t>(sel)];- }- return tr(f == Filter::Plan ? Str::FilterPlan- : f == Filter::Mode ? Str::FilterMode- : f == Filter::Genre ? Str::FilterGenre- : f == Filter::Publisher ? Str::FilterPublisher- : Str::FilterLanguage);-}--bool AppUi::filterOn(Filter f) const {- // Caller holds mutex_.- if (f == Filter::Free) return filterFree_;- if (f == Filter::Cheapest) return filterCheapest_;- if (f == Filter::MouseKeyboard) return filterMouseKeyboard_;- if (f == Filter::Wishlist) return filterWishlist_;- return filterSelected(f) > 0;-}--void AppUi::pressFilter(Filter f) {- // Caller holds mutex_. A list opens its drop-down at the current choice.- if (isList(f)) {- filterList_ = static_cast<int>(f);- filterListIndex_ = filterSelected(f);- filterListTop_ = 0;- } else {- if (f == Filter::Free) filterFree_ ^= true;- else if (f == Filter::MouseKeyboard) filterMouseKeyboard_ ^= true;- else if (f == Filter::Cheapest) filterCheapest_ ^= true;- else if (f == Filter::Wishlist) filterWishlist_ ^= true;- runSearch();- }- dirty_ = true;-}--bool AppUi::wantsTextInput() const {- std::lock_guard<std::mutex> lock(mutex_);- return screen_ == Screen::Home && searching_ && searchOnKeys_ && filterList_ < 0 && keyRow_ <= kKeyRows;-}--void AppUi::typeText(std::string_view utf8) {- std::lock_guard<std::mutex> lock(mutex_);- if (!(screen_ == Screen::Home && searching_ && searchOnKeys_)) return;- bool edited = false;- for (char ch : utf8) {- if (ch == '\b') {- // The last character, all of its UTF-8 bytes.- while (!query_.empty() && (static_cast<unsigned char>(query_.back()) & 0xC0) == 0x80) query_.pop_back();- if (!query_.empty()) query_.pop_back(), edited = true;- } else if (ch == '\n') {- if (edited) runSearch(), edited = false;- if (!results_.empty()) {- searchOnKeys_ = false;- resultFocus_ = 0;- dirty_ = true;- }- } else if (static_cast<unsigned char>(ch) >= 0x20 && (query_.size() < 64 || (ch & 0xC0) == 0x80)) {- if (ch == ' ' && (query_.empty() || query_.back() == ' ')) continue; // as the Space key- query_ += ch;- edited = true;- }- }- if (edited) {- runSearch();- dirty_ = true;- }-}--std::pair<int, int> AppUi::searchKeyFocus() const {- std::lock_guard<std::mutex> lock(mutex_);- return {keyRow_, keyCol_};-}--int AppUi::searchResultFocus() const {- std::lock_guard<std::mutex> lock(mutex_);- return resultFocus_;-}--bool AppUi::isSearchOnKeys() const {- std::lock_guard<std::mutex> lock(mutex_);- return searchOnKeys_;-}--std::vector<int> AppUi::keyCenters(int row) const {- // Caller holds mutex_.- std::vector<int> out;- if (row < kKeyRows) {- for (int k = 0; k < kKeyCols; ++k) out.push_back(kMargin + k * (kKeyW + kKeyGap) + kKeyW / 2);- } else if (row == kKeyRows) {- for (int k = 0; k < 3; ++k)- out.push_back(kMargin + kWideCols[k] * (kKeyW + kKeyGap) + (kWideSpan[k] * kKeyW + (kWideSpan[k] - 1) * kKeyGap) / 2);- } else {- int r = row - kKeyRows - 1;- auto chips = filterRow(r);- int n = static_cast<int>(chips.size());- constexpr int kCols = 3;- int w = (kKeysW - kChipGap * (kCols - 1)) / kCols;- for (int k = 0; k < n; ++k) out.push_back(kMargin + k * (w + kChipGap) + w / 2);- }- return out;-}--void AppUi::handleSearchKeys(const NavInput& in) {- // Caller holds mutex_. keyRow_ == kKeyRows is the row of wide keys, where- // keyCol_ is 0..2 (Space, Delete, Clear); kKeyRows + 1, + 2 and + 3 the three- // rows of filters in the 3x3 grid.- if (filterList_ >= 0) {- // A filter's drop-down: up / down, Cross picks, Circle closes it unchanged.- Filter f = static_cast<Filter>(filterList_);- int n = static_cast<int>(filterOptions(f).size());- if (in.down && filterListIndex_ + 1 < n) ++filterListIndex_;- if (in.up && filterListIndex_ > 0) --filterListIndex_;- if (in.accept) chooseFilterLocked(f, filterListIndex_);- if (in.accept || in.back) filterList_ = -1;- dirty_ = true;- return;- }- bool wide = keyRow_ == kKeyRows, filters = keyRow_ > kKeyRows;- int filterCount = filters ? static_cast<int>(filterRow(keyRow_ - kKeyRows - 1).size()) : 0;- bool canDown = (keyRow_ < kKeyRows + 3) && (!filters || !filterRow(keyRow_ - kKeyRows).empty());- if ((in.up && keyRow_ > 0) || (in.down && canDown)) {- // To the item on the next row whose middle is nearest this one's- // (the rows have 6, 3 and a few items of different widths).- auto from = keyCenters(keyRow_);- int x = from[static_cast<size_t>(std::clamp(keyCol_, 0, static_cast<int>(from.size()) - 1))];- keyRow_ += in.up ? -1 : 1;- auto to = keyCenters(keyRow_);- int best = 0;- for (int k = 1; k < static_cast<int>(to.size()); ++k)- if (std::abs(to[static_cast<size_t>(k)] - x) < std::abs(to[static_cast<size_t>(best)] - x)) best = k;- keyCol_ = std::clamp(best, 0, std::max(0, static_cast<int>(to.size()) - 1));- } else if (in.left && keyCol_ > 0) {- --keyCol_;- } else if (in.right) {- int last = filters ? filterCount - 1 : wide ? 2 : kKeyCols - 1;- if (keyCol_ < last) {- ++keyCol_;- } else if (!results_.empty()) { // on to the results- searchOnKeys_ = false;- resultFocus_ = 0;- }- }- bool edited = false;- if (in.accept) {- if (filters) {- pressFilter(filterRow(keyRow_ - kKeyRows - 1)[static_cast<size_t>(keyCol_)]);- } else if (!wide) {- query_ += kKeys[keyRow_ * kKeyCols + keyCol_];- } else if (keyCol_ == 0) {- if (!query_.empty() && query_.back() != ' ') query_ += ' ';- } else if (keyCol_ == 1) {- if (!query_.empty()) query_.pop_back();- } else {- query_.clear();- }- edited = !filters;- dirty_ = true;- }- if (in.square && !query_.empty()) {- query_.pop_back();- edited = true;- }- if (edited) runSearch();- if (in.up || in.down || in.left || in.right || edited) dirty_ = true;-}--void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {- if (tester_ != Tester::None) {- handleTester(in);- if (tester_ == Tester::None) {- std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);- if (activeGameHasCustom_) perGameSettings_[key] = activeGameProfile_;- else perGameSettings_.erase(key);- ev.action = Action::GameSettingsChanged;- ev.game = detail_;- ev.hasGameProfile = activeGameHasCustom_;- ev.gameProfile = activeGameProfile_;- }- return;- }- // The rows on screen (gameSettingsRow_ is a position among them).- const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);- const int rowCount = static_cast<int>(rows.size());- if (in.up) {- gameSettingsRow_ = (gameSettingsRow_ + rowCount - 1) % rowCount;- dirty_ = true;- }- if (in.down) {- gameSettingsRow_ = (gameSettingsRow_ + 1) % rowCount;- dirty_ = true;- }- const int rowId = rows[static_cast<size_t>(std::clamp(gameSettingsRow_, 0, rowCount - 1))].row;- if (in.left || in.right) {- int dir = in.right ? 1 : -1;- switch (rowId) {- case 0:- activeGameHasCustom_ = !activeGameHasCustom_;- dirty_ = true;- break;- case 1: { // Upscaler (0 FSR, 2 FSR+clean, 1 AI, 3 AI+clean)- static constexpr int kOrder[4] = {0, 2, 1, 3};- int pos = 0;- for (int i = 0; i < 4; ++i) if (kOrder[i] == activeGameProfile_.upscaler) pos = i;- activeGameProfile_.upscaler = kOrder[(pos + 4 + dir) % 4];- activeGameHasCustom_ = true;- dirty_ = true;- break;- }- case 2: // Sharpness (0..3)- activeGameProfile_.sharpness = std::clamp(activeGameProfile_.sharpness + dir, 0, 3);- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 3: // Deband (0..3)- activeGameProfile_.deband = std::clamp(activeGameProfile_.deband + dir, 0, 3);- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 4: { // Resolution (1 = 720p, 0 = 1080p, 2 = Best (Auto))- static constexpr int kOrder[3] = {1, 0, 2};- int pos = 0;- for (int i = 0; i < 3; ++i) if (kOrder[i] == activeGameProfile_.resolution) pos = i;- activeGameProfile_.resolution = kOrder[(pos + 3 + dir) % 3];- activeGameHasCustom_ = true;- dirty_ = true;- break;- }- case 5: // Deadzone (0..30)- activeGameProfile_.deadzoneLeft = std::clamp(activeGameProfile_.deadzoneLeft + dir * 5, 0, 30);- activeGameProfile_.deadzoneRight = activeGameProfile_.deadzoneLeft;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 6: // Triggers (0..4)- activeGameProfile_.triggerStrength = std::clamp(activeGameProfile_.triggerStrength + dir, 0, 4);- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 16: // Audio-to-Haptics (0..3)- activeGameProfile_.audioHaptics = std::clamp(activeGameProfile_.audioHaptics + dir, 0, 3);- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 7: // Confirm button- activeGameProfile_.circleConfirms = !activeGameProfile_.circleConfirms;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 8: // 120 Hz output (VRR)- activeGameProfile_.highRefresh = !activeGameProfile_.highRefresh;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 12: // Gyro aiming (0 off, 1 always, 2 while aiming)- activeGameProfile_.gyroMode = (activeGameProfile_.gyroMode + 3 + dir) % 3;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 13: // Touchpad as mouse (in games with mouse support)- activeGameProfile_.touchpadMouse = !activeGameProfile_.touchpadMouse;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 14: { // Game Language- static const std::pair<const char*, const char*> kLocales[] = {- {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},- {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},- {"it-IT", "Italiano"}, {"ja-JP", "日本語"}- };- int pos = 0;- for (int k = 0; k < 8; ++k) if (kLocales[k].first == activeGameProfile_.locale) pos = k;- activeGameProfile_.locale = kLocales[(pos + 8 + dir) % 8].first;- activeGameHasCustom_ = true;- dirty_ = true;- break;- }- case 15: // Video decoder (0 Hardware, 1 Software)- activeGameProfile_.videoDecoder = (activeGameProfile_.videoDecoder == 0 ? 1 : 0);- activeGameHasCustom_ = true;- dirty_ = true;- break;- default: break;- }- }- if (in.accept) {- switch (rowId) {- case 0:- activeGameHasCustom_ = !activeGameHasCustom_;- dirty_ = true;- break;- case 1: {- static constexpr int kOrder[4] = {0, 2, 1, 3};- int pos = 0;- for (int i = 0; i < 4; ++i) if (kOrder[i] == activeGameProfile_.upscaler) pos = i;- activeGameProfile_.upscaler = kOrder[(pos + 1) % 4];- activeGameHasCustom_ = true;- dirty_ = true;- break;- }- case 2:- activeGameProfile_.sharpness = (activeGameProfile_.sharpness + 1) % 4;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 3:- activeGameProfile_.deband = (activeGameProfile_.deband + 1) % 4;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 4: {- static constexpr int kOrder[3] = {1, 0, 2};- int pos = 0;- for (int i = 0; i < 3; ++i) if (kOrder[i] == activeGameProfile_.resolution) pos = i;- activeGameProfile_.resolution = kOrder[(pos + 1) % 3];- activeGameHasCustom_ = true;- dirty_ = true;- break;- }- case 5: { // Open stick tester- tester_ = Tester::Sticks;- testerBackup_ = settings_;- settings_.deadzone[0] = activeGameProfile_.deadzoneLeft;- settings_.deadzone[1] = activeGameProfile_.deadzoneRight;- testerStick_ = 0;- dirty_ = true;- break;- }- case 6: { // Open trigger tester- tester_ = Tester::Triggers;- testerBackup_ = settings_;- settings_.triggerStrength = activeGameProfile_.triggerStrength;- settings_.triggerHz = activeGameProfile_.triggerHz;- settings_.triggerResistance = activeGameProfile_.triggerResistance;- settings_.triggerPulses = activeGameProfile_.triggerPulses;- settings_.triggerProfile = activeGameProfile_.triggerProfile;- testerRow_ = 0;- dirty_ = true;- break;- }- case 16:- activeGameProfile_.audioHaptics = (activeGameProfile_.audioHaptics + 1) % 4;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 7:- activeGameProfile_.circleConfirms = !activeGameProfile_.circleConfirms;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 8:- activeGameProfile_.highRefresh = !activeGameProfile_.highRefresh;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 12:- activeGameProfile_.gyroMode = (activeGameProfile_.gyroMode + 1) % 3;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 13:- activeGameProfile_.touchpadMouse = !activeGameProfile_.touchpadMouse;- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 14: {- static const std::pair<const char*, const char*> kLocales[] = {- {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},- {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},- {"it-IT", "Italiano"}, {"ja-JP", "日本語"}- };- int pos = 0;- for (int k = 0; k < 8; ++k) if (kLocales[k].first == activeGameProfile_.locale) pos = k;- activeGameProfile_.locale = kLocales[(pos + 1) % 8].first;- activeGameHasCustom_ = true;- dirty_ = true;- break;- }- case 15:- activeGameProfile_.videoDecoder = (activeGameProfile_.videoDecoder == 0 ? 1 : 0);- activeGameHasCustom_ = true;- dirty_ = true;- break;- case 9: // Keyboard keys: their own screen, on this game's- openTester(Tester::Keys);- settings_.keyMap = activeGameProfile_.keyMap;- break;- case 11: // Controller buttons: their own screen, on this game's- openPadTester();- break;- case 17: // Touchpad shortcuts: their own screen, on this game's- openTouchpadTester();- break;- case 10: // Reset to default- activeGameHasCustom_ = false;- activeGameProfile_.locale.clear();- activeGameProfile_.keyMap = settings_.keyMap;- activeGameProfile_.padMap = settings_.padMap;- activeGameProfile_.touchpadShortcuts = settings_.touchpadShortcuts;- activeGameProfile_.sharpness = settings_.sharpness;- activeGameProfile_.deband = settings_.deband;- activeGameProfile_.upscaler = settings_.upscaler;- activeGameProfile_.resolution = settings_.resolution;- activeGameProfile_.deadzoneLeft = settings_.deadzone[0];- activeGameProfile_.deadzoneRight = settings_.deadzone[1];- activeGameProfile_.triggerStrength = settings_.triggerStrength;- activeGameProfile_.triggerHz = settings_.triggerHz;- activeGameProfile_.triggerResistance = settings_.triggerResistance;- activeGameProfile_.triggerPulses = settings_.triggerPulses;- activeGameProfile_.triggerProfile = settings_.triggerProfile;- activeGameProfile_.audioHaptics = settings_.audioHaptics;- activeGameProfile_.circleConfirms = settings_.circleConfirms;- activeGameProfile_.highRefresh = settings_.highRefresh;- activeGameProfile_.gyroMode = gyroMode_;- activeGameProfile_.gyroLevel = gyroLevel_;- activeGameProfile_.touchpadMouse = settings_.touchpadMouse;- gameSettingsRow_ = 0;- dirty_ = true;- break;- default: break;- }- }- if ((in.left || in.right || in.accept) && tester_ == Tester::None) {- std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);- if (activeGameHasCustom_) {- perGameSettings_[key] = activeGameProfile_;- } else {- perGameSettings_.erase(key);- }- ev.action = Action::GameSettingsChanged;- ev.game = detail_;- ev.hasGameProfile = activeGameHasCustom_;- ev.gameProfile = activeGameProfile_;- }- if (in.back || in.options) {- gameSettingsOpen_ = false;- std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);- if (activeGameHasCustom_) {- perGameSettings_[key] = activeGameProfile_;- } else {- perGameSettings_.erase(key);- }- ev.action = Action::GameSettingsChanged;- ev.game = detail_;- ev.hasGameProfile = activeGameHasCustom_;- ev.gameProfile = activeGameProfile_;- dirty_ = true;- }-}--void AppUi::setMouseCursor(float x, float y, bool visible) {- std::lock_guard<std::mutex> lock(mutex_);- mouseCursorX_ = std::clamp(x, 0.0f, 1919.0f);- mouseCursorY_ = std::clamp(y, 0.0f, 1079.0f);- mouseCursorVisible_ = visible;- if (visible) {- mouseCursorVisibleUntil_ = platform::nowMs() + 3000;- }- dirty_ = true;-}--UiEvent AppUi::onMouseMove(float x, float y) {- std::lock_guard<std::mutex> lock(mutex_);- UiEvent ev;- mouseCursorX_ = std::clamp(x, 0.0f, 1919.0f);- mouseCursorY_ = std::clamp(y, 0.0f, 1079.0f);- mouseCursorVisible_ = true;- mouseCursorVisibleUntil_ = platform::nowMs() + 3000;- dirty_ = true;- if (screen_ == Screen::Streaming || screen_ == Screen::Splash) {- return ev;- }- if (screen_ == Screen::Home) {- if (tab_ == Tab::GamePass) {- constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;- const int gridLeft = (kW - kGridW) / 2;- int afterGridOffset = 0;- for (size_t r = 0; r < rows_.size(); ++r) {- float rel = static_cast<float>(r) - rowY_.value;- int rowBaseY = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;- const GameRow& row = rows_[r];- if (row.isGrid) {- int offset = static_cast<int>(std::lround(rowScroll_[r].value));- int cardY = rowBaseY - offset + 48;- for (size_t i = 0; i < row.tiles.size(); ++i) {- int c_col = static_cast<int>(i) % kLibraryCols;- int c_row = static_cast<int>(i) / kLibraryCols;- int cy = cardY + c_row * kGridPitchY;- int cx = gridLeft + c_col * kCardPitch;- if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {- if (focusRow_ != static_cast<int>(r) || focusCol_[r] != static_cast<int>(i)) {- focusRow_ = static_cast<int>(r);- focusCol_[r] = static_cast<int>(i);- retarget();- dirty_ = true;- }- return ev;- }- }- int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;- afterGridOffset += gridHeight - offset - kRowPitch;- } else {- int cardY = rowBaseY + 48;- int scroll = static_cast<int>(std::lround(rowScroll_[r].value));- int firstCol = std::max(0, scroll / kCardPitch - 1);- for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {- int cx = kMargin + static_cast<int>(col) * kCardPitch - scroll;- if (cx > kW) break;- if (x >= cx && x < cx + kCard && y >= cardY && y < cardY + kCard) {- if (focusRow_ != static_cast<int>(r) || focusCol_[r] != static_cast<int>(col)) {- focusRow_ = static_cast<int>(r);- focusCol_[r] = static_cast<int>(col);- retarget();- dirty_ = true;- }- return ev;- }- }- }- }- } else if (tab_ == Tab::Library) {- constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;- const int left = (kW - kGridW) / 2;- LibraryLayout L = libraryLayout();- int offset = static_cast<int>(std::lround(gridScroll_.value));- for (size_t i = 0; i < L.rowOf.size(); ++i) {- int cy = kLibraryTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;- int cx = left + L.colOf[i] * kCardPitch;- if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {- if (gridFocus_ != static_cast<int>(i)) {- gridFocus_ = static_cast<int>(i);- dirty_ = true;- }- return ev;- }- }- }- } else if (screen_ == Screen::Settings) {- constexpr int kRowW = 1200, kRowH = 32, kGap = 2, kGroupGap = 5;- int curY = 184;- for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {- if (groupStart) curY += kGroupGap;- if (x >= kMargin && x < kMargin + kRowW && y >= curY && y < curY + kRowH) {- if (settingsRow_ != i) {- settingsRow_ = i;- dirty_ = true;- }- return ev;- }- curY += kRowH + kGap;- }- } else if (screen_ == Screen::Details) {- if (gameSettingsOpen_) {- constexpr int kModalW = 1140, kModalH = 960;- constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;- const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);- const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);- auto groups = [](const std::vector<SettingsRowPos>& v) {- return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));- };- const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -- (groups(all) - groups(most)) * kGroupGap;- Rect panel{(kW - kModalW) / 2, (kH - modalH) / 2, kModalW, modalH};- int curY = panel.y + 92;- for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {- if (rows[static_cast<size_t>(pos)].groupStart) curY += kGroupGap;- Rect r{panel.x + 50, curY, panel.w - 100, kRowH};- if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {- if (gameSettingsRow_ != pos) {- gameSettingsRow_ = pos;- dirty_ = true;- }- return ev;- }- curY += kRowH + kGap;- }- return ev;- }- Rect play{kMargin, 620, 300, 76};- if (x >= play.x && x < play.x + play.w && y >= play.y && y < play.y + play.h) {- if (detailButtonFocus_ != 0) {- detailButtonFocus_ = 0;- dirty_ = true;- }- }- }- return ev;-}--UiEvent AppUi::onMouseDown(float x, float y, int button) {- std::lock_guard<std::mutex> lock(mutex_);- UiEvent ev;- mouseCursorX_ = std::clamp(x, 0.0f, 1919.0f);- mouseCursorY_ = std::clamp(y, 0.0f, 1079.0f);- mouseCursorVisible_ = true;- mouseCursorVisibleUntil_ = platform::nowMs() + 3000;- dirty_ = true;- if (screen_ == Screen::Streaming || screen_ == Screen::Splash) {- return ev;- }- if (button == 3) {- // Right click: Back- if (dropdownOpen_) {- dropdownOpen_ = false;- dirty_ = true;- return ev;- }- if (achievementsOpen_) {- achievementsOpen_ = false;- dirty_ = true;- return ev;- }- if (gameSettingsOpen_) {- closeGameSettings();- dirty_ = true;- return ev;- }- if (reportOpen_) {- reportOpen_ = false;- dirty_ = true;- return ev;- }- if (searching_) {- searching_ = false;- dirty_ = true;- return ev;- }- if (screen_ == Screen::Details || screen_ == Screen::Settings) {- if (screen_ == Screen::Details) {- syncHeroToRowsLocked(detail_.productId, detail_.titleId, detail_.heroUrl, detail_.description, detail_.publisher, detail_.categories);- }- screen_ = Screen::Home;- dirty_ = true;- return ev;- }- return ev;- }- if (button != 1) return ev;-- // Check avatar / profile click to open settings- if (screen_ == Screen::Home) {- constexpr int kAvatar = 52;- if (x >= kW - kMargin - kAvatar && x <= kW - kMargin && y >= 40 && y <= 100) {- screen_ = Screen::Settings;- settingsRow_ = 0;- settingsFromError_ = false;- settingsCountry_ = settings_.loginCountry;- dropdownOpen_ = false;- filterList_ = -1;- dirty_ = true;- return ev;- }- }-- // Check top bar tabs- if (screen_ == Screen::Home && y >= 45 && y <= 95) {- const char* labels[3] = {tr(Str::TabGamePass), tr(Str::YourGames), tr(Str::TabConsoles)};- constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;- int widths[3], total = 0;- for (int i = 0; i < 3; ++i) {- widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;- total += widths[i] + (i ? kGap : 0);- }- int tabX = (kW - total) / 2;- for (int i = 0; i < 3; ++i) {- if (x >= tabX && x < tabX + widths[i] && y >= kY && y < kY + kH) {- showTab(static_cast<Tab>(i));- if (tab_ == Tab::Consoles) ev.action = Action::ConsolesShown;- return ev;- }- tabX += widths[i] + kGap;- }- }-- if (screen_ == Screen::Home) {- if (tab_ == Tab::GamePass) {- constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;- const int gridLeft = (kW - kGridW) / 2;- int afterGridOffset = 0;- for (size_t r = 0; r < rows_.size(); ++r) {- float rel = static_cast<float>(r) - rowY_.value;- int rowBaseY = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;- const GameRow& row = rows_[r];- if (row.isGrid) {- int offset = static_cast<int>(std::lround(rowScroll_[r].value));- int cardY = rowBaseY - offset + 48;- for (size_t i = 0; i < row.tiles.size(); ++i) {- int c_col = static_cast<int>(i) % kLibraryCols;- int c_row = static_cast<int>(i) / kLibraryCols;- int cy = cardY + c_row * kGridPitchY;- int cx = gridLeft + c_col * kCardPitch;- if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {- focusRow_ = static_cast<int>(r);- focusCol_[r] = static_cast<int>(i);- openDetails(row.tiles[i]);- return ev;- }- }- int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;- afterGridOffset += gridHeight - offset - kRowPitch;- } else {- int cardY = rowBaseY + 48;- int scroll = static_cast<int>(std::lround(rowScroll_[r].value));- int firstCol = std::max(0, scroll / kCardPitch - 1);- for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {- int cx = kMargin + static_cast<int>(col) * kCardPitch - scroll;- if (cx > kW) break;- if (x >= cx && x < cx + kCard && y >= cardY && y < cardY + kCard) {- focusRow_ = static_cast<int>(r);- focusCol_[r] = static_cast<int>(col);- openDetails(row.tiles[col]);- return ev;- }- }- }- }- } else if (tab_ == Tab::Library) {- constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;- const int left = (kW - kGridW) / 2;- LibraryLayout L = libraryLayout();- int offset = static_cast<int>(std::lround(gridScroll_.value));- for (size_t i = 0; i < L.rowOf.size(); ++i) {- int cy = kLibraryTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;- int cx = left + L.colOf[i] * kCardPitch;- if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {- gridFocus_ = static_cast<int>(i);- const GameTile* t = libraryTile(static_cast<int>(i));- if (t) openDetails(*t);- return ev;- }- }- constexpr int kAvatar = 52;- int right = kW - kMargin - kAvatar - 16;- if (x >= right - 200 && x <= right && y >= 110 && y <= 145) {- librarySort_ = static_cast<LibrarySort>((static_cast<int>(librarySort_) + 1) %- static_cast<int>(LibrarySort::Count));- rebuild(true);- prefsEvent(ev);- dirty_ = true;- return ev;- }- }- } else if (screen_ == Screen::Details) {- if (gameSettingsOpen_) {- constexpr int kModalW = 1140, kModalH = 960;- constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;- const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);- const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);- auto groups = [](const std::vector<SettingsRowPos>& v) {- return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));- };- const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -- (groups(all) - groups(most)) * kGroupGap;- Rect panel{(kW - kModalW) / 2, (kH - modalH) / 2, kModalW, modalH};- int curY = panel.y + 92;- for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {- if (rows[static_cast<size_t>(pos)].groupStart) curY += kGroupGap;- Rect r{panel.x + 50, curY, panel.w - 100, kRowH};- if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {- gameSettingsRow_ = pos;- handleGameSettings(NavInput{.accept = true}, ev);- dirty_ = true;- return ev;- }- curY += kRowH + kGap;- }- if (x < panel.x || x >= panel.x + panel.w || y < panel.y || y >= panel.y + panel.h) {- closeGameSettings();- dirty_ = true;- }- return ev;- }- const GameTile* g = &detail_;- if (g->productId.empty()) return ev;- bool free = isFreeGame(*g);- if (!g->playable && free) {- ev.action = Action::ClaimFreeGame;- ev.game = detail_;- return ev;- } else if (g->playable) {- int btnY = 620;- Rect play{kMargin, btnY, 300, 76};- if (x >= play.x && x < play.x + play.w && y >= play.y - 20 && y < play.y + play.h + 20) {- ev.action = Action::Play;- ev.game = detail_;- return ev;- }- }- } else if (screen_ == Screen::Settings) {- if (dropdownOpen_) {- auto options = settingOptions(settingsRow_);- constexpr int kItemH = 62, kVisible = 8, kListW = 640;- int n = static_cast<int>(options.size());- int visible = std::min(n, kVisible);- constexpr int kRowW = 1200;- Rect panel{kMargin + kRowW - kListW, 184, kListW, visible * kItemH + 16};- int curY = 184;- for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {- if (groupStart) curY += 5;- if (i == settingsRow_) {- panel.y = curY + 32 + 8;- break;- }- curY += 32 + 2;- }- if (panel.y + panel.h > kH - 100) panel.y = std::max(120, kH - 100 - panel.h);-- if (x >= panel.x && x < panel.x + panel.w && y >= panel.y && y < panel.y + panel.h) {- for (int k = 0; k < visible; ++k) {- int i = dropdownTop_ + k;- Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};- if (x >= item.x && x < item.x + item.w && y >= item.y && y < item.y + item.h && i < n) {- applySetting(settingsRow_, i);- dropdownOpen_ = false;- dirty_ = true;- ev.action = Action::SettingsChanged;- ev.settings = settings_;- return ev;- }- }- } else {- dropdownOpen_ = false;- dirty_ = true;- return ev;- }- }- constexpr int kRowW = 1200, kRowH = 32, kGap = 2, kGroupGap = 5;- int curY = 184;- for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {- if (groupStart) curY += kGroupGap;- if (x >= kMargin && x < kMargin + kRowW && y >= curY && y < curY + kRowH) {- settingsRow_ = i;- if (i == 17) {- ev.action = Action::CheckSignIn;- return ev;- } else if (i == 18) {- ev.action = Action::RunNetworkTest;- return ev;- } else if (i == 19) {- ev.action = Action::OpenUrl;- ev.url = "https://ko-fi.com/rafaelngp";- return ev;- } else if (i == 22) {- openTouchpadTester();- return ev;- } else if (i == 5) {- settings_.circleConfirms = !settings_.circleConfirms;- ev.action = Action::SettingsChanged;- ev.settings = settings_;- dirty_ = true;- return ev;- } else {- auto opts = settingOptions(i);- if (opts.size() > 2 && i != 10) {- dropdownOpen_ = true;- dropdownIndex_ = settingSelected(i);- dropdownTop_ = std::max(0, dropdownIndex_ - 4);- dirty_ = true;- return ev;- }- changeSetting(1);- ev.action = Action::SettingsChanged;- ev.settings = settings_;- dirty_ = true;- return ev;- }- }- curY += kRowH + kGap;- }- }- return ev;-}--UiEvent AppUi::onMouseWheel(float dx, float dy) {- std::lock_guard<std::mutex> lock(mutex_);- UiEvent ev;- mouseCursorVisible_ = true;- mouseCursorVisibleUntil_ = platform::nowMs() + 3000;- dirty_ = true;- if (screen_ == Screen::Streaming || screen_ == Screen::Splash) {- return ev;- }- if (screen_ == Screen::Home) {- if (tab_ == Tab::Library) {- LibraryLayout L = libraryLayout();- float maxScroll = L.rowY.empty() ? 0.0f : static_cast<float>(std::max(0, L.rowY.back() + kGridPitchY - (kH - kLibraryTop)));- gridScroll_.target = std::clamp(gridScroll_.target - dy * 140.0f, 0.0f, maxScroll);- animating_ = true;- dirty_ = true;- } else if (tab_ == Tab::GamePass) {- if (!rows_.empty()) {- const GameRow& curRow = rows_[static_cast<size_t>(focusRow_)];- if (curRow.isGrid) {- int totalRows = (static_cast<int>(curRow.tiles.size()) + kLibraryCols - 1) / kLibraryCols;- float maxScroll = std::max(0.0f, static_cast<float>(totalRows * kGridPitchY - (kH - kRowTop - 48)));- if (dy > 0 && rowScroll_[static_cast<size_t>(focusRow_)].target <= 0.0f) {- if (focusRow_ > 0) {- --focusRow_;- retarget();- animating_ = true;- dirty_ = true;- }- } else {- rowScroll_[static_cast<size_t>(focusRow_)].target =- std::clamp(rowScroll_[static_cast<size_t>(focusRow_)].target - dy * 140.0f, 0.0f, maxScroll);- animating_ = true;- dirty_ = true;- }- } else {- if (std::abs(dy) > std::abs(dx)) {- int nextRow = std::clamp(static_cast<int>(rowY_.target - dy), 0, static_cast<int>(rows_.size()) - 1);- if (nextRow != focusRow_) {- focusRow_ = nextRow;- retarget();- animating_ = true;- dirty_ = true;- }- } else if (dx != 0.0f) {- float maxScroll = std::max(0.0f, static_cast<float>(static_cast<int>(curRow.tiles.size()) * kCardPitch - (kW - kMargin)));- rowScroll_[static_cast<size_t>(focusRow_)].target =- std::clamp(rowScroll_[static_cast<size_t>(focusRow_)].target - dx * 160.0f, 0.0f, maxScroll);- animating_ = true;- dirty_ = true;- }- }- }- }- } else if (screen_ == Screen::Details && achievementsOpen_) {- achScroll_ = std::max(0, achScroll_ - static_cast<int>(dy * 3));- dirty_ = true;- } else if (screen_ == Screen::Home && updatePrompt_ && showingUpdateNotes_) {- updateNotesScroll_ = std::clamp(updateNotesScroll_ - static_cast<int>(dy * 2), 0, updateNotesMaxScroll_);- dirty_ = true;- }- return ev;-}--UiEvent AppUi::handle(const NavInput& in) {- std::lock_guard<std::mutex> lock(mutex_);- UiEvent ev;- if (screen_ == Screen::Splash) {- return ev;- }- if (reportOpen_) { // the report's QR code: Circle (or Cross) closes it- if (in.accept && caps_.openUrl) {- // A desktop: Cross opens the form in the browser (the panel stays).- ev.action = Action::OpenUrl;- ev.url = reportUrl_;- } else if (in.back || in.accept) {- reportOpen_ = false, dirty_ = true;- }- return ev;- }- if (screen_ == Screen::Home && updatePrompt_) {- if (showingUpdateNotes_) {- if (in.up) {- if (updateNotesScroll_ > 0) {- --updateNotesScroll_;- dirty_ = true;- }- } else if (in.down) {- if (updateNotesScroll_ < updateNotesMaxScroll_) {- ++updateNotesScroll_;- dirty_ = true;- }- } else if (in.l1 || in.l2) {- if (updateNotesScroll_ > 0) {- updateNotesScroll_ = std::max(0, updateNotesScroll_ - 5);- dirty_ = true;- }- } else if (in.r1 || in.r2) {- if (updateNotesScroll_ < updateNotesMaxScroll_) {- updateNotesScroll_ = std::min(updateNotesMaxScroll_, updateNotesScroll_ + 5);- dirty_ = true;- }- } else if (in.scrollRows != 0) {- int next = std::clamp(updateNotesScroll_ + in.scrollRows, 0, updateNotesMaxScroll_);- if (next != updateNotesScroll_) {- updateNotesScroll_ = next;- dirty_ = true;- }- } else if (in.back || in.accept || in.square) {- showingUpdateNotes_ = false;- dirty_ = true;- }- return ev;- }- // 3 buttons: 0 Update now, 1 What's new, 2 Not now- if (in.square) {- showingUpdateNotes_ = true;- updateNotesScroll_ = 0;- formatUpdateNotes();- dirty_ = true;- return ev;- }- if (in.left) {- promptFocus_ = (promptFocus_ + 2) % 3;- dirty_ = true;- } else if (in.right) {- promptFocus_ = (promptFocus_ + 1) % 3;- dirty_ = true;- }- if (in.accept) {- if (promptFocus_ == 0) {- ev.action = Action::UpdateNow;- updatePrompt_ = false;- dirty_ = true;- } else if (promptFocus_ == 1) {- showingUpdateNotes_ = true;- updateNotesScroll_ = 0;- formatUpdateNotes();- dirty_ = true;- } else {- ev.action = Action::UpdateLater;- updatePrompt_ = false;- dirty_ = true;- }- } else if (in.back) {- ev.action = Action::UpdateLater;- updatePrompt_ = false;- dirty_ = true;- }- return ev;- }- if (countryPickerOpen_) {- // "Sign in as another country": up / down, Cross signs in as the- // one chosen, Circle closes it unchanged.- int n = 1 + static_cast<int>(std::size(kLoginCountries));- if (in.down && countryIndex_ + 1 < n) ++countryIndex_, dirty_ = true;- if (in.up && countryIndex_ > 0) --countryIndex_, dirty_ = true;- if (in.accept) {- settings_.loginCountry = countryIndex_ ? kLoginCountries[countryIndex_ - 1] : "";- ev.action = Action::LoginCountry;- ev.settings = settings_;- }- if (in.accept || in.back) countryPickerOpen_ = false, dirty_ = true;- return ev;- }- switch (screen_) {- case Screen::Home:- if (quitPrompt_) { // two buttons, Close / Cancel: left / right picks, Cross presses, Circle cancels- if (in.left || in.right) promptFocus_ = in.left ? 0 : 1, dirty_ = true;- if (in.accept && promptFocus_ == 0) ev.action = Action::Quit;- if (in.accept || in.back) quitPrompt_ = false, dirty_ = true;- break;- }- // A desktop window has no system menu to close it from (fullscreen,- // a controller in hand): Circle / Esc at the top of the home screen- // asks. On the PS5 the system closes the app; Circle does nothing here.- if (caps_.desktopWindow && in.back && !searching_) {- quitPrompt_ = true;- promptFocus_ = 1; // Cancel first: a second Circle / Esc never closes by accident- dirty_ = true;- break;- }- handleHome(in, ev);- break;- case Screen::SignIn:- // A desktop: Cross (Enter) opens the sign-in page in the browser.- if (in.accept && caps_.openUrl) {- ev.action = Action::OpenUrl;- ev.url = codeUrl_.empty() ? "https://www.microsoft.com/link" : codeUrl_;- }- break;- case Screen::Settings:- if (pickerOpen_) {- handleColourPicker(in);- if (!pickerOpen_ && in.accept) {- ev.action = Action::SettingsChanged;- ev.settings = settings_;- }- break;- }- if (tester_ == Tester::SignInCheck) {- if (in.back) {- tester_ = Tester::None;- dirty_ = true;- } else if (in.accept && !signInCheck_.running) {- ev.action = Action::CheckSignIn;- }- break;- }- if (tester_ == Tester::NetworkTest) {- if (in.back) {- tester_ = Tester::None;- dirty_ = true;- } else if (in.accept && !networkTest_.running) {- ev.action = Action::RunNetworkTest;- }- break;- }- if (tester_ == Tester::Donation) {- if (in.back || in.accept) {- tester_ = Tester::None;- dirty_ = true;- }- break;- }- if (tester_ != Tester::None) {- handleTester(in);- if (tester_ == Tester::None) {- ev.action = Action::SettingsChanged;- ev.settings = settings_;- }- break;- }- if (dropdownOpen_) {- // The list: up / down, Cross picks, Circle closes it unchanged.- int n = static_cast<int>(settingOptions(settingsRow_).size());- if (in.down && dropdownIndex_ + 1 < n) ++dropdownIndex_;- if (in.up && dropdownIndex_ > 0) --dropdownIndex_;- int before = settingSelected(settingsRow_);- if (in.accept) applySetting(settingsRow_, dropdownIndex_);- if (in.accept || in.back) dropdownOpen_ = false;- if (in.accept && settingsRow_ == 6 && dropdownIndex_ == 1) {- openColourPicker(before);- } else if (in.accept && settingsRow_ != 8) {- ev.action = Action::SettingsChanged;- ev.settings = settings_;- }- dirty_ = true;- break;- }- if (auto rows = visibleSettingsRows(caps_); true) { // the rows on screen, in their order- int pos = posOf(rows, settingsRow_);- if (in.down && pos + 1 < static_cast<int>(rows.size())) {- settingsRow_ = rows[static_cast<size_t>(pos + 1)].row;- resetSettingsHoldStart_ = 0;- dirty_ = true;- } else if (in.up && pos > 0) {- settingsRow_ = rows[static_cast<size_t>(pos - 1)].row;- resetSettingsHoldStart_ = 0;- dirty_ = true;- }- }- if (settingsRow_ == 23) {- if (in.acceptHeld) {- if (!resetSettingsHoldStart_) resetSettingsHoldStart_ = in.nowMs ? in.nowMs : 1;- if (in.nowMs - resetSettingsHoldStart_ >= 5000) {- ev.action = Action::ResetSettings;- resetSettingsHoldStart_ = 0;- }- animating_ = true;- dirty_ = true;- } else if (resetSettingsHoldStart_) {- resetSettingsHoldStart_ = 0;- dirty_ = true;- }- } else {- resetSettingsHoldStart_ = 0;- }- if (in.right && settingsRow_ != 23) {- changeSetting(+1);- if (settingsRow_ != 8) {- ev.action = Action::SettingsChanged;- ev.settings = settings_;- }- }- if (in.left && settingsRow_ != 23) {- changeSetting(-1);- if (settingsRow_ != 8) {- ev.action = Action::SettingsChanged;- ev.settings = settings_;- }- }- if (in.square && settingsRow_ == 16) {- ev.action = Action::TestQueueAlert;- }- if (in.accept && settingsRow_ == 14) {- openPadTester(); // controller buttons: their own screen- } else if (in.accept && (settingsRow_ == 3 || settingsRow_ == 4 || settingsRow_ == 12)) {- // Dead zone, trigger vibration, keyboard keys: their own screens instead of a list.- openTester(settingsRow_ == 3 ? Tester::Sticks : settingsRow_ == 4 ? Tester::Triggers : Tester::Keys);- } else if (in.accept && settingsRow_ == 17) {- openTester(Tester::SignInCheck);- ev.action = Action::CheckSignIn;- } else if (in.accept && settingsRow_ == 18) {- openTester(Tester::NetworkTest);- ev.action = Action::RunNetworkTest;- } else if (in.accept && settingsRow_ == 19) {- openTester(Tester::Donation);- } else if (in.accept && settingsRow_ == 7) {- // Updates: a newer version is installed (the settings saved- // first). Where the app doesn't install it, the release's- // page opens in the browser instead.- if (!caps_.selfUpdate) {- if (caps_.openUrl) {- ev.action = Action::OpenUrl;- ev.url = kReleasesPage;- }- } else if (!updateAvailable_.empty() && !updateChecking_) {- ev.action = Action::UpdateNow;- ev.settings = settings_;- }- } else if (in.accept && settingsRow_ == 10) {- // Inline bitrate slider: cycles to next option, no dropdown modal- int n = static_cast<int>(settingOptions(10).size());- if (n > 0) applySetting(10, (settingSelected(10) + 1) % n);- } else if (in.accept && settingsRow_ == 23) {- // Handled via hold- } else if (in.accept) {- dropdownOpen_ = true;- dropdownIndex_ = settingSelected(settingsRow_);- dropdownTop_ = 0;- dirty_ = true;- }- if (in.back || in.options) {- resetSettingsHoldStart_ = 0;- // Back where Settings was opened. A new sign-in country- // takes a new sign-in.- screen_ = settingsFromError_ ? Screen::Error : Screen::Home;- dirty_ = true;- ev.action = settings_.loginCountry != settingsCountry_ ? Action::LoginCountry : Action::SettingsChanged;- ev.settings = settings_;- } else if (in.triangle) {- ev.action = Action::Report; // "Report a problem"- }- break;- case Screen::Details:- if (achievementsOpen_) {- if (in.up && achScroll_ > 0) {- achScroll_--;- dirty_ = true;- }- int maxScroll = 0;- if (auto it = achievements_.find(detail_.xboxTitleId); it != achievements_.end()) {- maxScroll = std::max(0, static_cast<int>(it->second.items.size()) - 5);- }- if (in.down && achScroll_ < maxScroll) {- achScroll_++;- dirty_ = true;- }- if (in.back || in.l3) {- achievementsOpen_ = false;- dirty_ = true;- }- break;- }- if (gameSettingsOpen_) {- handleGameSettings(in, ev);- break;- }- if (in.options) {- openGameSettings();- dirty_ = true;- break;- }- {- bool hasAchievements = !detail_.xboxTitleId.empty();- if (in.right && hasAchievements && detailButtonFocus_ == 0) {- detailButtonFocus_ = 1;- dirty_ = true;- } else if (in.left && detailButtonFocus_ == 1) {- detailButtonFocus_ = 0;- dirty_ = true;- }- if (in.accept) {- if (detailButtonFocus_ == 1 && hasAchievements) {- openAchievements();- } else if (isFreeGame(detail_) && !detail_.playable) {- ev.action = Action::ClaimFreeGame;- ev.game = detail_;- ev.game.freeInStore = true;- } else if (detail_.playable) {- ev.action = Action::Play;- ev.game = detail_;- }- }- }- if (in.square) toggleHidden(detail_, ev); // the page stays open- if (in.triangle) toggleFavorite(detail_, ev);- if (in.r3 && !isAcquired(detail_)) toggleWishlist(detail_, ev);- if (in.l3 && !detail_.xboxTitleId.empty()) openAchievements();- if (in.back) {- syncHeroToRowsLocked(detail_.productId, detail_.titleId, detail_.heroUrl, detail_.description, detail_.publisher, detail_.categories);- screen_ = Screen::Home;- dirty_ = true;- }- break;- case Screen::Launching:- if (in.back) ev.action = Action::CancelLaunch;- break;- case Screen::Error:- if (!errorGame_.titleId.empty() || !errorGame_.productId.empty()) {- if (in.accept) {- if ((isFreeGame(errorGame_) || errorGame_.freeInStore) && !errorGame_.playable) {- ev.action = Action::ClaimFreeGame;- ev.game = errorGame_;- ev.game.freeInStore = true;- } else if (errorGame_.playable && !errorGame_.titleId.empty()) {- ev.action = Action::Play;- ev.game = errorGame_;- } else {- openDetails(errorGame_);- }- } else if (in.back && errorGame_.homeConsole) {- screen_ = Screen::Home; // back to My consoles- tab_ = Tab::Consoles;- dirty_ = true;- } else if (in.back) {- openDetails(errorGame_);- }- } else if (in.accept) {- ev.action = Action::Retry;- } else if ((in.square || in.back) && !regionRefused_ && (!rows_.empty() || !owned_.empty())) {- screen_ = Screen::Home;- loading_ = false;- dirty_ = true;- }- if (regionRefused_ && in.square) {- countryPickerOpen_ = true;- countryIndex_ = settingSelected(8);- dirty_ = true;- } else if (regionRefused_ && in.options) { // Settings, on the sign-in country- screen_ = Screen::Settings;- settingsRow_ = 8;- settingsFromError_ = true;- settingsCountry_ = settings_.loginCountry;- dropdownOpen_ = false;- dirty_ = true;- }- if (in.triangle) { // "Report a problem", with the error shown- ev.action = Action::Report;- ev.reportWhat = error_;- }- break;- default: break;- }- // Sign out: hold TOUCHPAD for 5 s on the home or error screen.- bool canSignOut = screen_ == Screen::Home || screen_ == Screen::Error;- if (canSignOut && in.touchpad && !signOutLatched_) {- if (!signOutHoldStart_) signOutHoldStart_ = in.nowMs ? in.nowMs : 1;- if (in.nowMs - signOutHoldStart_ >= kSignOutHoldMs) {- ev.action = Action::SignOut;- signOutHoldStart_ = 0;- signOutLatched_ = true;- }- dirty_ = true;- } else if (!in.touchpad || !canSignOut) {- if (signOutHoldStart_) dirty_ = true;- signOutHoldStart_ = 0;- if (!in.touchpad) signOutLatched_ = false;- }- if (displayModeChanged_) {- // A desktop's display mode applies (and is saved) as it is picked,- // not when Settings closes.- displayModeChanged_ = false;- if (ev.action == Action::None) {- ev.action = Action::SettingsChanged;- ev.settings = settings_;- }- }- return ev;-}--// --- Rendering -------------------------------------------------------------------bool AppUi::needsRedraw(uint64_t nowMs) const {- std::lock_guard<std::mutex> lock(mutex_);- if (screen_ == Screen::Streaming) return false;- if (dirty_ || animating_) return true;- if (mouseCursorVisible_ && nowMs >= mouseCursorVisibleUntil_) return true;- // A desktop's toast came or went (the PS5 sends system notifications).- if (platform::toastsEnabled() && platform::toasts().version(nowMs) != toastsDrawn_) return true;- // Spinners keep moving (about 30 fps is enough).- bool spinner = screen_ == Screen::Splash || screen_ == Screen::SignIn || screen_ == Screen::Launching ||- screen_ == Screen::Updating ||- (screen_ == Screen::Settings && ((tester_ == Tester::SignInCheck && signInCheck_.running) ||- (tester_ == Tester::NetworkTest && networkTest_.running)));- return spinner && nowMs - lastRender_ >= 33;-}--void AppUi::drawCentered(Canvas& c, const Font& f, const std::string& text, int y, int px, Color color) {- f.draw(c, text, (kW - f.measure(text, px)) / 2, y, px, color);-}--void AppUi::drawBackground(Canvas& c) {- c.clear(kBg);- c.gradientV({0, 0, kW, kH}, rgba(24, 28, 24), kBg);-}--void AppUi::drawLogo(Canvas& c, float cx, float cy, float r) { drawBrandMark(c, cx, cy, r); }--void AppUi::drawGamerscoreBadge(Canvas& c, float cx, float cy, float r) {- // A filled disc with a "G" cut out of it, drawn from shapes (a letter of- // the font never sits in the middle of a circle): a ring open at the- // upper right, and its bar from the centre to the ring.- c.fillCircle(cx, cy, r, kGray);- const float ring = r * 0.56f, t = r * 0.24f;- const float kGap = 0.95f; // radians left open, above 3 o'clock- c.strokeArc(cx, cy, ring, t, 0.0f, 6.2832f - kGap, kBg);- c.line(cx + r * 0.05f, cy, cx + ring + t * 0.5f, cy, t, kBg);-}--void AppUi::drawTopBar(Canvas& c) {- drawLogo(c, kMargin + 22, 72, 22);- fonts_.semibold.draw(c, tr(Str::CloudGaming), kMargin + 64, 60, 22, kWhite);-- // Cloud playtime remaining badge positioned under the "PSBox Cloud Gaming" brand mark.- // Purely informative; hidden from the active UI for now until Xbox Cloud Gaming enforces limits.- constexpr bool kShowPlaytimeBadge = false;- if (kShowPlaytimeBadge && playtimeRemaining_ >= 0) {- int hours = static_cast<int>((playtimeRemaining_ + 3599) / 3600);- std::string pt = trf(Str::HoursRemaining, std::to_string(hours));- bool warn = playtimeRemaining_ <= 7200;- Color col = warn ? rgba(255, 160, 40) : kGray;- fonts_.semibold.draw(c, pt, kMargin + 64, 86, 14, col);- }-- int x = kW - kMargin;- constexpr int kAvatar = 52;- x -= kAvatar;- if (auto pic = images_.get(gamerpicUrl_, kAvatar, kAvatar)) {- c.drawImage(*pic, x, 46, 255, -1);- } else {- c.fillCircle(x + kAvatar / 2.0f, 72, kAvatar / 2.0f, kPanel);- }- if (!gamertag_.empty()) {- // The name; under it the gamerscore (its badge and the number, the- // thousands grouped as the language writes them) and the Game Pass- // plan, right-aligned to the picture as the Xbox app shows them.- bool second = !gamerscore_.empty() || !subscription_.empty();- int w = fonts_.semibold.measure(gamertag_, 22);- fonts_.semibold.draw(c, gamertag_, x - 16 - w, second ? 44 : 59, 22, kWhite);- int right = x - 16;- constexpr int kLineY = 76, kLineH = 22, kLinePx = 17;- const float midY = kLineY + kLineH / 2.0f;- if (!subscription_.empty()) {- // "GAME PASS", and the plan in an outlined box when it is known- // ("GamePass": a member, the plan not known).- int left = right;- if (subscription_ != "GamePass") {- std::string plan = subscription_;- for (auto& ch : plan) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));- int pw = fonts_.bold.measure(plan, 11);- Rect box{right - pw - 10, static_cast<int>(midY) - 8, pw + 10, 16};- c.strokeRect(box, kGray, 1, 2);- fonts_.bold.draw(c, plan, box.x + 5, fonts_.bold.centeredY(box.y, box.h, 11), 11, kGray);- left = box.x - 6;- }- const char* gp = "GAME PASS";- int gw = fonts_.semibold.measure(gp, 14);- fonts_.semibold.draw(c, gp, left - gw, fonts_.semibold.centeredY(kLineY, kLineH, 14), 14, kGray);- right = left - gw - 16;- }- if (!gamerscore_.empty()) {- std::string n;- const char* sep = language() == Language::English ? "," : ".";- for (size_t i = 0; i < gamerscore_.size(); ++i) {- if (i && (gamerscore_.size() - i) % 3 == 0) n += sep;- n += gamerscore_[i];- }- int nw = fonts_.semibold.measure(n, kLinePx);- int nx = right - nw;- fonts_.semibold.draw(c, n, nx, fonts_.semibold.centeredY(kLineY, kLineH, kLinePx), kLinePx, kGray);- drawGamerscoreBadge(c, nx - 13.0f, midY, 8.5f);- right = nx - 26;- }- }-}--// A face button (an Icon: Cross, Circle, Square, Triangle) as on the pad,-// in the glyphs of the pad in use (pad_glyphs.h), `r` its radius (14 in the-// button hints).-static PadButton faceOf(int icon) {- return icon == kIconCross ? PadButton::Cross- : icon == kIconCircle ? PadButton::Circle- : icon == kIconSquare ? PadButton::Square- : PadButton::Triangle;-}-static void drawFaceButton(Canvas& c, const Font& letters, int icon, float cx, float cy, float r) {- ui::drawFaceButton(c, letters, g_glyphStyle, faceOf(icon), cx, cy, r);-}--void AppUi::drawHints(Canvas& c, const std::vector<std::pair<int, const char*>>& hints) {- // Right-aligned PlayStation button glyphs with labels.- constexpr int kPx = 22, kR = 14, kGap = 36;- int x = kW - kMargin;- const int y = kH - 64;- for (auto it = hints.rbegin(); it != hints.rend(); ++it) {- // With Circle confirming, the pad reports it as Cross (and the- // other way round): the hints show the button to press.- int icon = it->first;- int w = fonts_.semibold.measure(it->second, kPx);- x -= w;- fonts_.semibold.draw(c, it->second, x, y, kPx, kGray);- if (g_keyboardHints) { // the keyboard's key, as a key cap- const char* key = keyLabel(icon);- int kw = fonts_.bold.measure(key, 15) + 18;- Rect cap{x - 10 - kw, y + 1, kw, 26};- c.fillRect(cap, rgba(255, 255, 255, 30), 6);- c.strokeRect(cap, kGray, 2, 6);- fonts_.bold.draw(c, key, cap.x + 9, fonts_.bold.centeredY(cap.y, cap.h, 15), 15, kWhite);- x = cap.x - kGap;- continue;- }- if (circleConfirms_ && (icon == kIconCross || icon == kIconCircle))- icon = icon == kIconCross ? kIconCircle : kIconCross;- x -= 10 + 2 * kR;- float cx = x + kR, cy = y + 13;- const GlyphStyle style = g_glyphStyle;- const bool xbox = style == GlyphStyle::Xbox;- if (icon == kIconL2R2 || icon == kIconL1R1) {- const char* l = buttonName(style, icon == kIconL1R1 ? PadButton::L1 : PadButton::L2);- const char* r = buttonName(style, icon == kIconL1R1 ? PadButton::R1 : PadButton::R2);- int lw = fonts_.bold.measure(l, 14) + 16;- int rw = fonts_.bold.measure(r, 14) + 16;- int sepW = fonts_.regular.measure("|", 14);- constexpr int kPillGap = 6;- int rightX = x + 2 * kR;- Rect rPill{rightX - rw, static_cast<int>(cy) - 12, rw, 24};- c.fillRect(rPill, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, r, rPill.x + (rw - fonts_.bold.measure(r, 14)) / 2,- fonts_.bold.centeredY(rPill.y, rPill.h, 14), 14, kGray);- int sepX = rPill.x - kPillGap - sepW;- fonts_.regular.draw(c, "|", sepX, fonts_.regular.centeredY(static_cast<int>(cy) - 12, 24, 14), 14,- rgba(255, 255, 255, 120));- Rect lPill{sepX - kPillGap - lw, static_cast<int>(cy) - 12, lw, 24};- c.fillRect(lPill, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, l, lPill.x + (lw - fonts_.bold.measure(l, 14)) / 2,- fonts_.bold.centeredY(lPill.y, lPill.h, 14), 14, kGray);- x = lPill.x;- } else if (icon == kIconDpadLR) {- const char* l = "\xE2\x86\x90";- const char* r = "\xE2\x86\x92";- int lw = fonts_.bold.measure(l, 14) + 14;- int rw = fonts_.bold.measure(r, 14) + 14;- constexpr int kPillGap = 4;- int rightX = x + 2 * kR;- Rect rPill{rightX - rw, static_cast<int>(cy) - 12, rw, 24};- c.fillRect(rPill, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, r, rPill.x + (rw - fonts_.bold.measure(r, 14)) / 2,- fonts_.bold.centeredY(rPill.y, rPill.h, 14), 14, kGray);- Rect lPill{rPill.x - kPillGap - lw, static_cast<int>(cy) - 12, lw, 24};- c.fillRect(lPill, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, l, lPill.x + (lw - fonts_.bold.measure(l, 14)) / 2,- fonts_.bold.centeredY(lPill.y, lPill.h, 14), 14, kGray);- x = lPill.x;- } else if (icon == kIconR3 || icon == kIconL3) {- const char* label = buttonName(style, icon == kIconR3 ? PadButton::R3 : PadButton::L3);- int pillW = fonts_.bold.measure(label, 14) + 16;- int rightX = x + 2 * kR;- Rect pill{rightX - pillW, static_cast<int>(cy) - 12, pillW, 24};- c.fillRect(pill, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, label, pill.x + (pillW - fonts_.bold.measure(label, 14)) / 2,- fonts_.bold.centeredY(pill.y, pill.h, 14), 14, kGray);- x = pill.x;- } else if (xbox && icon == kIconTouchpad) { // View- drawXboxViewButton(c, cx, cy, kR, kGray);- } else if (xbox && icon == kIconOptions) { // Menu- drawXboxMenuButton(c, cx, cy, kR, kGray);- } else if (icon == kIconTouchpad) {- Rect pad{x - 18, static_cast<int>(cy) - 10, 2 * kR + 12, 20};- c.fillRect(pad, rgba(255, 255, 255, 40), 6);- c.strokeRect(pad, kGray, 2, 6);- x -= 10;- } else if (icon == kIconOptions) {- c.fillRect({x - 4, static_cast<int>(cy) - 11, 2 * kR + 8, 22}, rgba(255, 255, 255, 40), 11);- for (int k = -1; k <= 1; ++k) c.line(cx - 8, cy + k * 5, cx + 8, cy + k * 5, 2, kGray);- } else {- drawFaceButton(c, fonts_.bold, icon, cx, cy, kR);- }- x -= kGap;- }-}--void AppUi::drawSpinner(Canvas& c, float cx, float cy, float r, uint64_t nowMs) {- float t = static_cast<float>(nowMs % 1000) / 1000.0f * 6.2832f;- c.strokeArc(cx, cy, r, r * 0.18f, t, 4.4f, kWhite);-}--void AppUi::drawToast(Canvas& c, uint64_t nowMs) {- if (caps_.console) return;- if (toast_.empty()) return;- if (toastUntil_ == 0) toastUntil_ = nowMs + 3500;- if (nowMs >= toastUntil_) {- toast_.clear();- return;- }- int w = fonts_.semibold.measure(toast_, 24) + 64;- Rect r{(kW - w) / 2, kH - 150, w, 56};- c.fillRect(r, rgba(40, 40, 40, 235), 28);- fonts_.semibold.draw(c, toast_, r.x + 32, r.y + 14, 24, kWhite);-}--bool AppUi::drawHero(Canvas& c, uint64_t nowMs, const std::string& url, bool details) {- if (url != heroUrl_) {- // The previous art may only cross-fade into a new one that is already- // there; it is never kept up while the new one downloads.- prevHeroUrl_ = heroShownAt_ ? heroUrl_ : std::string();- heroUrl_ = url;- heroSince_ = nowMs;- heroShownAt_ = 0;- }- auto current = heroUrl_.empty() ? nullptr : images_.get(heroUrl_, kW, kH);- if (current) {- if (!heroShownAt_) heroShownAt_ = nowMs;- uint64_t age = nowMs - heroShownAt_;- // Arrived at once (cached): cross-fade from the previous art. Arrived- // later: fade in from the plain background.- bool crossFade = heroShownAt_ - heroSince_ < 150 && !prevHeroUrl_.empty();- auto previous = crossFade && age < kHeroFadeMs ? images_.get(prevHeroUrl_, kW, kH) : nullptr;- if (previous) c.drawImage(*previous, 0, 0);- uint8_t alpha = age >= kHeroFadeMs ? 255 : static_cast<uint8_t>(age * 255 / kHeroFadeMs);- c.drawImage(*current, 0, 0, alpha);- if (alpha < 255) animating_ = true;- } else {- prevHeroUrl_.clear(); // nothing on screen to fade from any more- }- // Darken towards the left (text) and the bottom (rows).- c.gradientH({0, 0, details ? 1400 : 1200, kH}, rgba(0, 0, 0, details ? 240 : 225), rgba(0, 0, 0, 0));- if (details) {- c.gradientV({0, 640, kW, 440}, withAlpha(kBg, 0), withAlpha(kBg, 230));- } else {- c.gradientV({0, 360, kW, 420}, withAlpha(kBg, 0), kBg);- c.fillRect({0, 780, kW, kH - 780}, kBg);- }- c.gradientV({0, 0, kW, 160}, rgba(0, 0, 0, 150), rgba(0, 0, 0, 0));- return current != nullptr;-}--void AppUi::drawSplash(Canvas& c, uint64_t nowMs) {- drawBackground(c);- drawLogo(c, kW / 2.0f, 400, 64);- drawCentered(c, fonts_.bold, tr(Str::AppName), 500, 52, kWhite);- drawCentered(c, fonts_.regular, status_, 590, 28, kGray);- drawSpinner(c, kW / 2.0f, 720, 26, nowMs);-}--void AppUi::drawSignIn(Canvas& c, uint64_t nowMs) {- drawBackground(c);- const int left = 180;- drawLogo(c, left + 26, 160, 26);- fonts_.semibold.draw(c, tr(Str::AppName), left + 70, 144, 30, kWhite);- fonts_.bold.draw(c, tr(Str::SignInTitle), left, 260, 72, kWhite);- fonts_.regular.draw(c, tr(Str::SignInStep1), left, 400, 32, kGray);- std::string shortUrl = codeUrl_;- for (const char* p : {"https://", "http://", "www."})- if (shortUrl.rfind(p, 0) == 0) shortUrl = shortUrl.substr(std::string(p).size());- fonts_.semibold.draw(c, shortUrl, left, 450, 44, kWhite);- fonts_.regular.draw(c, tr(Str::SignInStep2), left, 540, 32, kGray);-- // The code, letter by letter, in a panel.- constexpr int kPx = 96;- int letters = static_cast<int>(code_.size());- int cell = 82;- Rect panel{left, 600, std::max(400, letters * cell + 64), 150};- c.fillRect(panel, kPanel, 18);- int x = panel.x + 32;- for (char ch : code_) {- std::string s(1, ch);- fonts_.bold.draw(c, s, x + (cell - fonts_.bold.measure(s, kPx)) / 2, panel.y + 18, kPx, kWhite);- x += cell;- }- drawSpinner(c, left + 18, 830, 14, nowMs);- fonts_.regular.draw(c, tr(Str::SignInWaiting), left + 48, 815, 26, kDim);-- if (!platform::dataDirWritable()) {- std::string pathAndErr = platform::dataDir() + " (errno " + std::to_string(platform::dataDirErrno()) + ")";- std::string warn1 = trf(Str::StorageNotWritable, pathAndErr);- std::string warn2 = trf(Str::StorageFixHint, platform::dataDir());- fonts_.semibold.draw(c, warn1, left, 875, 22, rgba(255, 160, 40));- fonts_.regular.draw(c, warn2, left, 905, 20, kGray);- }-- // QR code for the sign-in page. Not "?otc=<code>": that prefilled link- // goes through a consent flow that rejects this client id ("first party- // application ... pre-authorization"), so the code is typed on the phone.- std::string target = codeUrl_.empty() ? "https://www.microsoft.com/link" : codeUrl_;- uint8_t qr[qrcodegen_BUFFER_LEN_MAX], tmp[qrcodegen_BUFFER_LEN_MAX];- if (qrcodegen_encodeText(target.c_str(), tmp, qr, qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN,- qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {- int n = qrcodegen_getSize(qr);- constexpr int kBox = 440;- int module = (kBox - 60) / (n + 2);- int size = module * (n + 2);- Rect box{1280, 300, size + 40, size + 40};- c.fillRect(box, kWhite, 24);- int ox = box.x + 20 + module, oy = box.y + 20 + 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);- int w = fonts_.regular.measure(tr(Str::SignInScan), 26);- fonts_.regular.draw(c, tr(Str::SignInScan), box.x + (box.w - w) / 2, box.y + box.h + 24, 26, kGray);- }- if (caps_.openUrl) drawHints(c, {{kIconCross, tr(Str::OpenInBrowser)}}); // a desktop: the page in the browser-}--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::TabConsoles)};- constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;- int widths[3], total = 0;- for (int i = 0; i < 3; ++i) {- widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;- total += widths[i] + (i ? kGap : 0);- }- int x = (kW - total) / 2;- auto shoulder = [&](const char* name, int cx) {- Rect r{cx - 22, kY + 8, 44, 28};- c.fillRect(r, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, name, cx - fonts_.bold.measure(name, 16) / 2, fonts_.bold.centeredY(r.y, r.h, 16), 16, kGray);- };- shoulder(g_keyboardHints ? "Q" : buttonName(g_glyphStyle, PadButton::L1), x - 40);- for (int i = 0; i < 3; ++i) {- bool on = static_cast<int>(tab_) == i;- Rect r{x, kY, widths[i], kH};- if (on) c.fillRect(r, kWhite, kH / 2);- fonts_.semibold.draw(c, labels[i], x + kPad, fonts_.semibold.centeredY(kY, kH, kPx), kPx, on ? kBg : kGray);- x += widths[i] + kGap;- }- shoulder(g_keyboardHints ? "E" : buttonName(g_glyphStyle, PadButton::R1), x - kGap + 40);-}--namespace {--// A QR code of `url` on a white card whose top-right corner is (right, top),-// about `target` px of code; the card's rect (empty when it can't be encoded).-Rect drawQr(Canvas& c, const std::string& url, int right, int top, int target,- qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM) {- uint8_t qr[qrcodegen_BUFFER_LEN_MAX], tmp[qrcodegen_BUFFER_LEN_MAX];- if (!qrcodegen_encodeText(url.c_str(), tmp, qr, ecc, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX,- qrcodegen_Mask_AUTO, true))- return {};- int n = qrcodegen_getSize(qr);- int module = target / (n + 2), size = module * (n + 2);- Rect box{right - size - 40, top, size + 40, size + 40};- c.fillRect(box, kWhite, 20);- int ox = box.x + 20 + module, oy = box.y + 20 + 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);- return box;-}--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;-}--const char* planBadgeLabel(uint8_t plan) {- if (plan == xcloud::kPlanEssential) return "ESSENTIAL";- if (plan == xcloud::kPlanPremium) return "PREMIUM";- if (plan == xcloud::kPlanUltimate) return "ULTIMATE";- return nullptr;-}--const char* planDisplayName(uint8_t plan) {- if (plan == xcloud::kPlanEssential) return "Essential";- if (plan == xcloud::kPlanPremium) return "Premium";- if (plan == xcloud::kPlanUltimate) return "Ultimate";- return nullptr;-}--// A shopping bag centred on (cx, cy), about 22x24 px: a game to buy.-// A shopping bag (body + handle) centred on (cx, cy); `size` scales it-// (1 = 22 x 23 px).-void drawBag(Canvas& c, int cx, int cy, Color color, float size = 1.0f) {- float w = 22 * size, h = 17 * size, r = 6 * size;- float bodyTop = cy - (h + r) / 2 + r;- c.fillRect({static_cast<int>(std::lround(cx - w / 2)), static_cast<int>(std::lround(bodyTop)),- static_cast<int>(std::lround(w)), static_cast<int>(std::lround(h))},- color, std::max(1, static_cast<int>(3 * size)));- c.strokeArc(static_cast<float>(cx), bodyTop, r, std::max(1.5f, 2.5f * size), 3.1416f, 3.1416f, color);-}--// A 5-pointed star centred on (cx, cy) with outer radius r.-void drawStar(Canvas& c, float cx, float cy, float r, Color color) {- constexpr float kPi = 3.14159265358979323846f;- float innerR = r * 0.42f;- float px[10], py[10];- for (int i = 0; i < 10; ++i) {- float angle = -kPi / 2.0f + i * (kPi / 5.0f);- float radius = (i % 2 == 0) ? r : innerR;- px[i] = cx + radius * std::cos(angle);- py[i] = cy + radius * std::sin(angle);- }- for (int i = 0; i < 10; ++i) {- int next = (i + 1) % 10;- c.line(px[i], py[i], px[next], py[next], 1.2f, color);- c.line(cx, cy, px[i], py[i], 1.5f, color);- }- c.fillCircle(cx, cy, innerR * 0.95f, color);- for (int i = 0; i < 5; ++i) {- int pt = i * 2;- c.line(cx, cy, px[pt], py[pt], 2.0f, 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);- }- // Top-left: time played on this title, when recorded.- uint64_t cardPlayedSec = 0;- if (!t.productId.empty()) {- auto it = settings_.titlePlaytime.find(t.productId);- if (it != settings_.titlePlaytime.end()) cardPlayedSec = it->second;- }- if (!cardPlayedSec && !t.titleId.empty()) {- auto it = settings_.titlePlaytime.find(t.titleId);- if (it != settings_.titlePlaytime.end()) cardPlayedSec = it->second;- }- if (cardPlayedSec > 0) {- std::string ptLabel = formatPlaytime(cardPlayedSec);- int pw = std::min(kCard - 56, fonts_.bold.measure(ptLabel, 11) + 14);- Rect ptBadge{x + 10, y + 10, pw, 22};- c.fillRect(ptBadge, rgba(0, 0, 0, 215), 4);- fonts_.bold.draw(c, ptLabel, ptBadge.x + (ptBadge.w - fonts_.bold.measure(ptLabel, 11)) / 2,- fonts_.bold.centeredY(ptBadge.y, ptBadge.h, 11), 11, kWhite);- }- // Top-right: Wishlist blue star when marked (or lock if unplayable and not wishlisted)- bool isWishlisted = !t.productId.empty() && wishlist_.count(t.productId) > 0;- if (isWishlisted) {- c.fillCircle(x + kCard - 24, y + 24, 14, rgba(10, 20, 35, 230));- c.strokeCircle(x + kCard - 24, y + 24, 14, 1.5f, rgba(40, 140, 255, 180));- drawStar(c, x + kCard - 24, y + 24, 7.5f, rgba(50, 160, 255));- }-- // Bottom-right: console badge and input badge.- // Calculate rightBadgeLeft so bottom-left badges never overlap them.- int rightEdge = x + kCard - 10;- int rightBadgeLeft = rightEdge;- if (const char* p = platformLabel(t.platform)) {- int pTextW = fonts_.bold.measure(p, 11);- int pBadgeW = std::clamp(pTextW + 12, 54, 66);- Rect badge{rightBadgeLeft - pBadgeW, y + kCard - 34, pBadgeW, 24};- c.fillRect(badge, rgba(0, 0, 0, 220), 4);- fonts_.bold.draw(c, p, badge.x + (badge.w - pTextW) / 2,- fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);- rightBadgeLeft = badge.x - 4;- }- if (t.mouseKeyboard || fonts_.hasIcons) {- constexpr int kInputW = 28;- Rect k{rightBadgeLeft - kInputW, y + kCard - 34, kInputW, 24};- c.fillRect(k, rgba(0, 0, 0, 220), 4);- const char* glyph = t.mouseKeyboard ? kIconKeyboardMouse : kIconGamepad;- if (fonts_.hasIcons) {- int gw = fonts_.icons.measure(glyph, 18);- int gx = k.x + (k.w - gw) / 2;- fonts_.icons.draw(c, glyph, gx, k.y + 3, 18, kWhite);- } else {- int kw = 16, kh = kw * 10 / 24;- int kx = k.x + (k.w - kw) / 2;- int ky = k.y + (k.h - kh) / 2;- drawKeyboardGlyph(c, kx, ky, kw, kWhite);- }- rightBadgeLeft = k.x - 6;- }-- // Bottom-left: price badge, plan badge, or friends playing; bounded by rightBadgeLeft.- int maxLeftW = std::max(40, rightBadgeLeft - (x + 10) - 4);- const char* planBadge = planBadgeLabel(t.plan);- uint8_t myPlan = xcloud::planTier(subscription_);- bool otherPlan = planBadge && (!t.playable || (myPlan > 0 && !xcloud::planIncludes(myPlan, t.plan, isFreeGame(t))));- bool showPlan = otherPlan || (planBadge && searching_ && tab_ == Tab::GamePass && filterPlan_ > 0 && t.friends.empty());- if (!t.playable && (t.purchasable || isFreeGame(t))) {- c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 70), 10);- auto price = prices_.find(t.productId);- bool free = isFreeGame(t);- std::string label = free ? tr(Str::Free)- : price != prices_.end() ? price->second.now- : tr(Str::BuyBadge);- int tw = fonts_.bold.measure(label, 11);- int w = std::min(maxLeftW, 20 + tw + 8);- if (w < 20 + tw + 8) {- label = fonts_.bold.fit(label, 11, w - 22);- }- Rect badge{x + 10, y + kCard - 34, w, 24};- c.fillRect(badge, rgba(16, 124, 16, 235), 4);- drawBag(c, badge.x + 10, badge.y + badge.h / 2, kWhite, 0.52f);- fonts_.bold.draw(c, label, badge.x + 18, fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);- } else if (!t.playable) {- c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 150), 10);- drawLock(c, isWishlisted ? x + kCard - 54 : x + kCard - 34, isWishlisted ? y + 24 : y + 30);- if (planBadge) {- int w = std::min(maxLeftW, fonts_.bold.measure(planBadge, 11) + 14);- Rect badge{x + 10, y + kCard - 34, w, 24};- c.fillRect(badge, rgba(0, 0, 0, 220), 4);- fonts_.bold.draw(c, planBadge, badge.x + (badge.w - fonts_.bold.measure(planBadge, 11)) / 2,- fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);- }- } else if (showPlan) {- int w = std::min(maxLeftW, fonts_.bold.measure(planBadge, 11) + 14);- Rect badge{x + 10, y + kCard - 34, w, 24};- c.fillRect(badge, rgba(0, 0, 0, 220), 4);- fonts_.bold.draw(c, planBadge, badge.x + (badge.w - fonts_.bold.measure(planBadge, 11)) / 2,- fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);- } else if (!t.friends.empty()) {- int numAvatars = std::min<int>(static_cast<int>(t.friends.size()), 2);- int extraCount = static_cast<int>(t.friends.size()) - numAvatars;- constexpr int kAvatarSz = 20;- constexpr int kAvatarOverlap = 13;- constexpr int kPillH = 26;- constexpr int kPadX = 4;- constexpr int kPadY = 3;-- int avatarsW = numAvatars == 1 ? kAvatarSz : (kAvatarSz + (numAvatars - 1) * kAvatarOverlap);- std::string tagText;- if (t.friends.size() == 1) {- tagText = t.friends[0].gamertag;- } else if (extraCount > 0) {- tagText = "+" + std::to_string(extraCount);- } else if (t.friends.size() == 2) {- tagText = t.friends[0].gamertag;- }-- int maxPillW = maxLeftW;- int maxTextW = maxPillW - avatarsW - kPadX * 2 - 8;- int textW = !tagText.empty() ? fonts_.semibold.measure(tagText, 12) + 6 : 0;- if (textW > maxTextW && maxTextW > 15) {- while (!tagText.empty() && fonts_.semibold.measure(tagText + "…", 12) + 6 > maxTextW) {- tagText.pop_back();- }- tagText += "…";- textW = fonts_.semibold.measure(tagText, 12) + 6;- }-- int pillW = kPadX * 2 + avatarsW + textW;- Rect pill{x + 10, y + kCard - 10 - kPillH, pillW, kPillH};- c.fillRect(pill, rgba(0, 0, 0, 215), kPillH / 2);- c.strokeRect(pill, rgba(255, 255, 255, 50), 1, kPillH / 2);-- int curX = pill.x + kPadX;- int curY = pill.y + kPadY;- for (int i = 0; i < numAvatars; ++i) {- int ax = curX + i * kAvatarOverlap;- const auto& friendInfo = t.friends[static_cast<size_t>(i)];- if (auto pic = images_.get(friendInfo.gamerpicUrl, kAvatarSz, kAvatarSz)) {- c.drawImage(*pic, ax, curY, 255, -1);- } else {- c.fillCircle(ax + kAvatarSz / 2.0f, curY + kAvatarSz / 2.0f, kAvatarSz / 2.0f, rgba(48, 56, 68, 255));- if (!friendInfo.gamertag.empty()) {- std::string initial(1, static_cast<char>(std::toupper(static_cast<unsigned char>(friendInfo.gamertag[0]))));- int iw = fonts_.bold.measure(initial, 11);- int iy = fonts_.bold.centeredY(curY, kAvatarSz, 11);- fonts_.bold.draw(c, initial, ax + (kAvatarSz - iw) / 2, iy, 11, kWhite);- }- }- c.strokeCircle(ax + kAvatarSz / 2.0f, curY + kAvatarSz / 2.0f, kAvatarSz / 2.0f, 1.2f, rgba(255, 255, 255, 200));- }-- if (!tagText.empty()) {- int tx = curX + avatarsW + 4;- int ty = fonts_.semibold.centeredY(pill.y, pill.h, 12);- if (extraCount > 0 && numAvatars == 2) {- fonts_.bold.draw(c, tagText, tx, ty, 12, rgba(16, 124, 16, 255));- } else {- fonts_.semibold.draw(c, tagText, tx, ty, 12, 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));- for (size_t i = 0; i < tiles.size(); ++i) {- int col = static_cast<int>(i) % cols, row = static_cast<int>(i) / cols;- int x = x0 + col * kCardPitch;- int y = y0 + row * kGridPitchY - offset;- if (y + kCard + 40 < clipTop) continue;- if (y > kH) break;- bool focused = static_cast<int>(i) == focus;- 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);- }- // Rows scrolled up (cards and names) disappear under the header.- c.fillRect({0, 0, kW, clipTop}, kBg);- c.gradientV({0, clipTop, kW, 12}, kBg, withAlpha(kBg, 0));-}--void AppUi::drawLibrary(Canvas& c, uint64_t nowMs) {- drawBackground(c);- constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;- const int left = (kW - kGridW) / 2;- const int clipTop = kLibraryTop - 10;- LibraryLayout L = libraryLayout();- int offset = static_cast<int>(std::lround(gridScroll_.value));- // Each section has its heading in the grid: a title, the count, a line- // of explanation (the games to buy have a bag).- auto heading = [&](int section, const char* title, size_t count, const char* line, bool bag) {- int hy = kLibraryTop + L.headerY[section] - offset;- if (hy < clipTop - kSectionHeaderH || hy > kH) return;- int x = left;- if (bag) {- drawBag(c, left + 14, hy + 30, kGreen);- x += 40;- }- fonts_.bold.draw(c, title, x, hy + 8, 34, kWhite);- int w = fonts_.bold.measure(title, 34);- fonts_.semibold.draw(c, gamesCount(count), x + w + 20, hy + 20, 22, kDim);- if (line) fonts_.regular.draw(c, line, x, hy + 52, 22, kGray);- };- if (!owned_.empty()) heading(0, tr(Str::YourGames), owned_.size(), nullptr, false);- if (!purchasable_.empty()) heading(1, tr(Str::AvailableToBuy), purchasable_.size(), tr(Str::BuyToPlay), true);- if (!hiddenTiles_.empty()) heading(2, tr(Str::HiddenSection), hiddenTiles_.size(), tr(Str::HiddenHint), false);- for (size_t i = 0; i < L.rowOf.size(); ++i) {- int y = kLibraryTop + 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);- if (hidden_.count(t->productId)) c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 120), 10);- 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);- if (owned_.empty() && purchasable_.empty() && hiddenTiles_.empty()) {- if (!ownedKnown_) {- drawSpinner(c, kW / 2.0f, 470, 26, nowMs);- drawCentered(c, fonts_.semibold, tr(Str::LoadingGames), 530, 28, kGray);- animating_ = true;- } else {- drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 30, kGray);- }- }- {- drawLoadingBar(c, left, 112, 420, nowMs);- // The order (the whole tab's), right-aligned under the tabs, with its button.- Str sortName = librarySort_ == LibrarySort::AZ ? Str::SortAZ- : librarySort_ == LibrarySort::Console ? Str::SortConsole- : Str::SortRecent;- std::string label = trf(Str::SortLabel, tr(sortName));- int w = fonts_.semibold.measure(label, 22);- constexpr int kAvatar = 52;- int right = kW - kMargin - kAvatar - 16;- fonts_.semibold.draw(c, label, right - w, fonts_.semibold.centeredY(112, 28, 22), 22, kGray);- }- c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));- c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));- const GameTile* focus = libraryTile(gridFocus_);- bool focusHidden = focus && hidden_.count(focus->productId);- drawHints(c, {{kIconCross, tr(Str::Select)},- {kIconSquare, tr(focusHidden ? Str::Unhide : Str::Hide)},- {kIconTriangle, tr(Str::TabSearch)},- {kIconL3, tr(Str::RefreshLibrary)},- {kIconR3, tr(Str::SortHint)},- {kIconL2R2, tr(Str::Sections)},- {kIconOptions, tr(Str::Settings)}});- drawPads(c);- drawToast(c, nowMs);-}--void AppUi::drawSearch(Canvas& c, uint64_t nowMs) {- drawBackground(c);- // Results on the right.- drawGrid(c, results_, kResultsX, kGridTop, kResultCols, resultScroll_.value, searchOnKeys_ ? -1 : resultFocus_,- kGridTop - 20);- drawTopBar(c);- drawTabs(c);- const char* scope = tab_ == Tab::GamePass ? tr(Str::TabGamePass) : tr(Str::YourGames);- bool filtering = anyFilter();- if (query_.empty() && !filtering) {- fonts_.semibold.draw(c, tr(Str::SearchHint), kResultsX, 150, 26, kDim);- } else if (results_.empty()) {- const char* emptyMsg = (tab_ == Tab::Library && filterWishlist_) ? tr(Str::WishlistEmpty) : tr(Str::NoResults);- fonts_.semibold.draw(c, emptyMsg, kResultsX, 150, 26, kGray);- } else {- fonts_.semibold.draw(c, trf(Str::ResultsCount, std::to_string(results_.size())), kResultsX, 150, 26, kGray);- }- drawLoadingBar(c, kResultsX + 420, 150, 420, nowMs);-- // The query.- const int kbW = kKeyCols * (kKeyW + kKeyGap) - kKeyGap;- Rect box{kMargin, 140, kbW, 76};- c.fillRect(box, kPanel, 14);- if (searchOnKeys_) c.strokeRect(box, rgba(255, 255, 255, 90), 2, 14);- int tx = box.x + 24;- if (query_.empty()) {- fonts_.regular.draw(c, 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({query_.empty() ? box.x + 20 : tx, box.y + 18, 3, 40}, kWhite);- if (searchOnKeys_) animating_ = true; // the caret blinks-- // The keys.- for (int r = 0; r <= kKeyRows; ++r) {- int n = r == kKeyRows ? 3 : kKeyCols;- for (int k = 0; k < n; ++k) {- int col = r == kKeyRows ? kWideCols[k] : k;- int span = r == kKeyRows ? kWideSpan[k] : 1;- Rect key{kMargin + col * (kKeyW + kKeyGap), kKeysY + r * (kKeyH + kKeyGap),- span * kKeyW + (span - 1) * kKeyGap, kKeyH};- bool focused = searchOnKeys_ && keyRow_ == r && keyCol_ == k;- c.fillRect(key, focused ? kWhite : kPanel, 10);- std::string label = r == kKeyRows ? tr(k == 0 ? Str::KeySpace : k == 1 ? Str::KeyDelete : Str::KeyClear)- : std::string(1, static_cast<char>(std::toupper(kKeys[r * kKeyCols + k])));- int px = r == kKeyRows ? 22 : 28;- int w = fonts_.semibold.measure(label, px);- fonts_.semibold.draw(c, label, key.x + (key.w - w) / 2, fonts_.semibold.centeredY(key.y, kKeyH, px), px,- focused ? kBg : kWhite);- }- }- c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));- c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));- // The filters, 3x3 grid under the keys: green when on; the lists with a chevron.- const int gap = kChipGap, px = 18, fh = 48;- const int fy0 = kKeysY + (kKeyRows + 1) * (kKeyH + kKeyGap) + 8;- constexpr int kCols = 3;- const int chipW = (kKeysW - gap * (kCols - 1)) / kCols;- Rect openChip{};- for (int row = 0; row < 3; ++row) {- auto chips = filterRow(row);- if (chips.empty()) continue;- int fy = fy0 + row * (fh + 8);- for (size_t k = 0; k < chips.size(); ++k) {- Filter f = chips[k];- bool on = filterOn(f);- bool focused = searchOnKeys_ && keyRow_ == kKeyRows + 1 + row && keyCol_ == static_cast<int>(k);- Rect chip{kMargin + static_cast<int>(k) * (chipW + gap), fy, chipW, fh};- if (filterList_ == static_cast<int>(f)) openChip = chip;- c.fillRect(chip, focused ? kWhite : on ? rgba(16, 124, 16, 255) : kPanel, fh / 2);- if (on && focused) c.strokeRect({chip.x + 3, chip.y + 3, chip.w - 6, chip.h - 6}, kGreen, 3, fh / 2 - 3);- Color text = focused ? kBg : kWhite;- int room = chip.w - (isList(f) ? 56 : 20);- int chipPx = px;- while (chipPx > 13 && fonts_.semibold.measure(filterText(f), chipPx) > room) --chipPx;- std::string label = fonts_.semibold.fit(filterText(f), chipPx, room);- int tw = fonts_.semibold.measure(label, chipPx);- int tx = chip.x + (chip.w - tw) / 2;- fonts_.semibold.draw(c, label, tx, fonts_.semibold.centeredY(chip.y, chip.h, chipPx), chipPx, text);- if (isList(f)) { // a list: a chevron at the right- float cx = static_cast<float>(chip.x + chip.w - 20), cy = static_cast<float>(chip.y + chip.h / 2);- c.line(cx - 5, cy - 3, cx, cy + 2, 2.2f, text);- c.line(cx, cy + 2, cx + 5, cy - 3, 2.2f, text);- }- }- }- if (filterList_ >= 0) {- // The open list, above its chip (they are near the bottom); scrolls- // past kVisible choices.- Filter f = static_cast<Filter>(filterList_);- auto options = filterOptions(f);- int sel = filterSelected(f);- constexpr int kItemH = 54, kVisible = 9;- int n = static_cast<int>(options.size()), visible = std::min(n, kVisible);- if (filterListIndex_ < filterListTop_) filterListTop_ = filterListIndex_;- if (filterListIndex_ >= filterListTop_ + visible) filterListTop_ = filterListIndex_ - visible + 1;- int listW = std::max(openChip.w, 460);- Rect panel{openChip.x, openChip.y - 10 - (visible * kItemH + 16), listW, visible * kItemH + 16};- panel.y = std::max(120, panel.y);- c.fillRect({panel.x + 6, panel.y + 10, panel.w, panel.h}, rgba(0, 0, 0, 120), 18); // shadow- c.fillRect(panel, rgba(38, 38, 38, 250), 18);- c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 18);- for (int k = 0; k < visible; ++k) {- int i = filterListTop_ + k;- Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};- bool on = i == filterListIndex_;- if (on) c.fillRect(item, kWhite, 12);- Color text = on ? kBg : (i == sel ? kWhite : kGray);- std::string label = fonts_.semibold.fit(options[static_cast<size_t>(i)], 24, item.w - 70);- fonts_.semibold.draw(c, label, item.x + 20, fonts_.semibold.centeredY(item.y, item.h, 24), 24, text);- if (i == sel) { // a check mark on the current choice- float cx = static_cast<float>(item.x + item.w - 30), cy = static_cast<float>(item.y + item.h / 2);- c.line(cx - 9, cy, cx - 3, cy + 6, 3, on ? kBg : kGreen);- c.line(cx - 3, cy + 6, cx + 9, cy - 6, 3, on ? kBg : kGreen);- }- }- if (filterListTop_ > 0) { // more above / below- float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y - 12);- c.line(cx - 9, cy + 4, cx, cy - 4, 3, kGray);- c.line(cx, cy - 4, cx + 9, cy + 4, 3, kGray);- }- if (filterListTop_ + visible < n) {- float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y + panel.h + 12);- c.line(cx - 9, cy - 4, cx, cy + 4, 3, kGray);- c.line(cx, cy + 4, cx + 9, cy - 4, 3, kGray);- }- }- if (filterList_ >= 0)- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});- else if (searchOnKeys_)- drawHints(c, {{kIconCross, tr(Str::KeyType)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconCircle, tr(Str::Back)}});- drawToast(c, nowMs);-}--void AppUi::drawConsoles(Canvas& c, uint64_t nowMs) {- drawBackground(c);- drawTopBar(c);- drawTabs(c);- fonts_.bold.draw(c, tr(Str::TabConsoles), kMargin, 170, 52, kWhite);- fonts_.regular.draw(c, tr(Str::ConsolesHint), kMargin, 240, 26, kGray);- if (consoles_.empty()) {- if (!consolesKnown_) {- drawSpinner(c, kW / 2.0f, 520, 26, nowMs);- drawCentered(c, fonts_.semibold, tr(Str::ConsolesLoading), 580, 28, kGray);- animating_ = true;- drawHints(c, {{kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});- } else {- // How a console shows up: three numbered steps, and Microsoft's- // help on the phone.- fonts_.bold.draw(c, tr(Str::NoConsoles), kMargin, 340, 40, kWhite);- int y = 420;- const Str steps[] = {Str::ConsoleStep1, Str::ConsoleStep2, Str::ConsoleStep3};- for (int i = 0; i < 3; ++i) {- c.fillCircle(static_cast<float>(kMargin + 22), static_cast<float>(y + 20), 22, kGreen);- std::string num = std::to_string(i + 1);- fonts_.bold.draw(c, num, kMargin + 22 - fonts_.bold.measure(num, 24) / 2,- fonts_.bold.centeredY(y - 2, 44, 24), 24, kWhite);- for (const auto& line : fonts_.regular.wrap(tr(steps[i]), 28, 980, 2)) {- fonts_.regular.draw(c, line, kMargin + 70, y + 2, 28, kGray);- y += 40;- }- y += 34;- }- Rect box = drawQr(c, "https://support.xbox.com/help/games-apps/game-setup-and-play/how-to-use-remote-play",- kW - kMargin, 330, 340);- if (box.w > 0) {- int w = fonts_.semibold.measure(tr(Str::ScanForHelp), 24);- fonts_.semibold.draw(c, tr(Str::ScanForHelp), box.x + (box.w - w) / 2, box.y + box.h + 22, 24, kWhite);- }- drawHints(c, {{kIconCross, tr(Str::SearchAgain)},- {kIconOptions, tr(Str::Settings)},- {kIconTouchpad, tr(Str::HoldSignOut)}});- }- drawPads(c);- return;- }- // One card per console: a drawn Xbox, its name, model and state.- constexpr int kCardW = 480, kCardH = 380, kGap = 40, kTop = 320;- for (size_t i = 0; i < consoles_.size(); ++i) {- const ConsoleTile& con = consoles_[i];- int x = kMargin + static_cast<int>(i) * (kCardW + kGap);- if (x > kW) break;- bool focused = static_cast<int>(i) == consoleFocus_;- Rect card{x, kTop, kCardW, kCardH};- if (focused) c.strokeRect({card.x - 7, card.y - 7, card.w + 14, card.h + 14}, kWhite, 4, 22);- c.fillRect(card, kPanel, 16);- // The console: a Series X stands as a tower, the others lie flat.- bool tower = con.type == "XboxSeriesX";- Rect box = tower ? Rect{x + kCardW / 2 - 55, kTop + 40, 110, 170} : Rect{x + kCardW / 2 - 120, kTop + 90, 240, 70};- c.fillRect(box, rgba(20, 20, 20), 12);- c.strokeRect(box, rgba(70, 70, 70), 2, 12);- bool on = con.power == "On";- c.fillCircle(static_cast<float>(box.x + (tower ? box.w / 2 : 24)), static_cast<float>(box.y + (tower ? 22 : box.h / 2)),- tower ? 16.0f : 9.0f, on ? kGreen : rgba(90, 90, 90));- std::string name = con.name.empty() ? "Xbox" : con.name;- auto lines = fonts_.semibold.wrap(name, 30, kCardW - 48, 1);- if (!lines.empty()) fonts_.semibold.draw(c, lines[0], x + 24, kTop + 236, 30, kWhite);- std::string model = con.type == "XboxSeriesX" ? "Xbox Series X"- : con.type == "XboxSeriesS" ? "Xbox Series S"- : con.type == "XboxOneX" ? "Xbox One X"- : con.type == "XboxOneS" ? "Xbox One S"- : con.type == "XboxOne" ? "Xbox One"- : con.type;- fonts_.regular.draw(c, model, x + 24, kTop + 284, 24, kGray);- const char* state = on ? tr(Str::ConsoleOn)- : con.power == "ConnectedStandby" ? tr(Str::ConsoleSleeping)- : tr(Str::ConsoleOff);- c.fillCircle(static_cast<float>(x + 32), static_cast<float>(kTop + 336), 6, on ? rgba(60, 200, 60) : kDim);- fonts_.semibold.draw(c, state, x + 48, kTop + 322, 24, on ? kWhite : kGray);- }- drawHints(c, {{kIconCross, tr(Str::Play)},- {kIconTriangle, tr(Str::SearchAgain)},- {kIconOptions, tr(Str::Settings)},- {kIconTouchpad, tr(Str::HoldSignOut)}});- drawPads(c);-}--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::Consoles) return drawConsoles(c, nowMs);- const GameTile* focus = focusedTile();- c.clear(kBg);- std::string hero;- if (focus) {- hero = focus->heroUrl;- if (hero.empty() && !focus->productId.empty()) {- auto it = detailInfo_.find(focus->productId);- if (it != detailInfo_.end() && !it->second.heroUrl.empty()) {- hero = it->second.heroUrl;- }- }- if (hero.empty()) {- auto matchHero = [&](const GameTile& t) -> bool {- if (!t.heroUrl.empty()) {- if (!focus->productId.empty() && t.productId == focus->productId) return true;- if (!focus->titleId.empty() && t.titleId == focus->titleId) return true;- if (!focus->xboxTitleId.empty() && t.xboxTitleId == focus->xboxTitleId) return true;- }- return false;- };- const GameTile* matched = nullptr;- for (const auto& r : rows_) {- for (const auto& t : r.tiles) {- if (matchHero(t)) { matched = &t; break; }- }- if (matched) break;- }- if (!matched) {- for (const auto& r : allRows_) {- for (const auto& t : r.tiles) {- if (matchHero(t)) { matched = &t; break; }- }- if (matched) break;- }- }- if (!matched) {- for (const auto* list : {&gamePassPool_, &libraryPool_, &allOwned_, &allPurchasable_}) {- for (const auto& t : *list) {- if (matchHero(t)) { matched = &t; break; }- }- if (matched) break;- }- }- if (matched) {- hero = matched->heroUrl;- syncHeroToRowsLocked(matched->productId, matched->titleId, matched->heroUrl,- matched->description, matched->publisher, matched->categories);- }- }- if (!hero.empty()) {- syncHeroToRowsLocked(focus->productId, focus->titleId, hero);- }- }- drawHero(c, nowMs, hero, false);-- if (rows_.empty()) {- drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 32, kGray);- drawHints(c, {{kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});- drawTopBar(c);- drawTabs(c);- return;- }-- if (focus) {- float heroAlpha = 1.0f;- for (size_t r = 0; r < rows_.size(); ++r) {- if (rows_[r].isGrid) {- float dist = static_cast<float>(r) - rowY_.value;- if (dist < 1.0f) heroAlpha = std::clamp(dist, 0.0f, 1.0f);- break;- }- }- if (heroAlpha > 0.05f) {- Color titleColor = withAlpha(kWhite, static_cast<int>(255 * heroAlpha));- Color grayColor = withAlpha(kGray, static_cast<int>(255 * heroAlpha));- auto title = fonts_.bold.wrap(focus->name, 60, 1100, 1);- if (!title.empty()) fonts_.bold.draw(c, title[0], kMargin, 190, 60, titleColor);- std::string meta = focus->publisher;- for (size_t i = 0; i < focus->categories.size() && i < 2; ++i)- meta += (meta.empty() ? "" : " \xE2\x80\xA2 ") + focus->categories[i];- fonts_.regular.draw(c, meta, kMargin, 272, 24, grayColor);- auto desc = fonts_.regular.wrap(focus->description, 22, 860, 2);- for (size_t i = 0; i < desc.size(); ++i)- fonts_.regular.draw(c, desc[i], kMargin, 318 + static_cast<int>(i) * 32, 22, grayColor);- }- }-- constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;- const int gridLeft = (kW - kGridW) / 2;- int afterGridOffset = 0;-- for (size_t r = 0; r < rows_.size(); ++r) {- float rel = static_cast<float>(r) - rowY_.value;- int y = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;- const GameRow& row = rows_[r];-- if (row.isGrid) {- int offset = static_cast<int>(std::lround(rowScroll_[r].value));- int hy = y - offset;- int cardY = hy + 48;-- if (hy > 80 && hy < kH) {- fonts_.bold.draw(c, row.title, gridLeft, hy + 8, 34, kWhite);- int w = fonts_.bold.measure(row.title, 34);- fonts_.semibold.draw(c, gamesCount(row.tiles.size()), gridLeft + w + 20, hy + 20, 22, kDim);- }-- for (size_t i = 0; i < row.tiles.size(); ++i) {- int c_col = static_cast<int>(i) % kLibraryCols;- int c_row = static_cast<int>(i) / kLibraryCols;- int cy = cardY + c_row * kGridPitchY;- if (cy + kCard + 40 < 140) continue;- if (cy > kH) break;- int cx = gridLeft + c_col * kCardPitch;- bool focused = static_cast<int>(r) == focusRow_ && static_cast<int>(i) == focusCol_[r];- drawCard(c, row.tiles[i], cx, cy, focused, row.gamePassBadges);- if (hidden_.count(row.tiles[i].productId)) c.fillRect({cx, cy, kCard, kCard}, rgba(0, 0, 0, 120), 10);- auto name = fonts_.semibold.wrap(row.tiles[i].name, 20, kCard, 1);- if (!name.empty()) fonts_.semibold.draw(c, name[0], cx, cy + kCard + 12, 20, focused ? kWhite : kGray);- }-- int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;- afterGridOffset += gridHeight - offset - kRowPitch;- } else {- if (rel < -0.7f && afterGridOffset == 0) continue;- if (y > kH && afterGridOffset == 0) break;- fonts_.semibold.draw(c, row.title, kMargin, y, 30, kWhite);- int cardY = y + 48;- int scroll = static_cast<int>(std::lround(rowScroll_[r].value));- int firstCol = std::max(0, scroll / kCardPitch - 1);- for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {- int x = kMargin + static_cast<int>(col) * kCardPitch - scroll;- if (x > kW) break;- if (x + kCard < 0) continue;- bool focused = static_cast<int>(r) == focusRow_ && static_cast<int>(col) == focusCol_[r];- drawCard(c, row.tiles[col], x, cardY, focused, row.gamePassBadges);- if (hidden_.count(row.tiles[col].productId)) c.fillRect({x, cardY, kCard, kCard}, rgba(0, 0, 0, 120), 10);- }- }- }-- constexpr int clipTop = 140;- c.fillRect({0, 0, kW, clipTop}, kBg);- c.gradientV({0, clipTop, kW, 16}, kBg, withAlpha(kBg, 0));-- drawTopBar(c);- drawTabs(c);-- // 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)},- {kIconSquare, tr(focus && hidden_.count(focus->productId) ? Str::Unhide : Str::Hide)},- {kIconTriangle, tr(Str::TabSearch)},- {kIconL3, tr(Str::RefreshLibrary)},- {kIconOptions, tr(Str::Settings)},- {kIconTouchpad, tr(Str::HoldSignOut)}});- drawPads(c);- drawToast(c, nowMs);-}--void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {- const GameTile* g = &detail_;- c.clear(kBg);- if (g->productId.empty()) return;- // Without its hero art (games to buy, search results, or not downloaded- // yet): the cover on the right, never another game's backdrop.- constexpr int kCover = 420;- const Rect cover{kW - kMargin - kCover, 170, kCover, kCover};- if (!drawHero(c, nowMs, g->heroUrl, true)) {- // No hero art (yet): the cover, until the art arrives and fades in.- drawBackground(c);- if (g->playable || !g->purchasable || isFreeGame(*g)) { // paid games show their QR code there instead- if (auto img = images_.get(g->tileUrl, kCover, kCover)) c.drawImage(*img, cover.x, cover.y, 255, 16);- else c.fillRect(cover, kPlaceholder, 16);- }- }- drawTopBar(c);- int y = 260;- for (const auto& line : fonts_.bold.wrap(g->name, 68, 960, 2)) {- fonts_.bold.draw(c, line, kMargin, y, 68, kWhite);- y += 82;- }- y += 6;- const char* planName = planDisplayName(g->plan);- std::string byLine;- if (!g->publisher.empty()) byLine = trf(Str::PublisherBy, g->publisher);- if (planName && g->playable)- byLine += (byLine.empty() ? "" : " \xE2\x80\xA2 ") + trf(Str::IncludedWithPlan, planName);- if (!byLine.empty()) {- fonts_.semibold.draw(c, byLine, kMargin, y, 26, kGray);- y += 40;- }-- // Age rating & content descriptors (ClassInd, ESRB, PEGI)- if (!g->ratingAge.empty()) {- Color badgeBg = rgba(100, 100, 100);- Color badgeFg = kWhite;- if (g->ratingAge == "Livre" || g->ratingAge == "E" || g->ratingAge == "3+" || g->ratingAge == "0") {- badgeBg = rgba(0, 160, 60);- } else if (g->ratingAge == "10+" || g->ratingAge == "E10+" || g->ratingAge == "7+") {- badgeBg = rgba(0, 120, 220);- } else if (g->ratingAge == "12+") {- badgeBg = rgba(230, 180, 0);- badgeFg = rgba(20, 20, 20);- } else if (g->ratingAge == "14+" || g->ratingAge == "T") {- badgeBg = rgba(235, 100, 0);- } else if (g->ratingAge == "16+" || g->ratingAge == "M") {- badgeBg = rgba(210, 30, 30);- } else if (g->ratingAge == "18+" || g->ratingAge == "AO") {- badgeBg = rgba(30, 30, 30);- }-- int textW = fonts_.bold.measure(g->ratingAge, 20);- int badgeW = std::max(38, textW + 16);- int badgeH = 28;- Rect badge{kMargin, y + 2, badgeW, badgeH};- c.fillRect(badge, badgeBg, 6);- if (badgeBg == rgba(30, 30, 30)) {- c.strokeRect(badge, rgba(255, 255, 255, 160), 1, 6);- }- fonts_.bold.draw(c, g->ratingAge, badge.x + (badge.w - textW) / 2, fonts_.bold.centeredY(badge.y, badge.h, 20), 20, badgeFg);-- std::string descLine;- if (!g->ratingSystem.empty()) descLine = g->ratingSystem;- for (const auto& d : g->ratingDescriptors) {- std::string next = (descLine.empty() ? "" : " \xE2\x80\xA2 ") + d;- if (fonts_.semibold.measure(descLine + next, 22) > 750) {- descLine += " ...";- break;- }- descLine += next;- }- if (!descLine.empty()) {- fonts_.semibold.draw(c, descLine, badge.x + badge.w + 14, fonts_.semibold.centeredY(badge.y, badge.h, 22), 22, kDim);- }- y += 38;- }- 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 (g->mouseKeyboard) cats += std::string(cats.empty() ? "" : " \xE2\x80\xA2 ") + tr(Str::MouseKeyboardSupport);- if (!cats.empty()) {- fonts_.regular.draw(c, cats, kMargin, y, 24, kDim);- y += 44;- }- y += 10;- // Shorter for a free game, whose page also has the hint and Play below.- int descLines = !g->playable && isFreeGame(*g) ? 4 : 6;- for (const auto& line : fonts_.regular.wrap(g->description, 24, 880, descLines)) {- fonts_.regular.draw(c, line, kMargin, y, 24, kGray);- y += 34;- }- if (!g->playable && (g->purchasable || isFreeGame(*g))) {- // Streams once bought: the price and how to buy it on the left, a- // large QR code of the store page (for the phone) on the right. The- // console's browser can't run the xbox.com store, so no button.- int ty = y + 30;- auto price = prices_.find(g->productId);- bool free = isFreeGame(*g);- if (free) {- // Free to play: "Get Free" button to claim license directly.- fonts_.bold.draw(c, tr(Str::Free), kMargin, ty, 52, kWhite);- ty += 84;- fonts_.semibold.draw(c, tr(Str::FreeToPlay), kMargin, ty, 28, kWhite);- ty += 48;- for (const auto& line : fonts_.regular.wrap(tr(Str::FreeAcquireHint), 24, 820, 3)) {- fonts_.regular.draw(c, line, kMargin, ty, 24, kGray);- ty += 34;- }- const char* label = tr(Str::ClaimFree);- int tw = fonts_.semibold.measure(label, 30);- int btnW = std::max(320, tw + 64);- Rect claimBtn{kMargin, ty + 30, btnW, 76};- c.strokeRect({claimBtn.x - 7, claimBtn.y - 7, claimBtn.w + 14, claimBtn.h + 14}, kWhite, 4, 45);- c.fillRect(claimBtn, kGreen, 38);- fonts_.semibold.draw(c, label, claimBtn.x + (claimBtn.w - tw) / 2, claimBtn.y + 22, 30, kWhite);- } else if (price != prices_.end()) {- // The price, and the regular one crossed out while on sale.- int px = kMargin;- fonts_.bold.draw(c, price->second.now, px, ty, 52, kWhite);- px += fonts_.bold.measure(price->second.now, 52) + 24;- if (!price->second.was.empty()) {- int w = fonts_.semibold.measure(price->second.was, 30);- fonts_.semibold.draw(c, price->second.was, px, ty + 14, 30, kDim);- c.line(static_cast<float>(px), static_cast<float>(ty + 32), static_cast<float>(px + w),- static_cast<float>(ty + 32), 2, kDim);- }- ty += 84;- }- if (!free) {- drawBag(c, kMargin + 12, ty + 16, kGreen);- fonts_.semibold.draw(c, tr(Str::BuyToPlay), kMargin + 36, ty, 28, kWhite);- ty += 48;- for (const auto& line : fonts_.regular.wrap(tr(Str::BuyHint), 24, 820, 3)) {- fonts_.regular.draw(c, line, kMargin, ty, 24, kGray);- ty += 34;- }- Rect box = drawQr(c, "https://www.xbox.com/games/store/p/" + g->productId, kW - kMargin, 190, 440);- if (box.w > 0) {- const char* scan = tr(Str::ScanToBuy);- int w = fonts_.semibold.measure(scan, 26);- fonts_.semibold.draw(c, scan, box.x + (box.w - w) / 2, box.y + box.h + 22, 26, kWhite);- }- }- std::vector<Hint> hints;- if (free) hints.push_back({kIconCross, tr(Str::ClaimFree)});- hints.push_back({kIconOptions, tr(Str::GameSettings)});- hints.push_back({kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)});- hints.push_back({kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)});- if (!isAcquired(*g)) hints.push_back({kIconR3, tr(wishlist_.count(g->productId) ? Str::RemoveWishlist : Str::AddWishlist)});- if (!g->xboxTitleId.empty()) hints.push_back({kIconL3, tr(Str::Achievements)});- hints.push_back({kIconCircle, tr(Str::Back)});- drawHints(c, hints);- drawToast(c, nowMs);- return;- }- if (!g->playable) {- // Bought separately or outside the subscription: no Play button.- std::string msg = planName ? trf(Str::IncludedWithPlan, planName) : std::string(tr(Str::NotPlayable));- int w = std::max(560, fonts_.semibold.measure(msg, 28) + 124);- Rect note{kMargin, std::max(y + 48, 620), w, 76};- c.fillRect(note, rgba(255, 255, 255, 40), 38);- drawLock(c, note.x + 52, note.y + note.h / 2);- fonts_.semibold.draw(c, msg, note.x + 90, note.y + 22, 28, kGray);- std::vector<Hint> hints = {- {kIconOptions, tr(Str::GameSettings)},- {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},- {kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)}- };- if (!isAcquired(*g)) hints.push_back({kIconR3, tr(wishlist_.count(g->productId) ? Str::RemoveWishlist : Str::AddWishlist)});- if (!g->xboxTitleId.empty()) hints.push_back({kIconL3, tr(Str::Achievements)});- hints.push_back({kIconCircle, tr(Str::Back)});- drawHints(c, hints);- drawToast(c, nowMs);- return;- }- bool hasAchievements = !g->xboxTitleId.empty();- bool playFocused = (detailButtonFocus_ == 0);- bool achFocused = (detailButtonFocus_ == 1 && hasAchievements);-- // Play button- Rect play{kMargin, std::max(y + 48, 620), 300, 76};- if (playFocused) {- c.strokeRect({play.x - 7, play.y - 7, play.w + 14, play.h + 14}, kWhite, 4, 45);- c.fillRect(play, kGreen, 38);- } else {- c.fillRect(play, rgba(16, 124, 65, 140), 38);- }- float tx = play.x + 70, ty = play.y + play.h / 2.0f;- c.line(tx - 8, ty - 13, tx - 8, ty + 13, 4, kWhite);- c.line(tx - 8, ty - 13, tx + 13, ty, 4, kWhite);- c.line(tx - 8, ty + 13, tx + 13, ty, 4, kWhite);- fonts_.semibold.draw(c, tr(Str::Play), play.x + 108, play.y + 20, 32, kWhite);-- int nextBadgeX = play.x + play.w + 24;-- // Achievements button beside Play- if (hasAchievements) {- std::string achText = tr(Str::Achievements);- auto it = achievements_.find(g->xboxTitleId);- if (it != achievements_.end() && it->second.totalCount > 0) {- const auto& ach = it->second;- achText = std::to_string(ach.unlockedCount) + "/" + std::to_string(ach.totalCount) +- " (" + std::to_string(ach.unlockedGamerscore) + "/" + std::to_string(ach.totalGamerscore) + " G)";- }- int textW = fonts_.semibold.measure(achText, 26);- int achW = std::max(240, textW + 80);- Rect achBtn{nextBadgeX, play.y, achW, 76};- if (achFocused) {- c.strokeRect({achBtn.x - 7, achBtn.y - 7, achBtn.w + 14, achBtn.h + 14}, kWhite, 4, 45);- c.fillRect(achBtn, kGreen, 38);- } else {- c.fillRect(achBtn, rgba(255, 255, 255, 30), 38);- }- drawGamerscoreBadge(c, static_cast<float>(achBtn.x + 36), static_cast<float>(achBtn.y + 38), 13.0f);- fonts_.semibold.draw(c, achText, achBtn.x + 60, achBtn.y + 22, 26, kWhite);- nextBadgeX += achBtn.w + 24;- }-- // The service's estimate of the wait to start it, beside Play.- if (queueTitle_ == g->titleId && queueSeconds_ >= 0) {- std::string wait = queueSeconds_ < 60 ? trf(Str::QueueSeconds, std::to_string(queueSeconds_))- : trf(Str::QueueMinutes, std::to_string((queueSeconds_ + 59) / 60));- int w = fonts_.regular.measure(wait, 26);- Rect pill{nextBadgeX, play.y + 14, w + 44, 48};- c.fillRect(pill, rgba(0, 0, 0, 150), 24); // readable over any hero art- fonts_.regular.draw(c, wait, pill.x + 22, pill.y + 10, 26, kWhite);- nextBadgeX += pill.w + 16;- }- uint64_t playedSeconds = 0;- if (!g->productId.empty()) {- auto it = settings_.titlePlaytime.find(g->productId);- if (it != settings_.titlePlaytime.end()) playedSeconds = it->second;- }- if (!playedSeconds && !g->titleId.empty()) {- auto it = settings_.titlePlaytime.find(g->titleId);- if (it != settings_.titlePlaytime.end()) playedSeconds = it->second;- }- if (playedSeconds > 0) {- std::string playedText = trf(Str::PlaytimePlayed, formatPlaytime(playedSeconds));- int w = fonts_.semibold.measure(playedText, 24);- Rect pill{nextBadgeX, play.y + 14, w + 44, 48};- c.fillRect(pill, rgba(0, 0, 0, 150), 24);- fonts_.semibold.draw(c, playedText, pill.x + 22, pill.y + 12, 24, kWhite);- nextBadgeX += pill.w + 16;- }- std::vector<Hint> hints = {- {kIconCross, tr(achFocused ? Str::Achievements : Str::Play)},- {kIconOptions, tr(Str::GameSettings)},- {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},- {kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)}- };- if (!isAcquired(*g)) hints.push_back({kIconR3, tr(wishlist_.count(g->productId) ? Str::RemoveWishlist : Str::AddWishlist)});- hints.push_back({kIconCircle, tr(Str::Back)});- drawHints(c, hints);- drawToast(c, nowMs);-}--void AppUi::drawLaunching(Canvas& c, uint64_t nowMs) {- c.clear(kBg);- if (auto hero = images_.get(launching_.heroUrl, kW, kH)) c.drawImage(*hero, 0, 0);- c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 175));- drawSpinner(c, kW / 2.0f, 420, 40, nowMs);- drawCentered(c, fonts_.bold, launching_.name, 500, 48, kWhite);- drawCentered(c, fonts_.semibold, tr(Str::GettingReady), 576, 30, kGray);- drawCentered(c, fonts_.regular, status_, 630, 26, kDim);- // Helpful tips rotating every ~10 seconds from when the launching screen opened.- static constexpr Str kTips[] = {- Str::TipTouchpadMenu,- Str::TipKeyboardMouse,- Str::TipFreeStore,- Str::TipBugReportQr,- Str::TipSupportKofi,- Str::Tip120HzVideo,- Str::TipAnalogDeadzone,- Str::TipDualSenseMic,- };- constexpr size_t kTipCount = sizeof(kTips) / sizeof(kTips[0]);- if (!launchingStartMs_) launchingStartMs_ = nowMs;- uint64_t elapsedMs = nowMs >= launchingStartMs_ ? (nowMs - launchingStartMs_) : 0;- size_t tipIndex = (elapsedMs / 10000) % kTipCount;- drawCentered(c, fonts_.regular, tr(kTips[tipIndex]), 900, 22, kDim);- drawHints(c, {{kIconCircle, tr(Str::Cancel)}});-}--void AppUi::drawError(Canvas& c) {- drawBackground(c);- int panelW = errorUrl_.empty() ? 1040 : 1300;- int maxTextW = errorUrl_.empty() ? (panelW - 112) : (panelW - 460);- auto lines = fonts_.regular.wrap(error_, 26, maxTextW, 8);- int h = 132 + static_cast<int>(lines.size()) * 38 + 56;- if (!errorUrl_.empty() && h < 460) h = 460;- Rect panel{(kW - panelW) / 2, (kH - h) / 2 - 40, panelW, h};- c.fillRect(panel, kPanel, 24);- fonts_.bold.draw(c, tr(Str::ErrorTitle), panel.x + 56, panel.y + 52, 44, kWhite);- int y = panel.y + 132;- for (const auto& line : lines) {- fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);- y += 38;- }- if (!errorUrl_.empty()) {- y += 16;- for (const auto& line : fonts_.regular.wrap(tr(Str::ScanQrToResolve), 24, maxTextW, 4)) {- fonts_.regular.draw(c, line, panel.x + 56, y, 24, rgba(220, 220, 255));- y += 34;- }- drawQr(c, errorUrl_, panel.x + panel.w - 56, panel.y + 56, 320, qrcodegen_Ecc_LOW);- }- if (!errorGame_.titleId.empty() || !errorGame_.productId.empty()) {- bool free = (isFreeGame(errorGame_) || errorGame_.freeInStore) && !errorGame_.playable;- const char* acceptLabel = free ? tr(Str::ClaimFree) : tr(Str::TryAgain);- drawHints(c, {{kIconCross, acceptLabel}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});- }- else if (regionRefused_)- drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconSquare, tr(Str::TryOtherCountry)},- {kIconOptions, tr(Str::Settings)}, {kIconTriangle, tr(Str::ReportProblem)},- {kIconTouchpad, tr(Str::HoldSignOut)}});- else if (!rows_.empty() || !owned_.empty())- drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconSquare, tr(Str::OfflineMode)},- {kIconTriangle, tr(Str::ReportProblem)}, {kIconTouchpad, tr(Str::HoldSignOut)}});- else- drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconTriangle, tr(Str::ReportProblem)},- {kIconTouchpad, tr(Str::HoldSignOut)}});-}--void AppUi::drawSettings(Canvas& c) {- drawBackground(c);- drawTopBar(c);- fonts_.bold.draw(c, tr(Str::Settings), kMargin, 134, 46, kWhite);- const char* labels[kSettingRows] = {tr(Str::Language), tr(Str::Resolution), tr(Str::Region),- tr(Str::Deadzone), tr(Str::TriggerRumble), tr(Str::ConfirmButton),- tr(Str::LightBar), tr(Str::Updates), tr(Str::LoginCountry),- tr(Str::HighRefresh), tr(Str::BitrateCap), tr(Str::GameVolume),- tr(Str::KeyboardKeys), tr(Str::DisplayMode), tr(Str::ControllerButtons),- tr(Str::Gyro), tr(Str::QueueReadyNotification),- tr(Str::CheckSignIn), tr(Str::NetworkTest), tr(Str::SupportProject),- tr(Str::VideoDecoder), tr(Str::AudioHaptics), tr(Str::TouchpadShortcuts),- tr(Str::ResetSettings)};- constexpr int kRowW = 1140, kRowH = 32, kGap = 2, kGroupGap = 5, kRowPx = 22;- Rect rows[kSettingRows]; // by row id- int y = 184;- for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) { // what caps_ rules out is hidden- if (groupStart) y += kGroupGap;- Rect r{kMargin, y, kRowW, kRowH};- rows[i] = r;- bool focused = i == settingsRow_;- int ty = fonts_.semibold.centeredY(r.y, r.h, kRowPx);-- if (i == 23) {- // Restore factory defaults button: red background- Color redBg = focused ? rgba(220, 38, 38, 255) : rgba(185, 28, 28, 220);- c.fillRect(r, redBg, 12);- if (focused && !dropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 3, 16);-- // Progress fill animation when holding Cross/accept- if (focused && resetSettingsHoldStart_ > 0) {- uint64_t elapsed = (lastRender_ > resetSettingsHoldStart_) ? (lastRender_ - resetSettingsHoldStart_) : 0;- float progress = std::min(1.0f, static_cast<float>(elapsed) / 5000.0f);- int fillW = static_cast<int>(r.w * progress);- if (fillW > 0) {- c.fillRect({r.x, r.y, fillW, r.h}, rgba(255, 255, 255, 70), 12);- }- }- int textW = fonts_.bold.measure(labels[i], kRowPx);- int textX = r.x + (r.w - textW) / 2;- fonts_.bold.draw(c, labels[i], textX, ty, kRowPx, kWhite);- } else {- c.fillRect(r, focused ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 12);- if (focused && !dropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 3, 16);- fonts_.semibold.draw(c, labels[i], r.x + 32, ty, kRowPx, kWhite);- float cx = static_cast<float>(r.x + r.w - 40), cy = static_cast<float>(r.y + r.h / 2);- if (i != 7 && i != 17 && i != 18 && i != 19) {- c.line(cx - 8, cy - 3, cx, cy + 4, 2.5f, focused ? kWhite : kGray);- c.line(cx, cy + 4, cx + 8, cy - 3, 2.5f, focused ? kWhite : kGray);- }- int vx = r.x + r.w - 68;-- if (i == 7) {- // Updates: the state; Cross updates when there is a newer version.- std::string value = updateChecking_ ? tr(Str::UpdateChecking)- : !updateAvailable_.empty()- ? trf(caps_.selfUpdate ? Str::UpdateReady : Str::UpdateReadyPc, updateAvailable_)- : trf(Str::UpToDate, "v" + updateCurrent_);- Color color = !updateAvailable_.empty() && !updateChecking_ ? rgba(120, 220, 120) : focused ? kWhite : kGray;- int w = fonts_.regular.measure(value, kRowPx);- fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx, color);- } else if (i == 17 || i == 18 || i == 19) {- // Action items (Check sign-in, Network test, Support)- std::string label = (i == 17) ? tr(Str::RunCheck) : (i == 18) ? tr(Str::RunTest) : tr(Str::SupportKoFi);- int w = fonts_.regular.measure(label, kRowPx);- fonts_.regular.draw(c, label, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx,- focused ? kWhite : kGray);- } else if (i == 5) {- // The confirm button, as the button itself.- drawFaceButton(c, fonts_.bold, settings_.circleConfirms ? kIconCircle : kIconCross, vx - 16.0f, cy, 16);- } else {- auto options = settingOptions(i);- int sel = settingSelected(i);- std::string value = sel < static_cast<int>(options.size()) ? options[static_cast<size_t>(sel)] : "";- int w = fonts_.regular.measure(value, kRowPx);- fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx, focused ? kWhite : kGray);- if (i == 6 && settings_.lightBarMode == 1) { // the colour chosen- c.fillCircle(vx - w - 26.0f, cy, 11, settings_.lightBarColour);- c.strokeArc(vx - w - 26.0f, cy, 11, 2, 0, 6.2832f, rgba(255, 255, 255, 120));- }- }- }- y += kRowH + kGap;- }- static constexpr Str kSettingDescs[kSettingRows] = {- Str::SettingDescLanguage,- Str::SettingDescResolution,- Str::SettingDescRegion,- Str::SettingDescDeadzone,- Str::SettingDescTriggerRumble,- Str::SettingDescConfirmButton,- Str::SettingDescLightBar,- Str::SettingDescUpdates,- Str::SettingDescLoginCountry,- Str::SettingDescHighRefresh,- Str::SettingDescBitrateCap,- Str::SettingDescGameVolume,- Str::SettingDescKeyboardKeys,- Str::SettingDescDisplayMode,- Str::SettingDescControllerButtons,- Str::SettingDescGyro,- Str::SettingDescQueueReady,- Str::SettingDescCheckSignIn,- Str::SettingDescNetworkTest,- Str::SettingDescSupportProject,- Str::SettingDescVideoDecoder,- Str::SettingDescAudioHaptics,- Str::SettingDescTouchpadShortcuts,- Str::SettingDescResetSettings,- };- if (settingsRow_ >= 0 && settingsRow_ < kSettingRows) {- int dy = 925;- const char* desc = tr(kSettingDescs[settingsRow_]);- for (const auto& line : fonts_.regular.wrap(desc, 22, kRowW, 3)) {- fonts_.regular.draw(c, line, kMargin, dy, 22, kDim);- dy += 26;- }- }-- // Web UI / Remote QR panel on the right side (x = 1310..1850)- if (tester_ == Tester::None && !pickerOpen_) {- std::string qrUrl = !webUrl_.empty() ? webUrl_ : "http://" + platform::localIPv4() + ":8080";- Rect panel{1310, 184, 540, 724};- c.fillRect(panel, rgba(255, 255, 255, 14), 16);- c.strokeRect(panel, rgba(255, 255, 255, 30), 1, 16);-- int py = panel.y + 30;- int titleW = fonts_.bold.measure(tr(Str::WebControlTitle), 28);- fonts_.bold.draw(c, tr(Str::WebControlTitle), panel.x + (panel.w - titleW) / 2, py, 28, kWhite);- py += 40;-- auto descLines = fonts_.regular.wrap(tr(Str::WebControlDesc), 17, panel.w - 56, 5);- for (const auto& l : descLines) {- int lw = fonts_.regular.measure(l, 17);- fonts_.regular.draw(c, l, panel.x + (panel.w - lw) / 2, py, 17, kGray);- py += 22;- }-- uint8_t qrBuf[qrcodegen_BUFFER_LEN_MAX], tmpBuf[qrcodegen_BUFFER_LEN_MAX];- int qrTarget = 260;- int qrCardW = 300;- if (qrcodegen_encodeText(qrUrl.c_str(), tmpBuf, qrBuf, qrcodegen_Ecc_LOW, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {- int n = qrcodegen_getSize(qrBuf);- int mod = qrTarget / (n + 2);- qrCardW = mod * (n + 2) + 40;- }- int qrRight = panel.x + (panel.w + qrCardW) / 2;-- Rect pill{panel.x + 36, panel.y + panel.h - 42 - 18, panel.w - 72, 42};-- // Center QR vertically in available space between py and pill.y- int availH = pill.y - py;- int qrTop = py + (availH - qrCardW) / 2;- drawQr(c, qrUrl, qrRight, qrTop, qrTarget, qrcodegen_Ecc_LOW);-- c.fillRect(pill, rgba(0, 0, 0, 70), 12);- c.strokeRect(pill, rgba(255, 255, 255, 30), 1, 12);-- int urlW = fonts_.semibold.measure(qrUrl, 20);- fonts_.semibold.draw(c, qrUrl, pill.x + (pill.w - urlW) / 2, fonts_.semibold.centeredY(pill.y, pill.h, 20), 20, rgba(140, 230, 160));- }-- if (pickerOpen_) {- drawColourPicker(c);- return;- }- if (tester_ == Tester::Sticks) return drawStickTester(c);- if (tester_ == Tester::Triggers) return drawTriggerTester(c);- if (tester_ == Tester::Keys) return drawKeysTester(c);- if (tester_ == Tester::Pad) return drawPadTester(c);- if (tester_ == Tester::Touchpad) return drawTouchpadTester(c);- if (tester_ == Tester::SignInCheck) return drawSignInCheck(c, lastRender_);- if (tester_ == Tester::NetworkTest) return drawNetworkTest(c, lastRender_);- if (tester_ == Tester::Donation) return drawDonationModal(c);- if (dropdownOpen_) {- // The list under (or, near the bottom, over) the row, right-aligned- // with it; scrolls past kVisible choices.- auto options = settingOptions(settingsRow_);- int sel = settingSelected(settingsRow_);- constexpr int kItemH = 62, kVisible = 8, kListW = 640;- int n = static_cast<int>(options.size());- int visible = std::min(n, kVisible);- if (dropdownIndex_ < dropdownTop_) dropdownTop_ = dropdownIndex_;- if (dropdownIndex_ >= dropdownTop_ + visible) dropdownTop_ = dropdownIndex_ - visible + 1;- const Rect& row = rows[settingsRow_];- Rect panel{row.x + row.w - kListW, row.y + row.h + 8, kListW, visible * kItemH + 16};- if (panel.y + panel.h > kH - 100) panel.y = std::max(120, kH - 100 - panel.h);- c.fillRect({panel.x + 6, panel.y + 10, panel.w, panel.h}, rgba(0, 0, 0, 120), 18); // shadow- c.fillRect(panel, rgba(38, 38, 38), 18);- c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 18);- for (int k = 0; k < visible; ++k) {- int i = dropdownTop_ + k;- Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};- bool on = i == dropdownIndex_;- if (on) c.fillRect(item, kWhite, 12);- Color text = on ? kBg : (i == sel ? kWhite : kGray);- if (settingsRow_ == 5)- drawFaceButton(c, fonts_.bold, i == 1 ? kIconCircle : kIconCross, item.x + 44.0f, item.y + item.h / 2.0f, 20);- else- fonts_.semibold.draw(c, options[static_cast<size_t>(i)], item.x + 24,- fonts_.semibold.centeredY(item.y, item.h, 26), 26, text);- if (settingsRow_ == 6 && i == 1)- c.fillCircle(item.x + item.w - 84.0f, item.y + item.h / 2.0f, 12, settings_.lightBarColour);- if (i == sel) { // a check mark on the current choice- float cx = static_cast<float>(item.x + item.w - 36), cy = static_cast<float>(item.y + item.h / 2);- c.line(cx - 10, cy, cx - 3, cy + 7, 3, on ? kBg : kGreen);- c.line(cx - 3, cy + 7, cx + 10, cy - 7, 3, on ? kBg : kGreen);- }- }- // Scroll hints: more choices above / below.- if (dropdownTop_ > 0) {- float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y - 14);- c.line(cx - 10, cy + 4, cx, cy - 4, 3, kGray);- c.line(cx, cy - 4, cx + 10, cy + 4, 3, kGray);- }- if (dropdownTop_ + visible < n) {- float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y + panel.h + 14);- c.line(cx - 10, cy - 4, cx, cy + 4, 3, kGray);- c.line(cx, cy + 4, cx + 10, cy - 4, 3, kGray);- }- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});- } else {- if (settingsRow_ == 23) {- drawHints(c, {{kIconCross, tr(Str::HoldToReset)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});- } else if (settingsRow_ == 16) {- drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconSquare, tr(Str::TestSound)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});- } else if (settingsRow_ == 10) {- drawHints(c, {{kIconDpadLR, tr(Str::Adjust)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});- } else {- drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});- }- }-}--void AppUi::drawReport(Canvas& c) {- // A panel over the screen: the heading and what the QR code does on the- // left, the code on the right (dense: about 1.8 KB, so large).- c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 170));- constexpr int kPanelW = 1500, kPanelH = 720;- Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 30, kPanelW, kPanelH};- c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26);- c.fillRect(panel, kPanel, 24);- c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);- Rect qr = drawQr(c, reportUrl_, panel.x + panel.w - 48, panel.y + 48, 600, qrcodegen_Ecc_LOW);- int textW = (qr.w ? qr.x : panel.x + panel.w) - panel.x - 112;- int y = panel.y + 56;- for (const auto& line : fonts_.bold.wrap(reportHeading_, 40, textW, 3)) {- fonts_.bold.draw(c, line, panel.x + 56, y, 40, kWhite);- y += 54;- }- y += 24;- for (Str s : {Str::ReportScan, Str::ReportIncludes}) {- for (const auto& line : fonts_.regular.wrap(tr(s), 26, textW, 4)) {- fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);- y += 38;- }- y += 20;- }- if (!reportDetail_.empty()) {- y += 8;- for (const auto& line : fonts_.regular.wrap(reportDetail_, 22, textW, 3)) {- fonts_.regular.draw(c, line, panel.x + 56, y, 22, kWhite);- y += 32;- }- }- c.fillRect({0, kH - 80, kW, 80}, kBg);- if (caps_.openUrl) // a desktop: Cross opens the form in the browser- drawHints(c, {{kIconCross, tr(Str::OpenInBrowser)}, {kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCircle, tr(Str::Back)}});-}--void AppUi::drawCountryPicker(Canvas& c) {- // Over the refused sign-in: the warning, then the countries.- constexpr int kPanelW = 1100, kItemH = 58;- auto warning = fonts_.regular.wrap(tr(Str::LoginCountryWarning), 26, kPanelW - 112, 6);- int n = 1 + static_cast<int>(std::size(kLoginCountries));- int listY = 124 + static_cast<int>(warning.size()) * 36 + 24;- Rect panel = drawModal(c, kPanelW, listY + n * kItemH + 40, tr(Str::TryOtherCountry));- int y = panel.y + 124;- for (const auto& line : warning) {- fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);- y += 36;- }- int sel = settingSelected(8);- for (int i = 0; i < n; ++i) {- Rect item{panel.x + 48, panel.y + listY + i * kItemH, panel.w - 96, kItemH};- bool on = i == countryIndex_;- if (on) c.fillRect(item, kWhite, 12);- std::string label = i ? loginCountryName(kLoginCountries[i - 1]) : loginCountryOffText();- fonts_.semibold.draw(c, label, item.x + 24, fonts_.semibold.centeredY(item.y, item.h, 26), 26,- on ? kBg : (i == sel ? kWhite : kGray));- if (i == sel) { // a check mark on the current choice- float cx = static_cast<float>(item.x + item.w - 36), cy = static_cast<float>(item.y + item.h / 2);- c.line(cx - 10, cy, cx - 3, cy + 7, 3, on ? kBg : kGreen);- c.line(cx - 3, cy + 7, cx + 10, cy - 7, 3, on ? kBg : kGreen);- }- }-}--void AppUi::drawQuitPrompt(Canvas& c) {- // As the update pop-up: the question, then Close and Cancel as buttons.- constexpr int kButtonW = 300, kButtonH = 72, kPanelW = 2 * kButtonW + 24 + 112, kPanelH = 250;- Rect panel = drawModal(c, kPanelW, kPanelH, tr(Str::QuitTitle));- const char* labels[2] = {tr(Str::QuitConfirm), tr(Str::Cancel)};- for (int i = 0; i < 2; ++i) {- Rect b{panel.x + 56 + i * (kButtonW + 24), panel.y + panel.h - kButtonH - 44, kButtonW, kButtonH};- bool on = i == promptFocus_;- c.fillRect(b, on ? kWhite : rgba(255, 255, 255, 30), 14);- int tw = fonts_.semibold.measure(labels[i], 28);- fonts_.semibold.draw(c, labels[i], b.x + (b.w - tw) / 2, fonts_.semibold.centeredY(b.y, b.h, 28), 28,- on ? kBg : kWhite);- }- c.fillRect({0, kH - 80, kW, 80}, kBg); // its own hints over drawModal's- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Cancel)}});-}--void AppUi::drawUpdatePrompt(Canvas& c) {- c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));- constexpr int kPanelW = 960, kPanelH = 340, kButtonW = 260, kButtonH = 72;- Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 40, kPanelW, kPanelH};- c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow- c.fillRect(panel, kPanel, 24);- c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);- fonts_.bold.draw(c, trf(Str::UpdateAvailable, updateAvailable_), panel.x + 56, panel.y + 48, 44, kWhite);- auto lines = fonts_.regular.wrap(tr(Str::UpdatePrompt), 26, kPanelW - 112, 2);- for (size_t i = 0; i < lines.size(); ++i)- fonts_.regular.draw(c, lines[i], panel.x + 56, panel.y + 124 + static_cast<int>(i) * 36, 26, kGray);-- // 3 buttons: Update now (0), What's new (1), Not now (2)- const char* labels[3] = {tr(Str::UpdateNow), tr(Str::WhatsNew), tr(Str::NotNow)};- constexpr int kGap = (kPanelW - 112 - 3 * kButtonW) / 2;- for (int i = 0; i < 3; ++i) {- Rect b{panel.x + 56 + i * (kButtonW + kGap), panel.y + panel.h - kButtonH - 44, kButtonW, kButtonH};- bool on = i == promptFocus_;- c.fillRect(b, on ? kWhite : rgba(255, 255, 255, 30), 14);- int tw = fonts_.semibold.measure(labels[i], 24);- fonts_.semibold.draw(c, labels[i], b.x + (b.w - tw) / 2, fonts_.semibold.centeredY(b.y, b.h, 24), 24,- on ? kBg : kWhite);- }- c.fillRect({0, kH - 80, kW, 80}, kBg); // the home screen's hints, under the pop-up's- drawPads(c);- drawHints(c, {- {kIconCross, tr(Str::Select)},- {kIconSquare, tr(Str::WhatsNew)},- {kIconCircle, tr(Str::NotNow)}- });-}--void AppUi::formatUpdateNotes() {- updateNotesLines_.clear();- std::string lang = languageCode(language());- updateNotesLang_ = lang;- std::string raw = xc::app::filterReleaseNotes(updateNotes_, lang);- if (raw.empty()) raw = updateNotes_;- if (raw.empty()) raw = "No release notes provided.";-- constexpr int kModalW = 1200, kModalH = 740;- int textW = kModalW - 128 - 28;- int textH = kModalH - 175;-- size_t pos = 0;- while (pos < raw.size()) {- size_t next = raw.find('\n', pos);- std::string rawLine = raw.substr(pos, next == std::string::npos ? std::string::npos : next - pos);- if (!rawLine.empty() && rawLine.back() == '\r') rawLine.pop_back();-- if (rawLine.rfind("### ", 0) == 0) {- std::string sub = rawLine.substr(4);- auto wrapped = fonts_.semibold.wrap(sub, 22, textW, 4);- for (const auto& w : wrapped) updateNotesLines_.push_back({w, false, true, false, false});- } else if (rawLine.rfind("## ", 0) == 0) {- std::string hdr = rawLine.substr(3);- auto wrapped = fonts_.bold.wrap(hdr, 26, textW, 4);- for (const auto& w : wrapped) updateNotesLines_.push_back({w, true, false, false, false});- } else if (rawLine.rfind("# ", 0) == 0) {- std::string hdr = rawLine.substr(2);- auto wrapped = fonts_.bold.wrap(hdr, 28, textW, 4);- for (const auto& w : wrapped) updateNotesLines_.push_back({w, true, false, false, false});- } else if (rawLine.rfind("- ", 0) == 0 || rawLine.rfind("* ", 0) == 0) {- std::string bullet = "• " + rawLine.substr(2);- auto wrapped = fonts_.regular.wrap(bullet, 22, textW, 6);- for (size_t wi = 0; wi < wrapped.size(); ++wi) {- updateNotesLines_.push_back({wrapped[wi], false, false, wi == 0, wi > 0});- }- } else if (!rawLine.empty()) {- auto wrapped = fonts_.regular.wrap(rawLine, 22, textW, 8);- for (const auto& w : wrapped) updateNotesLines_.push_back({w, false, false, false, false});- } else {- updateNotesLines_.push_back({"", false, false, false, false});- }-- if (next == std::string::npos) break;- pos = next + 1;- }-- constexpr int kLineH = 32;- int visibleLines = textH / kLineH;- int totalLines = static_cast<int>(updateNotesLines_.size());- updateNotesMaxScroll_ = std::max(0, totalLines - visibleLines);- updateNotesScroll_ = std::clamp(updateNotesScroll_, 0, updateNotesMaxScroll_);-}--void AppUi::drawUpdateNotesModal(Canvas& c) {- std::string currentLang = languageCode(language());- if (updateNotesLines_.empty() || updateNotesLang_ != currentLang) {- formatUpdateNotes();- }-- std::string title = tr(Str::WhatsNewTitle);- if (!updateAvailable_.empty()) {- title += " - " + updateAvailable_;- }- constexpr int kModalW = 1200, kModalH = 740;- Rect panel = drawModal(c, kModalW, kModalH, title);-- int textX = panel.x + 64;- int textY = panel.y + 115;- int textH = panel.h - 175;-- constexpr int kLineH = 32;- int visibleLines = textH / kLineH;- int totalLines = static_cast<int>(updateNotesLines_.size());- updateNotesScroll_ = std::clamp(updateNotesScroll_, 0, updateNotesMaxScroll_);-- c.fillRect({panel.x + 44, textY - 12, panel.w - 88, textH + 24}, rgba(18, 18, 18, 220), 12);- c.strokeRect({panel.x + 44, textY - 12, panel.w - 88, textH + 24}, rgba(255, 255, 255, 25), 1, 12);-- int curY = textY;- int endIdx = std::min(totalLines, updateNotesScroll_ + visibleLines);- for (int i = updateNotesScroll_; i < endIdx; ++i) {- const auto& fl = updateNotesLines_[static_cast<size_t>(i)];- if (!fl.text.empty()) {- if (fl.isHeader) {- fonts_.bold.draw(c, fl.text, textX, curY, 26, kWhite);- } else if (fl.isSubHeader) {- fonts_.semibold.draw(c, fl.text, textX, curY, 22, rgba(120, 220, 120));- } else if (fl.isBullet) {- fonts_.regular.draw(c, fl.text, textX + 6, curY, 22, rgba(235, 235, 235));- } else if (fl.isBulletContinuation) {- fonts_.regular.draw(c, fl.text, textX + 28, curY, 22, rgba(235, 235, 235));- } else {- fonts_.regular.draw(c, fl.text, textX, curY, 22, kGray);- }- }- curY += kLineH;- }-- if (totalLines > visibleLines) {- int barTrackX = panel.x + panel.w - 60;- int barTrackY = textY - 4;- int barTrackH = textH + 8;- c.fillRect({barTrackX, barTrackY, 6, barTrackH}, rgba(255, 255, 255, 30), 3);- float ratio = static_cast<float>(visibleLines) / totalLines;- int thumbH = std::max(32, static_cast<int>(barTrackH * ratio));- float scrollPct = updateNotesMaxScroll_ > 0 ? static_cast<float>(updateNotesScroll_) / updateNotesMaxScroll_ : 0.0f;- int thumbY = barTrackY + static_cast<int>((barTrackH - thumbH) * scrollPct);- c.fillRect({barTrackX, thumbY, 6, thumbH}, kWhite, 3);- }-- c.fillRect({0, kH - 80, kW, 80}, kBg);- drawPads(c);- drawHints(c, {- {kIconCircle, tr(Str::Back)}- });-}--Rect AppUi::drawModal(Canvas& c, int w, int h, const std::string& title) {- c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));- Rect panel{(kW - w) / 2, (kH - h) / 2 - 30, w, h};- c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow- c.fillRect(panel, kPanel, 24);- c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);- fonts_.bold.draw(c, title, panel.x + 56, panel.y + 44, 40, kWhite);- c.fillRect({0, kH - 80, kW, 80}, kBg); // Settings' hints, under the panel's- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});- return panel;-}--void AppUi::drawStickTester(Canvas& c) {- Rect panel = drawModal(c, 1240, 740, tr(Str::Deadzone));- constexpr int R = 180;- const Color raw = rgba(170, 170, 170), game = rgba(90, 220, 110);- for (int s = 0; s < 2; ++s) {- const float dz = settings_.deadzone[s] / 100.0f;- const bool chosen = s == testerStick_;- const float cx = panel.x + (s ? 930.0f : 310.0f), cy = panel.y + 170.0f + R;- // Its dead zone above it, in white on the stick being adjusted.- std::string value = std::to_string(settings_.deadzone[s]) + " %";- fonts_.bold.draw(c, value, static_cast<int>(cx) - fonts_.bold.measure(value, 34) / 2, static_cast<int>(cy) - R - 56, 34,- chosen ? kWhite : kDim);- c.fillCircle(cx, cy, R, rgba(255, 255, 255, chosen ? 22 : 10));- c.line(cx - R, cy, cx + R, cy, 1, rgba(255, 255, 255, 30));- c.line(cx, cy - R, cx, cy + R, 1, rgba(255, 255, 255, 30));- c.strokeArc(cx, cy, R, chosen ? 4.0f : 2.0f, 0, 6.2832f, chosen ? kWhite : rgba(255, 255, 255, 70));- // The dead zone: nothing reaches the game in there.- if (dz > 0) {- c.fillCircle(cx, cy, dz * R, rgba(230, 70, 70, 60));- c.strokeArc(cx, cy, dz * R, 2, 0, 6.2832f, rgba(230, 90, 90, 180));- }- float x = testSticks_[2 * s], y = testSticks_[2 * s + 1], gx = x, gy = y;- input::radialDeadzone(gx, gy, dz);- c.fillCircle(cx + x * R, cy + y * R, 9, raw);- c.fillCircle(cx + gx * R, cy + gy * R, 12, game);- const char* name = tr(s ? Str::StickRight : Str::StickLeft);- fonts_.semibold.draw(c, name, static_cast<int>(cx) - fonts_.semibold.measure(name, 26) / 2, static_cast<int>(cy) + R + 22,- 26, kWhite);- // How far each one is, in percent of the travel.- auto pct = [](float a, float b) { return std::to_string(static_cast<int>(std::lround(std::min(1.0f, std::hypot(a, b)) * 100))) + " %"; };- std::string line = pct(x, y) + " \xE2\x86\x92 " + pct(gx, gy);- int tw = fonts_.regular.measure(line, 24);- fonts_.regular.draw(c, line, static_cast<int>(cx) - tw / 2, static_cast<int>(cy) + R + 58, 24, kGray);- }- // The legend, then the help.- int ly = panel.y + panel.h - 92, lx = panel.x + 56;- c.fillCircle(lx + 9.0f, ly + 13.0f, 9, raw);- fonts_.regular.draw(c, tr(Str::StickPosition), lx + 28, ly, 24, kGray);- lx += 28 + fonts_.regular.measure(tr(Str::StickPosition), 24) + 48;- c.fillCircle(lx + 12.0f, ly + 13.0f, 12, game);- fonts_.regular.draw(c, tr(Str::StickGameGets), lx + 32, ly, 24, kGray);- fonts_.regular.draw(c, tr(Str::StickTestHelp), panel.x + 56, ly + 44, 22, kDim);-}--void AppUi::drawTriggerTester(Canvas& c) {- // Without adaptive triggers, no resistance, style or profile rows: the panel shorter by them.- const int rows = triggerTesterRows(), lessY = (5 - rows) * 84;- Rect panel = drawModal(c, 1100, 890 - lessY, tr(Str::TriggerRumble));- // The choices, as Settings' rows: up / down picks one, left / right changes it.- const char* strengths[] = {tr(Str::Deactivated), tr(Str::TriggerLight), tr(Str::TriggerMedium), tr(Str::TriggerStrong),- tr(Str::TriggerMax)};- const char* freqs[] = {tr(Str::FrequencyLow), tr(Str::TriggerMedium), tr(Str::FrequencyHigh)};- static constexpr Str kProfileStrs[] = {Str::TriggerProfileStd, Str::TriggerProfileShooter, Str::TriggerProfileRacing};- const char* labels[] = {tr(Str::TriggerIntensity), tr(Str::TriggerFrequency), tr(Str::TriggerResistance),- tr(Str::TriggerStyle), tr(Str::TriggerProfile)};- // Pulses go at their own, slower rates.- int hz = settings_.triggerPulses ? input::kTriggerPulseHz[settings_.triggerHz] : input::kTriggerHz[settings_.triggerHz];- int prof = std::clamp(settings_.triggerProfile, 0, 2);- const std::string values[] = {strengths[settings_.triggerStrength],- std::string(freqs[settings_.triggerHz]) + " (" + std::to_string(hz) + " Hz)",- strengths[settings_.triggerResistance], // off, light, medium, strong- tr(settings_.triggerPulses ? Str::StylePulses : Str::StyleVibration),- tr(kProfileStrs[prof])};- for (int i = 0; i < rows; ++i) {- Rect r{panel.x + 56, panel.y + 120 + i * 84, panel.w - 112, 70};- bool on = i == testerRow_;- c.fillRect(r, on ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 16);- if (on) c.strokeRect({r.x - 5, r.y - 5, r.w + 10, r.h + 10}, kWhite, 3, 20);- fonts_.semibold.draw(c, labels[i], r.x + 36, fonts_.semibold.centeredY(r.y, r.h, 30), 30, kWhite);- std::string v = "\xE2\x80\xB9 " + values[i] + " \xE2\x80\xBA"; // ‹ value ›- int w = fonts_.regular.measure(v, 30);- fonts_.regular.draw(c, v, r.x + r.w - 36 - w, fonts_.regular.centeredY(r.y, r.h, 30), 30, on ? kWhite : kGray);- }- // L2 and R2: how far each is pressed, and the level it sends to the trigger.- const float pressed[2] = {testL2_, testR2_};- for (int t = 0; t < 2; ++t) {- constexpr int kBarW = 90, kBarH = 150;- int bx = panel.x + panel.w / 2 + (t ? 80 : -80 - kBarW), by = panel.y + 560 - lessY;- c.fillRect({bx, by, kBarW, kBarH}, rgba(255, 255, 255, 20), 16);- int fill = static_cast<int>(kBarH * std::clamp(pressed[t], 0.0f, 1.0f));- int level = input::triggerAmplitude(static_cast<uint8_t>(std::lround(pressed[t] * 255)), settings_.triggerStrength);- if (fill > 0) c.fillRect({bx, by + kBarH - fill, kBarW, fill}, level ? rgba(90, 220, 110) : rgba(120, 120, 120), 16);- std::string name = buttonName(g_glyphStyle, t ? PadButton::R2 : PadButton::L2);- fonts_.bold.draw(c, name, bx + (kBarW - fonts_.bold.measure(name, 26)) / 2, by + kBarH + 14, 26, kWhite);- std::string lv = trf(Str::TriggerLevel, std::to_string(level) + " / 8");- fonts_.regular.draw(c, lv, bx + (kBarW - fonts_.regular.measure(lv, 22)) / 2, by + kBarH + 48, 22, kGray);- }- auto help = fonts_.regular.wrap(tr(Str::TriggerTestHelp), 22, panel.w - 112, 2);- for (size_t i = 0; i < help.size(); ++i)- fonts_.regular.draw(c, help[i], panel.x + 56, panel.y + panel.h - 70 + static_cast<int>(i) * 30, 22, kDim);-}--void AppUi::drawPadTester(Canvas& c) {- Rect panel = drawModal(c, 1500, 860, tr(Str::ControllerButtons));-- // Top tab selector: [ Botões ] [ Touchpad ]- if (caps_.touchpad) {- int tabW = 280, tabH = 38, tabGap = 20;- int totalTabsW = 2 * tabW + tabGap;- int tabStartX = panel.x + (panel.w - totalTabsW) / 2;- int tabY = panel.y + 60;-- auto shoulder = [&](const char* name, int cx) {- Rect r{cx - 22, tabY + 5, 44, 28};- c.fillRect(r, rgba(255, 255, 255, 40), 8);- fonts_.bold.draw(c, name, cx - fonts_.bold.measure(name, 16) / 2, fonts_.bold.centeredY(r.y, r.h, 16), 16, kGray);- };- shoulder(g_keyboardHints ? "Q" : buttonName(g_glyphStyle, PadButton::L1), tabStartX - 32);-- for (int t = 0; t < 2; ++t) {- Rect trRect{tabStartX + t * (tabW + tabGap), tabY, tabW, tabH};- bool active = (padTesterTab_ == t);- c.fillRect(trRect, active ? rgba(255, 255, 255, 40) : rgba(255, 255, 255, 14), 12);- if (active) c.strokeRect(trRect, kWhite, 2, 12);- const char* tabLabel = t == 0 ? tr(Str::ControllerButtons) : tr(Str::TouchpadShortcuts);- int tw = fonts_.semibold.measure(tabLabel, 22);- fonts_.semibold.draw(c, tabLabel, trRect.x + (trRect.w - tw) / 2,- fonts_.semibold.centeredY(trRect.y, trRect.h, 22), 22, active ? kWhite : kGray);- }-- shoulder(g_keyboardHints ? "E" : buttonName(g_glyphStyle, PadButton::R1), tabStartX + totalTabsW + 32);- }-- if (padTesterTab_ == 1) {- constexpr int kTouchRowH = 56, kTouchGap = 8;- const input::TouchpadAction vals[6] = {- touchpadWork_.swipeUp, touchpadWork_.swipeDown,- touchpadWork_.swipeLeft, touchpadWork_.swipeRight,- touchpadWork_.clickLeft, touchpadWork_.clickRight,- };- int y = panel.y + 116;- for (int i = 0; i < 6; ++i) {- Rect r{panel.x + 80, y, panel.w - 160, kTouchRowH};- bool on = (touchpadRow_ == i);- c.fillRect(r, on ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);- if (on && !touchpadDropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 2, 18);- int ty = fonts_.semibold.centeredY(r.y, r.h, 26);- fonts_.semibold.draw(c, touchpadTriggerLabel(i), r.x + 32, ty, 26, kWhite);-- float cx = static_cast<float>(r.x + r.w - 40), cy = static_cast<float>(r.y + r.h / 2);- c.line(cx - 8, cy - 3, cx, cy + 4, 2.5f, on ? kWhite : kGray);- c.line(cx, cy + 4, cx + 8, cy - 3, 2.5f, on ? kWhite : kGray);-- std::string val = touchpadActionLabel(static_cast<int>(vals[i]));- int vw = fonts_.regular.measure(val, 26);- int vx = r.x + r.w - 68;- fonts_.regular.draw(c, val, vx - vw, fonts_.regular.centeredY(r.y, r.h, 26), 26, on ? kWhite : kGray);-- y += kTouchRowH + kTouchGap;- }-- Rect reset{panel.x + 80, y + 8, panel.w - 160, kTouchRowH};- bool resetOn = (touchpadRow_ == 6);- c.fillRect(reset, resetOn ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);- if (resetOn && !touchpadDropdownOpen_) c.strokeRect({reset.x - 4, reset.y - 4, reset.w + 8, reset.h + 8}, kWhite, 2, 18);- const char* resetLabel = tr(Str::ResetToDefault);- fonts_.semibold.draw(c, resetLabel, reset.x + (reset.w - fonts_.semibold.measure(resetLabel, 24)) / 2,- fonts_.semibold.centeredY(reset.y, reset.h, 24), 24, resetOn ? kWhite : rgba(240, 100, 100));-- int hy = reset.y + kTouchRowH + 22;- auto help = fonts_.regular.wrap(tr(Str::SettingDescTouchpadShortcuts), 22, panel.w - 160, 2);- for (size_t i = 0; i < help.size(); ++i)- fonts_.regular.draw(c, help[i], panel.x + 80, hy + static_cast<int>(i) * 28, 22, kDim);-- if (touchpadDropdownOpen_) {- constexpr int kListW = 500, kItemH = 46, kMaxVisible = 8;- constexpr int n = input::kTouchpadActions;- int visible = std::min(n, kMaxVisible);- int anchorY = panel.y + 116 + touchpadRow_ * (kTouchRowH + kTouchGap);- Rect dropPanel{panel.x + panel.w - 80 - kListW, anchorY + kTouchRowH + 6, kListW, visible * kItemH + 16};- if (dropPanel.y + dropPanel.h > kH - 100) dropPanel.y = std::max(120, anchorY - dropPanel.h - 6);- c.fillRect({dropPanel.x + 6, dropPanel.y + 10, dropPanel.w, dropPanel.h}, rgba(0, 0, 0, 160), 18);- c.fillRect(dropPanel, rgba(38, 38, 38), 18);- c.strokeRect(dropPanel, rgba(255, 255, 255, 60), 2, 18);- int curAction = static_cast<int>(touchpadWork_.get(touchpadRow_));- for (int k = 0; k < visible; ++k) {- int itemIdx = touchpadDropdownTop_ + k;- if (itemIdx >= n) break;- Rect item{dropPanel.x + 8, dropPanel.y + 8 + k * kItemH, dropPanel.w - 16, kItemH};- bool isFocused = (itemIdx == touchpadDropdownIndex_);- bool isSelected = (itemIdx == curAction);- if (isFocused) c.fillRect(item, kWhite, 12);- Color textCol = isFocused ? kBg : (isSelected ? kWhite : kGray);- std::string itemText = touchpadActionLabel(itemIdx);- fonts_.semibold.draw(c, itemText, item.x + 24, fonts_.semibold.centeredY(item.y, item.h, 24), 24, textCol);- if (isSelected) {- float markX = static_cast<float>(item.x + item.w - 36), markY = static_cast<float>(item.y + item.h / 2);- c.line(markX - 10, markY, markX - 3, markY + 7, 3, isFocused ? kBg : kGreen);- c.line(markX - 3, markY + 7, markX + 10, markY - 7, 3, isFocused ? kBg : kGreen);- }- }- if (touchpadDropdownTop_ > 0) {- float scx = static_cast<float>(dropPanel.x + dropPanel.w / 2), scy = static_cast<float>(dropPanel.y - 14);- c.line(scx - 10, scy + 4, scx, scy - 4, 3, kGray);- c.line(scx, scy - 4, scx + 10, scy + 4, 3, kGray);- }- if (touchpadDropdownTop_ + visible < n) {- float scx = static_cast<float>(dropPanel.x + dropPanel.w / 2), scy = static_cast<float>(dropPanel.y + dropPanel.h + 14);- c.line(scx - 10, scy - 4, scx, scy + 4, 3, kGray);- c.line(scx, scy + 4, scx + 10, scy - 4, 3, kGray);- }- }-- c.fillRect({0, kH - 80, kW, 80}, kBg);- if (touchpadDropdownOpen_)- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});- else if (resetOn)- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconSquare, tr(Str::ClearKey)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});- return;- }-- // Each Xbox button the game gets (as an Xbox pad shows it), then the- // button on this pad that plays it (in the pad's own glyphs). Left- // column the face buttons, shoulders and triggers; right the rest.- constexpr int kPerColumn = input::kPadFns / 2;- constexpr int kRowH = 52, kGap = 8, kChipW = 300, kColGap = 40;- constexpr const char* kArrows[4] = {" \xE2\x86\x91", " \xE2\x86\x93", " \xE2\x86\x90", " \xE2\x86\x92"};- static constexpr PadButton kButtons[12] = {PadButton::Cross, PadButton::Circle, PadButton::Square, PadButton::Triangle,- PadButton::L1, PadButton::R1, PadButton::L2, PadButton::R2,- PadButton::L3, PadButton::R3, PadButton::Touchpad, PadButton::Options};- const GlyphStyle style = g_glyphStyle;- const bool mapSwap = gameSettingsOpen_ ? activeGameProfile_.circleConfirms : settings_.circleConfirms;- const bool capturing = padCaptureSince_ != 0;- const std::string dpad = tr(Str::DPad);- // A button (a PadFn index) drawn at (x, cy), left-aligned, in `s`'s glyphs.- auto drawButton = [&](int i, GlyphStyle s, int x, int cy, Color color) {- const int ty = fonts_.semibold.centeredY(cy - kRowH / 2, kRowH, 24);- if (i >= 12) {- fonts_.semibold.draw(c, dpad + kArrows[i - 12], x, ty, 24, color);- } else if (i < 4) {- ui::drawFaceButton(c, fonts_.bold, s, kButtons[i], x + 16.0f, static_cast<float>(cy), 16);- if (s == GlyphStyle::PlayStation)- fonts_.semibold.draw(c, buttonName(s, kButtons[i]), x + 44, ty, 24, color);- } else {- fonts_.semibold.draw(c, buttonName(s, kButtons[i]), x, ty, 24, color);- }- };- const int colW = (panel.w - 112 - kColGap) / 2;- for (int f = 0; f < input::kPadFns; ++f) {- const int col = f / kPerColumn, row = f % kPerColumn;- Rect r{panel.x + 56 + col * (colW + kColGap), panel.y + 106 + row * (kRowH + kGap), colW, kRowH};- const bool on = row == padRow_ && col == padCol_;- const int cy = r.y + r.h / 2;- c.fillRect(r, on ? rgba(255, 255, 255, 30) : rgba(255, 255, 255, 12), 14);- if (on && !capturing) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 2, 18);- drawButton(f, GlyphStyle::Xbox, r.x + 22, cy, kWhite);- Rect chip{r.x + r.w - 10 - kChipW, r.y + 7, kChipW, r.h - 14};- fonts_.regular.draw(c, "\xE2\x86\x90", chip.x - 44, fonts_.regular.centeredY(r.y, r.h, 24), 24, kDim);- const uint8_t src = padWork_[static_cast<size_t>(f)];- const bool none = src >= input::kPadFns, changed = src != f;- c.fillRect(chip, none ? rgba(240, 100, 100, 40) : changed ? rgba(90, 170, 255, 60) : rgba(255, 255, 255, 26), 10);- if (on && capturing) {- c.strokeRect({chip.x - 4, chip.y - 4, chip.w + 8, chip.h + 8}, rgba(90, 220, 110), 3, 13);- fonts_.semibold.draw(c, "...", chip.x + 20, fonts_.semibold.centeredY(chip.y, chip.h, 24), 24, kWhite);- } else if (none) {- fonts_.semibold.draw(c, "\xE2\x80\x94", chip.x + 20, fonts_.semibold.centeredY(chip.y, chip.h, 24), 24,- rgba(240, 100, 100));- } else {- drawButton(input::physicalSource(src, mapSwap), style, chip.x + 16, cy, kWhite);- }- }- // Reset to default and Discard changes, side by side under the columns.- const int by = panel.y + 106 + kPerColumn * (kRowH + kGap) + 8;- for (int col = 0; col < 2; ++col) {- Rect b{panel.x + 56 + col * (colW + kColGap), by, colW, kRowH};- const bool on = padRow_ == kPerColumn && padCol_ == col;- c.fillRect(b, on ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);- if (on) c.strokeRect({b.x - 4, b.y - 4, b.w + 8, b.h + 8}, kWhite, 2, 18);- const char* label = tr(col == 0 ? Str::ResetToDefault : Str::DiscardChanges);- fonts_.semibold.draw(c, label, b.x + (b.w - fonts_.semibold.measure(label, 24)) / 2,- fonts_.semibold.centeredY(b.y, b.h, 24), 24, on ? kWhite : rgba(240, 100, 100));- }- // Waiting for a press: say for what. Else what's missing (Circle won't- // leave then), or the help.- int hy = by + kRowH + 34;- const uint32_t missing = input::padMapMissing(padWork_);- if (capturing) {- const auto fn = static_cast<input::PadFn>(padCol_ * kPerColumn + std::min(padRow_, kPerColumn - 1));- std::string ask = trf(Str::PadPressButton, input::padFnName(fn));- fonts_.bold.draw(c, ask, panel.x + (panel.w - fonts_.bold.measure(ask, 28)) / 2, hy, 28, kWhite);- } else if (missing || !input::padMapValid(padWork_)) {- std::string names;- for (int f = 0; f < input::kPadFns; ++f)- if (missing & (1u << f)) names += (names.empty() ? "" : ", ") + std::string(input::padFnName(static_cast<input::PadFn>(f)));- auto lines = fonts_.semibold.wrap(trf(Str::PadMissing, names), 24, panel.w - 112, 2);- for (size_t i = 0; i < lines.size(); ++i)- fonts_.semibold.draw(c, lines[i], panel.x + 56, hy + static_cast<int>(i) * 32, 24, rgba(240, 100, 100));- } else {- auto help = fonts_.regular.wrap(tr(Str::PadHelp), 22, panel.w - 112, 2);- for (size_t i = 0; i < help.size(); ++i)- fonts_.regular.draw(c, help[i], panel.x + 56, hy + static_cast<int>(i) * 30, 22, kDim);- }- c.fillRect({0, kH - 80, kW, 80}, kBg); // its own hints over drawModal's- if (capturing)- return;- if (padRow_ == kPerColumn)- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCross, tr(Str::ChangeKey)}, {kIconSquare, tr(Str::ClearKey)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});-}--void AppUi::drawTouchpadTester(Canvas& c) {- padTesterTab_ = 1;- drawPadTester(c);-}--void AppUi::drawSignInCheck(Canvas& c, uint64_t nowMs) {- Rect panel = drawModal(c, 1180, 620, tr(Str::CheckSignIn));- if (signInCheck_.running) {- drawSpinner(c, static_cast<float>(panel.x + panel.w - 76), static_cast<float>(panel.y + 64), 14.0f, nowMs);- animating_ = true;- }- int y = panel.y + 120;- constexpr int kRowH = 66, kGap = 10;- for (size_t i = 0; i < signInCheck_.stages.size() && i < 6; ++i) {- const auto& st = signInCheck_.stages[i];- Rect r{panel.x + 56, y, panel.w - 112, kRowH};- c.fillRect(r, rgba(255, 255, 255, 14), 14);- float cx = static_cast<float>(r.x + 36), cy = static_cast<float>(r.y + r.h / 2);- if (st.pending) {- drawSpinner(c, cx, cy, 12.0f, nowMs);- animating_ = true;- } else if (st.ok) {- c.fillCircle(cx, cy, 14.0f, kGreen);- c.line(cx - 6, cy, cx - 2, cy + 5, 2.5f, kWhite);- c.line(cx - 2, cy + 5, cx + 7, cy - 5, 2.5f, kWhite);- } else {- c.fillCircle(cx, cy, 14.0f, rgba(220, 65, 65));- c.line(cx - 5, cy - 5, cx + 5, cy + 5, 2.5f, kWhite);- c.line(cx - 5, cy + 5, cx + 5, cy - 5, 2.5f, kWhite);- }- int ty = fonts_.semibold.centeredY(r.y, r.h, 24);- fonts_.semibold.draw(c, st.name, r.x + 70, ty, 24, kWhite);- if (!st.detail.empty()) {- int maxW = r.w - 380;- std::string det = fonts_.regular.fit(st.detail, 22, maxW);- int dw = fonts_.regular.measure(det, 22);- Color detCol = st.pending ? kDim : (st.ok ? kGray : rgba(255, 130, 130));- fonts_.regular.draw(c, det, r.x + r.w - 28 - dw, fonts_.regular.centeredY(r.y, r.h, 22), 22, detCol);- }- y += kRowH + kGap;- }- c.fillRect({0, kH - 80, kW, 80}, kBg);- if (signInCheck_.running)- drawHints(c, {{kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconCircle, tr(Str::Back)}});-}--void AppUi::drawNetworkTest(Canvas& c, uint64_t nowMs) {- Rect panel = drawModal(c, 1180, 740, tr(Str::NetworkTest));- if (networkTest_.running) {- drawSpinner(c, static_cast<float>(panel.x + panel.w - 76), static_cast<float>(panel.y + 64), 14.0f, nowMs);- animating_ = true;- }- Rect natBox{panel.x + 56, panel.y + 114, panel.w - 112, 56};- c.fillRect(natBox, rgba(255, 255, 255, 18), 14);- fonts_.semibold.draw(c, "UDP / STUN (NAT)", natBox.x + 28, fonts_.semibold.centeredY(natBox.y, natBox.h, 24), 24, kWhite);- std::string natVal = networkTest_.natStatus.empty() ? "..." : networkTest_.natStatus;- int nw = fonts_.regular.measure(natVal, 24);- Color natCol = natVal.find("OK") != std::string::npos || natVal.find("Reachable") != std::string::npos- ? rgba(110, 225, 120)- : (networkTest_.running ? kDim : rgba(255, 180, 90));- fonts_.regular.draw(c, natVal, natBox.x + natBox.w - 28 - nw, fonts_.regular.centeredY(natBox.y, natBox.h, 24), 24, natCol);-- int y = panel.y + 188;- constexpr int kRowH = 54, kGap = 8;- for (size_t i = 0; i < networkTest_.regions.size() && i < 8; ++i) {- const auto& reg = networkTest_.regions[i];- Rect r{panel.x + 56, y, panel.w - 112, kRowH};- c.fillRect(r, i == 0 && reg.rttMs >= 0 ? rgba(16, 124, 16, 45) : rgba(255, 255, 255, 12), 12);- std::string label = prettyRegion(reg.name);- if (i == 0 && reg.rttMs >= 0) label += " \xE2\x98\x85";- fonts_.semibold.draw(c, label, r.x + 28, fonts_.semibold.centeredY(r.y, r.h, 24), 24, kWhite);- std::string val;- Color valCol = kDim;- if (reg.rttMs >= 0) {- val = "RTT " + std::to_string(reg.rttMs) + " ms \xC2\xB7 Jitter " +- std::to_string(std::max(0, reg.jitterMs)) + " ms";- valCol = reg.rttMs < 60 ? rgba(110, 225, 120) : (reg.rttMs < 120 ? rgba(255, 200, 80) : rgba(255, 120, 120));- } else {- val = networkTest_.running ? "..." : "--";- }- int vw = fonts_.regular.measure(val, 22);- fonts_.regular.draw(c, val, r.x + r.w - 28 - vw, fonts_.regular.centeredY(r.y, r.h, 22), 22, valCol);- y += kRowH + kGap;- }- c.fillRect({0, kH - 80, kW, 80}, kBg);- if (networkTest_.running)- drawHints(c, {{kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconCircle, tr(Str::Back)}});-}--void AppUi::drawDonationModal(Canvas& c) {- Rect panel = drawModal(c, 1260, 680, tr(Str::SupportTitle));-- // Calculate dimensions for QR code (larger target = 420px)- constexpr int kQrTarget = 420;- int qrTotalH = 460;- int contentTop = panel.y + 90;- int contentH = panel.h - 110;- int centerY = contentTop + contentH / 2;-- int qrTop = centerY - qrTotalH / 2;- Rect qrBox = drawQr(c, "https://ko-fi.com/RafaelNGP", panel.x + panel.w - 60, qrTop, kQrTarget, qrcodegen_Ecc_MEDIUM);- if (qrBox.w > 0) {- std::string scanText = tr(Str::ScanToDonate);- int tw = fonts_.semibold.measure(scanText, 22);- fonts_.semibold.draw(c, scanText, qrBox.x + (qrBox.w - tw) / 2, qrBox.y + qrBox.h + 16, 22, kWhite);- }-- // Left column: message and link vertically centered aligned with QR code- int textW = 600;- int textX = panel.x + 60;- auto lines = fonts_.regular.wrap(tr(Str::SupportMessage), 26, textW, 10);- constexpr int kLineH = 38;- int textContentH = static_cast<int>(lines.size()) * kLineH + 24 + 26;- int textY = centerY - textContentH / 2;-- for (const auto& line : lines) {- fonts_.regular.draw(c, line, textX, textY, 26, rgba(230, 230, 230));- textY += kLineH;- }-- textY += 24;- fonts_.semibold.draw(c, "https://ko-fi.com/RafaelNGP", textX, textY, 24, rgba(255, 215, 80));-- c.fillRect({0, kH - 80, kW, 80}, kBg);- drawHints(c, {{kIconCircle, tr(Str::Back)}});-}--void AppUi::drawAchievementsModal(Canvas& c, uint64_t nowMs) {- Rect panel = drawModal(c, 1180, 720, tr(Str::Achievements));-- auto it = achievements_.find(detail_.xboxTitleId);- if (it == achievements_.end()) {- drawSpinner(c, static_cast<float>(panel.x + panel.w / 2), static_cast<float>(panel.y + panel.h / 2), 24.0f, nowMs);- animating_ = true;- c.fillRect({0, kH - 80, kW, 80}, kBg);- drawHints(c, {{kIconCircle, tr(Str::Back)}});- return;- }-- const auto& ach = it->second;- if (ach.totalCount == 0) {- std::string emptyStr = tr(Str::NoAchievements);- int tw = fonts_.regular.measure(emptyStr, 28);- fonts_.regular.draw(c, emptyStr, panel.x + (panel.w - tw) / 2, panel.y + panel.h / 2, 28, kDim);- c.fillRect({0, kH - 80, kW, 80}, kBg);- drawHints(c, {{kIconCircle, tr(Str::Back)}});- return;- }-- std::string summary = std::to_string(ach.unlockedCount) + " / " + std::to_string(ach.totalCount) +- " (" + std::to_string(ach.unlockedGamerscore) + " / " + std::to_string(ach.totalGamerscore) + " G)";- int sw = fonts_.semibold.measure(summary, 24);- fonts_.semibold.draw(c, summary, panel.x + panel.w - 56 - sw, panel.y + 56, 24, kWhite);-- int barX = panel.x + 56;- int barY = panel.y + 104;- int barW = panel.w - 112;- int barH = 10;- c.fillRect({barX, barY, barW, barH}, rgba(255, 255, 255, 30), 5);- if (ach.totalCount > 0 && ach.unlockedCount > 0) {- int fillW = std::clamp(static_cast<int>(barW * static_cast<float>(ach.unlockedCount) / ach.totalCount), 10, barW);- c.fillRect({barX, barY, fillW, barH}, kGreen, 5);- }-- constexpr int kRowH = 80;- constexpr int kGap = 8;- constexpr int kVisibleCount = 5;- int y = barY + 22;-- int total = static_cast<int>(ach.items.size());- int startIdx = std::clamp(achScroll_, 0, std::max(0, total - kVisibleCount));-- for (int i = startIdx; i < total && i < startIdx + kVisibleCount; ++i) {- const auto& item = ach.items[i];- Rect r{panel.x + 56, y, panel.w - 112, kRowH};- c.fillRect(r, rgba(255, 255, 255, 14), 14);-- float cx = static_cast<float>(r.x + 36), cy = static_cast<float>(r.y + r.h / 2);- if (item.unlocked) {- c.fillCircle(cx, cy, 18.0f, kGreen);- c.line(cx - 7, cy, cx - 2, cy + 6, 3.0f, kWhite);- c.line(cx - 2, cy + 6, cx + 9, cy - 6, 3.0f, kWhite);- } else {- c.fillCircle(cx, cy, 18.0f, rgba(255, 255, 255, 20));- c.strokeCircle(cx, cy - 3.0f, 4.0f, 2.0f, kDim);- c.fillRect({static_cast<int>(cx) - 6, static_cast<int>(cy) - 2, 12, 10}, kDim, 2);- }-- int textX = r.x + 72;- int maxTextW = r.w - 200;- if (item.unlocked) {- fonts_.semibold.draw(c, item.name, textX, r.y + 14, 24, kWhite);- std::string desc = fonts_.regular.fit(item.description, 20, maxTextW);- fonts_.regular.draw(c, desc, textX, r.y + 44, 20, kGray);- } else if (item.isSecret) {- fonts_.semibold.draw(c, tr(Str::SecretAchievement), textX, r.y + 14, 24, kDim);- fonts_.regular.draw(c, tr(Str::AchievementLocked), textX, r.y + 44, 20, rgba(255, 255, 255, 90));- } else {- fonts_.semibold.draw(c, item.name, textX, r.y + 14, 24, rgba(230, 230, 230));- std::string desc = item.lockedDescription.empty() ? item.description : item.lockedDescription;- desc = fonts_.regular.fit(desc, 20, maxTextW);- fonts_.regular.draw(c, desc, textX, r.y + 44, 20, kDim);- }-- std::string score = std::to_string(item.gamerscore) + " G";- int scw = fonts_.semibold.measure(score, 22);- Color scCol = item.unlocked ? rgba(110, 225, 120) : kDim;- fonts_.semibold.draw(c, score, r.x + r.w - 28 - scw, fonts_.semibold.centeredY(r.y, r.h, 22), 22, scCol);-- y += kRowH + kGap;- }-- if (total > kVisibleCount) {- int trackH = kVisibleCount * (kRowH + kGap) - kGap;- int trackY = barY + 22;- int trackX = panel.x + panel.w - 40;- c.fillRect({trackX, trackY, 4, trackH}, rgba(255, 255, 255, 20), 2);- int thumbH = std::max(20, trackH * kVisibleCount / total);- int thumbY = trackY + (trackH - thumbH) * startIdx / (total - kVisibleCount);- c.fillRect({trackX, thumbY, 4, thumbH}, rgba(255, 255, 255, 120), 2);- }-- c.fillRect({0, kH - 80, kW, 80}, kBg);- drawHints(c, {{kIconCircle, tr(Str::Back)}});-}--void AppUi::drawKeysTester(Canvas& c) {- Rect panel = drawModal(c, 1500, 860, tr(Str::KeyboardKeys));- // Each input: its name (the PlayStation button, the Xbox one beside),- // then its two keys. Left column the sticks, D-pad, A and B; right the rest.- constexpr const char* kUp = " \xE2\x86\x91", *kDown = " \xE2\x86\x93", *kLeft = " \xE2\x86\x90", *kRight = " \xE2\x86\x92";- const std::string stick = tr(Str::StickLeft), dpad = tr(Str::DPad);- const std::string names[input::kKeyActions] = {- stick + kUp, stick + kDown, stick + kLeft, stick + kRight, dpad + kUp, dpad + kDown, dpad + kLeft, dpad + kRight,- "A", "B", "X", "Y", "L1 (LB)", "R1 (RB)", "L2 (LT)", "R2 (RT)", "L3", "R3", "View", "Menu"};- const int faceIcon[4] = {kIconCross, kIconCircle, kIconSquare, kIconTriangle}; // A B X Y- // An Xbox pad: its own names alone.- const bool xbox = g_glyphStyle == GlyphStyle::Xbox;- std::string xboxNames[input::kKeyActions];- if (xbox) {- static constexpr PadButton kShoulders[6] = {PadButton::L1, PadButton::R1, PadButton::L2,- PadButton::R2, PadButton::L3, PadButton::R3};- for (int i = 0; i < 6; ++i)- xboxNames[static_cast<int>(input::KeyAction::LB) + i] = buttonName(GlyphStyle::Xbox, kShoulders[i]);- }- constexpr int kRowH = 52, kGap = 8, kChipW = 170, kColGap = 40;- const int colW = (panel.w - 112 - kColGap) / 2;- const bool capturing = captureSince_ != 0;- for (int a = 0; a < input::kKeyActions; ++a) {- const int col = a / kKeysPerColumn, row = a % kKeysPerColumn;- Rect r{panel.x + 56 + col * (colW + kColGap), panel.y + 106 + row * (kRowH + kGap), colW, kRowH};- const bool rowOn = row == keysRow_ && col == keysCol_ / 2;- c.fillRect(r, rowOn ? rgba(255, 255, 255, 30) : rgba(255, 255, 255, 12), 14);- int ty = fonts_.semibold.centeredY(r.y, r.h, 24);- if (a >= static_cast<int>(input::KeyAction::A) && a <= static_cast<int>(input::KeyAction::Y)) {- int k = a - static_cast<int>(input::KeyAction::A);- drawFaceButton(c, fonts_.bold, faceIcon[k], r.x + 38.0f, r.y + r.h / 2.0f, 16);- if (!xbox) fonts_.semibold.draw(c, "(" + names[a] + ")", r.x + 66, ty, 24, kGray);- } else {- fonts_.semibold.draw(c, xbox && !xboxNames[a].empty() ? xboxNames[a] : names[a], r.x + 22, ty, 24, kWhite);- }- for (int slot = 0; slot < 2; ++slot) {- Rect chip{r.x + r.w - 10 - (2 - slot) * kChipW - (1 - slot) * 10, r.y + 7, kChipW, r.h - 14};- const bool on = rowOn && keysCol_ % 2 == slot;- uint8_t code = settings_.keyMap[static_cast<size_t>(a)][static_cast<size_t>(slot)];- std::string text = on && capturing ? "..." : code ? input::keyName(code) : "\xE2\x80\x94"; // an em dash: none- c.fillRect(chip, on ? kWhite : rgba(255, 255, 255, code ? 26 : 10), 10);- if (on && capturing) c.strokeRect({chip.x - 4, chip.y - 4, chip.w + 8, chip.h + 8}, rgba(90, 220, 110), 3, 13);- int tw = fonts_.semibold.measure(text, 22);- fonts_.semibold.draw(c, text, chip.x + (chip.w - tw) / 2, fonts_.semibold.centeredY(chip.y, chip.h, 22), 22,- on ? kBg : code ? kWhite : kDim);- }- }- // Reset to default, across both columns.- Rect reset{panel.x + 56, panel.y + 106 + kKeysPerColumn * (kRowH + kGap) + 8, panel.w - 112, kRowH};- const bool resetOn = keysRow_ == kKeysPerColumn;- c.fillRect(reset, resetOn ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);- if (resetOn) c.strokeRect({reset.x - 4, reset.y - 4, reset.w + 8, reset.h + 8}, kWhite, 2, 18);- const char* resetLabel = tr(Str::ResetToDefault);- fonts_.semibold.draw(c, resetLabel, reset.x + (reset.w - fonts_.semibold.measure(resetLabel, 24)) / 2,- fonts_.semibold.centeredY(reset.y, reset.h, 24), 24, resetOn ? kWhite : rgba(240, 100, 100));- // Waiting for a key: say so (and why a key was refused); else the help.- int hy = panel.y + panel.h - 74;- if (capturing) {- std::string ask = tr(Str::PressKey);- fonts_.bold.draw(c, ask, panel.x + (panel.w - fonts_.bold.measure(ask, 28)) / 2, hy - 4, 28, kWhite);- if (keyRefused_) {- std::string why = trf(Str::KeyReserved, input::keyName(keyRefused_));- fonts_.regular.draw(c, why, panel.x + (panel.w - fonts_.regular.measure(why, 22)) / 2, hy + 34, 22,- rgba(240, 100, 100));- }- } else {- auto help = fonts_.regular.wrap(tr(Str::KeysHelp), 22, panel.w - 112, 2);- for (size_t i = 0; i < help.size(); ++i)- fonts_.regular.draw(c, help[i], panel.x + 56, hy + static_cast<int>(i) * 30, 22, kDim);- }- c.fillRect({0, kH - 80, kW, 80}, kBg); // its own hints over drawModal's- if (capturing)- drawHints(c, {{kIconCircle, tr(Str::Cancel)}});- else if (resetOn)- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});- else- drawHints(c, {{kIconCross, tr(Str::ChangeKey)}, {kIconSquare, tr(Str::ClearKey)}, {kIconCircle, tr(Str::Back)}});-}--void AppUi::drawColourPicker(Canvas& c) {- c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));- constexpr int kPanelW = 1000, kPanelH = 540;- Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 20, kPanelW, kPanelH};- c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow- c.fillRect(panel, kPanel, 24);- c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);- fonts_.bold.draw(c, tr(Str::LightBarColour), panel.x + 56, panel.y + 44, 40, kWhite);-- // The wheel: angle = hue, distance from the centre = saturation, at the- // brightness chosen (its pixels kept until that changes).- const int R = kWheelR, cx = panel.x + 56 + R, cy = panel.y + 120 + R;- if (wheelValue_ != pickValue_ || wheel_.empty()) {- wheel_.assign(static_cast<size_t>(4 * R * R), 0);- for (int y = 0; y < 2 * R; ++y)- for (int x = 0; x < 2 * R; ++x) {- float u = (x + 0.5f - R) / R, v = (y + 0.5f - R) / R, d = std::hypot(u, v);- if (d > 1.0f + 1.0f / R) continue;- float h = std::atan2(v, u) / 6.2832f;- Color col = hsvColour(h < 0 ? h + 1 : h, std::min(1.0f, d), pickValue_);- // Edge coverage, for a smooth rim.- uint32_t a = static_cast<uint32_t>(std::clamp((1.0f - d) * R + 0.5f, 0.0f, 1.0f) * 255);- wheel_[static_cast<size_t>(y * 2 * R + x)] = (col & 0x00FFFFFF) | a << 24;- }- wheelValue_ = pickValue_;- }- uint32_t* px = c.data();- for (int y = 0; y < 2 * R; ++y)- for (int x = 0; x < 2 * R; ++x) {- uint32_t w = wheel_[static_cast<size_t>(y * 2 * R + x)], a = w >> 24;- if (!a) continue;- uint32_t& d = px[static_cast<size_t>((cy - R + y) * kW + (cx - R + x))];- auto mix = [&](int shift) {- uint32_t s = w >> shift & 0xFF, t = d >> shift & 0xFF;- return ((s * a + t * (255 - a)) / 255) << shift;- };- d = mix(0) | mix(8) | mix(16) | 0xFF000000u;- }- float kx = cx + pickU_ * R, ky = cy + pickV_ * R; // the cursor- c.strokeArc(kx, ky, 15, 3, 0, 6.2832f, rgba(0, 0, 0, 160));- c.strokeArc(kx, ky, 12, 3, 0, 6.2832f, kWhite);-- // The colour chosen, and the brightness under it.- const int sx = panel.x + 56 + 2 * R + 80, sw = panel.x + panel.w - 56 - sx;- Color chosen = pickerColour();- c.fillRect({sx, cy - R + 10, sw, 170}, chosen, 20);- c.strokeRect({sx, cy - R + 10, sw, 170}, rgba(255, 255, 255, 60), 2, 20);- Rect bar{sx, cy + 30, sw, 18};- float h = std::atan2(pickV_, pickU_) / 6.2832f, s = std::min(1.0f, std::hypot(pickU_, pickV_));- c.gradientH(bar, hsvColour(h < 0 ? h + 1 : h, s, kMinValue), hsvColour(h < 0 ? h + 1 : h, s, 1));- float mx = bar.x + (pickValue_ - kMinValue) / (1 - kMinValue) * bar.w;- c.fillCircle(mx, bar.y + bar.h / 2.0f, 14, kWhite);- c.fillCircle(mx, bar.y + bar.h / 2.0f, 9, chosen);- // The help, a line per control (its parts are four spaces apart).- std::string help = tr(Str::ColourPickerHelp);- int hy = cy + 90;- for (size_t start = 0; start < help.size();) {- size_t gap = help.find(" ", start);- std::string part = help.substr(start, gap == std::string::npos ? std::string::npos : gap - start);- for (const auto& line : fonts_.regular.wrap(part, 22, sw, 2)) {- fonts_.regular.draw(c, line, sx, hy, 22, kGray);- hy += 32;- }- if (gap == std::string::npos) break;- start = help.find_first_not_of(' ', gap);- if (start == std::string::npos) break;- }-- c.fillRect({0, kH - 80, kW, 80}, kBg);- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});-}--void AppUi::drawUpdating(Canvas& c, uint64_t nowMs) {- drawBackground(c);- drawLogo(c, kW / 2.0f, 330, 56);- drawCentered(c, fonts_.bold, trf(Str::UpdatingTo, updatingTo_), 440, 48, kWhite);- drawCentered(c, fonts_.regular, updateStatus_, 520, 28, kGray);- if (updateFraction_ >= 0) {- constexpr int kBarW = 720;- Rect bar{(kW - kBarW) / 2, 590, kBarW, 12};- c.fillRect(bar, rgba(255, 255, 255, 40), 6);- c.fillRect({bar.x, bar.y, static_cast<int>(kBarW * std::min(1.0f, updateFraction_)), bar.h}, kGreen, 6);- } else {- drawSpinner(c, kW / 2.0f, 610, 24, nowMs);- }-}--void AppUi::drawSignOutHold(Canvas& c, uint64_t nowMs) {- if (!signOutHoldStart_) return;- float progress = std::min(1.0f, static_cast<float>(nowMs - signOutHoldStart_) / kSignOutHoldMs);- int secondsLeft = static_cast<int>((kSignOutHoldMs - std::min<uint64_t>(kSignOutHoldMs, nowMs - signOutHoldStart_) + 999) / 1000);- std::string text = trf(Str::SigningOutIn, std::to_string(secondsLeft));- int tw = fonts_.semibold.measure(text, 28);- Rect panel{(kW - (tw + 170)) / 2, kH - 250, tw + 170, 110};- c.fillRect(panel, rgba(30, 30, 30, 240), 55);- c.strokeRect(panel, rgba(255, 255, 255, 60), 2, 55);- float cx = panel.x + 62, cy = panel.y + panel.h / 2.0f;- c.strokeArc(cx, cy, 30, 6, 0, 6.2832f, rgba(255, 255, 255, 50));- // Progress ring from 12 o'clock, clockwise, in red as it nears the end.- Color ring = progress < 0.8f ? kWhite : rgba(255, 110, 110);- if (progress > 0.01f) c.strokeArc(cx, cy, 30, 6, -1.5708f, 6.2832f * progress, ring);- fonts_.bold.draw(c, std::to_string(secondsLeft), static_cast<int>(cx) - fonts_.bold.measure(std::to_string(secondsLeft), 26) / 2,- static_cast<int>(cy) - 16, 26, kWhite);- fonts_.semibold.draw(c, text, panel.x + 120, panel.y + 38, 28, kWhite);- animating_ = true;-}--void AppUi::drawGameSettings(Canvas& c) {- if (tester_ == Tester::Sticks) {- drawStickTester(c);- return;- }- if (tester_ == Tester::Triggers) {- drawTriggerTester(c);- return;- }- if (tester_ == Tester::Keys) {- drawKeysTester(c);- return;- }- if (tester_ == Tester::Pad) {- drawPadTester(c);- return;- }- if (tester_ == Tester::Touchpad) {- drawTouchpadTester(c);- return;- }- std::string title = tr(Str::GameSettings);- if (!detail_.name.empty()) {- std::string full = title + " \xE2\x80\xA2 " + detail_.name;- if (fonts_.bold.measure(full, 40) <= 960) {- title = full;- } else {- std::string cut = detail_.name;- while (!cut.empty() && fonts_.bold.measure(title + " \xE2\x80\xA2 " + cut + "...", 40) > 960) {- do {- cut.pop_back();- } while (!cut.empty() && (static_cast<uint8_t>(cut.back()) & 0xC0) == 0x80);- }- title = title + " \xE2\x80\xA2 " + cut + "...";- }- }- constexpr int kModalW = 1140, kModalH = 960;- constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;- // The rows caps_ allows; the panel loses the height of those it hides- // (the same as ever with all of them, "Reset to default" or not).- const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);- const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);- auto groups = [](const std::vector<SettingsRowPos>& v) {- return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));- };- const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -- (groups(all) - groups(most)) * kGroupGap;- Rect panel = drawModal(c, kModalW, modalH, title);- int y = panel.y + 92;-- for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {- const int i = rows[static_cast<size_t>(pos)].row;- if (rows[static_cast<size_t>(pos)].groupStart) y += kGroupGap;- Rect r{panel.x + 50, y, panel.w - 100, kRowH};- bool focused = (pos == gameSettingsRow_);- c.fillRect(r, focused ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);- if (focused) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 2, 18);-- int ty = fonts_.semibold.centeredY(r.y, r.h, 26);-- if (i == 10) {- const char* resetLabel = tr(Str::ResetToDefault);- int tw = fonts_.semibold.measure(resetLabel, 26);- fonts_.semibold.draw(c, resetLabel, r.x + (r.w - tw) / 2, ty, 26, focused ? kWhite : rgba(240, 100, 100));- y += kRowH + kGap;- continue;- }-- const char* label = "";- std::string value;-- switch (i) {- case 0:- label = tr(Str::Profile);- value = tr(activeGameHasCustom_ ? Str::ProfileCustom : Str::ProfileDefault);- break;- case 1:- label = tr(Str::MenuUpscaler);- value = activeGameProfile_.upscaler == 3 ? tr(Str::UpscalerAiClean)- : activeGameProfile_.upscaler == 2 ? tr(Str::UpscalerFsrClean)- : activeGameProfile_.upscaler == 1 ? tr(Str::UpscalerAi)- : "FSR";- break;- case 2: {- label = tr(Str::MenuSharpness);- static constexpr Str kLevels[] = {Str::SharpOff, Str::SharpLow, Str::SharpMedium, Str::SharpHigh};- value = tr(kLevels[std::clamp(activeGameProfile_.sharpness, 0, 3)]);- break;- }- case 3: {- label = tr(Str::MenuDeband);- static constexpr Str kLevels[] = {Str::SharpOff, Str::SharpLow, Str::SharpHigh};- value = activeGameProfile_.deband == 3 ? "Auto"- : tr(kLevels[std::clamp(activeGameProfile_.deband, 0, 2)]);- break;- }- case 4:- label = tr(Str::Resolution);- value = activeGameProfile_.resolution == 1 ? "720p" : activeGameProfile_.resolution == 2 ? tr(Str::ResBest) : "1080p";- break;- case 5:- label = tr(Str::Deadzone);- value = std::to_string(activeGameProfile_.deadzoneLeft) + " %";- break;- case 6: {- label = tr(Str::TriggerRumble);- static constexpr Str kStrengths[] = {Str::Deactivated, Str::TriggerLight, Str::TriggerMedium,- Str::TriggerStrong, Str::TriggerMax};- value = tr(kStrengths[std::clamp(activeGameProfile_.triggerStrength, 0, 4)]);- break;- }- case 16: {- label = tr(Str::AudioHaptics);- static constexpr Str kHapticsLevels[] = {Str::Off, Str::SharpLow, Str::SharpMedium, Str::SharpHigh};- value = tr(kHapticsLevels[std::clamp(activeGameProfile_.audioHaptics, 0, 3)]);- break;- }- case 7:- label = tr(Str::ConfirmButton);- break;- case 8:- label = tr(Str::HighRefresh);- value = tr(activeGameProfile_.highRefresh ? Str::HighRefreshOn : Str::Deactivated);- break;- case 9:- label = tr(Str::KeyboardKeys);- value = tr(activeGameProfile_.keyMap == input::defaultKeyMap() ? Str::ProfileDefault : Str::ProfileCustom);- break;- case 11:- label = tr(Str::ControllerButtons);- value = tr(activeGameProfile_.padMap == input::defaultPadMap() ? Str::ProfileDefault : Str::ProfileCustom);- break;- case 17:- label = tr(Str::TouchpadShortcuts);- value = tr(activeGameProfile_.touchpadShortcuts == input::defaultTouchpadShortcuts() ? Str::ProfileDefault : Str::ProfileCustom);- break;- case 12:- label = tr(Str::Gyro);- value = tr(activeGameProfile_.gyroMode == 1 ? Str::GyroAlways- : activeGameProfile_.gyroMode == 2 ? Str::GyroAiming- : Str::Off);- break;- case 13:- label = tr(Str::TouchpadMouse);- value = tr(activeGameProfile_.touchpadMouse ? Str::Activated : Str::Deactivated);- break;- case 14: {- static const std::pair<const char*, const char*> kLocales[] = {- {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},- {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},- {"it-IT", "Italiano"}, {"ja-JP", "日本語"}- };- label = tr(Str::GameLanguage);- if (activeGameProfile_.locale.empty()) {- value = tr(Str::ProfileDefault);- } else {- for (const auto& [code, name] : kLocales) {- if (activeGameProfile_.locale == code) {- value = name;- break;- }- }- if (value.empty()) value = activeGameProfile_.locale;- }- break;- }- case 15:- label = tr(Str::VideoDecoder);- value = activeGameProfile_.videoDecoder == 1 ? tr(Str::VideoDecoderSw) : tr(Str::VideoDecoderHw);- break;- default: break;- }-- fonts_.semibold.draw(c, label, r.x + 28, ty, 26, kWhite);-- if (i == 7) {- float cx = static_cast<float>(r.x + r.w - 50), cy = static_cast<float>(r.y + r.h / 2);- if (focused) {- fonts_.regular.draw(c, "\xE2\x80\xB9", static_cast<int>(cx) - 40, fonts_.regular.centeredY(r.y, r.h, 26), 26, kWhite);- fonts_.regular.draw(c, "\xE2\x80\xBA", static_cast<int>(cx) + 28, fonts_.regular.centeredY(r.y, r.h, 26), 26, kWhite);- }- drawFaceButton(c, fonts_.bold, activeGameProfile_.circleConfirms ? kIconCircle : kIconCross, cx, cy, 16);- } else {- std::string disp = focused ? ("\xE2\x80\xB9 " + value + " \xE2\x80\xBA") : value;- int vw = fonts_.regular.measure(disp, 26);- fonts_.regular.draw(c, disp, r.x + r.w - 28 - vw, fonts_.regular.centeredY(r.y, r.h, 26), 26,- focused ? kWhite : kGray);- }-- y += kRowH + kGap;- }-}--void AppUi::render(Canvas& c, uint64_t nowMs) {- std::lock_guard<std::mutex> lock(mutex_);- float dt = lastRender_ ? std::min(0.1f, (nowMs - lastRender_) / 1000.0f) : 0.0f;- lastRender_ = nowMs;- animating_ = rowY_.step(dt);- for (auto& a : rowScroll_) animating_ |= a.step(dt);- animating_ |= gridScroll_.step(dt);- animating_ |= resultScroll_.step(dt);- dirty_ = false;- switch (screen_) {- case Screen::Splash: drawSplash(c, nowMs); break;- case Screen::SignIn: drawSignIn(c, nowMs); break;- case Screen::Home: drawHome(c, nowMs); break;- case Screen::Details:- drawDetails(c, nowMs);- if (gameSettingsOpen_) drawGameSettings(c);- if (achievementsOpen_) drawAchievementsModal(c, nowMs);- break;- case Screen::Launching: drawLaunching(c, nowMs); break;- case Screen::Error: drawError(c); break;- case Screen::Settings: drawSettings(c); break;- case Screen::Updating: drawUpdating(c, nowMs); break;- case Screen::Streaming: break;- }- if (screen_ == Screen::Home && updatePrompt_) {- if (showingUpdateNotes_) drawUpdateNotesModal(c);- else drawUpdatePrompt(c);- }- if (screen_ == Screen::Home && quitPrompt_) drawQuitPrompt(c);- if (screen_ == Screen::Error && countryPickerOpen_) drawCountryPicker(c);- if (reportOpen_) drawReport(c);- if ((screen_ == Screen::Home && !updatePrompt_) || screen_ == Screen::Error) drawSignOutHold(c, nowMs);- if (!toast_.empty()) animating_ = true; // to expire it- if (platform::toastsEnabled()) {- // platform::notify() on a desktop: over everything, under the top bar's right side.- toastsDrawn_ = platform::toasts().version(nowMs);- drawToasts(c, fonts_, platform::toasts().visible(nowMs), kW - kMargin, 132);- }- if (mouseCursorVisible_ && nowMs >= mouseCursorVisibleUntil_) {- mouseCursorVisible_ = false;- }- if (mouseCursorVisible_ && screen_ != Screen::Streaming && screen_ != Screen::Splash) {- drawMouseCursor(c, mouseCursorX_, mouseCursorY_);- }-}--static const char* const kCursorRows[23] = {- "#...............",- "##..............",- "#W#.............",- "#WW#............",- "#WWW#...........",- "#WWWW#..........",- "#WWWWW#.........",- "#WWWWWW#........",- "#WWWWWWW#.......",- "#WWWWWWWW#......",- "#WWWWWWWWW#.....",- "#WWWWWWWWWW#....",- "#WWWWWWWWWWW#...",- "#WWWWWW######...",- "#WWWW##WW#......",- "#WW##.#WW#......",- "#W#...#WW#......",- "##.....#WW#.....",- "#......#WW#.....",- "........#WW#....",- "........#WW#....",- ".........#WW#...",- ".........####..."-};--void AppUi::drawMouseCursor(Canvas& c, float cursorX, float cursorY) {- static bool s_inited = false;- static uint8_t s_outline[23 * 16];- static uint8_t s_fill[23 * 16];- static uint8_t s_shadow[23 * 16];- if (!s_inited) {- s_inited = true;- for (int y = 0; y < 23; ++y) {- for (int x = 0; x < 16; ++x) {- char ch = kCursorRows[y][x];- s_shadow[y * 16 + x] = (ch == '#' || ch == 'W') ? 255 : 0;- s_outline[y * 16 + x] = (ch == '#') ? 255 : 0;- s_fill[y * 16 + x] = (ch == 'W') ? 255 : 0;- }- }- }- int ix = static_cast<int>(std::round(cursorX));- int iy = static_cast<int>(std::round(cursorY));- // Sombra sutil- c.drawMask(s_shadow, 16, 23, 16, ix + 2, iy + 2, rgba(0, 0, 0, 80));- // Borda preta fina- c.drawMask(s_outline, 16, 23, 16, ix, iy, rgba(0, 0, 0, 240));- // Seta branca nítida- c.drawMask(s_fill, 16, 23, 16, ix, iy, rgba(255, 255, 255, 255));+ cachedLibLayout_ = std::move(L);+ libLayoutValid_ = true;+ return cachedLibLayout_;}} // namespace xc::uidiff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 1f84a14..e3a4da6 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -134,6 +134,7 @@ struct SettingsChoice {int maxBitrateMbps = 0; // 0 automatic, else 5 / 10 / 15 / 20 / 25 / 30 / 35 / 40 / 45 / 50int gameVolume = 100; // percent: 25 / 50 / 75 / 100 / 150bool queueReadyAlert = true; // Queue-ready chime and rumble alert+ bool previewFeatures = true; // xCloud preview client identification & ad-supported F2P streaminginput::KeyMap keyMap = input::defaultKeyMap(); // the keyboard as a player's controllerinput::PadMap padMap = input::defaultPadMap(); // the controller's buttons toward the game (always complete)int gyroMode = 0; // gyro aiming (input/gyro.h): 0 off, 1 always, 2 while L2 is held@@ -308,6 +309,10 @@ public:// "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);+ // Coalesced update of rows, owned/purchasable, membership, search pools, and loading bar under a single lock and rebuild.+ void setCatalogState(std::vector<GameRow> rows, std::vector<GameTile> owned, std::vector<GameTile> purchasable,+ bool ownedKnown, bool member, std::vector<GameTile> gpPool, std::vector<GameTile> libPool,+ bool loadingActive = false, size_t loadingDone = 0, size_t loadingTotal = 0);// "My consoles"; `known` false while they load.void setConsoles(std::vector<ConsoleTile> consoles, bool known);// The lists' background refresh: shown as a bar in "Your games" and the@@ -370,7 +375,11 @@ public:void showError(const std::string& message, const std::string& url = {});// A game that could not start but may on another try (a free game got// on the phone meanwhile): Cross plays it again, Circle opens its page.- void showPlayError(const std::string& message, const GameTile& game);+ void showPlayError(const std::string& message, const GameTile& game, const std::string& url = {});+ bool isFreeAccount() const;+ bool isFreeAccountLocked() const;+ bool isEffectivePlayable(const GameTile& t) const;+ bool isEffectivePlayableLocked(const GameTile& t) const;// The sign-in refused by xCloud: an error that also offers to sign in as// another country (Square), and Settings (Options).void showRegionRefused(const std::string& message);@@ -533,7 +542,7 @@ private:std::vector<int> rowFirst; // first tile index of each rowint headerY[3] = {0, 0, 0}; // section headers, relative (0: yours, 1: to buy, 2: hidden)};- LibraryLayout libraryLayout() const;+ const LibraryLayout& libraryLayout() const;const GameTile* libraryTile(int index) const;// Applies hiding and sorting to the received lists (caller holds mutex_).// `keepPosition`: the cursor stays where it is on screen (same section@@ -665,6 +674,8 @@ private:bool ownedKnown_ = false;int gridFocus_ = 0;Anim gridScroll_;+ mutable LibraryLayout cachedLibLayout_;+ mutable bool libLayoutValid_ = false;bool searching_ = false; // the search of `tab_` is openstd::vector<GameTile> gamePassPool_, libraryPool_, results_;std::string query_;@@ -792,6 +803,7 @@ private:bool achievementsOpen_ = false;int achScroll_ = 0;int detailButtonFocus_ = 0; // 0 = Play / Claim, 1 = Achievements+ Rect playRect_{}, achRect_{}, claimRect_{};std::string webUrl_;float mouseCursorX_ = 960.0f;float mouseCursorY_ = 540.0f;@@ -799,5 +811,4 @@ private:uint64_t mouseCursorVisibleUntil_ = 0;void drawMouseCursor(Canvas& c, float cursorX, float cursorY);};-} // namespace xc::uidiff --git a/src/ui/app_ui_input.cpp b/src/ui/app_ui_input.cppnew file mode 100644index 0000000..2e54d91--- /dev/null+++ b/src/ui/app_ui_input.cpp@@ -0,0 +1,1262 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "ui/app_ui_internal.h"++namespace xc::ui {++void AppUi::handleHome(const NavInput& in, UiEvent& ev) {+ // Caller holds mutex_.+ if ((in.scrollRows || in.scrollCards) && !(searching_ && searchOnKeys_)) {+ // Smooth scrolling: the rows and cards it moved by since the last+ // pass, one step at a time (the view glides after the focus).+ auto steps = [&](int n, bool vertical) {+ NavInput step;+ step.nowMs = in.nowMs;+ (vertical ? (n > 0 ? step.down : step.up) : (n > 0 ? step.right : step.left)) = true;+ for (int k = 0; k < std::abs(n); ++k) {+ // In the search's results, sideways stops at the row's edge+ // (left of it is the keyboard).+ if (searching_ && !vertical && (n < 0 ? resultFocus_ % kResultCols == 0+ : (resultFocus_ + 1) % kResultCols == 0))+ break;+ handleHome(step, ev);+ }+ };+ if (in.scrollRows) steps(in.scrollRows, true);+ if (in.scrollCards) steps(in.scrollCards, false);+ return;+ }+ if (in.l1 || in.r1) {+ // Game Pass, Your games, My consoles, round.+ int n = static_cast<int>(tab_) + (in.r1 ? 1 : 2);+ tab_ = static_cast<Tab>(n % 3);+ searching_ = false;+ dirty_ = true;+ if (tab_ == Tab::Consoles) ev.action = Action::ConsolesShown;+ return;+ }+ if (in.l3 && !searching_) {+ ev.action = Action::RefreshLibrary;+ return;+ }+ if (in.options) {+ screen_ = Screen::Settings;+ settingsRow_ = 0;+ settingsFromError_ = false;+ settingsCountry_ = settings_.loginCountry;+ dropdownOpen_ = false;+ filterList_ = -1;+ dirty_ = true;+ return;+ }+ if (in.triangle && !searching_ && tab_ != Tab::Consoles) { // search this tab+ searching_ = true;+ searchOnKeys_ = true;+ query_.clear();+ runSearch();+ dirty_ = true;+ return;+ }+ if (searching_) {+ if (searchOnKeys_) {+ if ((in.back || in.triangle) && filterList_ < 0) { // close the search (Circle closes an open list first)+ 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::Consoles: {+ int n = static_cast<int>(consoles_.size());+ // Search again: Cross with none listed, Triangle otherwise.+ if (consolesKnown_ && ((n == 0 && in.accept) || in.triangle)) {+ if (n == 0) consolesKnown_ = false; // the spinner while it looks+ ev.action = Action::ConsolesShown;+ dirty_ = true;+ break;+ }+ if (n == 0) break;+ int before = consoleFocus_;+ if (in.right && consoleFocus_ + 1 < n) ++consoleFocus_;+ if (in.left && consoleFocus_ > 0) --consoleFocus_;+ if (consoleFocus_ != before) dirty_ = true;+ if (in.accept) {+ const ConsoleTile& con = consoles_[static_cast<size_t>(consoleFocus_)];+ ev.action = Action::Play;+ ev.game.titleId = con.serverId;+ ev.game.name = con.name.empty() ? "Xbox" : con.name;+ ev.game.homeConsole = true;+ }+ break;+ }+ case Tab::GamePass: {+ if (rows_.empty()) break;+ int rows = static_cast<int>(rows_.size());+ const GameRow& curRow = rows_[static_cast<size_t>(focusRow_)];+ int& col = focusCol_[static_cast<size_t>(focusRow_)];+ int count = static_cast<int>(curRow.tiles.size());++ if (curRow.isGrid) {+ if (in.up && col < kLibraryCols) {+ if (focusRow_ > 0) {+ --focusRow_;+ int upCols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());+ focusCol_[static_cast<size_t>(focusRow_)] = std::clamp(focusCol_[static_cast<size_t>(focusRow_)], 0, upCols - 1);+ }+ } else if (in.down && col + kLibraryCols >= count && col / kLibraryCols == (count - 1) / kLibraryCols) {+ if (focusRow_ + 1 < rows) {+ ++focusRow_;+ int downCols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());+ focusCol_[static_cast<size_t>(focusRow_)] = std::clamp(focusCol_[static_cast<size_t>(focusRow_)], 0, downCols - 1);+ }+ } else {+ moveInGrid(col, count, kLibraryCols, in);+ }+ } else {+ if (in.down && focusRow_ + 1 < rows) {+ ++focusRow_;+ if (rows_[static_cast<size_t>(focusRow_)].isGrid) {+ int gCols = static_cast<int>(rows_[static_cast<size_t>(focusRow_)].tiles.size());+ int targetCol = std::min(col % kLibraryCols, gCols - 1);+ focusCol_[static_cast<size_t>(focusRow_)] = std::max(0, targetCol);+ }+ }+ if (in.up && focusRow_ > 0) --focusRow_;+ if (in.right && col + 1 < count) ++col;+ if (in.left && col > 0) --col;+ }+ if (in.up || in.down || in.left || in.right) {+ retarget();+ dirty_ = true;+ }+ if (in.accept && focusedTile()) openDetails(*focusedTile());+ if (in.square && focusedTile()) toggleHidden(*focusedTile(), ev);+ break;+ }+ case Tab::Library: {+ if (!libraryTile(0)) break;+ const 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 && libraryTile(f)) openDetails(*libraryTile(f));+ if (in.square && libraryTile(f)) {+ GameTile t = *libraryTile(f);+ toggleHidden(t, ev);+ }+ if (in.l2 || in.r2) {+ // Jump between sections: the account's games, games to buy,+ // hidden games. L2 goes to the start of this section first.+ int starts[3] = {0, static_cast<int>(owned_.size()),+ static_cast<int>(owned_.size() + purchasable_.size())};+ int total = starts[2] + static_cast<int>(hiddenTiles_.size());+ int section = f >= starts[2] ? 2 : f >= starts[1] ? 1 : 0;+ int target = f;+ if (in.r2) {+ for (int k = section + 1; k < 3; ++k)+ if (starts[k] < total && (k == 2 ? !hiddenTiles_.empty() : starts[k] < starts[k + 1])) {+ target = starts[k];+ break;+ }+ } else if (f != starts[section]) {+ target = starts[section];+ } else {+ for (int k = section - 1; k >= 0; --k)+ if (starts[k] < starts[k + 1]) {+ target = starts[k];+ break;+ }+ }+ if (target != f) {+ gridFocus_ = target;+ int section2 = target >= starts[2] ? 2 : target >= starts[1] ? 1 : 0;+ gridScroll_.target = static_cast<float>(L.headerY[section2]); // its heading at the top+ dirty_ = true;+ }+ }+ if (in.r3) { // next sort order+ librarySort_ = static_cast<LibrarySort>((static_cast<int>(librarySort_) + 1) %+ static_cast<int>(LibrarySort::Count));+ rebuild(true); // same place on screen, not back to the top+ prefsEvent(ev);+ }+ break;+ }+ }+}++void AppUi::setMouseCursor(float x, float y, bool visible) {+ std::lock_guard<std::mutex> lock(mutex_);+ mouseCursorX_ = std::clamp(x, 0.0f, 1919.0f);+ mouseCursorY_ = std::clamp(y, 0.0f, 1079.0f);+ mouseCursorVisible_ = visible;+ if (visible) {+ mouseCursorVisibleUntil_ = platform::nowMs() + 3000;+ }+ dirty_ = true;+}++UiEvent AppUi::onMouseMove(float x, float y) {+ std::lock_guard<std::mutex> lock(mutex_);+ UiEvent ev;+ mouseCursorX_ = std::clamp(x, 0.0f, 1919.0f);+ mouseCursorY_ = std::clamp(y, 0.0f, 1079.0f);+ mouseCursorVisible_ = true;+ mouseCursorVisibleUntil_ = platform::nowMs() + 3000;+ dirty_ = true;+ if (screen_ == Screen::Streaming || screen_ == Screen::Splash) {+ return ev;+ }+ if (screen_ == Screen::Home && !searching_ && !reportOpen_ && !updatePrompt_ && !quitPrompt_) {+ if (tab_ == Tab::GamePass && y >= 140 && y < kH - 80) {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int gridLeft = (kW - kGridW) / 2;+ int afterGridOffset = 0;+ for (size_t r = 0; r < rows_.size(); ++r) {+ float rel = static_cast<float>(r) - rowY_.value;+ int rowBaseY = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;+ const GameRow& row = rows_[r];+ if (row.isGrid) {+ int offset = static_cast<int>(std::lround(rowScroll_[r].value));+ int cardY = rowBaseY - offset + 48;+ for (size_t i = 0; i < row.tiles.size(); ++i) {+ int c_col = static_cast<int>(i) % kLibraryCols;+ int c_row = static_cast<int>(i) / kLibraryCols;+ int cy = cardY + c_row * kGridPitchY;+ int cx = gridLeft + c_col * kCardPitch;+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {+ if (focusRow_ != static_cast<int>(r) || focusCol_[r] != static_cast<int>(i)) {+ focusRow_ = static_cast<int>(r);+ focusCol_[r] = static_cast<int>(i);+ retarget();+ dirty_ = true;+ }+ return ev;+ }+ }+ int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;+ afterGridOffset += gridHeight - offset - kRowPitch;+ } else {+ int cardY = rowBaseY + 48;+ int scroll = static_cast<int>(std::lround(rowScroll_[r].value));+ int firstCol = std::max(0, scroll / kCardPitch - 1);+ for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {+ int cx = kMargin + static_cast<int>(col) * kCardPitch - scroll;+ if (cx > kW) break;+ if (x >= cx && x < cx + kCard && y >= cardY && y < cardY + kCard) {+ if (focusRow_ != static_cast<int>(r) || focusCol_[r] != static_cast<int>(col)) {+ focusRow_ = static_cast<int>(r);+ focusCol_[r] = static_cast<int>(col);+ retarget();+ dirty_ = true;+ }+ return ev;+ }+ }+ }+ }+ } else if (tab_ == Tab::Library && y >= 150 && y < kH - 80) {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int left = (kW - kGridW) / 2;+ const LibraryLayout& L = libraryLayout();+ int offset = static_cast<int>(std::lround(gridScroll_.value));+ for (size_t i = 0; i < L.rowOf.size(); ++i) {+ int cy = kLibraryTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;+ int cx = left + L.colOf[i] * kCardPitch;+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {+ if (gridFocus_ != static_cast<int>(i)) {+ gridFocus_ = static_cast<int>(i);+ dirty_ = true;+ }+ return ev;+ }+ }+ }+ } else if (screen_ == Screen::Settings) {+ if (dropdownOpen_ || tester_ != Tester::None || pickerOpen_ || countryPickerOpen_ || reportOpen_) {+ return ev;+ }+ constexpr int kRowW = 1140, kRowH = 30, kGap = 2, kGroupGap = 4;+ int curY = 184;+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {+ if (groupStart) curY += kGroupGap;+ if (x >= kMargin && x < kMargin + kRowW && y >= curY && y < curY + kRowH) {+ if (settingsRow_ != i) {+ settingsRow_ = i;+ dirty_ = true;+ }+ return ev;+ }+ curY += kRowH + kGap;+ }+ } else if (screen_ == Screen::Details) {+ if (achievementsOpen_ || reportOpen_) {+ return ev;+ }+ if (gameSettingsOpen_) {+ constexpr int kModalW = 1140, kModalH = 960;+ constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);+ const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);+ auto groups = [](const std::vector<SettingsRowPos>& v) {+ return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));+ };+ const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -+ (groups(all) - groups(most)) * kGroupGap;+ Rect panel{(kW - kModalW) / 2, (kH - modalH) / 2, kModalW, modalH};+ int curY = panel.y + 92;+ for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {+ if (rows[static_cast<size_t>(pos)].groupStart) curY += kGroupGap;+ Rect r{panel.x + 50, curY, panel.w - 100, kRowH};+ if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {+ if (gameSettingsRow_ != pos) {+ gameSettingsRow_ = pos;+ dirty_ = true;+ }+ return ev;+ }+ curY += kRowH + kGap;+ }+ return ev;+ }+ auto inRect = [&](const Rect& r) {+ return r.w > 0 && r.h > 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;+ };+ Rect play = playRect_.w > 0 ? playRect_ : Rect{kMargin, 620, 300, 76};+ if (inRect(play) || inRect(claimRect_)) {+ if (detailButtonFocus_ != 0) {+ detailButtonFocus_ = 0;+ dirty_ = true;+ }+ } else if (inRect(achRect_)) {+ if (detailButtonFocus_ != 1) {+ detailButtonFocus_ = 1;+ dirty_ = true;+ }+ }+ }+ return ev;+}++UiEvent AppUi::onMouseDown(float x, float y, int button) {+ std::lock_guard<std::mutex> lock(mutex_);+ UiEvent ev;+ mouseCursorX_ = std::clamp(x, 0.0f, 1919.0f);+ mouseCursorY_ = std::clamp(y, 0.0f, 1079.0f);+ mouseCursorVisible_ = true;+ mouseCursorVisibleUntil_ = platform::nowMs() + 3000;+ dirty_ = true;+ if (screen_ == Screen::Streaming || screen_ == Screen::Splash) {+ return ev;+ }+ if (button == 3) {+ // Right click: Back+ if (reportOpen_) {+ reportOpen_ = false;+ dirty_ = true;+ return ev;+ }+ if (screen_ == Screen::Home && updatePrompt_) {+ if (showingUpdateNotes_) {+ showingUpdateNotes_ = false;+ } else {+ ev.action = Action::UpdateLater;+ updatePrompt_ = false;+ }+ dirty_ = true;+ return ev;+ }+ if (countryPickerOpen_) {+ countryPickerOpen_ = false;+ dirty_ = true;+ return ev;+ }+ if (screen_ == Screen::Home && quitPrompt_) {+ quitPrompt_ = false;+ dirty_ = true;+ return ev;+ }+ if (screen_ == Screen::Settings) {+ if (pickerOpen_) {+ handleColourPicker(NavInput{.back = true});+ dirty_ = true;+ return ev;+ }+ if (tester_ == Tester::SignInCheck || tester_ == Tester::NetworkTest || tester_ == Tester::Donation) {+ tester_ = Tester::None;+ dirty_ = true;+ return ev;+ }+ if (tester_ != Tester::None) {+ handleTester(NavInput{.back = true});+ if (tester_ == Tester::None) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ dirty_ = true;+ return ev;+ }+ }+ if (dropdownOpen_) {+ dropdownOpen_ = false;+ dirty_ = true;+ return ev;+ }+ if (achievementsOpen_) {+ achievementsOpen_ = false;+ dirty_ = true;+ return ev;+ }+ if (gameSettingsOpen_) {+ handleGameSettings(NavInput{.back = true}, ev);+ return ev;+ }+ if (searching_) {+ searching_ = false;+ dirty_ = true;+ return ev;+ }+ if (screen_ == Screen::Settings) {+ resetSettingsHoldStart_ = 0;+ screen_ = settingsFromError_ ? Screen::Error : Screen::Home;+ dirty_ = true;+ ev.action = settings_.loginCountry != settingsCountry_ ? Action::LoginCountry : Action::SettingsChanged;+ ev.settings = settings_;+ return ev;+ }+ if (screen_ == Screen::Details) {+ syncHeroToRowsLocked(detail_.productId, detail_.titleId, detail_.heroUrl, detail_.description, detail_.publisher, detail_.categories);+ screen_ = Screen::Home;+ dirty_ = true;+ return ev;+ }+ return ev;+ }+ if (button != 1) return ev;++ if (reportOpen_ || countryPickerOpen_ || (screen_ == Screen::Home && (updatePrompt_ || quitPrompt_))) {+ return ev;+ }++ // Check avatar / profile click to open settings+ if (screen_ == Screen::Home && !searching_) {+ constexpr int kAvatar = 52;+ if (x >= kW - kMargin - kAvatar && x <= kW - kMargin && y >= 40 && y <= 100) {+ screen_ = Screen::Settings;+ settingsRow_ = 0;+ settingsFromError_ = false;+ settingsCountry_ = settings_.loginCountry;+ dropdownOpen_ = false;+ filterList_ = -1;+ dirty_ = true;+ return ev;+ }+ }++ // Check top bar tabs+ if (screen_ == Screen::Home && !searching_ && y >= 45 && y <= 95) {+ const char* labels[3] = {tr(Str::TabGamePass), tr(Str::YourGames), tr(Str::TabConsoles)};+ constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;+ int widths[3], total = 0;+ for (int i = 0; i < 3; ++i) {+ widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;+ total += widths[i + 0] + (i ? kGap : 0);+ }+ int tabX = (kW - total) / 2;+ for (int i = 0; i < 3; ++i) {+ if (x >= tabX && x < tabX + widths[i] && y >= kY && y < kY + kH) {+ tab_ = static_cast<Tab>(i);+ searching_ = false;+ dirty_ = true;+ if (tab_ == Tab::Consoles) ev.action = Action::ConsolesShown;+ return ev;+ }+ tabX += widths[i] + kGap;+ }+ }++ if (screen_ == Screen::Home && !searching_) {+ if (tab_ == Tab::GamePass && y >= 140 && y < kH - 80) {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int gridLeft = (kW - kGridW) / 2;+ int afterGridOffset = 0;+ for (size_t r = 0; r < rows_.size(); ++r) {+ float rel = static_cast<float>(r) - rowY_.value;+ int rowBaseY = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;+ const GameRow& row = rows_[r];+ if (row.isGrid) {+ int offset = static_cast<int>(std::lround(rowScroll_[r].value));+ int cardY = rowBaseY - offset + 48;+ for (size_t i = 0; i < row.tiles.size(); ++i) {+ int c_col = static_cast<int>(i) % kLibraryCols;+ int c_row = static_cast<int>(i) / kLibraryCols;+ int cy = cardY + c_row * kGridPitchY;+ int cx = gridLeft + c_col * kCardPitch;+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {+ focusRow_ = static_cast<int>(r);+ focusCol_[r] = static_cast<int>(i);+ openDetails(row.tiles[i]);+ return ev;+ }+ }+ int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;+ afterGridOffset += gridHeight - offset - kRowPitch;+ } else {+ int cardY = rowBaseY + 48;+ int scroll = static_cast<int>(std::lround(rowScroll_[r].value));+ int firstCol = std::max(0, scroll / kCardPitch - 1);+ for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {+ int cx = kMargin + static_cast<int>(col) * kCardPitch - scroll;+ if (cx > kW) break;+ if (x >= cx && x < cx + kCard && y >= cardY && y < cardY + kCard) {+ focusRow_ = static_cast<int>(r);+ focusCol_[r] = static_cast<int>(col);+ openDetails(row.tiles[col]);+ return ev;+ }+ }+ }+ }+ } else if (tab_ == Tab::Library) {+ if (y >= 150 && y < kH - 80) {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int left = (kW - kGridW) / 2;+ const LibraryLayout& L = libraryLayout();+ int offset = static_cast<int>(std::lround(gridScroll_.value));+ for (size_t i = 0; i < L.rowOf.size(); ++i) {+ int cy = kLibraryTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;+ int cx = left + L.colOf[i] * kCardPitch;+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {+ gridFocus_ = static_cast<int>(i);+ const GameTile* t = libraryTile(static_cast<int>(i));+ if (t) openDetails(*t);+ return ev;+ }+ }+ }+ constexpr int kAvatar = 52;+ int right = kW - kMargin - kAvatar - 16;+ if (x >= right - 200 && x <= right && y >= 110 && y <= 145) {+ librarySort_ = static_cast<LibrarySort>((static_cast<int>(librarySort_) + 1) %+ static_cast<int>(LibrarySort::Count));+ rebuild(true);+ prefsEvent(ev);+ dirty_ = true;+ return ev;+ }+ }+ } else if (screen_ == Screen::Details) {+ if (gameSettingsOpen_) {+ constexpr int kModalW = 1140, kModalH = 960;+ constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);+ const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);+ auto groups = [](const std::vector<SettingsRowPos>& v) {+ return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));+ };+ const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -+ (groups(all) - groups(most)) * kGroupGap;+ Rect panel{(kW - kModalW) / 2, (kH - modalH) / 2, kModalW, modalH};+ int curY = panel.y + 92;+ for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {+ if (rows[static_cast<size_t>(pos)].groupStart) curY += kGroupGap;+ Rect r{panel.x + 50, curY, panel.w - 100, kRowH};+ if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {+ gameSettingsRow_ = pos;+ handleGameSettings(NavInput{.accept = true}, ev);+ dirty_ = true;+ return ev;+ }+ curY += kRowH + kGap;+ }+ if (x < panel.x || x >= panel.x + panel.w || y < panel.y || y >= panel.y + panel.h) {+ handleGameSettings(NavInput{.back = true}, ev);+ }+ return ev;+ }+ if (achievementsOpen_) {+ return ev;+ }+ const GameTile* g = &detail_;+ if (g->productId.empty() && g->titleId.empty()) return ev;+ bool isF2P = isFreeGame(*g);+ bool effectivePlayable = isEffectivePlayableLocked(*g);+ auto inRect = [&](const Rect& r) {+ return r.w > 0 && r.h > 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;+ };+ if (!effectivePlayable && isF2P && !g->playable) {+ Rect claim = claimRect_.w > 0 ? claimRect_ : Rect{kMargin, 620, 380, 68};+ if (inRect(claim)) {+ detailButtonFocus_ = 0;+ ev.action = Action::ClaimFreeGame;+ ev.game = detail_;+ ev.game.freeInStore = true;+ return ev;+ }+ } else if (effectivePlayable) {+ Rect play = playRect_.w > 0 ? playRect_ : Rect{kMargin, 620, 300, 76};+ if (inRect(play)) {+ detailButtonFocus_ = 0;+ ev.action = Action::Play;+ ev.game = detail_;+ return ev;+ }+ if (inRect(achRect_) && !detail_.xboxTitleId.empty()) {+ detailButtonFocus_ = 1;+ openAchievements();+ return ev;+ }+ }+ } else if (screen_ == Screen::Settings) {+ if (tester_ != Tester::None || pickerOpen_) {+ return ev;+ }+ if (dropdownOpen_) {+ auto options = settingOptions(settingsRow_);+ constexpr int kItemH = 62, kVisible = 8, kListW = 640;+ int n = static_cast<int>(options.size());+ int visible = std::min(n, kVisible);+ constexpr int kRowW = 1140, kRowH = 30, kGap = 2, kGroupGap = 4;+ Rect panel{kMargin + kRowW - kListW, 184, kListW, visible * kItemH + 16};+ int curY = 184;+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {+ if (groupStart) curY += kGroupGap;+ if (i == settingsRow_) {+ panel.y = curY + kRowH + 8;+ break;+ }+ curY += kRowH + kGap;+ }+ if (panel.y + panel.h > kH - 100) panel.y = std::max(120, kH - 100 - panel.h);++ if (x >= panel.x && x < panel.x + panel.w && y >= panel.y && y < panel.y + panel.h) {+ for (int k = 0; k < visible; ++k) {+ int i = dropdownTop_ + k;+ Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};+ if (x >= item.x && x < item.x + item.w && y >= item.y && y < item.y + item.h && i < n) {+ int before = settingSelected(settingsRow_);+ applySetting(settingsRow_, i);+ dropdownOpen_ = false;+ dirty_ = true;+ if (settingsRow_ == 6 && i == 1) {+ openColourPicker(before);+ } else if (settingsRow_ != 8) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ return ev;+ }+ }+ } else {+ dropdownOpen_ = false;+ dirty_ = true;+ return ev;+ }+ }+ constexpr int kRowW = 1140, kRowH = 30, kGap = 2, kGroupGap = 4;+ int curY = 184;+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {+ if (groupStart) curY += kGroupGap;+ if (x >= kMargin && x < kMargin + kRowW && y >= curY && y < curY + kRowH) {+ settingsRow_ = i;+ if (i == 14) {+ openPadTester();+ return ev;+ } else if (i == 3 || i == 4 || i == 12) {+ openTester(i == 3 ? Tester::Sticks : i == 4 ? Tester::Triggers : Tester::Keys);+ return ev;+ } else if (i == 17) {+ openTester(Tester::SignInCheck);+ ev.action = Action::CheckSignIn;+ return ev;+ } else if (i == 18) {+ openTester(Tester::NetworkTest);+ ev.action = Action::RunNetworkTest;+ return ev;+ } else if (i == 19) {+ openTester(Tester::Donation);+ return ev;+ } else if (i == 7) {+ if (!caps_.selfUpdate) {+ if (caps_.openUrl) {+ ev.action = Action::OpenUrl;+ ev.url = kReleasesPage;+ }+ } else if (!updateAvailable_.empty() && !updateChecking_) {+ ev.action = Action::UpdateNow;+ ev.settings = settings_;+ }+ return ev;+ } else if (i == 10) {+ int n = static_cast<int>(settingOptions(10).size());+ if (n > 0) applySetting(10, (settingSelected(10) + 1) % n);+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ dirty_ = true;+ return ev;+ } else if (i == 23) {+ return ev;+ } else if (i == 5) {+ settings_.circleConfirms = !settings_.circleConfirms;+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ dirty_ = true;+ return ev;+ } else {+ auto opts = settingOptions(i);+ if (opts.size() > 2) {+ dropdownOpen_ = true;+ dropdownIndex_ = settingSelected(i);+ dropdownTop_ = std::max(0, dropdownIndex_ - 4);+ dirty_ = true;+ return ev;+ }+ changeSetting(1);+ if (i != 8) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ dirty_ = true;+ return ev;+ }+ }+ curY += kRowH + kGap;+ }+ }+ return ev;+}++UiEvent AppUi::onMouseWheel(float dx, float dy) {+ std::lock_guard<std::mutex> lock(mutex_);+ UiEvent ev;+ mouseCursorVisible_ = true;+ mouseCursorVisibleUntil_ = platform::nowMs() + 3000;+ dirty_ = true;+ if (screen_ == Screen::Streaming || screen_ == Screen::Splash) {+ return ev;+ }+ if (screen_ == Screen::Home && updatePrompt_ && showingUpdateNotes_) {+ updateNotesScroll_ = std::clamp(updateNotesScroll_ - static_cast<int>(dy * 2), 0, updateNotesMaxScroll_);+ dirty_ = true;+ return ev;+ }+ if (screen_ == Screen::Home && !searching_ && !updatePrompt_ && !quitPrompt_ && !reportOpen_) {+ if (tab_ == Tab::Library) {+ const LibraryLayout& L = libraryLayout();+ float maxScroll = L.rowY.empty() ? 0.0f : static_cast<float>(std::max(0, L.rowY.back() + kGridPitchY - (kH - kLibraryTop)));+ gridScroll_.target = std::clamp(gridScroll_.target - dy * 140.0f, 0.0f, maxScroll);+ animating_ = true;+ dirty_ = true;+ } else if (tab_ == Tab::GamePass) {+ if (!rows_.empty()) {+ const GameRow& curRow = rows_[static_cast<size_t>(focusRow_)];+ if (curRow.isGrid) {+ int totalRows = (static_cast<int>(curRow.tiles.size()) + kLibraryCols - 1) / kLibraryCols;+ float maxScroll = std::max(0.0f, static_cast<float>(totalRows * kGridPitchY - (kH - kRowTop - 48)));+ if (dy > 0 && rowScroll_[static_cast<size_t>(focusRow_)].target <= 0.0f) {+ if (focusRow_ > 0) {+ --focusRow_;+ retarget();+ animating_ = true;+ dirty_ = true;+ }+ } else {+ rowScroll_[static_cast<size_t>(focusRow_)].target =+ std::clamp(rowScroll_[static_cast<size_t>(focusRow_)].target - dy * 140.0f, 0.0f, maxScroll);+ animating_ = true;+ dirty_ = true;+ }+ } else {+ if (std::abs(dy) > std::abs(dx)) {+ int nextRow = std::clamp(static_cast<int>(rowY_.target - dy), 0, static_cast<int>(rows_.size()) - 1);+ if (nextRow != focusRow_) {+ focusRow_ = nextRow;+ retarget();+ animating_ = true;+ dirty_ = true;+ }+ } else if (dx != 0.0f) {+ float maxScroll = std::max(0.0f, static_cast<float>(static_cast<int>(curRow.tiles.size()) * kCardPitch - (kW - kMargin)));+ rowScroll_[static_cast<size_t>(focusRow_)].target =+ std::clamp(rowScroll_[static_cast<size_t>(focusRow_)].target - dx * 160.0f, 0.0f, maxScroll);+ animating_ = true;+ dirty_ = true;+ }+ }+ }+ }+ } else if (screen_ == Screen::Details && achievementsOpen_) {+ achScroll_ = std::max(0, achScroll_ - static_cast<int>(dy * 3));+ dirty_ = true;+ }+ return ev;+}++UiEvent AppUi::handle(const NavInput& in) {+ std::lock_guard<std::mutex> lock(mutex_);+ UiEvent ev;+ if (screen_ == Screen::Splash) {+ return ev;+ }+ if (reportOpen_) { // the report's QR code: Circle (or Cross) closes it+ if (in.accept && caps_.openUrl) {+ // A desktop: Cross opens the form in the browser (the panel stays).+ ev.action = Action::OpenUrl;+ ev.url = reportUrl_;+ } else if (in.back || in.accept) {+ reportOpen_ = false, dirty_ = true;+ }+ return ev;+ }+ if (screen_ == Screen::Home && updatePrompt_) {+ if (showingUpdateNotes_) {+ if (in.up) {+ if (updateNotesScroll_ > 0) {+ --updateNotesScroll_;+ dirty_ = true;+ }+ } else if (in.down) {+ if (updateNotesScroll_ < updateNotesMaxScroll_) {+ ++updateNotesScroll_;+ dirty_ = true;+ }+ } else if (in.l1 || in.l2) {+ if (updateNotesScroll_ > 0) {+ updateNotesScroll_ = std::max(0, updateNotesScroll_ - 5);+ dirty_ = true;+ }+ } else if (in.r1 || in.r2) {+ if (updateNotesScroll_ < updateNotesMaxScroll_) {+ updateNotesScroll_ = std::min(updateNotesMaxScroll_, updateNotesScroll_ + 5);+ dirty_ = true;+ }+ } else if (in.scrollRows != 0) {+ int next = std::clamp(updateNotesScroll_ + in.scrollRows, 0, updateNotesMaxScroll_);+ if (next != updateNotesScroll_) {+ updateNotesScroll_ = next;+ dirty_ = true;+ }+ } else if (in.back || in.accept || in.square) {+ showingUpdateNotes_ = false;+ dirty_ = true;+ }+ return ev;+ }+ // 3 buttons: 0 Update now, 1 What's new, 2 Not now+ if (in.square) {+ showingUpdateNotes_ = true;+ updateNotesScroll_ = 0;+ formatUpdateNotes();+ dirty_ = true;+ return ev;+ }+ if (in.left) {+ promptFocus_ = (promptFocus_ + 2) % 3;+ dirty_ = true;+ } else if (in.right) {+ promptFocus_ = (promptFocus_ + 1) % 3;+ dirty_ = true;+ }+ if (in.accept) {+ if (promptFocus_ == 0) {+ ev.action = Action::UpdateNow;+ updatePrompt_ = false;+ dirty_ = true;+ } else if (promptFocus_ == 1) {+ showingUpdateNotes_ = true;+ updateNotesScroll_ = 0;+ formatUpdateNotes();+ dirty_ = true;+ } else {+ ev.action = Action::UpdateLater;+ updatePrompt_ = false;+ dirty_ = true;+ }+ } else if (in.back) {+ ev.action = Action::UpdateLater;+ updatePrompt_ = false;+ dirty_ = true;+ }+ return ev;+ }+ if (countryPickerOpen_) {+ // "Sign in as another country": up / down, Cross signs in as the+ // one chosen, Circle closes it unchanged.+ int n = 1 + static_cast<int>(std::size(kLoginCountries));+ if (in.down && countryIndex_ + 1 < n) ++countryIndex_, dirty_ = true;+ if (in.up && countryIndex_ > 0) --countryIndex_, dirty_ = true;+ if (in.accept) {+ settings_.loginCountry = countryIndex_ ? kLoginCountries[countryIndex_ - 1] : "";+ ev.action = Action::LoginCountry;+ ev.settings = settings_;+ }+ if (in.accept || in.back) countryPickerOpen_ = false, dirty_ = true;+ return ev;+ }+ switch (screen_) {+ case Screen::Home:+ if (quitPrompt_) { // two buttons, Close / Cancel: left / right picks, Cross presses, Circle cancels+ if (in.left || in.right) promptFocus_ = in.left ? 0 : 1, dirty_ = true;+ if (in.accept && promptFocus_ == 0) ev.action = Action::Quit;+ if (in.accept || in.back) quitPrompt_ = false, dirty_ = true;+ break;+ }+ // A desktop window has no system menu to close it from (fullscreen,+ // a controller in hand): Circle / Esc at the top of the home screen+ // asks. On the PS5 the system closes the app; Circle does nothing here.+ if (caps_.desktopWindow && in.back && !searching_) {+ quitPrompt_ = true;+ promptFocus_ = 1; // Cancel first: a second Circle / Esc never closes by accident+ dirty_ = true;+ break;+ }+ handleHome(in, ev);+ break;+ case Screen::SignIn:+ // A desktop: Cross (Enter) opens the sign-in page in the browser.+ if (in.accept && caps_.openUrl) {+ ev.action = Action::OpenUrl;+ ev.url = codeUrl_.empty() ? "https://www.microsoft.com/link" : codeUrl_;+ }+ break;+ case Screen::Settings:+ if (pickerOpen_) {+ handleColourPicker(in);+ if (!pickerOpen_ && in.accept) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ break;+ }+ if (tester_ == Tester::SignInCheck) {+ if (in.back) {+ tester_ = Tester::None;+ dirty_ = true;+ } else if (in.accept && !signInCheck_.running) {+ ev.action = Action::CheckSignIn;+ }+ break;+ }+ if (tester_ == Tester::NetworkTest) {+ if (in.back) {+ tester_ = Tester::None;+ dirty_ = true;+ } else if (in.accept && !networkTest_.running) {+ ev.action = Action::RunNetworkTest;+ }+ break;+ }+ if (tester_ == Tester::Donation) {+ if (in.back || in.accept) {+ tester_ = Tester::None;+ dirty_ = true;+ }+ break;+ }+ if (tester_ != Tester::None) {+ handleTester(in);+ if (tester_ == Tester::None) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ break;+ }+ if (dropdownOpen_) {+ // The list: up / down, Cross picks, Circle closes it unchanged.+ int n = static_cast<int>(settingOptions(settingsRow_).size());+ if (in.down && dropdownIndex_ + 1 < n) ++dropdownIndex_;+ if (in.up && dropdownIndex_ > 0) --dropdownIndex_;+ int before = settingSelected(settingsRow_);+ if (in.accept) applySetting(settingsRow_, dropdownIndex_);+ if (in.accept || in.back) dropdownOpen_ = false;+ if (in.accept && settingsRow_ == 6 && dropdownIndex_ == 1) {+ openColourPicker(before);+ } else if (in.accept && settingsRow_ != 8) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ dirty_ = true;+ break;+ }+ if (auto rows = visibleSettingsRows(caps_); true) { // the rows on screen, in their order+ int pos = posOf(rows, settingsRow_);+ if (in.down && pos + 1 < static_cast<int>(rows.size())) {+ settingsRow_ = rows[static_cast<size_t>(pos + 1)].row;+ resetSettingsHoldStart_ = 0;+ dirty_ = true;+ } else if (in.up && pos > 0) {+ settingsRow_ = rows[static_cast<size_t>(pos - 1)].row;+ resetSettingsHoldStart_ = 0;+ dirty_ = true;+ }+ }+ if (settingsRow_ == 23) {+ if (in.acceptHeld) {+ if (!resetSettingsHoldStart_) resetSettingsHoldStart_ = in.nowMs ? in.nowMs : 1;+ if (in.nowMs - resetSettingsHoldStart_ >= 5000) {+ ev.action = Action::ResetSettings;+ resetSettingsHoldStart_ = 0;+ }+ animating_ = true;+ dirty_ = true;+ } else if (resetSettingsHoldStart_) {+ resetSettingsHoldStart_ = 0;+ dirty_ = true;+ }+ } else {+ resetSettingsHoldStart_ = 0;+ }+ if (in.right && settingsRow_ != 23) {+ changeSetting(+1);+ if (settingsRow_ != 8) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ }+ if (in.left && settingsRow_ != 23) {+ changeSetting(-1);+ if (settingsRow_ != 8) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ }+ if (in.square && settingsRow_ == 16) {+ ev.action = Action::TestQueueAlert;+ }+ if (in.accept && settingsRow_ == 14) {+ openPadTester(); // controller buttons: their own screen+ } else if (in.accept && (settingsRow_ == 3 || settingsRow_ == 4 || settingsRow_ == 12)) {+ // Dead zone, trigger vibration, keyboard keys: their own screens instead of a list.+ openTester(settingsRow_ == 3 ? Tester::Sticks : settingsRow_ == 4 ? Tester::Triggers : Tester::Keys);+ } else if (in.accept && settingsRow_ == 17) {+ openTester(Tester::SignInCheck);+ ev.action = Action::CheckSignIn;+ } else if (in.accept && settingsRow_ == 18) {+ openTester(Tester::NetworkTest);+ ev.action = Action::RunNetworkTest;+ } else if (in.accept && settingsRow_ == 19) {+ openTester(Tester::Donation);+ } else if (in.accept && settingsRow_ == 7) {+ // Updates: a newer version is installed (the settings saved+ // first). Where the app doesn't install it, the release's+ // page opens in the browser instead.+ if (!caps_.selfUpdate) {+ if (caps_.openUrl) {+ ev.action = Action::OpenUrl;+ ev.url = kReleasesPage;+ }+ } else if (!updateAvailable_.empty() && !updateChecking_) {+ ev.action = Action::UpdateNow;+ ev.settings = settings_;+ }+ } else if (in.accept && settingsRow_ == 10) {+ // Inline bitrate slider: cycles to next option, no dropdown modal+ int n = static_cast<int>(settingOptions(10).size());+ if (n > 0) {+ applySetting(10, (settingSelected(10) + 1) % n);+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ dirty_ = true;+ }+ } else if (in.accept && settingsRow_ == 23) {+ // Handled via hold+ } else if (in.accept) {+ dropdownOpen_ = true;+ dropdownIndex_ = settingSelected(settingsRow_);+ dropdownTop_ = 0;+ dirty_ = true;+ }+ if (in.back || in.options) {+ resetSettingsHoldStart_ = 0;+ // Back where Settings was opened. A new sign-in country+ // takes a new sign-in.+ screen_ = settingsFromError_ ? Screen::Error : Screen::Home;+ dirty_ = true;+ ev.action = settings_.loginCountry != settingsCountry_ ? Action::LoginCountry : Action::SettingsChanged;+ ev.settings = settings_;+ } else if (in.triangle) {+ ev.action = Action::Report; // "Report a problem"+ }+ break;+ case Screen::Details:+ if (achievementsOpen_) {+ if (in.up && achScroll_ > 0) {+ achScroll_--;+ dirty_ = true;+ }+ int maxScroll = 0;+ if (auto it = achievements_.find(detail_.xboxTitleId); it != achievements_.end()) {+ maxScroll = std::max(0, static_cast<int>(it->second.items.size()) - 5);+ }+ if (in.down && achScroll_ < maxScroll) {+ achScroll_++;+ dirty_ = true;+ }+ if (in.back || in.l3) {+ achievementsOpen_ = false;+ dirty_ = true;+ }+ break;+ }+ if (gameSettingsOpen_) {+ handleGameSettings(in, ev);+ break;+ }+ if (in.options) {+ openGameSettings();+ dirty_ = true;+ break;+ }+ {+ bool isF2P = isFreeGame(detail_);+ bool effectivePlayable = isEffectivePlayableLocked(detail_);+ bool hasAchievements = effectivePlayable && !detail_.xboxTitleId.empty();+ if (!hasAchievements && detailButtonFocus_ == 1) {+ detailButtonFocus_ = 0;+ }+ if (in.right && hasAchievements && detailButtonFocus_ == 0) {+ detailButtonFocus_ = 1;+ dirty_ = true;+ } else if (in.left && detailButtonFocus_ == 1) {+ detailButtonFocus_ = 0;+ dirty_ = true;+ }+ if (in.accept) {+ if (detailButtonFocus_ == 1 && hasAchievements) {+ openAchievements();+ } else if (!effectivePlayable && isF2P && !detail_.playable) {+ ev.action = Action::ClaimFreeGame;+ ev.game = detail_;+ ev.game.freeInStore = true;+ } else if (effectivePlayable) {+ ev.action = Action::Play;+ ev.game = detail_;+ }+ }+ }+ if (in.square) toggleHidden(detail_, ev); // the page stays open+ if (in.triangle) toggleFavorite(detail_, ev);+ if (in.r3 && !isAcquired(detail_)) toggleWishlist(detail_, ev);+ if (in.l3 && !detail_.xboxTitleId.empty()) openAchievements();+ if (in.back) {+ syncHeroToRowsLocked(detail_.productId, detail_.titleId, detail_.heroUrl, detail_.description, detail_.publisher, detail_.categories);+ screen_ = Screen::Home;+ dirty_ = true;+ }+ break;+ case Screen::Launching:+ if (in.back) ev.action = Action::CancelLaunch;+ break;+ case Screen::Error:+ if (!errorGame_.titleId.empty() || !errorGame_.productId.empty()) {+ if (in.accept) {+ if ((isFreeGame(errorGame_) || errorGame_.freeInStore) && !errorGame_.playable) {+ ev.action = Action::ClaimFreeGame;+ ev.game = errorGame_;+ ev.game.freeInStore = true;+ } else if (errorGame_.playable && !errorGame_.titleId.empty()) {+ ev.action = Action::Play;+ ev.game = errorGame_;+ } else {+ openDetails(errorGame_);+ }+ } else if (in.back && errorGame_.homeConsole) {+ screen_ = Screen::Home; // back to My consoles+ tab_ = Tab::Consoles;+ dirty_ = true;+ } else if (in.back) {+ openDetails(errorGame_);+ }+ } else if (in.accept) {+ ev.action = Action::Retry;+ } else if ((in.square || in.back) && !regionRefused_ && (!rows_.empty() || !owned_.empty())) {+ screen_ = Screen::Home;+ loading_ = false;+ dirty_ = true;+ }+ if (regionRefused_ && in.square) {+ countryPickerOpen_ = true;+ countryIndex_ = settingSelected(8);+ dirty_ = true;+ } else if (regionRefused_ && in.options) { // Settings, on the sign-in country+ screen_ = Screen::Settings;+ settingsRow_ = 8;+ settingsFromError_ = true;+ settingsCountry_ = settings_.loginCountry;+ dropdownOpen_ = false;+ dirty_ = true;+ }+ if (in.triangle) { // "Report a problem", with the error shown+ ev.action = Action::Report;+ ev.reportWhat = error_;+ }+ break;+ default: break;+ }+ // Sign out: hold TOUCHPAD for 5 s on the home or error screen.+ bool canSignOut = screen_ == Screen::Home || screen_ == Screen::Error;+ if (canSignOut && in.touchpad && !signOutLatched_) {+ if (!signOutHoldStart_) signOutHoldStart_ = in.nowMs ? in.nowMs : 1;+ if (in.nowMs - signOutHoldStart_ >= kSignOutHoldMs) {+ ev.action = Action::SignOut;+ signOutHoldStart_ = 0;+ signOutLatched_ = true;+ }+ dirty_ = true;+ } else if (!in.touchpad || !canSignOut) {+ if (signOutHoldStart_) dirty_ = true;+ signOutHoldStart_ = 0;+ if (!in.touchpad) signOutLatched_ = false;+ }+ if (displayModeChanged_) {+ // A desktop's display mode applies (and is saved) as it is picked,+ // not when Settings closes.+ displayModeChanged_ = false;+ if (ev.action == Action::None) {+ ev.action = Action::SettingsChanged;+ ev.settings = settings_;+ }+ }+ return ev;+}++// --- Rendering -----------------------------------------------------------------++} // namespace xc::uidiff --git a/src/ui/app_ui_internal.h b/src/ui/app_ui_internal.hnew file mode 100644index 0000000..c5c908b--- /dev/null+++ b/src/ui/app_ui_internal.h@@ -0,0 +1,386 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "ui/app_ui.h"+#include "ui/input_mode.h"+#include "ui/pad_glyphs.h"+#include "ui/pad_icons.h"++#include "input/tuning.h"+#include "xcloud/catalog.h"+#include "ui/accent_color.h"++#include "platform/platform.h"+#include "platform/toasts.h"+#include "ui/brand.h"+#include "ui/strings.h"+#include "ui/toast_view.h"+#include "app/update_check.h"++#include "qrcodegen.h"++#include <algorithm>+#include <cctype>+#include <cmath>+#include <map>+#include <unordered_map>+#include <unordered_set>++namespace xc::ui {++// A padlock centred on (cx, cy), about 24x30 px: a game the account can't play.+inline void drawLock(Canvas& c, int cx, int cy) {+ const Color white = rgba(255, 255, 255, 230);+ c.strokeArc(static_cast<float>(cx), static_cast<float>(cy - 4), 8, 3.5f, 3.1416f, 3.1416f, white);+ c.line(cx - 8.0f, cy - 4.0f, cx - 8.0f, cy + 1.0f, 3.5f, white);+ c.line(cx + 8.0f, cy - 4.0f, cx + 8.0f, cy + 1.0f, 3.5f, white);+ c.fillRect({cx - 12, cy, 24, 18}, white, 4);+}++constexpr int kW = 1920, kH = 1080;+constexpr int kMargin = 96;+constexpr int kCard = 240;+constexpr int kCardGap = 24;+constexpr int kCardPitch = kCard + kCardGap;+constexpr int kRowPitch = 340;+constexpr int kRowTop = 470; // y of the focused row's title+constexpr uint64_t kHeroFadeMs = 300;++constexpr Color kBg = rgba(14, 14, 14);+constexpr Color kWhite = rgba(255, 255, 255);+constexpr Color kGray = rgba(190, 190, 190);+constexpr Color kDim = rgba(140, 140, 140);+constexpr Color kGreen = rgba(16, 124, 16);+constexpr Color kPanel = rgba(36, 36, 36);+constexpr Color kPlaceholder = rgba(44, 44, 44);++enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle, kIconTouchpad, kIconSquare, kIconR3, kIconL3, kIconL2R2, kIconDpadLR, kIconL1R1 };++// The resolution list, lowest first: SettingsChoice::resolution value per+// position (0 = 1080p, 1 = 720p, 2 = 1440p, as saved).+constexpr int kResolutionOrder[3] = {1, 0, 2};+// Settings' rows on screen, alike ones together (the row ids stay what+// settingsRow_ and the helpers use): language, sign-in country, and sign-in check; the+// stream (resolution, a desktop's display mode, 120 Hz, bitrate, region, network test);+// the controller, keyboard and queue-ready alert; support and updates last. A group starts at each+// kSettingsGroupStart.+constexpr int kSettingsCount = 23;+constexpr int kSettingsOrder[kSettingsCount] = {0, 2, 8, 17, 18, 1, 20, 13, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 22, 19, 7, 23};+constexpr bool kSettingsGroupStart[kSettingsCount] = {false, false, false, false, false, true, false, false, false, false,+ true, false, false, false, false, false, false, false, false, false, true, false, true};+// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2+// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7+// confirm, 8 120 Hz, 9 keyboard keys, 10 back to the default, 11 controller+// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language, 15 video decoder, 16 audio-to-haptics).+constexpr int kGameRowCount = 17;+constexpr int kGameRowOrder[kGameRowCount] = {0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10};+constexpr bool kGameGroupStart[kGameRowCount] = {false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true};+// The keyboard keys' screen: two columns of inputs, then "Reset to default".+constexpr int kKeysPerColumn = input::kKeyActions / 2;+// Updates on a desktop: the newest release's page (the app doesn't install it there).+constexpr const char* kReleasesPage = "https://github.com/RafaelNGP/xbox-cloud-gaming-ps5/releases/latest";++// The rows of `order` that `shown` keeps. A group starts on screen where the+// row above belongs to another group (a hidden group leaves no gap).+template <size_t N, class Shown>+std::vector<SettingsRowPos> filterRows(const int (&order)[N], const bool (&groupStart)[N], Shown shown) {+ std::vector<SettingsRowPos> out;+ int group = 0, lastGroup = -1;+ for (size_t pos = 0; pos < N; ++pos) {+ if (groupStart[pos]) ++group;+ if (!shown(order[pos])) continue;+ out.push_back({order[pos], !out.empty() && group != lastGroup});+ lastGroup = group;+ }+ return out;+}++// Where `row` is in `rows` (0 when it isn't there).+inline int posOf(const std::vector<SettingsRowPos>& rows, int row) {+ for (size_t i = 0; i < rows.size(); ++i)+ if (rows[i].row == row) return static_cast<int>(i);+ return 0;+}++// Grids ("Your games", search results): cards with the name below.+constexpr int kGridPitchY = 300;+constexpr int kLibraryCols = 6;+constexpr int kResultCols = 4;+// Keeps the focused grid row on screen: scrolls once it passes the second row.+inline float gridTarget(int focus, int cols) { return static_cast<float>(std::max(0, focus / cols - 1) * kGridPitchY); }+constexpr int kGridTop = 236; // y of the first card row (search results)+constexpr int kLibraryTop = 160; // y where "Your games" starts (its first heading)+constexpr int kResultsX = 760;+constexpr int kSectionHeaderH = 96; // "Available to buy" heading in the grid+constexpr size_t kMaxResults = 60;+constexpr size_t kMaxFilterResults = 300; // filters with no words: lists, not lookups++// The search keyboard: 6 x 6 letters and digits, then Space / Delete / Clear.+constexpr const char* kKeys = "abcdefghijklmnopqrstuvwxyz0123456789";+constexpr int kKeyCols = 6, kKeyRows = 6; // + the row of wide keys+constexpr int kKeyW = 90, kKeyH = 62, kKeyGap = 10;+constexpr int kKeysY = 262;+constexpr int kWideCols[3] = {0, 3, 5}; // first column of Space, Delete, Clear+constexpr int kWideSpan[3] = {3, 2, 1};+constexpr int kKeysW = kKeyCols * (kKeyW + kKeyGap) - kKeyGap;+constexpr int kChipGap = 10;+inline int chipWidth(int count) { return (kKeysW - kChipGap * (count - 1)) / std::max(1, count); }++// Lower case, accents dropped (Latin-1 range), anything else a space: what+// the search compares.+inline std::string fold(const std::string& s) {+ static const char kLatin1[] = "aaaaaaaceeeeiiiidnooooo ouuuuytsaaaaaaaceeeeiiiidnooooo ouuuuyty";+ std::string out;+ out.reserve(s.size());+ for (size_t i = 0; i < s.size();) {+ unsigned char c = static_cast<unsigned char>(s[i]);+ uint32_t cp = ' ';+ size_t n = 1;+ if (c < 0x80) {+ cp = c;+ } else if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) {+ cp = ((c & 0x1Fu) << 6) | (static_cast<unsigned char>(s[i + 1]) & 0x3Fu);+ n = 2;+ } else if ((c & 0xF0) == 0xE0) {+ n = 3;+ } else if ((c & 0xF8) == 0xF0) {+ n = 4;+ }+ i += n;+ char ch = ' ';+ if (cp < 0x80 && std::isalnum(static_cast<int>(cp))) ch = static_cast<char>(std::tolower(static_cast<int>(cp)));+ else if (cp >= 0xC0 && cp <= 0xFF) ch = kLatin1[cp - 0xC0];+ out += ch;+ }+ return out;+}++// "164 games", "1 game".+inline std::string gamesCount(size_t n) { return n == 1 ? std::string(tr(Str::OneGame)) : trf(Str::GamesCount, std::to_string(n)); }++inline std::string withoutSpaces(std::string s) {+ s.erase(std::remove(s.begin(), s.end(), ' '), s.end());+ return s;+}++inline bool matchesPublisher(const std::string& rawPublisher, int filter) {+ if (filter <= 0) return true;+ std::string p = fold(rawPublisher);++ auto isXbox = [&]() {+ return p.find("xbox game studios") != std::string::npos ||+ p.find("microsoft") != std::string::npos ||+ p.find("bethesda") != std::string::npos ||+ p.find("mojang") != std::string::npos ||+ p.find("activision") != std::string::npos ||+ p.find("blizzard") != std::string::npos ||+ p.find("zenimax") != std::string::npos ||+ p.find("id software") != std::string::npos ||+ p.find("obsidian") != std::string::npos ||+ p.find("ninja theory") != std::string::npos ||+ p.find("double fine") != std::string::npos;+ };+ auto isEA = [&]() {+ return p.find("electronic arts") != std::string::npos ||+ p.find("ea swiss") != std::string::npos ||+ p.find("ea sports") != std::string::npos ||+ p == "ea" || p.find("ea ") == 0 ||+ p.find(" ea ") != std::string::npos;+ };+ auto isUbisoft = [&]() { return p.find("ubisoft") != std::string::npos; };+ auto isSquareEnix = [&]() { return p.find("square enix") != std::string::npos; };+ auto isWarner = [&]() { return p.find("warner") != std::string::npos || p.find("wb games") != std::string::npos; };+ auto is2K = [&]() {+ return p.find("2k") != std::string::npos ||+ p.find("take-two") != std::string::npos ||+ p.find("take two") != std::string::npos ||+ p.find("rockstar") != std::string::npos ||+ p.find("private division") != std::string::npos;+ };+ auto isCapcom = [&]() { return p.find("capcom") != std::string::npos; };+ auto isSega = [&]() { return p.find("sega") != std::string::npos || p.find("atlus") != std::string::npos; };+ auto isBandai = [&]() {+ return p.find("bandai namco") != std::string::npos ||+ p.find("namco bandai") != std::string::npos ||+ p.find("bandai") != std::string::npos;+ };+ auto isTHQ = [&]() {+ return p.find("thq nordic") != std::string::npos ||+ p.find("plaion") != std::string::npos ||+ p.find("deep silver") != std::string::npos ||+ p.find("koch media") != std::string::npos ||+ p.find("handygames") != std::string::npos ||+ p.find("embracer") != std::string::npos;+ };+ auto isFocus = [&]() { return p.find("focus entertainment") != std::string::npos || p.find("focus home") != std::string::npos || p == "focus"; };+ auto isDevolver = [&]() { return p.find("devolver") != std::string::npos; };+ auto isAnnapurna = [&]() { return p.find("annapurna") != std::string::npos; };+ auto isTeam17 = [&]() { return p.find("team17") != std::string::npos || p.find("team 17") != std::string::npos; };++ switch (filter) {+ case 1: return isXbox();+ case 2: return isEA();+ case 3: return isUbisoft();+ case 4: return isSquareEnix();+ case 5: return isWarner();+ case 6: return is2K();+ case 7: return isCapcom();+ case 8: return isSega();+ case 9: return isBandai();+ case 10: return isTHQ();+ case 11: return isFocus();+ case 12: return isDevolver();+ case 13: return isAnnapurna();+ case 14: return isTeam17();+ case 15: // Indies & Outras+ return !isXbox() && !isEA() && !isUbisoft() && !isSquareEnix() &&+ !isWarner() && !is2K() && !isCapcom() && !isSega() &&+ !isBandai() && !isTHQ() && !isFocus() && !isDevolver() &&+ !isAnnapurna() && !isTeam17();+ default: return true;+ }+}++constexpr uint64_t kSignOutHoldMs = 5000;++inline std::string loginCountryName(const std::string& country) {+ static const std::pair<const char*, Str> kNames[] = {+ {"br", Str::CountryBR}, {"jp", Str::CountryJP}, {"kr", Str::CountryKR}, {"pl", Str::CountryPL}, {"us", Str::CountryUS}};+ for (const auto& [code, name] : kNames)+ if (country == code) return tr(name);+ return {};+}++inline int consoleRank(const std::string& platform) {+ return platform == "XS" ? 0 : platform == "ONE" ? 1 : platform == "360" ? 2 : 3;+}++// Hue 0..1, saturation and value 0..1.+inline Color hsvColour(float h, float s, float v) {+ h = (h - std::floor(h)) * 6.0f;+ int i = static_cast<int>(h) % 6;+ float f = h - std::floor(h), p = v * (1 - s), q = v * (1 - s * f), t = v * (1 - s * (1 - f));+ float r = i == 0 || i == 5 ? v : i == 1 ? q : i == 2 || i == 3 ? p : t;+ float g = i == 0 ? t : i == 1 || i == 2 ? v : i == 3 ? q : p;+ float b = i == 2 ? t : i == 3 || i == 4 ? v : i == 5 ? q : p;+ auto byte = [](float x) { return static_cast<uint8_t>(std::lround(std::clamp(x, 0.0f, 1.0f) * 255)); };+ return rgba(byte(r), byte(g), byte(b));+}++inline void colourHsv(Color c, float& h, float& s, float& v) {+ float r = (c & 0xFF) / 255.0f, g = (c >> 8 & 0xFF) / 255.0f, b = (c >> 16 & 0xFF) / 255.0f;+ float mx = std::max({r, g, b}), mn = std::min({r, g, b}), d = mx - mn;+ v = mx;+ s = mx > 0 ? d / mx : 0;+ if (d <= 0) h = 0;+ else if (mx == r) h = (g - b) / d / 6.0f;+ else if (mx == g) h = ((b - r) / d + 2) / 6.0f;+ else h = ((r - g) / d + 4) / 6.0f;+ if (h < 0) h += 1;+}++constexpr int kWheelR = 180;+constexpr float kMinValue = 0.2f; // darker turns the light bar all but off++// Settings' bitrate caps (Mbps, after Automatic) and game volumes (percent).+constexpr int kBitrateCaps[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};+constexpr int kVolumes[] = {25, 50, 75, 100, 150};++// Moves `focus` in a grid of `count` items, `cols` wide. Returns true if it moved.+inline bool moveInGrid(int& focus, int count, int cols, const NavInput& in) {+ int before = focus;+ if (in.right && focus + 1 < count && (focus + 1) % cols != 0) ++focus;+ if (in.left && focus % cols != 0) --focus;+ if (in.down && focus + cols < count) focus += cols;+ else if (in.down && focus / cols < (count - 1) / cols) focus = count - 1; // onto a short last row+ if (in.up && focus >= cols) focus -= cols;+ return focus != before;+}++inline PadButton faceOf(int icon) {+ return icon == kIconCross ? PadButton::Cross+ : icon == kIconCircle ? PadButton::Circle+ : icon == kIconSquare ? PadButton::Square+ : PadButton::Triangle;+}+inline void drawFaceButton(Canvas& c, const Font& letters, int icon, float cx, float cy, float r) {+ ui::drawFaceButton(c, letters, g_glyphStyle, faceOf(icon), cx, cy, r);+}++// A QR code of `url` on a white card whose top-right corner is (right, top),+// about `target` px of code; the card's rect (empty when it can't be encoded).+inline Rect drawQr(Canvas& c, const std::string& url, int right, int top, int target,+ qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM) {+ uint8_t qr[qrcodegen_BUFFER_LEN_MAX], tmp[qrcodegen_BUFFER_LEN_MAX];+ if (!qrcodegen_encodeText(url.c_str(), tmp, qr, ecc, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX,+ qrcodegen_Mask_AUTO, true))+ return {};+ int n = qrcodegen_getSize(qr);+ int module = target / (n + 2), size = module * (n + 2);+ Rect box{right - size - 40, top, size + 40, size + 40};+ c.fillRect(box, kWhite, 20);+ int ox = box.x + 20 + module, oy = box.y + 20 + 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);+ return box;+}++inline 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;+}++inline const char* planBadgeLabel(uint8_t plan) {+ if (plan == xcloud::kPlanEssential) return "ESSENTIAL";+ if (plan == xcloud::kPlanPremium) return "PREMIUM";+ if (plan == xcloud::kPlanUltimate) return "ULTIMATE";+ return nullptr;+}++inline const char* planDisplayName(uint8_t plan) {+ if (plan == xcloud::kPlanEssential) return "Essential";+ if (plan == xcloud::kPlanPremium) return "Premium";+ if (plan == xcloud::kPlanUltimate) return "Ultimate";+ return nullptr;+}++// A shopping bag centred on (cx, cy), about 22x24 px: a game to buy.+// A shopping bag (body + handle) centred on (cx, cy); `size` scales it+// (1 = 22 x 23 px).+inline void drawBag(Canvas& c, int cx, int cy, Color color, float size = 1.0f) {+ float w = 22 * size, h = 17 * size, r = 6 * size;+ float bodyTop = cy - (h + r) / 2 + r;+ c.fillRect({static_cast<int>(std::lround(cx - w / 2)), static_cast<int>(std::lround(bodyTop)),+ static_cast<int>(std::lround(w)), static_cast<int>(std::lround(h))},+ color, std::max(1, static_cast<int>(3 * size)));+ c.strokeArc(static_cast<float>(cx), bodyTop, r, std::max(1.5f, 2.5f * size), 3.1416f, 3.1416f, color);+}++// A 5-pointed star centred on (cx, cy) with outer radius r.+inline void drawStar(Canvas& c, float cx, float cy, float r, Color color) {+ constexpr float kPi = 3.14159265358979323846f;+ float innerR = r * 0.42f;+ float px[10], py[10];+ for (int i = 0; i < 10; ++i) {+ float angle = -kPi / 2.0f + i * (kPi / 5.0f);+ float radius = (i % 2 == 0) ? r : innerR;+ px[i] = cx + radius * std::cos(angle);+ py[i] = cy + radius * std::sin(angle);+ }+ for (int i = 0; i < 10; ++i) {+ int next = (i + 1) % 10;+ c.line(px[i], py[i], px[next], py[next], 1.2f, color);+ c.line(cx, cy, px[i], py[i], 1.5f, color);+ }+ c.fillCircle(cx, cy, innerR * 0.95f, color);+ for (int i = 0; i < 5; ++i) {+ int pt = i * 2;+ c.line(cx, cy, px[pt], py[pt], 2.0f, color);+ }+}++} // namespace xc::uidiff --git a/src/ui/app_ui_render.cpp b/src/ui/app_ui_render.cppnew file mode 100644index 0000000..3d83ed4--- /dev/null+++ b/src/ui/app_ui_render.cpp@@ -0,0 +1,1822 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "ui/app_ui_internal.h"++namespace xc::ui {++void AppUi::drawPads(Canvas& c) {+ // Bottom left, on the line of the button hints (which are right-aligned).+ drawPadRow(c, fonts_.bold, kMargin, kH - 26 - padIconHeight(48), 48, 16, pads_, kBg,+ fonts_.hasIcons ? &fonts_.icons : nullptr);+}++bool AppUi::needsRedraw(uint64_t nowMs) const {+ std::lock_guard<std::mutex> lock(mutex_);+ if (screen_ == Screen::Streaming) return false;+ if (dirty_ || animating_) return true;+ if (mouseCursorVisible_ && nowMs >= mouseCursorVisibleUntil_) return true;+ // A desktop's toast came or went (the PS5 sends system notifications).+ if (platform::toastsEnabled() && platform::toasts().version(nowMs) != toastsDrawn_) return true;+ // Spinners keep moving (about 30 fps is enough).+ bool spinner = screen_ == Screen::Splash || screen_ == Screen::SignIn || screen_ == Screen::Launching ||+ screen_ == Screen::Updating ||+ (screen_ == Screen::Settings && ((tester_ == Tester::SignInCheck && signInCheck_.running) ||+ (tester_ == Tester::NetworkTest && networkTest_.running)));+ return spinner && nowMs - lastRender_ >= 33;+}++void AppUi::drawCentered(Canvas& c, const Font& f, const std::string& text, int y, int px, Color color) {+ f.draw(c, text, (kW - f.measure(text, px)) / 2, y, px, color);+}++void AppUi::drawBackground(Canvas& c) {+ c.gradientV({0, 0, kW, kH}, rgba(24, 28, 24), kBg);+}++void AppUi::drawLogo(Canvas& c, float cx, float cy, float r) { drawBrandMark(c, cx, cy, r); }++void AppUi::drawGamerscoreBadge(Canvas& c, float cx, float cy, float r) {+ // A filled disc with a "G" cut out of it, drawn from shapes (a letter of+ // the font never sits in the middle of a circle): a ring open at the+ // upper right, and its bar from the centre to the ring.+ c.fillCircle(cx, cy, r, kGray);+ const float ring = r * 0.56f, t = r * 0.24f;+ const float kGap = 0.95f; // radians left open, above 3 o'clock+ c.strokeArc(cx, cy, ring, t, 0.0f, 6.2832f - kGap, kBg);+ c.line(cx + r * 0.05f, cy, cx + ring + t * 0.5f, cy, t, kBg);+}++void AppUi::drawTopBar(Canvas& c) {+ drawLogo(c, kMargin + 22, 72, 22);+ fonts_.semibold.draw(c, tr(Str::CloudGaming), kMargin + 64, 60, 22, kWhite);++ // Cloud playtime remaining badge positioned under the "PSBox Cloud Gaming" brand mark.+ // Purely informative; hidden from the active UI for now until Xbox Cloud Gaming enforces limits.+ constexpr bool kShowPlaytimeBadge = false;+ if (kShowPlaytimeBadge && playtimeRemaining_ >= 0) {+ int hours = static_cast<int>((playtimeRemaining_ + 3599) / 3600);+ std::string pt = trf(Str::HoursRemaining, std::to_string(hours));+ bool warn = playtimeRemaining_ <= 7200;+ Color col = warn ? rgba(255, 160, 40) : kGray;+ fonts_.semibold.draw(c, pt, kMargin + 64, 86, 14, col);+ }++ int x = kW - kMargin;+ constexpr int kAvatar = 52;+ x -= kAvatar;+ if (auto pic = images_.get(gamerpicUrl_, kAvatar, kAvatar)) {+ c.drawImage(*pic, x, 46, 255, -1);+ } else {+ c.fillCircle(x + kAvatar / 2.0f, 72, kAvatar / 2.0f, kPanel);+ }+ if (!gamertag_.empty()) {+ // The name; under it the gamerscore (its badge and the number, the+ // thousands grouped as the language writes them) and the Game Pass+ // plan, right-aligned to the picture as the Xbox app shows them.+ bool isFree = subscription_.empty() || (subscription_ != "GamePass" && xcloud::planTier(subscription_) == 0);+ bool second = !gamerscore_.empty() || !subscription_.empty() || isFree;+ int w = fonts_.semibold.measure(gamertag_, 22);+ fonts_.semibold.draw(c, gamertag_, x - 16 - w, second ? 44 : 59, 22, kWhite);+ int right = x - 16;+ constexpr int kLineY = 76, kLineH = 22, kLinePx = 17;+ const float midY = kLineY + kLineH / 2.0f;+ if (!subscription_.empty()) {+ // "GAME PASS", and the plan in an outlined box when it is known+ // ("GamePass": a member, the plan not known).+ int left = right;+ if (subscription_ != "GamePass") {+ std::string plan = subscription_;+ for (auto& ch : plan) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));+ int pw = fonts_.bold.measure(plan, 11);+ Rect box{right - pw - 10, static_cast<int>(midY) - 8, pw + 10, 16};+ c.strokeRect(box, kGray, 1, 2);+ fonts_.bold.draw(c, plan, box.x + 5, fonts_.bold.centeredY(box.y, box.h, 11), 11, kGray);+ left = box.x - 6;+ }+ const char* gp = "GAME PASS";+ int gw = fonts_.semibold.measure(gp, 14);+ fonts_.semibold.draw(c, gp, left - gw, fonts_.semibold.centeredY(kLineY, kLineH, 14), 14, kGray);+ right = left - gw - 16;+ } else if (isFree) {+ const char* freeLabel = "FREE";+ int fw = fonts_.bold.measure(freeLabel, 11);+ Rect box{right - fw - 12, static_cast<int>(midY) - 8, fw + 12, 16};+ c.fillRect(box, rgba(255, 255, 255, 20), 4);+ c.strokeRect(box, rgba(160, 160, 175, 180), 1, 4);+ fonts_.bold.draw(c, freeLabel, box.x + 6, fonts_.bold.centeredY(box.y, box.h, 11), 11, rgba(220, 225, 235, 255));+ right = box.x - 12;+ }+ if (!gamerscore_.empty()) {+ std::string n;+ const char* sep = language() == Language::English ? "," : ".";+ for (size_t i = 0; i < gamerscore_.size(); ++i) {+ if (i && (gamerscore_.size() - i) % 3 == 0) n += sep;+ n += gamerscore_[i];+ }+ int nw = fonts_.semibold.measure(n, kLinePx);+ int nx = right - nw;+ fonts_.semibold.draw(c, n, nx, fonts_.semibold.centeredY(kLineY, kLineH, kLinePx), kLinePx, kGray);+ drawGamerscoreBadge(c, nx - 13.0f, midY, 8.5f);+ right = nx - 26;+ }+ }+}++void AppUi::drawHints(Canvas& c, const std::vector<std::pair<int, const char*>>& hints) {+ // Right-aligned PlayStation button glyphs with labels.+ constexpr int kPx = 22, kR = 14, kGap = 36;+ int x = kW - kMargin;+ const int y = kH - 64;+ for (auto it = hints.rbegin(); it != hints.rend(); ++it) {+ // With Circle confirming, the pad reports it as Cross (and the+ // other way round): the hints show the button to press.+ int icon = it->first;+ int w = fonts_.semibold.measure(it->second, kPx);+ x -= w;+ fonts_.semibold.draw(c, it->second, x, y, kPx, kGray);+ if (g_keyboardHints) { // the keyboard's key, as a key cap+ const char* key = keyLabel(icon);+ int kw = fonts_.bold.measure(key, 15) + 18;+ Rect cap{x - 10 - kw, y + 1, kw, 26};+ c.fillRect(cap, rgba(255, 255, 255, 30), 6);+ c.strokeRect(cap, kGray, 2, 6);+ fonts_.bold.draw(c, key, cap.x + 9, fonts_.bold.centeredY(cap.y, cap.h, 15), 15, kWhite);+ x = cap.x - kGap;+ continue;+ }+ if (circleConfirms_ && (icon == kIconCross || icon == kIconCircle))+ icon = icon == kIconCross ? kIconCircle : kIconCross;+ x -= 10 + 2 * kR;+ float cx = x + kR, cy = y + 13;+ const GlyphStyle style = g_glyphStyle;+ const bool xbox = style == GlyphStyle::Xbox;+ if (icon == kIconL2R2 || icon == kIconL1R1) {+ const char* l = buttonName(style, icon == kIconL1R1 ? PadButton::L1 : PadButton::L2);+ const char* r = buttonName(style, icon == kIconL1R1 ? PadButton::R1 : PadButton::R2);+ int lw = fonts_.bold.measure(l, 14) + 16;+ int rw = fonts_.bold.measure(r, 14) + 16;+ int sepW = fonts_.regular.measure("|", 14);+ constexpr int kPillGap = 6;+ int rightX = x + 2 * kR;+ Rect rPill{rightX - rw, static_cast<int>(cy) - 12, rw, 24};+ c.fillRect(rPill, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, r, rPill.x + (rw - fonts_.bold.measure(r, 14)) / 2,+ fonts_.bold.centeredY(rPill.y, rPill.h, 14), 14, kGray);+ int sepX = rPill.x - kPillGap - sepW;+ fonts_.regular.draw(c, "|", sepX, fonts_.regular.centeredY(static_cast<int>(cy) - 12, 24, 14), 14,+ rgba(255, 255, 255, 120));+ Rect lPill{sepX - kPillGap - lw, static_cast<int>(cy) - 12, lw, 24};+ c.fillRect(lPill, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, l, lPill.x + (lw - fonts_.bold.measure(l, 14)) / 2,+ fonts_.bold.centeredY(lPill.y, lPill.h, 14), 14, kGray);+ x = lPill.x;+ } else if (icon == kIconDpadLR) {+ const char* l = "\xE2\x86\x90";+ const char* r = "\xE2\x86\x92";+ int lw = fonts_.bold.measure(l, 14) + 14;+ int rw = fonts_.bold.measure(r, 14) + 14;+ constexpr int kPillGap = 4;+ int rightX = x + 2 * kR;+ Rect rPill{rightX - rw, static_cast<int>(cy) - 12, rw, 24};+ c.fillRect(rPill, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, r, rPill.x + (rw - fonts_.bold.measure(r, 14)) / 2,+ fonts_.bold.centeredY(rPill.y, rPill.h, 14), 14, kGray);+ Rect lPill{rPill.x - kPillGap - lw, static_cast<int>(cy) - 12, lw, 24};+ c.fillRect(lPill, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, l, lPill.x + (lw - fonts_.bold.measure(l, 14)) / 2,+ fonts_.bold.centeredY(lPill.y, lPill.h, 14), 14, kGray);+ x = lPill.x;+ } else if (icon == kIconR3 || icon == kIconL3) {+ const char* label = buttonName(style, icon == kIconR3 ? PadButton::R3 : PadButton::L3);+ int pillW = fonts_.bold.measure(label, 14) + 16;+ int rightX = x + 2 * kR;+ Rect pill{rightX - pillW, static_cast<int>(cy) - 12, pillW, 24};+ c.fillRect(pill, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, label, pill.x + (pillW - fonts_.bold.measure(label, 14)) / 2,+ fonts_.bold.centeredY(pill.y, pill.h, 14), 14, kGray);+ x = pill.x;+ } else if (xbox && icon == kIconTouchpad) { // View+ drawXboxViewButton(c, cx, cy, kR, kGray);+ } else if (xbox && icon == kIconOptions) { // Menu+ drawXboxMenuButton(c, cx, cy, kR, kGray);+ } else if (icon == kIconTouchpad) {+ Rect pad{x - 18, static_cast<int>(cy) - 10, 2 * kR + 12, 20};+ c.fillRect(pad, rgba(255, 255, 255, 40), 6);+ c.strokeRect(pad, kGray, 2, 6);+ x -= 10;+ } else if (icon == kIconOptions) {+ c.fillRect({x - 4, static_cast<int>(cy) - 11, 2 * kR + 8, 22}, rgba(255, 255, 255, 40), 11);+ for (int k = -1; k <= 1; ++k) c.line(cx - 8, cy + k * 5, cx + 8, cy + k * 5, 2, kGray);+ } else {+ drawFaceButton(c, fonts_.bold, icon, cx, cy, kR);+ }+ x -= kGap;+ }+}++void AppUi::drawSpinner(Canvas& c, float cx, float cy, float r, uint64_t nowMs) {+ float t = static_cast<float>(nowMs % 1000) / 1000.0f * 6.2832f;+ c.strokeArc(cx, cy, r, r * 0.18f, t, 4.4f, kWhite);+}++void AppUi::drawToast(Canvas& c, uint64_t nowMs) {+ if (caps_.console) return;+ if (toast_.empty()) return;+ if (toastUntil_ == 0) toastUntil_ = nowMs + 3500;+ if (nowMs >= toastUntil_) {+ toast_.clear();+ return;+ }+ int w = fonts_.semibold.measure(toast_, 24) + 64;+ Rect r{(kW - w) / 2, kH - 150, w, 56};+ c.fillRect(r, rgba(40, 40, 40, 235), 28);+ fonts_.semibold.draw(c, toast_, r.x + 32, r.y + 14, 24, kWhite);+}++bool AppUi::drawHero(Canvas& c, uint64_t nowMs, const std::string& url, bool details) {+ if (url != heroUrl_) {+ // The previous art may only cross-fade into a new one that is already+ // there; it is never kept up while the new one downloads.+ prevHeroUrl_ = heroShownAt_ ? heroUrl_ : std::string();+ heroUrl_ = url;+ heroSince_ = nowMs;+ heroShownAt_ = 0;+ }+ auto current = heroUrl_.empty() ? nullptr : images_.get(heroUrl_, kW, kH);+ if (current) {+ if (!heroShownAt_) heroShownAt_ = nowMs;+ uint64_t age = nowMs - heroShownAt_;+ // Arrived at once (cached): cross-fade from the previous art. Arrived+ // later: fade in from the plain background.+ bool crossFade = heroShownAt_ - heroSince_ < 150 && !prevHeroUrl_.empty();+ auto previous = crossFade && age < kHeroFadeMs ? images_.get(prevHeroUrl_, kW, kH) : nullptr;+ if (previous) c.drawImage(*previous, 0, 0);+ uint8_t alpha = age >= kHeroFadeMs ? 255 : static_cast<uint8_t>(age * 255 / kHeroFadeMs);+ c.drawImage(*current, 0, 0, alpha);+ if (alpha < 255) animating_ = true;+ } else {+ prevHeroUrl_.clear(); // nothing on screen to fade from any more+ }+ // Darken towards the left (text) and the bottom (rows).+ c.gradientH({0, 0, details ? 1400 : 1200, kH}, rgba(0, 0, 0, details ? 240 : 225), rgba(0, 0, 0, 0));+ if (details) {+ c.gradientV({0, 640, kW, 440}, withAlpha(kBg, 0), withAlpha(kBg, 230));+ } else {+ c.gradientV({0, 360, kW, 420}, withAlpha(kBg, 0), kBg);+ c.fillRect({0, 780, kW, kH - 780}, kBg);+ }+ c.gradientV({0, 0, kW, 160}, rgba(0, 0, 0, 150), rgba(0, 0, 0, 0));+ return current != nullptr;+}++void AppUi::drawSplash(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ drawLogo(c, kW / 2.0f, 400, 64);+ drawCentered(c, fonts_.bold, tr(Str::AppName), 500, 52, kWhite);+ drawCentered(c, fonts_.regular, status_, 590, 28, kGray);+ drawSpinner(c, kW / 2.0f, 720, 26, nowMs);+}++void AppUi::drawSignIn(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ const int left = 180;+ drawLogo(c, left + 26, 160, 26);+ fonts_.semibold.draw(c, tr(Str::AppName), left + 70, 144, 30, kWhite);+ fonts_.bold.draw(c, tr(Str::SignInTitle), left, 260, 72, kWhite);+ fonts_.regular.draw(c, tr(Str::SignInStep1), left, 400, 32, kGray);+ std::string shortUrl = codeUrl_;+ for (const char* p : {"https://", "http://", "www."})+ if (shortUrl.rfind(p, 0) == 0) shortUrl = shortUrl.substr(std::string(p).size());+ fonts_.semibold.draw(c, shortUrl, left, 450, 44, kWhite);+ fonts_.regular.draw(c, tr(Str::SignInStep2), left, 540, 32, kGray);++ // The code, letter by letter, in a panel.+ constexpr int kPx = 96;+ int letters = static_cast<int>(code_.size());+ int cell = 82;+ Rect panel{left, 600, std::max(400, letters * cell + 64), 150};+ c.fillRect(panel, kPanel, 18);+ int x = panel.x + 32;+ for (char ch : code_) {+ std::string s(1, ch);+ fonts_.bold.draw(c, s, x + (cell - fonts_.bold.measure(s, kPx)) / 2, panel.y + 18, kPx, kWhite);+ x += cell;+ }+ drawSpinner(c, left + 18, 830, 14, nowMs);+ fonts_.regular.draw(c, tr(Str::SignInWaiting), left + 48, 815, 26, kDim);++ if (!platform::dataDirWritable()) {+ std::string pathAndErr = platform::dataDir() + " (errno " + std::to_string(platform::dataDirErrno()) + ")";+ std::string warn1 = trf(Str::StorageNotWritable, pathAndErr);+ std::string warn2 = trf(Str::StorageFixHint, platform::dataDir());+ fonts_.semibold.draw(c, warn1, left, 875, 22, rgba(255, 160, 40));+ fonts_.regular.draw(c, warn2, left, 905, 20, kGray);+ }++ // QR code for the sign-in page. Not "?otc=<code>": that prefilled link+ // goes through a consent flow that rejects this client id ("first party+ // application ... pre-authorization"), so the code is typed on the phone.+ std::string target = codeUrl_.empty() ? "https://www.microsoft.com/link" : codeUrl_;+ uint8_t qr[qrcodegen_BUFFER_LEN_MAX], tmp[qrcodegen_BUFFER_LEN_MAX];+ if (qrcodegen_encodeText(target.c_str(), tmp, qr, qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN,+ qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {+ int n = qrcodegen_getSize(qr);+ constexpr int kBox = 440;+ int module = (kBox - 60) / (n + 2);+ int size = module * (n + 2);+ Rect box{1280, 300, size + 40, size + 40};+ c.fillRect(box, kWhite, 24);+ int ox = box.x + 20 + module, oy = box.y + 20 + 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);+ int w = fonts_.regular.measure(tr(Str::SignInScan), 26);+ fonts_.regular.draw(c, tr(Str::SignInScan), box.x + (box.w - w) / 2, box.y + box.h + 24, 26, kGray);+ }+ if (caps_.openUrl) drawHints(c, {{kIconCross, tr(Str::OpenInBrowser)}}); // a desktop: the page in the browser+}++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::TabConsoles)};+ constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;+ int widths[3], total = 0;+ for (int i = 0; i < 3; ++i) {+ widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;+ total += widths[i] + (i ? kGap : 0);+ }+ int x = (kW - total) / 2;+ auto shoulder = [&](const char* name, int cx) {+ Rect r{cx - 22, kY + 8, 44, 28};+ c.fillRect(r, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, name, cx - fonts_.bold.measure(name, 16) / 2, fonts_.bold.centeredY(r.y, r.h, 16), 16, kGray);+ };+ shoulder(g_keyboardHints ? "Q" : buttonName(g_glyphStyle, PadButton::L1), x - 40);+ for (int i = 0; i < 3; ++i) {+ bool on = static_cast<int>(tab_) == i;+ Rect r{x, kY, widths[i], kH};+ if (on) c.fillRect(r, kWhite, kH / 2);+ fonts_.semibold.draw(c, labels[i], x + kPad, fonts_.semibold.centeredY(kY, kH, kPx), kPx, on ? kBg : kGray);+ x += widths[i] + kGap;+ }+ shoulder(g_keyboardHints ? "E" : buttonName(g_glyphStyle, PadButton::R1), x - kGap + 40);+}++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);+ }+ // Top-left: time played on this title, when recorded.+ uint64_t cardPlayedSec = 0;+ if (!t.productId.empty()) {+ auto it = settings_.titlePlaytime.find(t.productId);+ if (it != settings_.titlePlaytime.end()) cardPlayedSec = it->second;+ }+ if (!cardPlayedSec && !t.titleId.empty()) {+ auto it = settings_.titlePlaytime.find(t.titleId);+ if (it != settings_.titlePlaytime.end()) cardPlayedSec = it->second;+ }+ if (cardPlayedSec > 0) {+ std::string ptLabel = formatPlaytime(cardPlayedSec);+ int pw = std::min(kCard - 56, fonts_.bold.measure(ptLabel, 11) + 14);+ Rect ptBadge{x + 10, y + 10, pw, 22};+ c.fillRect(ptBadge, rgba(0, 0, 0, 215), 4);+ fonts_.bold.draw(c, ptLabel, ptBadge.x + (ptBadge.w - fonts_.bold.measure(ptLabel, 11)) / 2,+ fonts_.bold.centeredY(ptBadge.y, ptBadge.h, 11), 11, kWhite);+ }+ // Top-right: Wishlist blue star when marked (or lock if unplayable and not wishlisted)+ bool isWishlisted = !t.productId.empty() && wishlist_.count(t.productId) > 0;+ if (isWishlisted) {+ c.fillCircle(x + kCard - 24, y + 24, 14, rgba(10, 20, 35, 230));+ c.strokeCircle(x + kCard - 24, y + 24, 14, 1.5f, rgba(40, 140, 255, 180));+ drawStar(c, x + kCard - 24, y + 24, 7.5f, rgba(50, 160, 255));+ }++ // Bottom-right: console badge and input badge.+ // Calculate rightBadgeLeft so bottom-left badges never overlap them.+ int rightEdge = x + kCard - 10;+ int rightBadgeLeft = rightEdge;+ if (const char* p = platformLabel(t.platform)) {+ int pTextW = fonts_.bold.measure(p, 11);+ int pBadgeW = std::clamp(pTextW + 12, 54, 66);+ Rect badge{rightBadgeLeft - pBadgeW, y + kCard - 34, pBadgeW, 24};+ c.fillRect(badge, rgba(0, 0, 0, 220), 4);+ fonts_.bold.draw(c, p, badge.x + (badge.w - pTextW) / 2,+ fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);+ rightBadgeLeft = badge.x - 4;+ }+ if (t.mouseKeyboard || fonts_.hasIcons) {+ constexpr int kInputW = 28;+ Rect k{rightBadgeLeft - kInputW, y + kCard - 34, kInputW, 24};+ c.fillRect(k, rgba(0, 0, 0, 220), 4);+ const char* glyph = t.mouseKeyboard ? kIconKeyboardMouse : kIconGamepad;+ if (fonts_.hasIcons) {+ int gw = fonts_.icons.measure(glyph, 18);+ int gx = k.x + (k.w - gw) / 2;+ fonts_.icons.draw(c, glyph, gx, k.y + 3, 18, kWhite);+ } else {+ int kw = 16, kh = kw * 10 / 24;+ int kx = k.x + (k.w - kw) / 2;+ int ky = k.y + (k.h - kh) / 2;+ drawKeyboardGlyph(c, kx, ky, kw, kWhite);+ }+ rightBadgeLeft = k.x - 6;+ }++ // Bottom-left: price badge, plan badge, or friends playing; bounded by rightBadgeLeft.+ int maxLeftW = std::max(40, rightBadgeLeft - (x + 10) - 4);+ const char* planBadge = planBadgeLabel(t.plan);+ uint8_t myPlan = xcloud::planTier(subscription_);+ bool otherPlan = planBadge && (!t.playable || (myPlan > 0 && !xcloud::planIncludes(myPlan, t.plan, isFreeGame(t))));+ bool showPlan = otherPlan || (planBadge && searching_ && tab_ == Tab::GamePass && filterPlan_ > 0 && t.friends.empty());+ bool isF2P = isFreeGame(t);+ bool effectivePlayable = isEffectivePlayableLocked(t);+ if (!effectivePlayable && !t.playable && (isF2P || t.purchasable)) {+ c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 70), 10);+ auto price = prices_.find(t.productId);+ bool free = isFreeGame(t);+ std::string label = free ? tr(Str::Free)+ : price != prices_.end() ? price->second.now+ : tr(Str::BuyBadge);+ int tw = fonts_.bold.measure(label, 11);+ int w = std::min(maxLeftW, 20 + tw + 8);+ if (w < 20 + tw + 8) {+ label = fonts_.bold.fit(label, 11, w - 22);+ }+ Rect badge{x + 10, y + kCard - 34, w, 24};+ c.fillRect(badge, rgba(16, 124, 16, 235), 4);+ drawBag(c, badge.x + 10, badge.y + badge.h / 2, kWhite, 0.52f);+ fonts_.bold.draw(c, label, badge.x + 18, fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);+ } else if (!effectivePlayable) {+ c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 150), 10);+ drawLock(c, isWishlisted ? x + kCard - 54 : x + kCard - 34, isWishlisted ? y + 24 : y + 30);+ if (planBadge) {+ int w = std::min(maxLeftW, fonts_.bold.measure(planBadge, 11) + 14);+ Rect badge{x + 10, y + kCard - 34, w, 24};+ c.fillRect(badge, rgba(0, 0, 0, 220), 4);+ fonts_.bold.draw(c, planBadge, badge.x + (badge.w - fonts_.bold.measure(planBadge, 11)) / 2,+ fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);+ }+ } else if (showPlan) {+ int w = std::min(maxLeftW, fonts_.bold.measure(planBadge, 11) + 14);+ Rect badge{x + 10, y + kCard - 34, w, 24};+ c.fillRect(badge, rgba(0, 0, 0, 220), 4);+ fonts_.bold.draw(c, planBadge, badge.x + (badge.w - fonts_.bold.measure(planBadge, 11)) / 2,+ fonts_.bold.centeredY(badge.y, badge.h, 11), 11, kWhite);+ } else if (!t.friends.empty()) {+ int numAvatars = std::min<int>(static_cast<int>(t.friends.size()), 2);+ int extraCount = static_cast<int>(t.friends.size()) - numAvatars;+ constexpr int kAvatarSz = 20;+ constexpr int kAvatarOverlap = 13;+ constexpr int kPillH = 26;+ constexpr int kPadX = 4;+ constexpr int kPadY = 3;++ int avatarsW = numAvatars == 1 ? kAvatarSz : (kAvatarSz + (numAvatars - 1) * kAvatarOverlap);+ std::string tagText;+ if (t.friends.size() == 1) {+ tagText = t.friends[0].gamertag;+ } else if (extraCount > 0) {+ tagText = "+" + std::to_string(extraCount);+ } else if (t.friends.size() == 2) {+ tagText = t.friends[0].gamertag;+ }++ int maxPillW = maxLeftW;+ int maxTextW = maxPillW - avatarsW - kPadX * 2 - 8;+ int textW = !tagText.empty() ? fonts_.semibold.measure(tagText, 12) + 6 : 0;+ if (textW > maxTextW && maxTextW > 15) {+ while (!tagText.empty() && fonts_.semibold.measure(tagText + "…", 12) + 6 > maxTextW) {+ tagText.pop_back();+ }+ tagText += "…";+ textW = fonts_.semibold.measure(tagText, 12) + 6;+ }++ int pillW = kPadX * 2 + avatarsW + textW;+ Rect pill{x + 10, y + kCard - 10 - kPillH, pillW, kPillH};+ c.fillRect(pill, rgba(0, 0, 0, 215), kPillH / 2);+ c.strokeRect(pill, rgba(255, 255, 255, 50), 1, kPillH / 2);++ int curX = pill.x + kPadX;+ int curY = pill.y + kPadY;+ for (int i = 0; i < numAvatars; ++i) {+ int ax = curX + i * kAvatarOverlap;+ const auto& friendInfo = t.friends[static_cast<size_t>(i)];+ if (auto pic = images_.get(friendInfo.gamerpicUrl, kAvatarSz, kAvatarSz)) {+ c.drawImage(*pic, ax, curY, 255, -1);+ } else {+ c.fillCircle(ax + kAvatarSz / 2.0f, curY + kAvatarSz / 2.0f, kAvatarSz / 2.0f, rgba(48, 56, 68, 255));+ if (!friendInfo.gamertag.empty()) {+ std::string initial(1, static_cast<char>(std::toupper(static_cast<unsigned char>(friendInfo.gamertag[0]))));+ int iw = fonts_.bold.measure(initial, 11);+ int iy = fonts_.bold.centeredY(curY, kAvatarSz, 11);+ fonts_.bold.draw(c, initial, ax + (kAvatarSz - iw) / 2, iy, 11, kWhite);+ }+ }+ c.strokeCircle(ax + kAvatarSz / 2.0f, curY + kAvatarSz / 2.0f, kAvatarSz / 2.0f, 1.2f, rgba(255, 255, 255, 200));+ }++ if (!tagText.empty()) {+ int tx = curX + avatarsW + 4;+ int ty = fonts_.semibold.centeredY(pill.y, pill.h, 12);+ if (extraCount > 0 && numAvatars == 2) {+ fonts_.bold.draw(c, tagText, tx, ty, 12, rgba(16, 124, 16, 255));+ } else {+ fonts_.semibold.draw(c, tagText, tx, ty, 12, 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));+ c.setClip({0, clipTop, kW, kH - clipTop});+ int firstRow = std::max(0, (clipTop - y0 + offset - kCard - 40) / kGridPitchY);+ size_t startIdx = static_cast<size_t>(firstRow) * static_cast<size_t>(cols);+ for (size_t i = startIdx; i < tiles.size(); ++i) {+ int col = static_cast<int>(i) % cols, row = static_cast<int>(i) / cols;+ int x = x0 + col * kCardPitch;+ int y = y0 + row * kGridPitchY - offset;+ if (y + kCard + 40 < clipTop) continue;+ if (y > kH) break;+ bool focused = static_cast<int>(i) == focus;+ 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);+ }+ c.clearClip();+ c.fillRect({0, 0, kW, clipTop}, kBg);+ c.gradientV({0, clipTop, kW, 12}, kBg, withAlpha(kBg, 0));+}++void AppUi::drawLibrary(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int left = (kW - kGridW) / 2;+ const int clipTop = kLibraryTop - 10;+ const LibraryLayout& L = libraryLayout();+ int offset = static_cast<int>(std::lround(gridScroll_.value));+ c.setClip({0, clipTop, kW, kH - clipTop});+ // Each section has its heading in the grid: a title, the count, a line+ // of explanation (the games to buy have a bag).+ auto heading = [&](int section, const char* title, size_t count, const char* line, bool bag) {+ int hy = kLibraryTop + L.headerY[section] - offset;+ if (hy < clipTop - kSectionHeaderH || hy > kH) return;+ int x = left;+ if (bag) {+ drawBag(c, left + 14, hy + 30, kGreen);+ x += 40;+ }+ fonts_.bold.draw(c, title, x, hy + 8, 34, kWhite);+ int w = fonts_.bold.measure(title, 34);+ fonts_.semibold.draw(c, gamesCount(count), x + w + 20, hy + 20, 22, kDim);+ if (line) fonts_.regular.draw(c, line, x, hy + 52, 22, kGray);+ };+ if (!owned_.empty()) heading(0, tr(Str::YourGames), owned_.size(), nullptr, false);+ if (!purchasable_.empty()) heading(1, tr(Str::AvailableToBuy), purchasable_.size(), tr(Str::BuyToPlay), true);+ if (!hiddenTiles_.empty()) heading(2, tr(Str::HiddenSection), hiddenTiles_.size(), tr(Str::HiddenHint), false);+ int minRowY = clipTop - kLibraryTop + offset - kCard - 40;+ auto rowIt = std::lower_bound(L.rowY.begin(), L.rowY.end(), minRowY);+ int firstVisRow = static_cast<int>(rowIt - L.rowY.begin());+ auto tileIt = std::lower_bound(L.rowOf.begin(), L.rowOf.end(), firstVisRow);+ for (size_t i = static_cast<size_t>(tileIt - L.rowOf.begin()); i < L.rowOf.size(); ++i) {+ int y = kLibraryTop + 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);+ if (hidden_.count(t->productId)) c.fillRect({x, y, kCard, kCard}, rgba(0, 0, 0, 120), 10);+ 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.clearClip();+ c.fillRect({0, 0, kW, clipTop}, kBg);+ c.gradientV({0, clipTop, kW, 12}, kBg, withAlpha(kBg, 0));+ drawTopBar(c);+ drawTabs(c);+ if (owned_.empty() && purchasable_.empty() && hiddenTiles_.empty()) {+ if (!ownedKnown_) {+ drawSpinner(c, kW / 2.0f, 470, 26, nowMs);+ drawCentered(c, fonts_.semibold, tr(Str::LoadingGames), 530, 28, kGray);+ animating_ = true;+ } else {+ drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 30, kGray);+ }+ }+ {+ drawLoadingBar(c, left, 112, 420, nowMs);+ // The order (the whole tab's), right-aligned under the tabs, with its button.+ Str sortName = librarySort_ == LibrarySort::AZ ? Str::SortAZ+ : librarySort_ == LibrarySort::Console ? Str::SortConsole+ : Str::SortRecent;+ std::string label = trf(Str::SortLabel, tr(sortName));+ int w = fonts_.semibold.measure(label, 22);+ constexpr int kAvatar = 52;+ int right = kW - kMargin - kAvatar - 16;+ fonts_.semibold.draw(c, label, right - w, fonts_.semibold.centeredY(112, 28, 22), 22, kGray);+ }+ c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));+ c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));+ const GameTile* focus = libraryTile(gridFocus_);+ bool focusHidden = focus && hidden_.count(focus->productId);+ drawHints(c, {{kIconCross, tr(Str::Select)},+ {kIconSquare, tr(focusHidden ? Str::Unhide : Str::Hide)},+ {kIconTriangle, tr(Str::TabSearch)},+ {kIconL3, tr(Str::RefreshLibrary)},+ {kIconR3, tr(Str::SortHint)},+ {kIconL2R2, tr(Str::Sections)},+ {kIconOptions, tr(Str::Settings)}});+ drawPads(c);+ drawToast(c, nowMs);+}++void AppUi::drawSearch(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ // Results on the right.+ drawGrid(c, results_, kResultsX, kGridTop, kResultCols, resultScroll_.value, searchOnKeys_ ? -1 : resultFocus_,+ kGridTop - 20);+ drawTopBar(c);+ drawTabs(c);+ const char* scope = tab_ == Tab::GamePass ? tr(Str::TabGamePass) : tr(Str::YourGames);+ bool filtering = anyFilter();+ if (query_.empty() && !filtering) {+ fonts_.semibold.draw(c, tr(Str::SearchHint), kResultsX, 150, 26, kDim);+ } else if (results_.empty()) {+ const char* emptyMsg = (tab_ == Tab::Library && filterWishlist_) ? tr(Str::WishlistEmpty) : tr(Str::NoResults);+ fonts_.semibold.draw(c, emptyMsg, kResultsX, 150, 26, kGray);+ } else {+ fonts_.semibold.draw(c, trf(Str::ResultsCount, std::to_string(results_.size())), kResultsX, 150, 26, kGray);+ }+ drawLoadingBar(c, kResultsX + 420, 150, 420, nowMs);++ // The query.+ const int kbW = kKeyCols * (kKeyW + kKeyGap) - kKeyGap;+ Rect box{kMargin, 140, kbW, 76};+ c.fillRect(box, kPanel, 14);+ if (searchOnKeys_) c.strokeRect(box, rgba(255, 255, 255, 90), 2, 14);+ int tx = box.x + 24;+ if (query_.empty()) {+ fonts_.regular.draw(c, 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({query_.empty() ? box.x + 20 : tx, box.y + 18, 3, 40}, kWhite);+ if (searchOnKeys_) animating_ = true; // the caret blinks++ // The keys.+ for (int r = 0; r <= kKeyRows; ++r) {+ int n = r == kKeyRows ? 3 : kKeyCols;+ for (int k = 0; k < n; ++k) {+ int col = r == kKeyRows ? kWideCols[k] : k;+ int span = r == kKeyRows ? kWideSpan[k] : 1;+ Rect key{kMargin + col * (kKeyW + kKeyGap), kKeysY + r * (kKeyH + kKeyGap),+ span * kKeyW + (span - 1) * kKeyGap, kKeyH};+ bool focused = searchOnKeys_ && keyRow_ == r && keyCol_ == k;+ c.fillRect(key, focused ? kWhite : kPanel, 10);+ std::string label = r == kKeyRows ? tr(k == 0 ? Str::KeySpace : k == 1 ? Str::KeyDelete : Str::KeyClear)+ : std::string(1, static_cast<char>(std::toupper(kKeys[r * kKeyCols + k])));+ int px = r == kKeyRows ? 22 : 28;+ int w = fonts_.semibold.measure(label, px);+ fonts_.semibold.draw(c, label, key.x + (key.w - w) / 2, fonts_.semibold.centeredY(key.y, kKeyH, px), px,+ focused ? kBg : kWhite);+ }+ }+ c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));+ c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));+ // The filters, 3x3 grid under the keys: green when on; the lists with a chevron.+ const int gap = kChipGap, px = 18, fh = 48;+ const int fy0 = kKeysY + (kKeyRows + 1) * (kKeyH + kKeyGap) + 8;+ constexpr int kCols = 3;+ const int chipW = (kKeysW - gap * (kCols - 1)) / kCols;+ Rect openChip{};+ for (int row = 0; row < 3; ++row) {+ auto chips = filterRow(row);+ if (chips.empty()) continue;+ int fy = fy0 + row * (fh + 8);+ for (size_t k = 0; k < chips.size(); ++k) {+ Filter f = chips[k];+ bool on = filterOn(f);+ bool focused = searchOnKeys_ && keyRow_ == kKeyRows + 1 + row && keyCol_ == static_cast<int>(k);+ Rect chip{kMargin + static_cast<int>(k) * (chipW + gap), fy, chipW, fh};+ if (filterList_ == static_cast<int>(f)) openChip = chip;+ c.fillRect(chip, focused ? kWhite : on ? rgba(16, 124, 16, 255) : kPanel, fh / 2);+ if (on && focused) c.strokeRect({chip.x + 3, chip.y + 3, chip.w - 6, chip.h - 6}, kGreen, 3, fh / 2 - 3);+ Color text = focused ? kBg : kWhite;+ int room = chip.w - (isList(f) ? 56 : 20);+ int chipPx = px;+ while (chipPx > 13 && fonts_.semibold.measure(filterText(f), chipPx) > room) --chipPx;+ std::string label = fonts_.semibold.fit(filterText(f), chipPx, room);+ int tw = fonts_.semibold.measure(label, chipPx);+ int tx = chip.x + (chip.w - tw) / 2;+ fonts_.semibold.draw(c, label, tx, fonts_.semibold.centeredY(chip.y, chip.h, chipPx), chipPx, text);+ if (isList(f)) { // a list: a chevron at the right+ float cx = static_cast<float>(chip.x + chip.w - 20), cy = static_cast<float>(chip.y + chip.h / 2);+ c.line(cx - 5, cy - 3, cx, cy + 2, 2.2f, text);+ c.line(cx, cy + 2, cx + 5, cy - 3, 2.2f, text);+ }+ }+ }+ if (filterList_ >= 0) {+ // The open list, above its chip (they are near the bottom); scrolls+ // past kVisible choices.+ Filter f = static_cast<Filter>(filterList_);+ auto options = filterOptions(f);+ int sel = filterSelected(f);+ constexpr int kItemH = 54, kVisible = 9;+ int n = static_cast<int>(options.size()), visible = std::min(n, kVisible);+ if (filterListIndex_ < filterListTop_) filterListTop_ = filterListIndex_;+ if (filterListIndex_ >= filterListTop_ + visible) filterListTop_ = filterListIndex_ - visible + 1;+ int listW = std::max(openChip.w, 460);+ Rect panel{openChip.x, openChip.y - 10 - (visible * kItemH + 16), listW, visible * kItemH + 16};+ panel.y = std::max(120, panel.y);+ c.fillRect({panel.x + 6, panel.y + 10, panel.w, panel.h}, rgba(0, 0, 0, 120), 18); // shadow+ c.fillRect(panel, rgba(38, 38, 38, 250), 18);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 18);+ for (int k = 0; k < visible; ++k) {+ int i = filterListTop_ + k;+ Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};+ bool on = i == filterListIndex_;+ if (on) c.fillRect(item, kWhite, 12);+ Color text = on ? kBg : (i == sel ? kWhite : kGray);+ std::string label = fonts_.semibold.fit(options[static_cast<size_t>(i)], 24, item.w - 70);+ fonts_.semibold.draw(c, label, item.x + 20, fonts_.semibold.centeredY(item.y, item.h, 24), 24, text);+ if (i == sel) { // a check mark on the current choice+ float cx = static_cast<float>(item.x + item.w - 30), cy = static_cast<float>(item.y + item.h / 2);+ c.line(cx - 9, cy, cx - 3, cy + 6, 3, on ? kBg : kGreen);+ c.line(cx - 3, cy + 6, cx + 9, cy - 6, 3, on ? kBg : kGreen);+ }+ }+ if (filterListTop_ > 0) { // more above / below+ float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y - 12);+ c.line(cx - 9, cy + 4, cx, cy - 4, 3, kGray);+ c.line(cx, cy - 4, cx + 9, cy + 4, 3, kGray);+ }+ if (filterListTop_ + visible < n) {+ float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y + panel.h + 12);+ c.line(cx - 9, cy - 4, cx, cy + 4, 3, kGray);+ c.line(cx, cy + 4, cx + 9, cy - 4, 3, kGray);+ }+ }+ if (filterList_ >= 0)+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});+ else if (searchOnKeys_)+ drawHints(c, {{kIconCross, tr(Str::KeyType)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconSquare, tr(Str::KeyDelete)}, {kIconCircle, tr(Str::Back)}});+ drawToast(c, nowMs);+}++void AppUi::drawConsoles(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ drawTopBar(c);+ drawTabs(c);+ fonts_.bold.draw(c, tr(Str::TabConsoles), kMargin, 170, 52, kWhite);+ fonts_.regular.draw(c, tr(Str::ConsolesHint), kMargin, 240, 26, kGray);+ if (consoles_.empty()) {+ if (!consolesKnown_) {+ drawSpinner(c, kW / 2.0f, 520, 26, nowMs);+ drawCentered(c, fonts_.semibold, tr(Str::ConsolesLoading), 580, 28, kGray);+ animating_ = true;+ drawHints(c, {{kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});+ } else {+ // How a console shows up: three numbered steps, and Microsoft's+ // help on the phone.+ fonts_.bold.draw(c, tr(Str::NoConsoles), kMargin, 340, 40, kWhite);+ int y = 420;+ const Str steps[] = {Str::ConsoleStep1, Str::ConsoleStep2, Str::ConsoleStep3};+ for (int i = 0; i < 3; ++i) {+ c.fillCircle(static_cast<float>(kMargin + 22), static_cast<float>(y + 20), 22, kGreen);+ std::string num = std::to_string(i + 1);+ fonts_.bold.draw(c, num, kMargin + 22 - fonts_.bold.measure(num, 24) / 2,+ fonts_.bold.centeredY(y - 2, 44, 24), 24, kWhite);+ for (const auto& line : fonts_.regular.wrap(tr(steps[i]), 28, 980, 2)) {+ fonts_.regular.draw(c, line, kMargin + 70, y + 2, 28, kGray);+ y += 40;+ }+ y += 34;+ }+ Rect box = drawQr(c, "https://support.xbox.com/help/games-apps/game-setup-and-play/how-to-use-remote-play",+ kW - kMargin, 330, 340);+ if (box.w > 0) {+ int w = fonts_.semibold.measure(tr(Str::ScanForHelp), 24);+ fonts_.semibold.draw(c, tr(Str::ScanForHelp), box.x + (box.w - w) / 2, box.y + box.h + 22, 24, kWhite);+ }+ drawHints(c, {{kIconCross, tr(Str::SearchAgain)},+ {kIconOptions, tr(Str::Settings)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});+ }+ drawPads(c);+ return;+ }+ // One card per console: a drawn Xbox, its name, model and state.+ constexpr int kCardW = 480, kCardH = 380, kGap = 40, kTop = 320;+ for (size_t i = 0; i < consoles_.size(); ++i) {+ const ConsoleTile& con = consoles_[i];+ int x = kMargin + static_cast<int>(i) * (kCardW + kGap);+ if (x > kW) break;+ bool focused = static_cast<int>(i) == consoleFocus_;+ Rect card{x, kTop, kCardW, kCardH};+ if (focused) c.strokeRect({card.x - 7, card.y - 7, card.w + 14, card.h + 14}, kWhite, 4, 22);+ c.fillRect(card, kPanel, 16);+ // The console: a Series X stands as a tower, the others lie flat.+ bool tower = con.type == "XboxSeriesX";+ Rect box = tower ? Rect{x + kCardW / 2 - 55, kTop + 40, 110, 170} : Rect{x + kCardW / 2 - 120, kTop + 90, 240, 70};+ c.fillRect(box, rgba(20, 20, 20), 12);+ c.strokeRect(box, rgba(70, 70, 70), 2, 12);+ bool on = con.power == "On";+ c.fillCircle(static_cast<float>(box.x + (tower ? box.w / 2 : 24)), static_cast<float>(box.y + (tower ? 22 : box.h / 2)),+ tower ? 16.0f : 9.0f, on ? kGreen : rgba(90, 90, 90));+ std::string name = con.name.empty() ? "Xbox" : con.name;+ auto lines = fonts_.semibold.wrap(name, 30, kCardW - 48, 1);+ if (!lines.empty()) fonts_.semibold.draw(c, lines[0], x + 24, kTop + 236, 30, kWhite);+ std::string model = con.type == "XboxSeriesX" ? "Xbox Series X"+ : con.type == "XboxSeriesS" ? "Xbox Series S"+ : con.type == "XboxOneX" ? "Xbox One X"+ : con.type == "XboxOneS" ? "Xbox One S"+ : con.type == "XboxOne" ? "Xbox One"+ : con.type;+ fonts_.regular.draw(c, model, x + 24, kTop + 284, 24, kGray);+ const char* state = on ? tr(Str::ConsoleOn)+ : con.power == "ConnectedStandby" ? tr(Str::ConsoleSleeping)+ : tr(Str::ConsoleOff);+ c.fillCircle(static_cast<float>(x + 32), static_cast<float>(kTop + 336), 6, on ? rgba(60, 200, 60) : kDim);+ fonts_.semibold.draw(c, state, x + 48, kTop + 322, 24, on ? kWhite : kGray);+ }+ drawHints(c, {{kIconCross, tr(Str::Play)},+ {kIconTriangle, tr(Str::SearchAgain)},+ {kIconOptions, tr(Str::Settings)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});+ drawPads(c);+}++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::Consoles) return drawConsoles(c, nowMs);+ const GameTile* focus = focusedTile();+ c.clear(kBg);+ std::string hero;+ if (focus) {+ hero = focus->heroUrl;+ bool hadFocusHero = !hero.empty();+ if (hero.empty() && !focus->productId.empty()) {+ auto it = detailInfo_.find(focus->productId);+ if (it != detailInfo_.end() && !it->second.heroUrl.empty()) {+ hero = it->second.heroUrl;+ }+ }+ if (hero.empty()) {+ auto matchHero = [&](const GameTile& t) -> bool {+ if (t.heroUrl.empty()) return false;+ if (!focus->productId.empty() && !t.productId.empty()) {+ return t.productId == focus->productId;+ }+ if (!focus->productId.empty() && t.productId == focus->productId) return true;+ if (!focus->titleId.empty() && t.titleId == focus->titleId) return true;+ if (!focus->xboxTitleId.empty() && t.xboxTitleId == focus->xboxTitleId) return true;+ return false;+ };+ const GameTile* matched = nullptr;+ for (const auto& r : rows_) {+ for (const auto& t : r.tiles) {+ if (matchHero(t)) { matched = &t; break; }+ }+ if (matched) break;+ }+ if (!matched) {+ for (const auto& r : allRows_) {+ for (const auto& t : r.tiles) {+ if (matchHero(t)) { matched = &t; break; }+ }+ if (matched) break;+ }+ }+ if (!matched) {+ for (const auto* list : {&gamePassPool_, &libraryPool_, &allOwned_, &allPurchasable_}) {+ for (const auto& t : *list) {+ if (matchHero(t)) { matched = &t; break; }+ }+ if (matched) break;+ }+ }+ if (matched) {+ hero = matched->heroUrl;+ syncHeroToRowsLocked(matched->productId, matched->titleId, matched->heroUrl,+ matched->description, matched->publisher, matched->categories);+ hadFocusHero = true;+ }+ }+ if (!hadFocusHero && !hero.empty()) {+ syncHeroToRowsLocked(focus->productId, focus->titleId, hero);+ }+ }+ drawHero(c, nowMs, hero, false);++ if (rows_.empty()) {+ drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 32, kGray);+ drawHints(c, {{kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});+ c.fillRect({0, 0, kW, 140}, kBg);+ c.gradientV({0, 140, kW, 16}, kBg, withAlpha(kBg, 0));+ drawTopBar(c);+ drawTabs(c);+ return;+ }++ if (focus) {+ float heroAlpha = 1.0f;+ for (size_t r = 0; r < rows_.size(); ++r) {+ if (rows_[r].isGrid) {+ float dist = static_cast<float>(r) - rowY_.value;+ if (dist < 1.0f) heroAlpha = std::clamp(dist, 0.0f, 1.0f);+ break;+ }+ }+ if (heroAlpha > 0.05f) {+ Color titleColor = withAlpha(kWhite, static_cast<int>(255 * heroAlpha));+ Color grayColor = withAlpha(kGray, static_cast<int>(255 * heroAlpha));+ auto title = fonts_.bold.wrap(focus->name, 60, 1100, 1);+ if (!title.empty()) fonts_.bold.draw(c, title[0], kMargin, 190, 60, titleColor);+ std::string meta = focus->publisher;+ for (size_t i = 0; i < focus->categories.size() && i < 2; ++i)+ meta += (meta.empty() ? "" : " \xE2\x80\xA2 ") + focus->categories[i];+ fonts_.regular.draw(c, meta, kMargin, 272, 24, grayColor);+ auto desc = fonts_.regular.wrap(focus->description, 22, 860, 2);+ for (size_t i = 0; i < desc.size(); ++i)+ fonts_.regular.draw(c, desc[i], kMargin, 318 + static_cast<int>(i) * 32, 22, grayColor);+ }+ }++ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int gridLeft = (kW - kGridW) / 2;+ int afterGridOffset = 0;+ constexpr int clipTop = 140;+ c.setClip({0, clipTop, kW, kH - 220});++ for (size_t r = 0; r < rows_.size(); ++r) {+ float rel = static_cast<float>(r) - rowY_.value;+ int y = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;+ const GameRow& row = rows_[r];++ if (row.isGrid) {+ int offset = static_cast<int>(std::lround(rowScroll_[r].value));+ int hy = y - offset;+ int cardY = hy + 48;++ if (hy > 80 && hy < kH) {+ fonts_.bold.draw(c, row.title, gridLeft, hy + 8, 34, kWhite);+ int w = fonts_.bold.measure(row.title, 34);+ fonts_.semibold.draw(c, gamesCount(row.tiles.size()), gridLeft + w + 20, hy + 20, 22, kDim);+ }++ int firstGridRow = std::max(0, (clipTop - cardY - kCard - 40) / kGridPitchY);+ size_t startIdx = static_cast<size_t>(firstGridRow) * static_cast<size_t>(kLibraryCols);+ for (size_t i = startIdx; i < row.tiles.size(); ++i) {+ int c_col = static_cast<int>(i) % kLibraryCols;+ int c_row = static_cast<int>(i) / kLibraryCols;+ int cy = cardY + c_row * kGridPitchY;+ if (cy + kCard + 40 < clipTop) continue;+ if (cy > kH) break;+ int cx = gridLeft + c_col * kCardPitch;+ bool focused = static_cast<int>(r) == focusRow_ && static_cast<int>(i) == focusCol_[r];+ drawCard(c, row.tiles[i], cx, cy, focused, row.gamePassBadges);+ if (hidden_.count(row.tiles[i].productId)) c.fillRect({cx, cy, kCard, kCard}, rgba(0, 0, 0, 120), 10);+ auto name = fonts_.semibold.wrap(row.tiles[i].name, 20, kCard, 1);+ if (!name.empty()) fonts_.semibold.draw(c, name[0], cx, cy + kCard + 12, 20, focused ? kWhite : kGray);+ }++ int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;+ afterGridOffset += gridHeight - offset - kRowPitch;+ } else {+ if (rel < -0.7f && afterGridOffset == 0) continue;+ if (y > kH && afterGridOffset == 0) break;+ fonts_.semibold.draw(c, row.title, kMargin, y, 30, kWhite);+ int cardY = y + 48;+ int scroll = static_cast<int>(std::lround(rowScroll_[r].value));+ int firstCol = std::max(0, scroll / kCardPitch - 1);+ for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {+ int x = kMargin + static_cast<int>(col) * kCardPitch - scroll;+ if (x > kW) break;+ if (x + kCard < 0) continue;+ bool focused = static_cast<int>(r) == focusRow_ && static_cast<int>(col) == focusCol_[r];+ drawCard(c, row.tiles[col], x, cardY, focused, row.gamePassBadges);+ if (hidden_.count(row.tiles[col].productId)) c.fillRect({x, cardY, kCard, kCard}, rgba(0, 0, 0, 120), 10);+ }+ }+ }++ c.clearClip();+ c.fillRect({0, 0, kW, clipTop}, kBg);+ c.gradientV({0, clipTop, kW, 16}, kBg, withAlpha(kBg, 0));++ drawTopBar(c);+ drawTabs(c);++ // 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)},+ {kIconSquare, tr(focus && hidden_.count(focus->productId) ? Str::Unhide : Str::Hide)},+ {kIconTriangle, tr(Str::TabSearch)},+ {kIconL3, tr(Str::RefreshLibrary)},+ {kIconOptions, tr(Str::Settings)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});+ drawPads(c);+ drawToast(c, nowMs);+}++void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {+ const GameTile* g = &detail_;+ playRect_ = {};+ achRect_ = {};+ claimRect_ = {};+ c.clear(kBg);+ if (g->productId.empty() && g->titleId.empty()) return;+ // Without its hero art (games to buy, search results, or not downloaded+ // yet): the cover on the right, never another game's backdrop.+ constexpr int kCover = 420;+ const Rect cover{kW - kMargin - kCover, 170, kCover, kCover};+ if (!drawHero(c, nowMs, g->heroUrl, true)) {+ // No hero art (yet): the cover, until the art arrives and fades in.+ drawBackground(c);+ if (g->playable || !g->purchasable || isFreeGame(*g)) { // paid games show their QR code there instead+ if (auto img = images_.get(g->tileUrl, kCover, kCover)) c.drawImage(*img, cover.x, cover.y, 255, 16);+ else c.fillRect(cover, kPlaceholder, 16);+ }+ }+ drawTopBar(c);+ int y = 260;+ for (const auto& line : fonts_.bold.wrap(g->name, 68, 960, 2)) {+ fonts_.bold.draw(c, line, kMargin, y, 68, kWhite);+ y += 82;+ }+ y += 6;+ const char* planName = planDisplayName(g->plan);+ std::string byLine;+ if (!g->publisher.empty()) byLine = trf(Str::PublisherBy, g->publisher);+ if (planName && g->playable)+ byLine += (byLine.empty() ? "" : " \xE2\x80\xA2 ") + trf(Str::IncludedWithPlan, planName);+ if (!byLine.empty()) {+ fonts_.semibold.draw(c, byLine, kMargin, y, 26, kGray);+ y += 40;+ }++ // Age rating & content descriptors (ClassInd, ESRB, PEGI)+ if (!g->ratingAge.empty()) {+ Color badgeBg = rgba(100, 100, 100);+ Color badgeFg = kWhite;+ if (g->ratingAge == "Livre" || g->ratingAge == "E" || g->ratingAge == "3+" || g->ratingAge == "0") {+ badgeBg = rgba(0, 160, 60);+ } else if (g->ratingAge == "10+" || g->ratingAge == "E10+" || g->ratingAge == "7+") {+ badgeBg = rgba(0, 120, 220);+ } else if (g->ratingAge == "12+") {+ badgeBg = rgba(230, 180, 0);+ badgeFg = rgba(20, 20, 20);+ } else if (g->ratingAge == "14+" || g->ratingAge == "T") {+ badgeBg = rgba(235, 100, 0);+ } else if (g->ratingAge == "16+" || g->ratingAge == "M") {+ badgeBg = rgba(210, 30, 30);+ } else if (g->ratingAge == "18+" || g->ratingAge == "AO") {+ badgeBg = rgba(30, 30, 30);+ }++ int textW = fonts_.bold.measure(g->ratingAge, 20);+ int badgeW = std::max(38, textW + 16);+ int badgeH = 28;+ Rect badge{kMargin, y + 2, badgeW, badgeH};+ c.fillRect(badge, badgeBg, 6);+ if (badgeBg == rgba(30, 30, 30)) {+ c.strokeRect(badge, rgba(255, 255, 255, 160), 1, 6);+ }+ fonts_.bold.draw(c, g->ratingAge, badge.x + (badge.w - textW) / 2, fonts_.bold.centeredY(badge.y, badge.h, 20), 20, badgeFg);++ std::string descLine;+ if (!g->ratingSystem.empty()) descLine = g->ratingSystem;+ for (const auto& d : g->ratingDescriptors) {+ std::string next = (descLine.empty() ? "" : " \xE2\x80\xA2 ") + d;+ if (fonts_.semibold.measure(descLine + next, 22) > 750) {+ descLine += " ...";+ break;+ }+ descLine += next;+ }+ if (!descLine.empty()) {+ fonts_.semibold.draw(c, descLine, badge.x + badge.w + 14, fonts_.semibold.centeredY(badge.y, badge.h, 22), 22, kDim);+ }+ y += 38;+ }+ 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 (g->mouseKeyboard) cats += std::string(cats.empty() ? "" : " \xE2\x80\xA2 ") + tr(Str::MouseKeyboardSupport);+ if (!cats.empty()) {+ fonts_.regular.draw(c, cats, kMargin, y, 24, kDim);+ y += 44;+ }+ y += 10;+ bool isFreePlayer = isFreeAccountLocked();+ bool isF2P = isFreeGame(*g);+ bool effectivePlayable = isEffectivePlayableLocked(*g);+ // Shorter for a free or purchasable game, whose page also has the hint and Play/price below.+ int descLines = !effectivePlayable && !g->playable && (isF2P || g->purchasable) ? 4 : 6;+ for (const auto& line : fonts_.regular.wrap(g->description, 24, 880, descLines)) {+ fonts_.regular.draw(c, line, kMargin, y, 24, kGray);+ y += 34;+ }+ if (!effectivePlayable && !g->playable && (isF2P || g->purchasable)) {+ // Free to play: "Get Free" button to claim license directly; Paid: price & store QR.+ int ty = y + 30;+ auto price = prices_.find(g->productId);+ bool free = isFreeGame(*g);+ if (free) {+ // Free to play: "Get Free" button to claim license directly.+ fonts_.bold.draw(c, tr(Str::Free), kMargin, ty, 52, kWhite);+ ty += 84;+ fonts_.semibold.draw(c, tr(Str::FreeToPlay), kMargin, ty, 28, kWhite);+ ty += 48;+ for (const auto& line : fonts_.regular.wrap(tr(Str::FreeAcquireHint), 24, 820, 3)) {+ fonts_.regular.draw(c, line, kMargin, ty, 24, kGray);+ ty += 34;+ }+ const char* label = tr(Str::ClaimFree);+ int tw = fonts_.semibold.measure(label, 30);+ int btnW = std::max(320, tw + 64);+ Rect claimBtn{kMargin, ty + 30, btnW, 76};+ claimRect_ = claimBtn;+ if (detailButtonFocus_ == 0) {+ c.strokeRect({claimBtn.x - 7, claimBtn.y - 7, claimBtn.w + 14, claimBtn.h + 14}, kWhite, 4, 45);+ }+ c.fillRect(claimBtn, kGreen, 38);+ fonts_.semibold.draw(c, label, claimBtn.x + (claimBtn.w - tw) / 2, claimBtn.y + 22, 30, kWhite);+ } else if (price != prices_.end()) {+ // The price, and the regular one crossed out while on sale.+ int px = kMargin;+ fonts_.bold.draw(c, price->second.now, px, ty, 52, kWhite);+ px += fonts_.bold.measure(price->second.now, 52) + 24;+ if (!price->second.was.empty()) {+ int w = fonts_.semibold.measure(price->second.was, 30);+ fonts_.semibold.draw(c, price->second.was, px, ty + 14, 30, kDim);+ c.line(static_cast<float>(px), static_cast<float>(ty + 32), static_cast<float>(px + w),+ static_cast<float>(ty + 32), 2, kDim);+ }+ ty += 84;+ }+ if (!free) {+ drawBag(c, kMargin + 12, ty + 16, kGreen);+ fonts_.semibold.draw(c, tr(Str::BuyToPlay), kMargin + 36, ty, 28, kWhite);+ ty += 48;+ for (const auto& line : fonts_.regular.wrap(tr(Str::BuyHint), 24, 820, 3)) {+ fonts_.regular.draw(c, line, kMargin, ty, 24, kGray);+ ty += 34;+ }+ Rect box = drawQr(c, "https://www.xbox.com/games/store/p/" + g->productId, kW - kMargin, 190, 440);+ if (box.w > 0) {+ const char* scan = tr(Str::ScanToBuy);+ int w = fonts_.semibold.measure(scan, 26);+ fonts_.semibold.draw(c, scan, box.x + (box.w - w) / 2, box.y + box.h + 22, 26, kWhite);+ }+ }+ std::vector<Hint> hints;+ if (free) hints.push_back({kIconCross, tr(Str::ClaimFree)});+ hints.push_back({kIconOptions, tr(Str::GameSettings)});+ hints.push_back({kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)});+ hints.push_back({kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)});+ if (!isAcquired(*g)) hints.push_back({kIconR3, tr(wishlist_.count(g->productId) ? Str::RemoveWishlist : Str::AddWishlist)});+ if (!g->xboxTitleId.empty()) hints.push_back({kIconL3, tr(Str::Achievements)});+ hints.push_back({kIconCircle, tr(Str::Back)});+ drawHints(c, hints);+ drawToast(c, nowMs);+ return;+ }+ if (!effectivePlayable) {+ // Bought separately or outside the subscription: no Play button.+ std::string msg = (isFreePlayer && !isF2P) ? tr(Str::GamePassRequired) : (planName ? trf(Str::IncludedWithPlan, planName) : std::string(tr(Str::NotPlayable)));+ int w = std::max(560, fonts_.semibold.measure(msg, 28) + 124);+ Rect note{kMargin, std::max(y + 48, 620), w, 76};+ c.fillRect(note, rgba(255, 255, 255, 40), 38);+ drawLock(c, note.x + 52, note.y + note.h / 2);+ fonts_.semibold.draw(c, msg, note.x + 90, note.y + 22, 28, kGray);++ int nextBadgeX = note.x + note.w + 24;+ uint64_t playedSeconds = 0;+ if (!g->productId.empty()) {+ auto it = settings_.titlePlaytime.find(g->productId);+ if (it != settings_.titlePlaytime.end()) playedSeconds = it->second;+ }+ if (!playedSeconds && !g->titleId.empty()) {+ auto it = settings_.titlePlaytime.find(g->titleId);+ if (it != settings_.titlePlaytime.end()) playedSeconds = it->second;+ }+ if (playedSeconds > 0) {+ std::string playedText = trf(Str::PlaytimePlayed, formatPlaytime(playedSeconds));+ int pw = fonts_.semibold.measure(playedText, 24);+ Rect pill{nextBadgeX, note.y + 14, pw + 44, 48};+ c.fillRect(pill, rgba(0, 0, 0, 150), 24);+ fonts_.semibold.draw(c, playedText, pill.x + 22, pill.y + 12, 24, kWhite);+ }++ std::vector<Hint> hints = {+ {kIconOptions, tr(Str::GameSettings)},+ {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},+ {kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)}+ };+ if (!isAcquired(*g)) hints.push_back({kIconR3, tr(wishlist_.count(g->productId) ? Str::RemoveWishlist : Str::AddWishlist)});+ if (!g->xboxTitleId.empty()) hints.push_back({kIconL3, tr(Str::Achievements)});+ hints.push_back({kIconCircle, tr(Str::Back)});+ drawHints(c, hints);+ drawToast(c, nowMs);+ return;+ }+ bool hasAchievements = !g->xboxTitleId.empty();+ bool playFocused = (detailButtonFocus_ == 0);+ bool achFocused = (detailButtonFocus_ == 1 && hasAchievements);++ // Play button+ Rect play{kMargin, std::max(y + 48, 620), 300, 76};+ playRect_ = play;+ if (playFocused) {+ c.strokeRect({play.x - 7, play.y - 7, play.w + 14, play.h + 14}, kWhite, 4, 45);+ c.fillRect(play, kGreen, 38);+ } else {+ c.fillRect(play, rgba(16, 124, 65, 140), 38);+ }+ float tx = play.x + 70, ty = play.y + play.h / 2.0f;+ c.line(tx - 8, ty - 13, tx - 8, ty + 13, 4, kWhite);+ c.line(tx - 8, ty - 13, tx + 13, ty, 4, kWhite);+ c.line(tx - 8, ty + 13, tx + 13, ty, 4, kWhite);+ fonts_.semibold.draw(c, tr(Str::Play), play.x + 108, play.y + 20, 32, kWhite);++ int nextBadgeX = play.x + play.w + 24;++ // Achievements button beside Play+ if (hasAchievements) {+ std::string achText = tr(Str::Achievements);+ auto it = achievements_.find(g->xboxTitleId);+ if (it != achievements_.end() && it->second.totalCount > 0) {+ const auto& ach = it->second;+ achText = std::to_string(ach.unlockedCount) + "/" + std::to_string(ach.totalCount) ++ " (" + std::to_string(ach.unlockedGamerscore) + "/" + std::to_string(ach.totalGamerscore) + " G)";+ }+ int textW = fonts_.semibold.measure(achText, 26);+ int achW = std::max(240, textW + 80);+ Rect achBtn{nextBadgeX, play.y, achW, 76};+ achRect_ = achBtn;+ if (achFocused) {+ c.strokeRect({achBtn.x - 7, achBtn.y - 7, achBtn.w + 14, achBtn.h + 14}, kWhite, 4, 45);+ c.fillRect(achBtn, kGreen, 38);+ } else {+ c.fillRect(achBtn, rgba(255, 255, 255, 30), 38);+ }+ drawGamerscoreBadge(c, static_cast<float>(achBtn.x + 36), static_cast<float>(achBtn.y + 38), 13.0f);+ fonts_.semibold.draw(c, achText, achBtn.x + 60, achBtn.y + 22, 26, kWhite);+ nextBadgeX += achBtn.w + 24;+ }++ // The service's estimate of the wait to start it, beside Play.+ if (queueTitle_ == g->titleId && queueSeconds_ >= 0) {+ std::string wait = queueSeconds_ < 60 ? trf(Str::QueueSeconds, std::to_string(queueSeconds_))+ : trf(Str::QueueMinutes, std::to_string((queueSeconds_ + 59) / 60));+ int w = fonts_.regular.measure(wait, 26);+ Rect pill{nextBadgeX, play.y + 14, w + 44, 48};+ c.fillRect(pill, rgba(0, 0, 0, 150), 24); // readable over any hero art+ fonts_.regular.draw(c, wait, pill.x + 22, pill.y + 10, 26, kWhite);+ nextBadgeX += pill.w + 16;+ }+ uint64_t playedSeconds = 0;+ if (!g->productId.empty()) {+ auto it = settings_.titlePlaytime.find(g->productId);+ if (it != settings_.titlePlaytime.end()) playedSeconds = it->second;+ }+ if (!playedSeconds && !g->titleId.empty()) {+ auto it = settings_.titlePlaytime.find(g->titleId);+ if (it != settings_.titlePlaytime.end()) playedSeconds = it->second;+ }+ if (playedSeconds > 0) {+ std::string playedText = trf(Str::PlaytimePlayed, formatPlaytime(playedSeconds));+ int w = fonts_.semibold.measure(playedText, 24);+ Rect pill{nextBadgeX, play.y + 14, w + 44, 48};+ c.fillRect(pill, rgba(0, 0, 0, 150), 24);+ fonts_.semibold.draw(c, playedText, pill.x + 22, pill.y + 12, 24, kWhite);+ nextBadgeX += pill.w + 16;+ }+ std::vector<Hint> hints = {+ {kIconCross, tr(achFocused ? Str::Achievements : Str::Play)},+ {kIconOptions, tr(Str::GameSettings)},+ {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},+ {kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)}+ };+ if (!isAcquired(*g)) hints.push_back({kIconR3, tr(wishlist_.count(g->productId) ? Str::RemoveWishlist : Str::AddWishlist)});+ hints.push_back({kIconCircle, tr(Str::Back)});+ drawHints(c, hints);+ drawToast(c, nowMs);+}++void AppUi::drawLaunching(Canvas& c, uint64_t nowMs) {+ c.clear(kBg);+ if (auto hero = images_.get(launching_.heroUrl, kW, kH)) c.drawImage(*hero, 0, 0);+ c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 175));+ drawSpinner(c, kW / 2.0f, 420, 40, nowMs);+ drawCentered(c, fonts_.bold, launching_.name, 500, 48, kWhite);+ drawCentered(c, fonts_.semibold, tr(Str::GettingReady), 576, 30, kGray);+ drawCentered(c, fonts_.regular, status_, 630, 26, kDim);+ // Helpful tips rotating every ~10 seconds from when the launching screen opened.+ static constexpr Str kTips[] = {+ Str::TipTouchpadMenu,+ Str::TipKeyboardMouse,+ Str::TipFreeStore,+ Str::TipBugReportQr,+ Str::TipSupportKofi,+ Str::Tip120HzVideo,+ Str::TipAnalogDeadzone,+ Str::TipDualSenseMic,+ };+ constexpr size_t kTipCount = sizeof(kTips) / sizeof(kTips[0]);+ if (!launchingStartMs_) launchingStartMs_ = nowMs;+ uint64_t elapsedMs = nowMs >= launchingStartMs_ ? (nowMs - launchingStartMs_) : 0;+ size_t tipIndex = (elapsedMs / 10000) % kTipCount;+ drawCentered(c, fonts_.regular, tr(kTips[tipIndex]), 900, 22, kDim);+ drawHints(c, {{kIconCircle, tr(Str::Cancel)}});+}++void AppUi::drawError(Canvas& c) {+ drawBackground(c);+ int panelW = errorUrl_.empty() ? 1040 : 1300;+ int maxTextW = errorUrl_.empty() ? (panelW - 112) : (panelW - 460);+ auto lines = fonts_.regular.wrap(error_, 26, maxTextW, 8);+ int h = 132 + static_cast<int>(lines.size()) * 38 + 56;+ if (!errorUrl_.empty() && h < 460) h = 460;+ Rect panel{(kW - panelW) / 2, (kH - h) / 2 - 40, panelW, h};+ c.fillRect(panel, kPanel, 24);+ fonts_.bold.draw(c, tr(Str::ErrorTitle), panel.x + 56, panel.y + 52, 44, kWhite);+ int y = panel.y + 132;+ for (const auto& line : lines) {+ fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);+ y += 38;+ }+ if (!errorUrl_.empty()) {+ y += 16;+ for (const auto& line : fonts_.regular.wrap(tr(Str::ScanQrToResolve), 24, maxTextW, 4)) {+ fonts_.regular.draw(c, line, panel.x + 56, y, 24, rgba(220, 220, 255));+ y += 34;+ }+ drawQr(c, errorUrl_, panel.x + panel.w - 56, panel.y + 56, 320, qrcodegen_Ecc_LOW);+ }+ if (!errorGame_.titleId.empty() || !errorGame_.productId.empty()) {+ bool free = (isFreeGame(errorGame_) || errorGame_.freeInStore) && !errorGame_.playable;+ const char* acceptLabel = free ? tr(Str::ClaimFree) : tr(Str::TryAgain);+ drawHints(c, {{kIconCross, acceptLabel}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});+ }+ else if (regionRefused_)+ drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconSquare, tr(Str::TryOtherCountry)},+ {kIconOptions, tr(Str::Settings)}, {kIconTriangle, tr(Str::ReportProblem)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});+ else if (!rows_.empty() || !owned_.empty())+ drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconSquare, tr(Str::OfflineMode)},+ {kIconTriangle, tr(Str::ReportProblem)}, {kIconTouchpad, tr(Str::HoldSignOut)}});+ else+ drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconTriangle, tr(Str::ReportProblem)},+ {kIconTouchpad, tr(Str::HoldSignOut)}});+}++void AppUi::drawReport(Canvas& c) {+ // A panel over the screen: the heading and what the QR code does on the+ // left, the code on the right (dense: about 1.8 KB, so large).+ c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 170));+ constexpr int kPanelW = 1500, kPanelH = 720;+ Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 30, kPanelW, kPanelH};+ c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26);+ c.fillRect(panel, kPanel, 24);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);+ Rect qr = drawQr(c, reportUrl_, panel.x + panel.w - 48, panel.y + 48, 600, qrcodegen_Ecc_LOW);+ int textW = (qr.w ? qr.x : panel.x + panel.w) - panel.x - 112;+ int y = panel.y + 56;+ for (const auto& line : fonts_.bold.wrap(reportHeading_, 40, textW, 3)) {+ fonts_.bold.draw(c, line, panel.x + 56, y, 40, kWhite);+ y += 54;+ }+ y += 24;+ for (Str s : {Str::ReportScan, Str::ReportIncludes}) {+ for (const auto& line : fonts_.regular.wrap(tr(s), 26, textW, 4)) {+ fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);+ y += 38;+ }+ y += 20;+ }+ if (!reportDetail_.empty()) {+ y += 8;+ for (const auto& line : fonts_.regular.wrap(reportDetail_, 22, textW, 3)) {+ fonts_.regular.draw(c, line, panel.x + 56, y, 22, kWhite);+ y += 32;+ }+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg);+ if (caps_.openUrl) // a desktop: Cross opens the form in the browser+ drawHints(c, {{kIconCross, tr(Str::OpenInBrowser)}, {kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+}++void AppUi::drawCountryPicker(Canvas& c) {+ // Over the refused sign-in: the warning, then the countries.+ constexpr int kPanelW = 1100, kItemH = 58;+ auto warning = fonts_.regular.wrap(tr(Str::LoginCountryWarning), 26, kPanelW - 112, 6);+ int n = 1 + static_cast<int>(std::size(kLoginCountries));+ int listY = 124 + static_cast<int>(warning.size()) * 36 + 24;+ Rect panel = drawModal(c, kPanelW, listY + n * kItemH + 40, tr(Str::TryOtherCountry));+ int y = panel.y + 124;+ for (const auto& line : warning) {+ fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);+ y += 36;+ }+ int sel = settingSelected(8);+ for (int i = 0; i < n; ++i) {+ Rect item{panel.x + 48, panel.y + listY + i * kItemH, panel.w - 96, kItemH};+ bool on = i == countryIndex_;+ if (on) c.fillRect(item, kWhite, 12);+ std::string label = i ? loginCountryName(kLoginCountries[i - 1]) : loginCountryOffText();+ fonts_.semibold.draw(c, label, item.x + 24, fonts_.semibold.centeredY(item.y, item.h, 26), 26,+ on ? kBg : (i == sel ? kWhite : kGray));+ if (i == sel) { // a check mark on the current choice+ float cx = static_cast<float>(item.x + item.w - 36), cy = static_cast<float>(item.y + item.h / 2);+ c.line(cx - 10, cy, cx - 3, cy + 7, 3, on ? kBg : kGreen);+ c.line(cx - 3, cy + 7, cx + 10, cy - 7, 3, on ? kBg : kGreen);+ }+ }+}++void AppUi::drawQuitPrompt(Canvas& c) {+ // As the update pop-up: the question, then Close and Cancel as buttons.+ constexpr int kButtonW = 300, kButtonH = 72, kPanelW = 2 * kButtonW + 24 + 112, kPanelH = 250;+ Rect panel = drawModal(c, kPanelW, kPanelH, tr(Str::QuitTitle));+ const char* labels[2] = {tr(Str::QuitConfirm), tr(Str::Cancel)};+ for (int i = 0; i < 2; ++i) {+ Rect b{panel.x + 56 + i * (kButtonW + 24), panel.y + panel.h - kButtonH - 44, kButtonW, kButtonH};+ bool on = i == promptFocus_;+ c.fillRect(b, on ? kWhite : rgba(255, 255, 255, 30), 14);+ int tw = fonts_.semibold.measure(labels[i], 28);+ fonts_.semibold.draw(c, labels[i], b.x + (b.w - tw) / 2, fonts_.semibold.centeredY(b.y, b.h, 28), 28,+ on ? kBg : kWhite);+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg); // its own hints over drawModal's+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Cancel)}});+}++void AppUi::drawUpdatePrompt(Canvas& c) {+ c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));+ constexpr int kPanelW = 960, kPanelH = 340, kButtonW = 260, kButtonH = 72;+ Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 40, kPanelW, kPanelH};+ c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow+ c.fillRect(panel, kPanel, 24);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);+ fonts_.bold.draw(c, trf(Str::UpdateAvailable, updateAvailable_), panel.x + 56, panel.y + 48, 44, kWhite);+ auto lines = fonts_.regular.wrap(tr(Str::UpdatePrompt), 26, kPanelW - 112, 2);+ for (size_t i = 0; i < lines.size(); ++i)+ fonts_.regular.draw(c, lines[i], panel.x + 56, panel.y + 124 + static_cast<int>(i) * 36, 26, kGray);++ // 3 buttons: Update now (0), What's new (1), Not now (2)+ const char* labels[3] = {tr(Str::UpdateNow), tr(Str::WhatsNew), tr(Str::NotNow)};+ constexpr int kGap = (kPanelW - 112 - 3 * kButtonW) / 2;+ for (int i = 0; i < 3; ++i) {+ Rect b{panel.x + 56 + i * (kButtonW + kGap), panel.y + panel.h - kButtonH - 44, kButtonW, kButtonH};+ bool on = i == promptFocus_;+ c.fillRect(b, on ? kWhite : rgba(255, 255, 255, 30), 14);+ int tw = fonts_.semibold.measure(labels[i], 24);+ fonts_.semibold.draw(c, labels[i], b.x + (b.w - tw) / 2, fonts_.semibold.centeredY(b.y, b.h, 24), 24,+ on ? kBg : kWhite);+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg); // the home screen's hints, under the pop-up's+ drawPads(c);+ drawHints(c, {+ {kIconCross, tr(Str::Select)},+ {kIconSquare, tr(Str::WhatsNew)},+ {kIconCircle, tr(Str::NotNow)}+ });+}++void AppUi::formatUpdateNotes() {+ updateNotesLines_.clear();+ std::string lang = languageCode(language());+ updateNotesLang_ = lang;+ std::string raw = xc::app::filterReleaseNotes(updateNotes_, lang);+ if (raw.empty()) raw = updateNotes_;+ if (raw.empty()) raw = "No release notes provided.";++ constexpr int kModalW = 1200, kModalH = 740;+ int textW = kModalW - 128 - 28;+ int textH = kModalH - 175;++ size_t pos = 0;+ while (pos < raw.size()) {+ size_t next = raw.find('\n', pos);+ std::string rawLine = raw.substr(pos, next == std::string::npos ? std::string::npos : next - pos);+ if (!rawLine.empty() && rawLine.back() == '\r') rawLine.pop_back();++ if (rawLine.rfind("### ", 0) == 0) {+ std::string sub = rawLine.substr(4);+ auto wrapped = fonts_.semibold.wrap(sub, 22, textW, 4);+ for (const auto& w : wrapped) updateNotesLines_.push_back({w, false, true, false, false});+ } else if (rawLine.rfind("## ", 0) == 0) {+ std::string hdr = rawLine.substr(3);+ auto wrapped = fonts_.bold.wrap(hdr, 26, textW, 4);+ for (const auto& w : wrapped) updateNotesLines_.push_back({w, true, false, false, false});+ } else if (rawLine.rfind("# ", 0) == 0) {+ std::string hdr = rawLine.substr(2);+ auto wrapped = fonts_.bold.wrap(hdr, 28, textW, 4);+ for (const auto& w : wrapped) updateNotesLines_.push_back({w, true, false, false, false});+ } else if (rawLine.rfind("- ", 0) == 0 || rawLine.rfind("* ", 0) == 0) {+ std::string bullet = "• " + rawLine.substr(2);+ auto wrapped = fonts_.regular.wrap(bullet, 22, textW, 6);+ for (size_t wi = 0; wi < wrapped.size(); ++wi) {+ updateNotesLines_.push_back({wrapped[wi], false, false, wi == 0, wi > 0});+ }+ } else if (!rawLine.empty()) {+ auto wrapped = fonts_.regular.wrap(rawLine, 22, textW, 8);+ for (const auto& w : wrapped) updateNotesLines_.push_back({w, false, false, false, false});+ } else {+ updateNotesLines_.push_back({"", false, false, false, false});+ }++ if (next == std::string::npos) break;+ pos = next + 1;+ }++ constexpr int kLineH = 32;+ int visibleLines = textH / kLineH;+ int totalLines = static_cast<int>(updateNotesLines_.size());+ updateNotesMaxScroll_ = std::max(0, totalLines - visibleLines);+ updateNotesScroll_ = std::clamp(updateNotesScroll_, 0, updateNotesMaxScroll_);+}++void AppUi::drawUpdateNotesModal(Canvas& c) {+ std::string currentLang = languageCode(language());+ if (updateNotesLines_.empty() || updateNotesLang_ != currentLang) {+ formatUpdateNotes();+ }++ std::string title = tr(Str::WhatsNewTitle);+ if (!updateAvailable_.empty()) {+ title += " - " + updateAvailable_;+ }+ constexpr int kModalW = 1200, kModalH = 740;+ Rect panel = drawModal(c, kModalW, kModalH, title);++ int textX = panel.x + 64;+ int textY = panel.y + 115;+ int textH = panel.h - 175;++ constexpr int kLineH = 32;+ int visibleLines = textH / kLineH;+ int totalLines = static_cast<int>(updateNotesLines_.size());+ updateNotesScroll_ = std::clamp(updateNotesScroll_, 0, updateNotesMaxScroll_);++ c.fillRect({panel.x + 44, textY - 12, panel.w - 88, textH + 24}, rgba(18, 18, 18, 220), 12);+ c.strokeRect({panel.x + 44, textY - 12, panel.w - 88, textH + 24}, rgba(255, 255, 255, 25), 1, 12);++ int curY = textY;+ int endIdx = std::min(totalLines, updateNotesScroll_ + visibleLines);+ for (int i = updateNotesScroll_; i < endIdx; ++i) {+ const auto& fl = updateNotesLines_[static_cast<size_t>(i)];+ if (!fl.text.empty()) {+ if (fl.isHeader) {+ fonts_.bold.draw(c, fl.text, textX, curY, 26, kWhite);+ } else if (fl.isSubHeader) {+ fonts_.semibold.draw(c, fl.text, textX, curY, 22, rgba(120, 220, 120));+ } else if (fl.isBullet) {+ fonts_.regular.draw(c, fl.text, textX + 6, curY, 22, rgba(235, 235, 235));+ } else if (fl.isBulletContinuation) {+ fonts_.regular.draw(c, fl.text, textX + 28, curY, 22, rgba(235, 235, 235));+ } else {+ fonts_.regular.draw(c, fl.text, textX, curY, 22, kGray);+ }+ }+ curY += kLineH;+ }++ if (totalLines > visibleLines) {+ int barTrackX = panel.x + panel.w - 60;+ int barTrackY = textY - 4;+ int barTrackH = textH + 8;+ c.fillRect({barTrackX, barTrackY, 6, barTrackH}, rgba(255, 255, 255, 30), 3);+ float ratio = static_cast<float>(visibleLines) / totalLines;+ int thumbH = std::max(32, static_cast<int>(barTrackH * ratio));+ float scrollPct = updateNotesMaxScroll_ > 0 ? static_cast<float>(updateNotesScroll_) / updateNotesMaxScroll_ : 0.0f;+ int thumbY = barTrackY + static_cast<int>((barTrackH - thumbH) * scrollPct);+ c.fillRect({barTrackX, thumbY, 6, thumbH}, kWhite, 3);+ }++ c.fillRect({0, kH - 80, kW, 80}, kBg);+ drawPads(c);+ drawHints(c, {+ {kIconCircle, tr(Str::Back)}+ });+}++void AppUi::drawAchievementsModal(Canvas& c, uint64_t nowMs) {+ Rect panel = drawModal(c, 1180, 720, tr(Str::Achievements));++ auto it = achievements_.find(detail_.xboxTitleId);+ if (it == achievements_.end()) {+ drawSpinner(c, static_cast<float>(panel.x + panel.w / 2), static_cast<float>(panel.y + panel.h / 2), 24.0f, nowMs);+ animating_ = true;+ c.fillRect({0, kH - 80, kW, 80}, kBg);+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+ return;+ }++ const auto& ach = it->second;+ if (ach.totalCount == 0) {+ std::string emptyStr = tr(Str::NoAchievements);+ int tw = fonts_.regular.measure(emptyStr, 28);+ fonts_.regular.draw(c, emptyStr, panel.x + (panel.w - tw) / 2, panel.y + panel.h / 2, 28, kDim);+ c.fillRect({0, kH - 80, kW, 80}, kBg);+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+ return;+ }++ std::string summary = std::to_string(ach.unlockedCount) + " / " + std::to_string(ach.totalCount) ++ " (" + std::to_string(ach.unlockedGamerscore) + " / " + std::to_string(ach.totalGamerscore) + " G)";+ int sw = fonts_.semibold.measure(summary, 24);+ fonts_.semibold.draw(c, summary, panel.x + panel.w - 56 - sw, panel.y + 56, 24, kWhite);++ int barX = panel.x + 56;+ int barY = panel.y + 104;+ int barW = panel.w - 112;+ int barH = 10;+ c.fillRect({barX, barY, barW, barH}, rgba(255, 255, 255, 30), 5);+ if (ach.totalCount > 0 && ach.unlockedCount > 0) {+ int fillW = std::clamp(static_cast<int>(barW * static_cast<float>(ach.unlockedCount) / ach.totalCount), 10, barW);+ c.fillRect({barX, barY, fillW, barH}, kGreen, 5);+ }++ constexpr int kRowH = 80;+ constexpr int kGap = 8;+ constexpr int kVisibleCount = 5;+ int y = barY + 22;++ int total = static_cast<int>(ach.items.size());+ int startIdx = std::clamp(achScroll_, 0, std::max(0, total - kVisibleCount));++ for (int i = startIdx; i < total && i < startIdx + kVisibleCount; ++i) {+ const auto& item = ach.items[i];+ Rect r{panel.x + 56, y, panel.w - 112, kRowH};+ c.fillRect(r, rgba(255, 255, 255, 14), 14);++ float cx = static_cast<float>(r.x + 36), cy = static_cast<float>(r.y + r.h / 2);+ if (item.unlocked) {+ c.fillCircle(cx, cy, 18.0f, kGreen);+ c.line(cx - 7, cy, cx - 2, cy + 6, 3.0f, kWhite);+ c.line(cx - 2, cy + 6, cx + 9, cy - 6, 3.0f, kWhite);+ } else {+ c.fillCircle(cx, cy, 18.0f, rgba(255, 255, 255, 20));+ c.strokeCircle(cx, cy - 3.0f, 4.0f, 2.0f, kDim);+ c.fillRect({static_cast<int>(cx) - 6, static_cast<int>(cy) - 2, 12, 10}, kDim, 2);+ }++ int textX = r.x + 72;+ int maxTextW = r.w - 200;+ if (item.unlocked) {+ fonts_.semibold.draw(c, item.name, textX, r.y + 14, 24, kWhite);+ std::string desc = fonts_.regular.fit(item.description, 20, maxTextW);+ fonts_.regular.draw(c, desc, textX, r.y + 44, 20, kGray);+ } else if (item.isSecret) {+ fonts_.semibold.draw(c, tr(Str::SecretAchievement), textX, r.y + 14, 24, kDim);+ fonts_.regular.draw(c, tr(Str::AchievementLocked), textX, r.y + 44, 20, rgba(255, 255, 255, 90));+ } else {+ fonts_.semibold.draw(c, item.name, textX, r.y + 14, 24, rgba(230, 230, 230));+ std::string desc = item.lockedDescription.empty() ? item.description : item.lockedDescription;+ desc = fonts_.regular.fit(desc, 20, maxTextW);+ fonts_.regular.draw(c, desc, textX, r.y + 44, 20, kDim);+ }++ std::string score = std::to_string(item.gamerscore) + " G";+ int scw = fonts_.semibold.measure(score, 22);+ Color scCol = item.unlocked ? rgba(110, 225, 120) : kDim;+ fonts_.semibold.draw(c, score, r.x + r.w - 28 - scw, fonts_.semibold.centeredY(r.y, r.h, 22), 22, scCol);++ y += kRowH + kGap;+ }++ if (total > kVisibleCount) {+ int trackH = kVisibleCount * (kRowH + kGap) - kGap;+ int trackY = barY + 22;+ int trackX = panel.x + panel.w - 40;+ c.fillRect({trackX, trackY, 4, trackH}, rgba(255, 255, 255, 20), 2);+ int thumbH = std::max(20, trackH * kVisibleCount / total);+ int thumbY = trackY + (trackH - thumbH) * startIdx / (total - kVisibleCount);+ c.fillRect({trackX, thumbY, 4, thumbH}, rgba(255, 255, 255, 120), 2);+ }++ c.fillRect({0, kH - 80, kW, 80}, kBg);+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+}++void AppUi::render(Canvas& c, uint64_t nowMs) {+ std::lock_guard<std::mutex> lock(mutex_);+ float dt = lastRender_ ? std::min(0.1f, (nowMs - lastRender_) / 1000.0f) : 0.0f;+ lastRender_ = nowMs;+ animating_ = rowY_.step(dt);+ for (auto& a : rowScroll_) animating_ |= a.step(dt);+ animating_ |= gridScroll_.step(dt);+ animating_ |= resultScroll_.step(dt);+ dirty_ = false;+ switch (screen_) {+ case Screen::Splash: drawSplash(c, nowMs); break;+ case Screen::SignIn: drawSignIn(c, nowMs); break;+ case Screen::Home: drawHome(c, nowMs); break;+ case Screen::Details:+ drawDetails(c, nowMs);+ if (gameSettingsOpen_) drawGameSettings(c);+ if (achievementsOpen_) drawAchievementsModal(c, nowMs);+ break;+ case Screen::Launching: drawLaunching(c, nowMs); break;+ case Screen::Error: drawError(c); break;+ case Screen::Settings: drawSettings(c); break;+ case Screen::Updating: drawUpdating(c, nowMs); break;+ case Screen::Streaming: break;+ }+ if (screen_ == Screen::Home && updatePrompt_) {+ if (showingUpdateNotes_) drawUpdateNotesModal(c);+ else drawUpdatePrompt(c);+ }+ if (screen_ == Screen::Home && quitPrompt_) drawQuitPrompt(c);+ if (screen_ == Screen::Error && countryPickerOpen_) drawCountryPicker(c);+ if (reportOpen_) drawReport(c);+ if ((screen_ == Screen::Home && !updatePrompt_) || screen_ == Screen::Error) drawSignOutHold(c, nowMs);+ if (!toast_.empty()) animating_ = true; // to expire it+ if (platform::toastsEnabled()) {+ // platform::notify() on a desktop: over everything, under the top bar's right side.+ toastsDrawn_ = platform::toasts().version(nowMs);+ drawToasts(c, fonts_, platform::toasts().visible(nowMs), kW - kMargin, 132);+ }+ if (mouseCursorVisible_ && nowMs >= mouseCursorVisibleUntil_) {+ mouseCursorVisible_ = false;+ }+ if (mouseCursorVisible_ && screen_ != Screen::Streaming && screen_ != Screen::Splash) {+ drawMouseCursor(c, mouseCursorX_, mouseCursorY_);+ }+}++static const char* const kCursorRows[23] = {+ "#...............",+ "##..............",+ "#W#.............",+ "#WW#............",+ "#WWW#...........",+ "#WWWW#..........",+ "#WWWWW#.........",+ "#WWWWWW#........",+ "#WWWWWWW#.......",+ "#WWWWWWWW#......",+ "#WWWWWWWWW#.....",+ "#WWWWWWWWWW#....",+ "#WWWWWWWWWWW#...",+ "#WWWWWW######...",+ "#WWWW##WW#......",+ "#WW##.#WW#......",+ "#W#...#WW#......",+ "##.....#WW#.....",+ "#......#WW#.....",+ "........#WW#....",+ "........#WW#....",+ ".........#WW#...",+ ".........####..."+};++void AppUi::drawMouseCursor(Canvas& c, float cursorX, float cursorY) {+ static bool s_inited = false;+ static uint8_t s_outline[23 * 16];+ static uint8_t s_fill[23 * 16];+ static uint8_t s_shadow[23 * 16];+ if (!s_inited) {+ s_inited = true;+ for (int y = 0; y < 23; ++y) {+ for (int x = 0; x < 16; ++x) {+ char ch = kCursorRows[y][x];+ s_shadow[y * 16 + x] = (ch == '#' || ch == 'W') ? 255 : 0;+ s_outline[y * 16 + x] = (ch == '#') ? 255 : 0;+ s_fill[y * 16 + x] = (ch == 'W') ? 255 : 0;+ }+ }+ }+ int ix = static_cast<int>(std::round(cursorX));+ int iy = static_cast<int>(std::round(cursorY));+ // Sombra sutil+ c.drawMask(s_shadow, 16, 23, 16, ix + 2, iy + 2, rgba(0, 0, 0, 80));+ // Borda preta fina+ c.drawMask(s_outline, 16, 23, 16, ix, iy, rgba(0, 0, 0, 240));+ // Seta branca nítida+ c.drawMask(s_fill, 16, 23, 16, ix, iy, rgba(255, 255, 255, 255));+}+++} // namespace xc::uidiff --git a/src/ui/app_ui_search.cpp b/src/ui/app_ui_search.cppnew file mode 100644index 0000000..0f22472--- /dev/null+++ b/src/ui/app_ui_search.cpp@@ -0,0 +1,571 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "ui/app_ui_internal.h"++namespace xc::ui {++namespace {++bool containsWordBoundary(const std::string& text, const std::string& token) {+ size_t pos = 0;+ while ((pos = text.find(token, pos)) != std::string::npos) {+ bool startBound = (pos == 0 || !isalnum((unsigned char)text[pos - 1]));+ bool endBound = (pos + token.size() >= text.size() || !isalnum((unsigned char)text[pos + token.size()]));+ if (startBound && endBound) return true;+ pos += token.size();+ }+ return false;+}++bool matchSearchWord(const std::string& name, const std::string& word) {+ if (name.find(word) != std::string::npos) return true;+ static const std::pair<const char*, const char*> kRoman[] = {+ {"1", "i"}, {"i", "1"},+ {"2", "ii"}, {"ii", "2"},+ {"3", "iii"}, {"iii", "3"},+ {"4", "iv"}, {"iv", "4"},+ {"4", "iiii"}, {"iiii", "4"},+ {"5", "v"}, {"v", "5"},+ {"6", "vi"}, {"vi", "6"},+ };+ for (const auto& [num, rom] : kRoman) {+ if (word == num && containsWordBoundary(name, rom)) return true;+ }+ static const std::pair<const char*, const char*> kAcronyms[] = {+ {"cod", "call of duty"},+ {"cod4", "call of duty 4"},+ {"codmw", "modern warfare"},+ {"codmw4", "modern warfare 4"},+ {"mw", "modern warfare"},+ {"mw1", "modern warfare"},+ {"mw2", "modern warfare ii"},+ {"mwii", "modern warfare ii"},+ {"mw3", "modern warfare iii"},+ {"mwiii", "modern warfare iii"},+ {"mw4", "modern warfare 4"},+ {"mwiv", "modern warfare 4"},+ {"bo", "black ops"},+ {"bo1", "black ops"},+ {"bo2", "black ops ii"},+ {"bo3", "black ops iii"},+ {"bo4", "black ops iiii"},+ {"bo6", "black ops 6"},+ {"bops", "black ops"},+ {"gta", "grand theft auto"},+ {"rdr", "red dead"},+ {"re", "resident evil"},+ {"ac", "assassin"},+ {"gow", "gears of war"},+ {"nfs", "need for speed"},+ {"bf", "battlefield"},+ };+ for (const auto& [acro, full] : kAcronyms) {+ if (word == acro && name.find(full) != std::string::npos) return true;+ }+ return false;+}++} // namespace++void AppUi::runSearch(bool keepPosition) {+ // Caller holds mutex_. The typed words narrow by name; the filters by+ // price and console. With filters and no words: every game that passes.+ std::string focusedProductId;+ std::string focusedTitleId;+ int oldFocus = resultFocus_;+ float oldScrollVal = resultScroll_.value;+ if (keepPosition && resultFocus_ >= 0 && resultFocus_ < static_cast<int>(results_.size())) {+ focusedProductId = results_[static_cast<size_t>(resultFocus_)].productId;+ focusedTitleId = results_[static_cast<size_t>(resultFocus_)].titleId;+ }++ results_.clear();+ std::string q = fold(query_);+ std::vector<std::string> words;+ for (size_t i = 0; i < q.size();) {+ size_t j = q.find(' ', i);+ if (j == std::string::npos) j = q.size();+ if (j > i) words.push_back(q.substr(i, j - i));+ i = j + 1;+ }+ bool filtering = anyFilter();+ if (words.empty() && !filtering) {+ resultFocus_ = 0;+ resultScroll_ = Anim{};+ return;+ }+ std::string compact = withoutSpaces(q);+ static const char* kConsoleCodes[] = {"", "XS", "ONE", "360"};+ struct Hit {+ int score;+ double order; // the price now (with any discount), by the active order filter+ double discount; // the bigger first among equal prices+ const GameTile* tile;+ };+ std::vector<Hit> hits;+ for (const auto& t : tab_ == Tab::GamePass ? gamePassPool_ : libraryPool_) {+ if (hidden_.count(t.productId)) continue;+ if (tab_ == Tab::GamePass && filterPlan_ != 4) {+ if (filterPlan_ == 0) {+ uint8_t myPlan = xcloud::planTier(subscription_);+ bool inPlan = (myPlan > 0) ? xcloud::planIncludes(myPlan, t.plan, t.freeInStore) : true;+ if (!t.freeInStore && !t.playable && !inPlan) continue;+ } else {+ uint8_t want = filterPlan_ == 1 ? xcloud::kPlanUltimate+ : filterPlan_ == 2 ? xcloud::kPlanPremium+ : xcloud::kPlanEssential;+ if (!t.freeInStore && (want < xcloud::kPlanUltimate && t.plan == 0)) continue;+ if (!xcloud::planIncludes(want, t.plan, t.freeInStore)) continue;+ }+ }+ if (filterConsole_ && t.platform != kConsoleCodes[filterConsole_]) continue;+ if (filterMouseKeyboard_ && !t.mouseKeyboard) continue;+ // Play mode and language need the full details: a game without them+ // yet comes in when they arrive.+ static constexpr uint32_t kModeBits[] = {0, xcloud::kModeSingle, xcloud::kModeOnlineMulti, xcloud::kModeOnlineCoop,+ xcloud::kModeLocal};+ if (filterMode_ && !(t.modes & kModeBits[filterMode_])) continue;+ if (filterLanguage_ == 1 && !(t.languages & (xcloud::kLangInterface | xcloud::kLangSubtitles))) continue;+ if (filterLanguage_ == 2 && !(t.languages & xcloud::kLangAudio)) continue;+ if (!filterGenre_.empty() && std::find(t.categories.begin(), t.categories.end(), filterGenre_) == t.categories.end())+ continue;+ if (filterPublisher_ && !matchesPublisher(t.publisher, filterPublisher_))+ continue;+ auto price = prices_.find(t.productId);+ bool priced = price != prices_.end();+ if (tab_ == Tab::Library) {+ if (filterWishlist_ && !wishlist_.count(t.productId)) continue;+ // Free-to-play: free in the store and no regular price. A paid+ // game given away (price 0 now, regular price above 0) is a+ // sale, not free-to-play.+ bool zeroNow = t.purchasable && priced && price->second.list < 0.005;+ bool freeToPlay = (t.freeInStore || (zeroNow && price->second.msrp < 0.005)) && !unclaimable_.count(t.productId);+ if (filterFree_) {+ if (!freeToPlay && !zeroNow) continue; // Free: both+ if (t.playable || isAcquired(t)) continue; // Do not show games the user already owns on their account!+ }+ // Free-to-play games have their own filter: the price orders+ // leave them out, unless Free is on too. Giveaways stay (first).+ if (filterCheapest_ && freeToPlay && !filterFree_) continue;+ // Price filters look at games to buy only.+ if (filterCheapest_ && !t.purchasable) continue;+ }+ std::string name = fold(t.name);+ int score = 0;+ if (!words.empty()) {+ bool all = true;+ for (const auto& w : words)+ if (!matchSearchWord(name, w)) all = false;+ if (!all && withoutSpaces(name).find(compact) == std::string::npos) continue;+ // Starts with the query or acronym, then a word starting with it, then the rest.+ if (matchSearchWord(name, words[0])) {+ score = name.rfind(words[0], 0) == 0 ? 0 : name.find(" " + words[0]) != std::string::npos ? 1 : 2;+ if (words[0] == "cod" && name.find("call of duty") != std::string::npos) score = 0;+ else if ((words[0] == "cod4" || words[0] == "mw4" || words[0] == "codmw4" ||+ words[0] == "mwiv" || words[0] == "codmwiv") &&+ (name.find("modern warfare 4") != std::string::npos || name.find("call of duty 4") != std::string::npos)) score = 0;+ else if (words[0] == "codmw" && name.find("modern warfare") != std::string::npos) score = 0;+ } else {+ score = 2;+ }+ }+ if (!t.playable) score += 3; // in "Your games": owned before games to buy+ // Lowest price: by the price now (with any discount, not the regular+ // one), lowest first; unknown prices last; the bigger discount first+ // among equal prices.+ double order = 0, discount = 0;+ if (filterCheapest_) order = priced ? price->second.list : 1e12;+ if (filterCheapest_ && priced && price->second.msrp > 0) discount = 1.0 - price->second.list / price->second.msrp;+ hits.push_back({score, order, discount, &t});+ }+ bool byOrder = tab_ == Tab::Library && filterCheapest_;+ std::stable_sort(hits.begin(), hits.end(), [&](const Hit& a, const Hit& b) {+ if (byOrder && a.order != b.order) return a.order < b.order;+ if (byOrder && a.discount != b.discount) return a.discount > b.discount;+ if (a.score != b.score) return a.score < b.score;+ return fold(a.tile->name) < fold(b.tile->name);+ });+ size_t max = words.empty() ? kMaxFilterResults : kMaxResults;+ for (size_t i = 0; i < hits.size() && i < max; ++i) results_.push_back(*hits[i].tile);+ if (keepPosition && !results_.empty()) {+ int newFocus = -1;+ if (!focusedProductId.empty() || !focusedTitleId.empty()) {+ for (size_t i = 0; i < results_.size(); ++i) {+ if ((!focusedProductId.empty() && results_[i].productId == focusedProductId) ||+ (!focusedTitleId.empty() && results_[i].titleId == focusedTitleId)) {+ newFocus = static_cast<int>(i);+ break;+ }+ }+ }+ if (newFocus >= 0) {+ resultFocus_ = newFocus;+ } else {+ resultFocus_ = std::min(oldFocus, static_cast<int>(results_.size()) - 1);+ }+ resultScroll_.target = gridTarget(resultFocus_, kResultCols);+ resultScroll_.value = oldScrollVal;+ } else {+ resultFocus_ = 0;+ resultScroll_ = Anim{};+ }+}++void AppUi::setSearchQuery(const std::string& query) {+ std::lock_guard<std::mutex> lock(mutex_);+ query_ = query;+ if (screen_ == Screen::Home || screen_ == Screen::Details || screen_ == Screen::Settings || screen_ == Screen::Error) {+ screen_ = Screen::Home;+ searching_ = true;+ searchOnKeys_ = true;+ filterList_ = -1;+ runSearch();+ dirty_ = true;+ }+}++std::string AppUi::searchQuery() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return query_;+}++void AppUi::setSearchTab(Tab t) {+ setSearchState(nullptr, &t, nullptr);+}++Tab AppUi::searchTab() const {+ return tab();+}++void AppUi::setSearchState(const std::string* query, const Tab* tab,+ const std::vector<std::pair<Filter, int>>* filters) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (query) {+ query_ = *query;+ }+ if (tab) {+ tab_ = *tab;+ }+ if (filters) {+ for (const auto& [f, val] : *filters) {+ applyFilterLocked(f, val);+ }+ }+ if (screen_ == Screen::Home || screen_ == Screen::Details || screen_ == Screen::Settings || screen_ == Screen::Error) {+ screen_ = Screen::Home;+ searching_ = true;+ searchOnKeys_ = true;+ filterList_ = -1;+ runSearch();+ dirty_ = true;+ }+}++int AppUi::filterSelectedPublic(Filter f) const {+ std::lock_guard<std::mutex> lock(mutex_);+ if (f == Filter::Free) return filterFree_ ? 1 : 0;+ if (f == Filter::Cheapest) return filterCheapest_ ? 1 : 0;+ if (f == Filter::MouseKeyboard) return filterMouseKeyboard_ ? 1 : 0;+ if (f == Filter::Wishlist) return filterWishlist_ ? 1 : 0;+ return filterSelected(f);+}++bool AppUi::filterOnPublic(Filter f) const {+ std::lock_guard<std::mutex> lock(mutex_);+ return filterOn(f);+}++bool AppUi::anyFilter() const {+ // Caller holds mutex_. Free and Lowest price only count in "Your games";+ // Plan only in Game Pass.+ bool library = tab_ == Tab::Library && (filterFree_ || filterCheapest_ || filterWishlist_);+ bool gamePass = tab_ == Tab::GamePass && filterPlan_ > 0;+ return library || gamePass || filterConsole_ || filterMouseKeyboard_ || filterMode_ || !filterGenre_.empty() ||+ filterPublisher_ || filterLanguage_;+}++std::vector<AppUi::Filter> AppUi::filterRow(int row) const {+ // Caller holds mutex_. Prices only matter in "Your games" (Game Pass+ // games aren't bought).+ if (tab_ == Tab::GamePass) {+ if (row == 0) return {Filter::Plan, Filter::Console, Filter::MouseKeyboard};+ if (row == 1) return {Filter::Mode, Filter::Genre, Filter::Publisher};+ if (row == 2) return {Filter::Language};+ return {};+ }+ if (row == 0) return {Filter::Wishlist, Filter::Free, Filter::Cheapest};+ if (row == 1) return {Filter::Mode, Filter::Genre, Filter::Publisher};+ if (row == 2) return {Filter::Console, Filter::Language, Filter::MouseKeyboard};+ return {};+}++std::vector<std::string> AppUi::poolGenres() const {+ // Caller holds mutex_.+ std::map<std::string, int> count;+ for (const auto& t : tab_ == Tab::GamePass ? gamePassPool_ : libraryPool_)+ for (const auto& c : t.categories) ++count[c];+ std::vector<std::pair<int, std::string>> order;+ for (const auto& [g, n] : count) order.push_back({-n, g});+ std::sort(order.begin(), order.end());+ std::vector<std::string> out;+ for (const auto& [n, g] : order) out.push_back(g);+ return out;+}++std::vector<std::string> AppUi::filterOptions(Filter f) const {+ // Caller holds mutex_. The first choice is always "all".+ switch (f) {+ case Filter::Plan: return {tr(Str::PlanMine), "Ultimate", "Premium", "Essential", tr(Str::PlanAll)};+ case Filter::Console: return {tr(Str::FilterAllConsoles), "SERIES X|S", "XBOX ONE", "XBOX 360"};+ case Filter::Mode:+ return {tr(Str::ModeAll), tr(Str::ModeSingle), tr(Str::ModeOnlineMulti), tr(Str::ModeOnlineCoop), tr(Str::ModeLocal)};+ case Filter::Genre: {+ std::vector<std::string> out = {tr(Str::GenreAll)};+ for (auto& g : poolGenres()) out.push_back(std::move(g));+ return out;+ }+ case Filter::Publisher:+ return {+ tr(Str::PublisherAll),+ "Xbox Game Studios / Bethesda",+ "Electronic Arts",+ "Ubisoft",+ "Square Enix",+ "Warner Bros. Games",+ "2K / Take-Two",+ "Capcom",+ "SEGA / Atlus",+ "Bandai Namco",+ "THQ Nordic / Plaion",+ "Focus Entertainment",+ "Devolver Digital",+ "Annapurna Interactive",+ "Team17",+ tr(Str::PublisherIndies)+ };+ case Filter::Language:+ return {tr(Str::LanguageAll), trf(Str::LangSubtitles, tr(Str::LanguageNoun)), trf(Str::LangAudio, tr(Str::LanguageNoun))};+ default: return {};+ }+}++int AppUi::filterSelected(Filter f) const {+ // Caller holds mutex_.+ if (f == Filter::Plan) return filterPlan_;+ if (f == Filter::Console) return filterConsole_;+ if (f == Filter::Mode) return filterMode_;+ if (f == Filter::Publisher) return filterPublisher_;+ if (f == Filter::Language) return filterLanguage_;+ if (f == Filter::Genre) {+ auto genres = poolGenres();+ for (size_t i = 0; i < genres.size(); ++i)+ if (genres[i] == filterGenre_) return static_cast<int>(i) + 1;+ }+ return 0;+}++void AppUi::chooseFilter(Filter f, int index) {+ std::lock_guard<std::mutex> lock(mutex_);+ chooseFilterLocked(f, index);+}++void AppUi::applyFilterLocked(Filter f, int index) {+ // Caller holds mutex_.+ if (f == Filter::Plan) filterPlan_ = index;+ if (f == Filter::Console) filterConsole_ = index;+ if (f == Filter::Mode) filterMode_ = index;+ if (f == Filter::Publisher) filterPublisher_ = index;+ if (f == Filter::Language) filterLanguage_ = index;+ if (f == Filter::Free) filterFree_ = index != 0;+ if (f == Filter::Cheapest) filterCheapest_ = index != 0;+ if (f == Filter::MouseKeyboard) filterMouseKeyboard_ = index != 0;+ if (f == Filter::Wishlist) filterWishlist_ = index != 0;+ if (f == Filter::Genre) {+ auto genres = poolGenres();+ filterGenre_ = index > 0 && index <= static_cast<int>(genres.size()) ? genres[static_cast<size_t>(index - 1)] : "";+ }+}++void AppUi::chooseFilterLocked(Filter f, int index) {+ // Caller holds mutex_.+ applyFilterLocked(f, index);+ filterList_ = -1;+ runSearch();+ dirty_ = true;+}++std::string AppUi::filterText(Filter f) const {+ // Caller holds mutex_. A list shows its name until a choice is made.+ if (f == Filter::Free) return tr(Str::FilterFree);+ if (f == Filter::MouseKeyboard) return tr(Str::FilterMouseKeyboard);+ if (f == Filter::Cheapest) return tr(Str::FilterCheapest);+ if (f == Filter::Wishlist) return tr(Str::Wishlist);+ int sel = filterSelected(f);+ if (sel > 0 || f == Filter::Console) {+ auto options = filterOptions(f);+ if (sel < static_cast<int>(options.size())) return options[static_cast<size_t>(sel)];+ }+ return tr(f == Filter::Plan ? Str::FilterPlan+ : f == Filter::Mode ? Str::FilterMode+ : f == Filter::Genre ? Str::FilterGenre+ : f == Filter::Publisher ? Str::FilterPublisher+ : Str::FilterLanguage);+}++bool AppUi::filterOn(Filter f) const {+ // Caller holds mutex_.+ if (f == Filter::Free) return filterFree_;+ if (f == Filter::Cheapest) return filterCheapest_;+ if (f == Filter::MouseKeyboard) return filterMouseKeyboard_;+ if (f == Filter::Wishlist) return filterWishlist_;+ return filterSelected(f) > 0;+}++void AppUi::pressFilter(Filter f) {+ // Caller holds mutex_. A list opens its drop-down at the current choice.+ if (isList(f)) {+ filterList_ = static_cast<int>(f);+ filterListIndex_ = filterSelected(f);+ filterListTop_ = 0;+ } else {+ if (f == Filter::Free) filterFree_ ^= true;+ else if (f == Filter::MouseKeyboard) filterMouseKeyboard_ ^= true;+ else if (f == Filter::Cheapest) filterCheapest_ ^= true;+ else if (f == Filter::Wishlist) filterWishlist_ ^= true;+ runSearch();+ }+ dirty_ = true;+}++bool AppUi::wantsTextInput() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return screen_ == Screen::Home && searching_ && searchOnKeys_ && filterList_ < 0 && keyRow_ <= kKeyRows;+}++void AppUi::typeText(std::string_view utf8) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!(screen_ == Screen::Home && searching_ && searchOnKeys_)) return;+ bool edited = false;+ for (char ch : utf8) {+ if (ch == '\b') {+ // The last character, all of its UTF-8 bytes.+ while (!query_.empty() && (static_cast<unsigned char>(query_.back()) & 0xC0) == 0x80) query_.pop_back();+ if (!query_.empty()) query_.pop_back(), edited = true;+ } else if (ch == '\n') {+ if (edited) runSearch(), edited = false;+ if (!results_.empty()) {+ searchOnKeys_ = false;+ resultFocus_ = 0;+ dirty_ = true;+ }+ } else if (static_cast<unsigned char>(ch) >= 0x20 && (query_.size() < 64 || (ch & 0xC0) == 0x80)) {+ if (ch == ' ' && (query_.empty() || query_.back() == ' ')) continue; // as the Space key+ query_ += ch;+ edited = true;+ }+ }+ if (edited) {+ runSearch();+ dirty_ = true;+ }+}++std::pair<int, int> AppUi::searchKeyFocus() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return {keyRow_, keyCol_};+}++int AppUi::searchResultFocus() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return resultFocus_;+}++bool AppUi::isSearchOnKeys() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return searchOnKeys_;+}++std::vector<int> AppUi::keyCenters(int row) const {+ // Caller holds mutex_.+ std::vector<int> out;+ if (row < kKeyRows) {+ for (int k = 0; k < kKeyCols; ++k) out.push_back(kMargin + k * (kKeyW + kKeyGap) + kKeyW / 2);+ } else if (row == kKeyRows) {+ for (int k = 0; k < 3; ++k)+ out.push_back(kMargin + kWideCols[k] * (kKeyW + kKeyGap) + (kWideSpan[k] * kKeyW + (kWideSpan[k] - 1) * kKeyGap) / 2);+ } else {+ int r = row - kKeyRows - 1;+ auto chips = filterRow(r);+ int n = static_cast<int>(chips.size());+ constexpr int kCols = 3;+ int w = (kKeysW - kChipGap * (kCols - 1)) / kCols;+ for (int k = 0; k < n; ++k) out.push_back(kMargin + k * (w + kChipGap) + w / 2);+ }+ return out;+}++void AppUi::handleSearchKeys(const NavInput& in) {+ // Caller holds mutex_. keyRow_ == kKeyRows is the row of wide keys, where+ // keyCol_ is 0..2 (Space, Delete, Clear); kKeyRows + 1, + 2 and + 3 the three+ // rows of filters in the 3x3 grid.+ if (filterList_ >= 0) {+ // A filter's drop-down: up / down, Cross picks, Circle closes it unchanged.+ Filter f = static_cast<Filter>(filterList_);+ int n = static_cast<int>(filterOptions(f).size());+ if (in.down && filterListIndex_ + 1 < n) ++filterListIndex_;+ if (in.up && filterListIndex_ > 0) --filterListIndex_;+ if (in.accept) chooseFilterLocked(f, filterListIndex_);+ if (in.accept || in.back) filterList_ = -1;+ dirty_ = true;+ return;+ }+ bool wide = keyRow_ == kKeyRows, filters = keyRow_ > kKeyRows;+ int filterCount = filters ? static_cast<int>(filterRow(keyRow_ - kKeyRows - 1).size()) : 0;+ bool canDown = (keyRow_ < kKeyRows + 3) && (!filters || !filterRow(keyRow_ - kKeyRows).empty());+ if ((in.up && keyRow_ > 0) || (in.down && canDown)) {+ // To the item on the next row whose middle is nearest this one's+ // (the rows have 6, 3 and a few items of different widths).+ auto from = keyCenters(keyRow_);+ int x = from[static_cast<size_t>(std::clamp(keyCol_, 0, static_cast<int>(from.size()) - 1))];+ keyRow_ += in.up ? -1 : 1;+ auto to = keyCenters(keyRow_);+ int best = 0;+ for (int k = 1; k < static_cast<int>(to.size()); ++k)+ if (std::abs(to[static_cast<size_t>(k)] - x) < std::abs(to[static_cast<size_t>(best)] - x)) best = k;+ keyCol_ = std::clamp(best, 0, std::max(0, static_cast<int>(to.size()) - 1));+ } else if (in.left && keyCol_ > 0) {+ --keyCol_;+ } else if (in.right) {+ int last = filters ? filterCount - 1 : wide ? 2 : kKeyCols - 1;+ if (keyCol_ < last) {+ ++keyCol_;+ } else if (!results_.empty()) { // on to the results+ searchOnKeys_ = false;+ resultFocus_ = 0;+ }+ }+ bool edited = false;+ if (in.accept) {+ if (filters) {+ pressFilter(filterRow(keyRow_ - kKeyRows - 1)[static_cast<size_t>(keyCol_)]);+ } else if (!wide) {+ query_ += kKeys[keyRow_ * kKeyCols + keyCol_];+ } else if (keyCol_ == 0) {+ if (!query_.empty() && query_.back() != ' ') query_ += ' ';+ } else if (keyCol_ == 1) {+ if (!query_.empty()) query_.pop_back();+ } else {+ query_.clear();+ }+ edited = !filters;+ dirty_ = true;+ }+ if (in.square && !query_.empty()) {+ query_.pop_back();+ edited = true;+ }+ if (edited) runSearch();+ if (in.up || in.down || in.left || in.right || edited) dirty_ = true;+}++} // namespace xc::uidiff --git a/src/ui/app_ui_settings.cpp b/src/ui/app_ui_settings.cppnew file mode 100644index 0000000..54e4bae--- /dev/null+++ b/src/ui/app_ui_settings.cpp@@ -0,0 +1,1930 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "ui/app_ui_internal.h"++namespace xc::ui {++bool AppUi::settingsLightBar(int& mode, Color& colour) const {+ std::lock_guard<std::mutex> lock(mutex_);+ if (screen_ != Screen::Settings) return false;+ mode = pickerOpen_ ? 1 : settings_.lightBarMode;+ colour = pickerOpen_ ? pickerColour() : settings_.lightBarColour;+ return true;+}++bool AppUi::settingsTriggerFeel(int& strength, int& hzIndex, int& resistance, bool& pulses, int& profile) const {+ std::lock_guard<std::mutex> lock(mutex_);+ if (screen_ != Screen::Settings && !gameSettingsOpen_) return false;+ strength = settings_.triggerStrength;+ hzIndex = settings_.triggerHz;+ resistance = settings_.triggerResistance;+ pulses = settings_.triggerPulses;+ profile = settings_.triggerProfile;+ return true;+}++bool AppUi::triggerTest(float& l2, float& r2) const {+ std::lock_guard<std::mutex> lock(mutex_);+ if ((screen_ != Screen::Settings && !gameSettingsOpen_) || tester_ != Tester::Triggers) return false;+ l2 = testL2_;+ r2 = testR2_;+ return true;+}++void AppUi::openTester(Tester t) {+ // Caller holds mutex_. Circle puts back what was there.+ tester_ = t;+ testerRow_ = 0;+ testerStick_ = 0;+ testerBackup_ = settings_;+ keysRow_ = keysCol_ = 0;+ captureSince_ = 0;+ keyRefused_ = 0;+ dirty_ = true;+}++bool AppUi::capturingKey() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return tester_ == Tester::Keys && captureSince_ && (screen_ == Screen::Settings || gameSettingsOpen_);+}++void AppUi::captureKey(uint8_t code) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (tester_ != Tester::Keys || !captureSince_ || keysRow_ >= kKeysPerColumn) return;+ dirty_ = true;+ if (input::isReservedKey(code)) { // still waiting: another key+ keyRefused_ = code;+ return;+ }+ auto action = static_cast<input::KeyAction>((keysCol_ / 2) * kKeysPerColumn + keysRow_);+ input::assignKey(settings_.keyMap, action, keysCol_ % 2, code);+ captureSince_ = 0;+ keyRefused_ = 0;+}++void AppUi::handleKeysTester(const NavInput& in) {+ // Caller holds mutex_. Each change applies at once; Circle goes back+ // with them (as Settings itself), "Reset to default" puts the first back.+ auto& map = settings_.keyMap;+ if (captureSince_) {+ // Waiting for a key (captureKey): Circle or 10 s give up.+ if (in.back || (in.nowMs > captureSince_ && in.nowMs - captureSince_ > 10000))+ captureSince_ = 0, keyRefused_ = 0, dirty_ = true;+ return;+ }+ constexpr int kRows = kKeysPerColumn + 1;+ if (in.up) keysRow_ = (keysRow_ + kRows - 1) % kRows, dirty_ = true;+ if (in.down) keysRow_ = (keysRow_ + 1) % kRows, dirty_ = true;+ if (keysRow_ < kKeysPerColumn) {+ if (in.left && keysCol_ > 0) --keysCol_, dirty_ = true;+ if (in.right && keysCol_ < 3) ++keysCol_, dirty_ = true;+ }+ size_t action = static_cast<size_t>((keysCol_ / 2) * kKeysPerColumn + keysRow_);+ if (in.accept) {+ if (keysRow_ == kKeysPerColumn)+ map = input::defaultKeyMap();+ else+ captureSince_ = in.nowMs ? in.nowMs : 1;+ keyRefused_ = 0;+ dirty_ = true;+ }+ if (in.square && keysRow_ < kKeysPerColumn) map[action][static_cast<size_t>(keysCol_ % 2)] = 0, dirty_ = true;+ if (in.back) {+ if (gameSettingsOpen_) {+ if (map != activeGameProfile_.keyMap) activeGameProfile_.keyMap = map, activeGameHasCustom_ = true;+ settings_ = testerBackup_;+ }+ tester_ = Tester::None;+ dirty_ = true;+ }+}++void AppUi::openPadTester() {+ // Caller holds mutex_. A copy of the map and touchpad shortcuts in force+ // (Settings', or the game's with its settings open) is what the screen edits.+ tester_ = Tester::Pad;+ padWork_ = gameSettingsOpen_ ? activeGameProfile_.padMap : settings_.padMap;+ if (!input::padMapValid(padWork_)) padWork_ = input::defaultPadMap();+ touchpadWork_ = gameSettingsOpen_ ? activeGameProfile_.touchpadShortcuts : settings_.touchpadShortcuts;+ padRow_ = padCol_ = 0;+ padCaptureSince_ = 0;+ padTesterTab_ = 0;+ touchpadRow_ = 0;+ touchpadDropdownOpen_ = false;+ touchpadDropdownIndex_ = 0;+ touchpadDropdownTop_ = 0;+ dirty_ = true;+}++void AppUi::handlePadTester(const NavInput& in) {+ if (touchpadDropdownOpen_) {+ constexpr int kMaxVisible = 8;+ constexpr int n = input::kTouchpadActions;+ if (in.up) {+ touchpadDropdownIndex_ = (touchpadDropdownIndex_ + n - 1) % n;+ if (touchpadDropdownIndex_ < touchpadDropdownTop_) touchpadDropdownTop_ = touchpadDropdownIndex_;+ else if (touchpadDropdownIndex_ >= touchpadDropdownTop_ + kMaxVisible)+ touchpadDropdownTop_ = touchpadDropdownIndex_ - kMaxVisible + 1;+ dirty_ = true;+ }+ if (in.down) {+ touchpadDropdownIndex_ = (touchpadDropdownIndex_ + 1) % n;+ if (touchpadDropdownIndex_ < touchpadDropdownTop_) touchpadDropdownTop_ = touchpadDropdownIndex_;+ else if (touchpadDropdownIndex_ >= touchpadDropdownTop_ + kMaxVisible)+ touchpadDropdownTop_ = touchpadDropdownIndex_ - kMaxVisible + 1;+ dirty_ = true;+ }+ if (in.accept) {+ touchpadWork_.set(touchpadRow_, static_cast<input::TouchpadAction>(touchpadDropdownIndex_));+ touchpadDropdownOpen_ = false;+ dirty_ = true;+ }+ if (in.back) {+ touchpadDropdownOpen_ = false;+ dirty_ = true;+ }+ return;+ }++ if (caps_.touchpad && (in.l1 || in.r1)) {+ padTesterTab_ = 1 - padTesterTab_;+ dirty_ = true;+ return;+ }++ if (padTesterTab_ == 1) {+ constexpr int kRows = input::kTouchpadTriggers + 1; // 0..5 triggers, 6 Reset to default+ if (in.up) touchpadRow_ = (touchpadRow_ + kRows - 1) % kRows, dirty_ = true;+ if (in.down) touchpadRow_ = (touchpadRow_ + 1) % kRows, dirty_ = true;+ if (touchpadRow_ < input::kTouchpadTriggers) {+ if (in.accept) {+ touchpadDropdownOpen_ = true;+ touchpadDropdownIndex_ = static_cast<int>(touchpadWork_.get(touchpadRow_));+ constexpr int kMaxVisible = 8;+ touchpadDropdownTop_ = std::clamp(touchpadDropdownIndex_ - 3, 0, std::max(0, input::kTouchpadActions - kMaxVisible));+ dirty_ = true;+ }+ if (in.square) {+ touchpadWork_.set(touchpadRow_, input::defaultTouchpadShortcuts().get(touchpadRow_));+ dirty_ = true;+ }+ } else if (in.accept) {+ touchpadWork_ = input::defaultTouchpadShortcuts();+ dirty_ = true;+ }+ if (in.back) {+ dirty_ = true;+ if (!input::padMapValid(padWork_)) {+ padTesterTab_ = 0;+ return;+ }+ if (gameSettingsOpen_) {+ if (padWork_ != activeGameProfile_.padMap) activeGameProfile_.padMap = padWork_, activeGameHasCustom_ = true;+ if (touchpadWork_ != activeGameProfile_.touchpadShortcuts) activeGameProfile_.touchpadShortcuts = touchpadWork_, activeGameHasCustom_ = true;+ } else {+ settings_.padMap = padWork_;+ settings_.touchpadShortcuts = touchpadWork_;+ }+ tester_ = Tester::None;+ }+ return;+ }++ const bool mapSwap = gameSettingsOpen_ ? activeGameProfile_.circleConfirms : settings_.circleConfirms;+ constexpr int kPerColumn = input::kPadFns / 2, kButtonsRow = kPerColumn;+ const auto fn = static_cast<input::PadFn>(padCol_ * kPerColumn + std::min(padRow_, kPerColumn - 1));+ if (padCaptureSince_) {+ if (in.padPressed) {+ uint8_t slot = 0;+ while (!(in.padPressed & (1u << slot))) ++slot;+ const uint8_t onPad = input::physicalSource(slot, circleConfirms_);+ input::assignPadSource(padWork_, fn, input::physicalSource(onPad, mapSwap));+ padCaptureSince_ = 0;+ dirty_ = true;+ } else if (in.nowMs > padCaptureSince_ && in.nowMs - padCaptureSince_ > 5000) {+ padCaptureSince_ = 0;+ dirty_ = true;+ }+ return;+ }+ if (in.up) padRow_ = (padRow_ + kButtonsRow) % (kButtonsRow + 1), dirty_ = true;+ if (in.down) padRow_ = (padRow_ + 1) % (kButtonsRow + 1), dirty_ = true;+ if (in.left || in.right) padCol_ = 1 - padCol_, dirty_ = true;+ if (in.accept) {+ dirty_ = true;+ if (padRow_ < kButtonsRow) {+ padCaptureSince_ = in.nowMs ? in.nowMs : 1;+ } else if (padCol_ == 0) {+ padWork_ = input::defaultPadMap(); // Reset to default (kept on the way out)+ } else {+ tester_ = Tester::None; // Discard changes: what was saved stays+ return;+ }+ }+ if (in.square && padRow_ < kButtonsRow) input::assignPadSource(padWork_, fn, input::kPadNone), dirty_ = true;+ if (in.back) {+ dirty_ = true;+ if (!input::padMapValid(padWork_)) return; // incomplete: the warning says what's missing+ if (gameSettingsOpen_) {+ if (padWork_ != activeGameProfile_.padMap) activeGameProfile_.padMap = padWork_, activeGameHasCustom_ = true;+ if (touchpadWork_ != activeGameProfile_.touchpadShortcuts) activeGameProfile_.touchpadShortcuts = touchpadWork_, activeGameHasCustom_ = true;+ } else {+ settings_.padMap = padWork_;+ settings_.touchpadShortcuts = touchpadWork_;+ }+ tester_ = Tester::None;+ }+}++void AppUi::openTouchpadTester() {+ openPadTester();+ padTesterTab_ = 1;+}++void AppUi::handleTouchpadTester(const NavInput& in) {+ handlePadTester(in);+}++void AppUi::handleTester(const NavInput& in) {+ // Caller holds mutex_. Changes apply as they are made (the pad follows);+ // Cross keeps them, Circle puts the old ones back.+ if (tester_ == Tester::Keys) return handleKeysTester(in);+ if (tester_ == Tester::Pad) return handlePadTester(in);+ if (tester_ == Tester::Touchpad) return handleTouchpadTester(in);+ if (tester_ == Tester::Sticks) {+ // L1 / R1 pick the stick, the D-pad (only: the sticks are what is+ // being tried) changes its dead zone.+ if (in.l1 || in.r1) testerStick_ = in.r1 ? 1 : 0, dirty_ = true;+ int& zone = settings_.deadzone[testerStick_];+ int dz = std::clamp(zone + (in.dpadRight ? 1 : 0) - (in.dpadLeft ? 1 : 0), 0, kMaxDeadzone);+ if (dz != zone) zone = dz, dirty_ = true;+ const float now[4] = {in.rawLX, in.rawLY, in.rawRX, in.rawRY};+ for (int i = 0; i < 4; ++i)+ if (now[i] != testSticks_[i]) testSticks_[i] = now[i], dirty_ = true;+ } else {+ if (in.up && testerRow_ > 0) --testerRow_, dirty_ = true;+ if (in.down && testerRow_ < triggerTesterRows() - 1) ++testerRow_, dirty_ = true;+ int delta = (in.right ? 1 : 0) - (in.left ? 1 : 0);+ if (delta && testerRow_ == 0)+ settings_.triggerStrength = std::clamp(settings_.triggerStrength + delta, 0, input::kTriggerStrengths - 1);+ if (delta && testerRow_ == 1) settings_.triggerHz = std::clamp(settings_.triggerHz + delta, 0, 2);+ if (delta && testerRow_ == 2)+ settings_.triggerResistance = std::clamp(settings_.triggerResistance + delta, 0, input::kTriggerResistances - 1);+ if (delta && testerRow_ == 3) settings_.triggerPulses = !settings_.triggerPulses;+ if (delta && testerRow_ == 4) settings_.triggerProfile = std::clamp(settings_.triggerProfile + delta, 0, input::kTriggerProfiles - 1);+ if (delta) dirty_ = true;+ if (in.l2Analog != testL2_ || in.r2Analog != testR2_) testL2_ = in.l2Analog, testR2_ = in.r2Analog, dirty_ = true;+ }+ if (in.back) {+ settings_.deadzone[0] = testerBackup_.deadzone[0], settings_.deadzone[1] = testerBackup_.deadzone[1];+ settings_.triggerStrength = testerBackup_.triggerStrength, settings_.triggerHz = testerBackup_.triggerHz;+ settings_.triggerResistance = testerBackup_.triggerResistance, settings_.triggerPulses = testerBackup_.triggerPulses;+ settings_.triggerProfile = testerBackup_.triggerProfile;+ }+ if (in.accept || in.back) {+ if (gameSettingsOpen_) {+ if (in.accept) {+ activeGameProfile_.deadzoneLeft = settings_.deadzone[0];+ activeGameProfile_.deadzoneRight = settings_.deadzone[1];+ activeGameProfile_.triggerStrength = settings_.triggerStrength;+ activeGameProfile_.triggerHz = settings_.triggerHz;+ activeGameProfile_.triggerResistance = settings_.triggerResistance;+ activeGameProfile_.triggerPulses = settings_.triggerPulses;+ activeGameProfile_.triggerProfile = settings_.triggerProfile;+ activeGameHasCustom_ = true;+ }+ settings_ = testerBackup_;+ }+ tester_ = Tester::None;+ testL2_ = testR2_ = 0;+ dirty_ = true;+ }+}++void AppUi::openColourPicker(int previousMode) {+ // Caller holds mutex_. Starts on the colour saved.+ float h, s, v;+ colourHsv(settings_.lightBarColour, h, s, v);+ pickU_ = s * std::cos(h * 6.2832f);+ pickV_ = s * std::sin(h * 6.2832f);+ pickValue_ = std::max(kMinValue, v);+ pickerPrevMode_ = previousMode;+ pickerLastMs_ = 0;+ pickerOpen_ = true;+ dirty_ = true;+}++Color AppUi::pickerColour() const {+ float h = std::atan2(pickV_, pickU_) / 6.2832f;+ return hsvColour(h < 0 ? h + 1 : h, std::min(1.0f, std::hypot(pickU_, pickV_)), pickValue_);+}++void AppUi::handleColourPicker(const NavInput& in) {+ // Caller holds mutex_. The stick moves the cursor smoothly, the D-pad a+ // step at a time; L2 / R2 change the brightness.+ float dt = pickerLastMs_ && in.nowMs > pickerLastMs_ ? std::min(0.1f, (in.nowMs - pickerLastMs_) / 1000.0f) : 0;+ pickerLastMs_ = in.nowMs;+ float u = pickU_, v = pickV_;+ auto axis = [](float a) { return std::abs(a) < 0.2f ? 0.0f : a; };+ u += axis(in.stickX) * 1.1f * dt;+ v += axis(in.stickY) * 1.1f * dt;+ constexpr float kStep = 0.05f;+ if (in.left) u -= kStep;+ if (in.right) u += kStep;+ if (in.up) v -= kStep;+ if (in.down) v += kStep;+ if (float d = std::hypot(u, v); d > 1) u /= d, v /= d;+ if (u != pickU_ || v != pickV_) pickU_ = u, pickV_ = v, dirty_ = true;+ if (in.l2) pickValue_ = std::max(kMinValue, pickValue_ - 0.1f), dirty_ = true;+ if (in.r2) pickValue_ = std::min(1.0f, pickValue_ + 0.1f), dirty_ = true;+ if (in.accept) {+ settings_.lightBarColour = pickerColour();+ settings_.lightBarMode = 1;+ pickerOpen_ = false;+ dirty_ = true;+ } else if (in.back) {+ settings_.lightBarMode = pickerPrevMode_;+ pickerOpen_ = false;+ dirty_ = true;+ }+}++void AppUi::setGyroDefaults(int mode, int level) {+ std::lock_guard<std::mutex> lock(mutex_);+ gyroMode_ = mode;+ gyroLevel_ = level;+ settings_.gyroMode = mode;+ settings_.gyroLevel = level;+ dirty_ = true;+}++void AppUi::setPerGameSettings(const std::map<std::string, app::GameProfile>& perGame) {+ std::lock_guard<std::mutex> lock(mutex_);+ perGameSettings_ = perGame;+ dirty_ = true;+}++void AppUi::openGameSettings() {+ gameSettingsOpen_ = true;+ gameSettingsRow_ = 0;+ activeGameMouseSupported_ = detail_.mouseKeyboard;+ std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);+ auto it = perGameSettings_.find(key);+ if (it != perGameSettings_.end()) {+ activeGameHasCustom_ = true;+ activeGameProfile_ = it->second;+ } else {+ activeGameHasCustom_ = false;+ activeGameProfile_.sharpness = settings_.sharpness;+ activeGameProfile_.deband = settings_.deband;+ activeGameProfile_.upscaler = settings_.upscaler;+ activeGameProfile_.resolution = settings_.resolution;+ activeGameProfile_.deadzoneLeft = settings_.deadzone[0];+ activeGameProfile_.deadzoneRight = settings_.deadzone[1];+ activeGameProfile_.triggerStrength = settings_.triggerStrength;+ activeGameProfile_.triggerHz = settings_.triggerHz;+ activeGameProfile_.triggerResistance = settings_.triggerResistance;+ activeGameProfile_.triggerPulses = settings_.triggerPulses;+ activeGameProfile_.audioHaptics = settings_.audioHaptics;+ activeGameProfile_.circleConfirms = settings_.circleConfirms;+ activeGameProfile_.highRefresh = settings_.highRefresh;+ activeGameProfile_.keyMap = settings_.keyMap;+ activeGameProfile_.padMap = settings_.padMap;+ activeGameProfile_.gyroMode = gyroMode_;+ activeGameProfile_.gyroLevel = gyroLevel_;+ activeGameProfile_.touchpadMouse = settings_.touchpadMouse;+ activeGameProfile_.touchpadShortcuts = settings_.touchpadShortcuts;+ }+}++void AppUi::closeGameSettings() {+ gameSettingsOpen_ = false;+ tester_ = Tester::None;+}++void AppUi::setRegions(std::vector<std::string> regions, const std::string& defaultRegion) {+ std::lock_guard<std::mutex> lock(mutex_);+ regions_ = std::move(regions);+ defaultRegion_ = defaultRegion;+ dirty_ = true;+}++std::vector<std::string> AppUi::settingOptions(int row) const {+ // Caller holds mutex_.+ std::vector<std::string> out;+ auto withMs = [&](std::string label, const std::string& region) {+ auto ms = regionMs_.find(region);+ if (ms != regionMs_.end()) label += " \xE2\x80\xA2 " + std::to_string(ms->second) + " ms";+ return label;+ };+ if (row == 0) {+ for (int i = 0; i < static_cast<int>(Language::Count); ++i) out.push_back(languageName(static_cast<Language>(i)));+ } else if (row == 1) {+ out = {tr(Str::Res720), tr(Str::Res1080), tr(Str::ResBest)}; // kResolutionOrder+ } else if (row == 3) {+ // Left and right stick (the tester changes them).+ out = {std::to_string(settings_.deadzone[0]) + " % \xC2\xB7 " + std::to_string(settings_.deadzone[1]) + " %"};+ } else if (row == 4) {+ out = {tr(Str::Deactivated), tr(Str::TriggerLight), tr(Str::TriggerMedium), tr(Str::TriggerStrong),+ tr(Str::TriggerMax)};+ } else if (row == 5) {+ out = {"", ""}; // Cross, Circle: drawn as the buttons+ } else if (row == 6) {+ out = {tr(Str::LightBarGame), tr(Str::LightBarCustom), tr(Str::Deactivated)};+ } else if (row == 7) {+ // Updates: Cross acts, no list.+ } else if (row == 9) {+ out = {tr(Str::Deactivated), tr(Str::HighRefreshOn)};+ } else if (row == 13) {+ out = {tr(Str::DisplayWindow), tr(Str::DisplayFullscreen)};+ } else if (row == 10) {+ out.push_back(tr(Str::BitrateAuto));+ for (int mbps : kBitrateCaps) out.push_back(std::to_string(mbps) + " Mbps");+ } else if (row == 11) {+ for (int v : kVolumes) out.push_back(std::to_string(v) + " %");+ } else if (row == 16) {+ out = {tr(Str::Deactivated), tr(Str::Activated)};+ } else if (row == 12) {+ // The keys' own screen changes them.+ out = {tr(settings_.keyMap == input::defaultKeyMap() ? Str::ProfileDefault : Str::ProfileCustom)};+ } else if (row == 14) {+ // So do the controller buttons'.+ out = {tr(settings_.padMap == input::defaultPadMap() ? Str::ProfileDefault : Str::ProfileCustom)};+ } else if (row == 22) {+ out = {tr(Str::Deactivated), tr(Str::Activated)};+ } else if (row == 15) {+ out = {tr(Str::Off), tr(Str::GyroAlways), tr(Str::GyroAiming)};+ } else if (row == 17) {+ out = {tr(Str::RunCheck)};+ } else if (row == 18) {+ out = {tr(Str::RunTest)};+ } else if (row == 19) {+ out = {tr(Str::SupportKoFi)};+ } else if (row == 20) {+ out = {tr(Str::VideoDecoderHw), tr(Str::VideoDecoderSw)};+ } else if (row == 21) {+ out = {tr(Str::Off), tr(Str::SharpLow), tr(Str::SharpMedium), tr(Str::SharpHigh)};+ } else if (row == 23) {+ out = {tr(Str::ResetSettings)};+ } else if (row == 8) {+ out.push_back(loginCountryOffText());+ for (const char* country : kLoginCountries) out.push_back(loginCountryName(country));+ } else {+ // Automatic first, then the regions in the login's order.+ out.push_back(withMs(trf(Str::RegionAuto, defaultRegion_.empty() ? "-" : prettyRegion(defaultRegion_)),+ defaultRegion_));+ for (const auto& r : regions_) out.push_back(withMs(prettyRegion(r), r));+ }+ return out;+}++int AppUi::settingSelected(int row) const {+ // Caller holds mutex_.+ if (row == 0) return settings_.language;+ if (row == 1) {+ for (int i = 0; i < 3; ++i)+ if (kResolutionOrder[i] == settings_.resolution) return i;+ }+ if (row == 3 || row == 12 || row == 14 || row == 17 || row == 18 || row == 19 || row == 23) return 0;+ if (row == 4) return settings_.triggerStrength;+ if (row == 5) return settings_.circleConfirms ? 1 : 0;+ if (row == 6) return settings_.lightBarMode;+ if (row == 7) return 0;+ if (row == 9) return settings_.highRefresh ? 1 : 0;+ if (row == 13) return settings_.fullscreen ? 1 : 0;+ if (row == 15) return std::clamp(settings_.gyroMode, 0, 2);+ if (row == 16) return settings_.queueReadyAlert ? 1 : 0;+ if (row == 20) return std::clamp(settings_.videoDecoder, 0, 1);+ if (row == 21) return std::clamp(settings_.audioHaptics, 0, 3);+ if (row == 22) return settings_.previewFeatures ? 1 : 0;+ if (row == 10) {+ if (settings_.maxBitrateMbps <= 0) return 0;+ int closest = 1;+ int minDiff = 1000;+ for (size_t i = 0; i < std::size(kBitrateCaps); ++i) {+ int diff = std::abs(kBitrateCaps[i] - settings_.maxBitrateMbps);+ if (diff < minDiff) {+ minDiff = diff;+ closest = static_cast<int>(i) + 1;+ }+ }+ return closest;+ }+ if (row == 11) {+ for (size_t i = 0; i < std::size(kVolumes); ++i)+ if (kVolumes[i] == settings_.gameVolume) return static_cast<int>(i);+ return 3; // 100 %+ }+ if (row == 8) {+ for (size_t i = 0; i < std::size(kLoginCountries); ++i)+ if (settings_.loginCountry == kLoginCountries[i]) return static_cast<int>(i) + 1;+ return 0;+ }+ for (size_t i = 0; i < regions_.size(); ++i)+ if (regions_[i] == settings_.region) return static_cast<int>(i) + 1;+ return 0;+}++void AppUi::applySetting(int row, int index) {+ // Caller holds mutex_.+ if (row == 0) {+ settings_.language = index;+ setLanguage(static_cast<Language>(index)); // the UI switches right away+ } else if (row == 1) {+ settings_.resolution = kResolutionOrder[index];+ } else if (row == 3 || row == 12 || row == 14 || row == 17 || row == 18 || row == 23) {+ (void)index; // the tester sets each stick's, the keys' and buttons' screens theirs+ } else if (row == 4) {+ settings_.triggerStrength = index;+ } else if (row == 5) {+ settings_.circleConfirms = index == 1;+ circleConfirms_ = settings_.circleConfirms; // in force at once: the next press already uses it+ } else if (row == 6) {+ settings_.lightBarMode = index;+ } else if (row == 7) {+ } else if (row == 9) {+ settings_.highRefresh = index == 1;+ } else if (row == 13) {+ // In force at once (handle() sends the settings): the window follows.+ if (settings_.fullscreen != (index == 1)) displayModeChanged_ = true;+ settings_.fullscreen = index == 1;+ } else if (row == 15) {+ settings_.gyroMode = index;+ gyroMode_ = index;+ } else if (row == 10) {+ settings_.maxBitrateMbps = index == 0 ? 0 : kBitrateCaps[index - 1];+ } else if (row == 11) {+ settings_.gameVolume = kVolumes[index];+ } else if (row == 16) {+ settings_.queueReadyAlert = (index == 1);+ } else if (row == 20) {+ settings_.videoDecoder = index;+ } else if (row == 21) {+ settings_.audioHaptics = std::clamp(index, 0, 3);+ } else if (row == 22) {+ settings_.previewFeatures = (index == 1);+ } else if (row == 8) {+ settings_.loginCountry = index == 0 ? std::string() : kLoginCountries[index - 1];+ } else {+ settings_.region = index == 0 ? std::string() : regions_[static_cast<size_t>(index - 1)];+ }+ dirty_ = true;+}++void AppUi::changeSetting(int delta) {+ // Caller holds mutex_. Left / right: the previous / next choice.+ int n = static_cast<int>(settingOptions(settingsRow_).size());+ if (n <= 0) return;+ if (settingsRow_ == 10) {+ // Bitrate slider: clamp between 0 (Automatic) and n - 1 (50 Mbps)+ int cur = settingSelected(10);+ int next = std::clamp(cur + delta, 0, n - 1);+ if (next != cur) applySetting(10, next);+ return;+ }+ applySetting(settingsRow_, (settingSelected(settingsRow_) + delta + n) % n);+}++void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {+ if (tester_ != Tester::None) {+ handleTester(in);+ if (tester_ == Tester::None) {+ std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);+ if (activeGameHasCustom_) perGameSettings_[key] = activeGameProfile_;+ else perGameSettings_.erase(key);+ ev.action = Action::GameSettingsChanged;+ ev.game = detail_;+ ev.hasGameProfile = activeGameHasCustom_;+ ev.gameProfile = activeGameProfile_;+ }+ return;+ }+ // The rows on screen (gameSettingsRow_ is a position among them).+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);+ const int rowCount = static_cast<int>(rows.size());+ if (in.up) {+ gameSettingsRow_ = (gameSettingsRow_ + rowCount - 1) % rowCount;+ dirty_ = true;+ }+ if (in.down) {+ gameSettingsRow_ = (gameSettingsRow_ + 1) % rowCount;+ dirty_ = true;+ }+ const int rowId = rows[static_cast<size_t>(std::clamp(gameSettingsRow_, 0, rowCount - 1))].row;+ if (in.left || in.right) {+ int dir = in.right ? 1 : -1;+ switch (rowId) {+ case 0:+ activeGameHasCustom_ = !activeGameHasCustom_;+ dirty_ = true;+ break;+ case 1: { // Upscaler (0 FSR, 2 FSR+clean, 1 AI, 3 AI+clean)+ static constexpr int kOrder[4] = {0, 2, 1, 3};+ int pos = 0;+ for (int i = 0; i < 4; ++i) if (kOrder[i] == activeGameProfile_.upscaler) pos = i;+ activeGameProfile_.upscaler = kOrder[(pos + 4 + dir) % 4];+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ }+ case 2: // Sharpness (0..3)+ activeGameProfile_.sharpness = std::clamp(activeGameProfile_.sharpness + dir, 0, 3);+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 3: // Deband (0..3)+ activeGameProfile_.deband = std::clamp(activeGameProfile_.deband + dir, 0, 3);+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 4: { // Resolution (1 = 720p, 0 = 1080p, 2 = Best (Auto))+ static constexpr int kOrder[3] = {1, 0, 2};+ int pos = 0;+ for (int i = 0; i < 3; ++i) if (kOrder[i] == activeGameProfile_.resolution) pos = i;+ activeGameProfile_.resolution = kOrder[(pos + 3 + dir) % 3];+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ }+ case 5: // Deadzone (0..30)+ activeGameProfile_.deadzoneLeft = std::clamp(activeGameProfile_.deadzoneLeft + dir * 5, 0, 30);+ activeGameProfile_.deadzoneRight = activeGameProfile_.deadzoneLeft;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 6: // Triggers (0..4)+ activeGameProfile_.triggerStrength = std::clamp(activeGameProfile_.triggerStrength + dir, 0, 4);+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 16: // Audio-to-Haptics (0..3)+ activeGameProfile_.audioHaptics = std::clamp(activeGameProfile_.audioHaptics + dir, 0, 3);+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 7: // Confirm button+ activeGameProfile_.circleConfirms = !activeGameProfile_.circleConfirms;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 8: // 120 Hz output (VRR)+ activeGameProfile_.highRefresh = !activeGameProfile_.highRefresh;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 12: // Gyro aiming (0 off, 1 always, 2 while aiming)+ activeGameProfile_.gyroMode = (activeGameProfile_.gyroMode + 3 + dir) % 3;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 13: // Touchpad as mouse (in games with mouse support)+ activeGameProfile_.touchpadMouse = !activeGameProfile_.touchpadMouse;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 14: { // Game Language+ static const std::pair<const char*, const char*> kLocales[] = {+ {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},+ {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},+ {"it-IT", "Italiano"}, {"ja-JP", "日本語"}+ };+ int pos = 0;+ for (int k = 0; k < 8; ++k) if (kLocales[k].first == activeGameProfile_.locale) pos = k;+ activeGameProfile_.locale = kLocales[(pos + 8 + dir) % 8].first;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ }+ case 15: // Video decoder (0 Hardware, 1 Software)+ activeGameProfile_.videoDecoder = (activeGameProfile_.videoDecoder == 0 ? 1 : 0);+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ default: break;+ }+ }+ if (in.accept) {+ switch (rowId) {+ case 0:+ activeGameHasCustom_ = !activeGameHasCustom_;+ dirty_ = true;+ break;+ case 1: {+ static constexpr int kOrder[4] = {0, 2, 1, 3};+ int pos = 0;+ for (int i = 0; i < 4; ++i) if (kOrder[i] == activeGameProfile_.upscaler) pos = i;+ activeGameProfile_.upscaler = kOrder[(pos + 1) % 4];+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ }+ case 2:+ activeGameProfile_.sharpness = (activeGameProfile_.sharpness + 1) % 4;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 3:+ activeGameProfile_.deband = (activeGameProfile_.deband + 1) % 4;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 4: {+ static constexpr int kOrder[3] = {1, 0, 2};+ int pos = 0;+ for (int i = 0; i < 3; ++i) if (kOrder[i] == activeGameProfile_.resolution) pos = i;+ activeGameProfile_.resolution = kOrder[(pos + 1) % 3];+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ }+ case 5: { // Open stick tester+ tester_ = Tester::Sticks;+ testerBackup_ = settings_;+ settings_.deadzone[0] = activeGameProfile_.deadzoneLeft;+ settings_.deadzone[1] = activeGameProfile_.deadzoneRight;+ testerStick_ = 0;+ dirty_ = true;+ break;+ }+ case 6: { // Open trigger tester+ tester_ = Tester::Triggers;+ testerBackup_ = settings_;+ settings_.triggerStrength = activeGameProfile_.triggerStrength;+ settings_.triggerHz = activeGameProfile_.triggerHz;+ settings_.triggerResistance = activeGameProfile_.triggerResistance;+ settings_.triggerPulses = activeGameProfile_.triggerPulses;+ settings_.triggerProfile = activeGameProfile_.triggerProfile;+ testerRow_ = 0;+ dirty_ = true;+ break;+ }+ case 16:+ activeGameProfile_.audioHaptics = (activeGameProfile_.audioHaptics + 1) % 4;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 7:+ activeGameProfile_.circleConfirms = !activeGameProfile_.circleConfirms;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 8:+ activeGameProfile_.highRefresh = !activeGameProfile_.highRefresh;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 12:+ activeGameProfile_.gyroMode = (activeGameProfile_.gyroMode + 1) % 3;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 13:+ activeGameProfile_.touchpadMouse = !activeGameProfile_.touchpadMouse;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 14: {+ static const std::pair<const char*, const char*> kLocales[] = {+ {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},+ {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},+ {"it-IT", "Italiano"}, {"ja-JP", "日本語"}+ };+ int pos = 0;+ for (int k = 0; k < 8; ++k) if (kLocales[k].first == activeGameProfile_.locale) pos = k;+ activeGameProfile_.locale = kLocales[(pos + 1) % 8].first;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ }+ case 15:+ activeGameProfile_.videoDecoder = (activeGameProfile_.videoDecoder == 0 ? 1 : 0);+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;+ case 9: // Keyboard keys: their own screen, on this game's+ openTester(Tester::Keys);+ settings_.keyMap = activeGameProfile_.keyMap;+ break;+ case 11: // Controller buttons: their own screen, on this game's+ openPadTester();+ break;+ case 17: // Touchpad shortcuts: their own screen, on this game's+ openTouchpadTester();+ break;+ case 10: // Reset to default+ activeGameHasCustom_ = false;+ activeGameProfile_.locale.clear();+ activeGameProfile_.keyMap = settings_.keyMap;+ activeGameProfile_.padMap = settings_.padMap;+ activeGameProfile_.touchpadShortcuts = settings_.touchpadShortcuts;+ activeGameProfile_.sharpness = settings_.sharpness;+ activeGameProfile_.deband = settings_.deband;+ activeGameProfile_.upscaler = settings_.upscaler;+ activeGameProfile_.resolution = settings_.resolution;+ activeGameProfile_.deadzoneLeft = settings_.deadzone[0];+ activeGameProfile_.deadzoneRight = settings_.deadzone[1];+ activeGameProfile_.triggerStrength = settings_.triggerStrength;+ activeGameProfile_.triggerHz = settings_.triggerHz;+ activeGameProfile_.triggerResistance = settings_.triggerResistance;+ activeGameProfile_.triggerPulses = settings_.triggerPulses;+ activeGameProfile_.triggerProfile = settings_.triggerProfile;+ activeGameProfile_.audioHaptics = settings_.audioHaptics;+ activeGameProfile_.circleConfirms = settings_.circleConfirms;+ activeGameProfile_.highRefresh = settings_.highRefresh;+ activeGameProfile_.gyroMode = gyroMode_;+ activeGameProfile_.gyroLevel = gyroLevel_;+ activeGameProfile_.touchpadMouse = settings_.touchpadMouse;+ gameSettingsRow_ = 0;+ dirty_ = true;+ break;+ default: break;+ }+ }+ if ((in.left || in.right || in.accept) && tester_ == Tester::None) {+ std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);+ if (activeGameHasCustom_) {+ perGameSettings_[key] = activeGameProfile_;+ } else {+ perGameSettings_.erase(key);+ }+ ev.action = Action::GameSettingsChanged;+ ev.game = detail_;+ ev.hasGameProfile = activeGameHasCustom_;+ ev.gameProfile = activeGameProfile_;+ }+ if (in.back || in.options) {+ gameSettingsOpen_ = false;+ std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);+ if (activeGameHasCustom_) {+ perGameSettings_[key] = activeGameProfile_;+ } else {+ perGameSettings_.erase(key);+ }+ ev.action = Action::GameSettingsChanged;+ ev.game = detail_;+ ev.hasGameProfile = activeGameHasCustom_;+ ev.gameProfile = activeGameProfile_;+ dirty_ = true;+ }+}++void AppUi::drawSettings(Canvas& c) {+ drawBackground(c);+ drawTopBar(c);+ fonts_.bold.draw(c, tr(Str::Settings), kMargin, 116, 46, kWhite);+ const char* labels[kSettingRows] = {tr(Str::Language), tr(Str::Resolution), tr(Str::Region),+ tr(Str::Deadzone), tr(Str::TriggerRumble), tr(Str::ConfirmButton),+ tr(Str::LightBar), tr(Str::Updates), tr(Str::LoginCountry),+ tr(Str::HighRefresh), tr(Str::BitrateCap), tr(Str::GameVolume),+ tr(Str::KeyboardKeys), tr(Str::DisplayMode), tr(Str::ControllerButtons),+ tr(Str::Gyro), tr(Str::QueueReadyNotification),+ tr(Str::CheckSignIn), tr(Str::NetworkTest), tr(Str::SupportProject),+ tr(Str::VideoDecoder), tr(Str::AudioHaptics), tr(Str::PreviewFeatures),+ tr(Str::ResetSettings)};+ constexpr int kRowW = 1140, kRowH = 30, kGap = 2, kGroupGap = 4, kRowPx = 22;+ Rect rows[kSettingRows]; // by row id+ int y = 184;+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) { // what caps_ rules out is hidden+ if (groupStart) y += kGroupGap;+ Rect r{kMargin, y, kRowW, kRowH};+ rows[i] = r;+ bool focused = i == settingsRow_;+ int ty = fonts_.semibold.centeredY(r.y, r.h, kRowPx);++ if (i == 23) {+ // Restore factory defaults button: red background+ Color redBg = focused ? rgba(220, 38, 38, 255) : rgba(185, 28, 28, 220);+ c.fillRect(r, redBg, 12);+ if (focused && !dropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 3, 16);++ // Progress fill animation when holding Cross/accept+ if (focused && resetSettingsHoldStart_ > 0) {+ uint64_t elapsed = (lastRender_ > resetSettingsHoldStart_) ? (lastRender_ - resetSettingsHoldStart_) : 0;+ float progress = std::min(1.0f, static_cast<float>(elapsed) / 5000.0f);+ int fillW = static_cast<int>(r.w * progress);+ if (fillW > 0) {+ c.fillRect({r.x, r.y, fillW, r.h}, rgba(255, 255, 255, 70), 12);+ }+ }+ int textW = fonts_.bold.measure(labels[i], kRowPx);+ int textX = r.x + (r.w - textW) / 2;+ fonts_.bold.draw(c, labels[i], textX, ty, kRowPx, kWhite);+ } else {+ c.fillRect(r, focused ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 12);+ if (focused && !dropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 3, 16);+ fonts_.semibold.draw(c, labels[i], r.x + 32, ty, kRowPx, kWhite);+ float cx = static_cast<float>(r.x + r.w - 40), cy = static_cast<float>(r.y + r.h / 2);+ if (i != 7 && i != 17 && i != 18 && i != 19) {+ c.line(cx - 8, cy - 3, cx, cy + 4, 2.5f, focused ? kWhite : kGray);+ c.line(cx, cy + 4, cx + 8, cy - 3, 2.5f, focused ? kWhite : kGray);+ }+ int vx = r.x + r.w - 68;++ if (i == 7) {+ // Updates: the state; Cross updates when there is a newer version.+ std::string value = updateChecking_ ? tr(Str::UpdateChecking)+ : !updateAvailable_.empty()+ ? trf(caps_.selfUpdate ? Str::UpdateReady : Str::UpdateReadyPc, updateAvailable_)+ : trf(Str::UpToDate, "v" + updateCurrent_);+ Color color = !updateAvailable_.empty() && !updateChecking_ ? rgba(120, 220, 120) : focused ? kWhite : kGray;+ int w = fonts_.regular.measure(value, kRowPx);+ fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx, color);+ } else if (i == 17 || i == 18 || i == 19) {+ // Action items (Check sign-in, Network test, Support)+ std::string label = (i == 17) ? tr(Str::RunCheck) : (i == 18) ? tr(Str::RunTest) : tr(Str::SupportKoFi);+ int w = fonts_.regular.measure(label, kRowPx);+ fonts_.regular.draw(c, label, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx,+ focused ? kWhite : kGray);+ } else if (i == 5) {+ // The confirm button, as the button itself.+ drawFaceButton(c, fonts_.bold, settings_.circleConfirms ? kIconCircle : kIconCross, vx - 16.0f, cy, 16);+ } else {+ auto options = settingOptions(i);+ int sel = settingSelected(i);+ std::string value = sel < static_cast<int>(options.size()) ? options[static_cast<size_t>(sel)] : "";+ int w = fonts_.regular.measure(value, kRowPx);+ fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx, focused ? kWhite : kGray);+ if (i == 6 && settings_.lightBarMode == 1) { // the colour chosen+ c.fillCircle(vx - w - 26.0f, cy, 11, settings_.lightBarColour);+ c.strokeArc(vx - w - 26.0f, cy, 11, 2, 0, 6.2832f, rgba(255, 255, 255, 120));+ }+ }+ }+ y += kRowH + kGap;+ }+ static constexpr Str kSettingDescs[kSettingRows] = {+ Str::SettingDescLanguage,+ Str::SettingDescResolution,+ Str::SettingDescRegion,+ Str::SettingDescDeadzone,+ Str::SettingDescTriggerRumble,+ Str::SettingDescConfirmButton,+ Str::SettingDescLightBar,+ Str::SettingDescUpdates,+ Str::SettingDescLoginCountry,+ Str::SettingDescHighRefresh,+ Str::SettingDescBitrateCap,+ Str::SettingDescGameVolume,+ Str::SettingDescKeyboardKeys,+ Str::SettingDescDisplayMode,+ Str::SettingDescControllerButtons,+ Str::SettingDescGyro,+ Str::SettingDescQueueReady,+ Str::SettingDescCheckSignIn,+ Str::SettingDescNetworkTest,+ Str::SettingDescSupportProject,+ Str::SettingDescVideoDecoder,+ Str::SettingDescAudioHaptics,+ Str::SettingDescPreviewFeatures,+ Str::SettingDescResetSettings,+ };+ if (settingsRow_ >= 0 && settingsRow_ < kSettingRows) {+ int dy = std::max(y + 6, 922);+ const char* desc = tr(kSettingDescs[settingsRow_]);+ for (const auto& line : fonts_.regular.wrap(desc, 22, kRowW, 3)) {+ fonts_.regular.draw(c, line, kMargin, dy, 22, kDim);+ dy += 26;+ }+ }++ // Web UI / Remote QR panel on the right side (x = 1310..1850)+ if (tester_ == Tester::None && !pickerOpen_) {+ std::string qrUrl = !webUrl_.empty() ? webUrl_ : "http://" + platform::localIPv4() + ":8080";+ Rect panel{1310, 184, 540, 724};+ c.fillRect(panel, rgba(255, 255, 255, 14), 16);+ c.strokeRect(panel, rgba(255, 255, 255, 30), 1, 16);++ int py = panel.y + 30;+ int titleW = fonts_.bold.measure(tr(Str::WebControlTitle), 28);+ fonts_.bold.draw(c, tr(Str::WebControlTitle), panel.x + (panel.w - titleW) / 2, py, 28, kWhite);+ py += 40;++ auto descLines = fonts_.regular.wrap(tr(Str::WebControlDesc), 17, panel.w - 56, 5);+ for (const auto& l : descLines) {+ int lw = fonts_.regular.measure(l, 17);+ fonts_.regular.draw(c, l, panel.x + (panel.w - lw) / 2, py, 17, kGray);+ py += 22;+ }++ uint8_t qrBuf[qrcodegen_BUFFER_LEN_MAX], tmpBuf[qrcodegen_BUFFER_LEN_MAX];+ int qrTarget = 260;+ int qrCardW = 300;+ if (qrcodegen_encodeText(qrUrl.c_str(), tmpBuf, qrBuf, qrcodegen_Ecc_LOW, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {+ int n = qrcodegen_getSize(qrBuf);+ int mod = qrTarget / (n + 2);+ qrCardW = mod * (n + 2) + 40;+ }+ int qrRight = panel.x + (panel.w + qrCardW) / 2;++ Rect pill{panel.x + 36, panel.y + panel.h - 42 - 18, panel.w - 72, 42};++ // Center QR vertically in available space between py and pill.y+ int availH = pill.y - py;+ int qrTop = py + (availH - qrCardW) / 2;+ drawQr(c, qrUrl, qrRight, qrTop, qrTarget, qrcodegen_Ecc_LOW);++ c.fillRect(pill, rgba(0, 0, 0, 70), 12);+ c.strokeRect(pill, rgba(255, 255, 255, 30), 1, 12);++ int urlW = fonts_.semibold.measure(qrUrl, 20);+ fonts_.semibold.draw(c, qrUrl, pill.x + (pill.w - urlW) / 2, fonts_.semibold.centeredY(pill.y, pill.h, 20), 20, rgba(140, 230, 160));+ }++ if (pickerOpen_) {+ drawColourPicker(c);+ return;+ }+ if (tester_ == Tester::Sticks) return drawStickTester(c);+ if (tester_ == Tester::Triggers) return drawTriggerTester(c);+ if (tester_ == Tester::Keys) return drawKeysTester(c);+ if (tester_ == Tester::Pad) return drawPadTester(c);+ if (tester_ == Tester::Touchpad) return drawTouchpadTester(c);+ if (tester_ == Tester::SignInCheck) return drawSignInCheck(c, lastRender_);+ if (tester_ == Tester::NetworkTest) return drawNetworkTest(c, lastRender_);+ if (tester_ == Tester::Donation) return drawDonationModal(c);+ if (dropdownOpen_) {+ // The list under (or, near the bottom, over) the row, right-aligned+ // with it; scrolls past kVisible choices.+ auto options = settingOptions(settingsRow_);+ int sel = settingSelected(settingsRow_);+ constexpr int kItemH = 62, kVisible = 8, kListW = 640;+ int n = static_cast<int>(options.size());+ int visible = std::min(n, kVisible);+ if (dropdownIndex_ < dropdownTop_) dropdownTop_ = dropdownIndex_;+ if (dropdownIndex_ >= dropdownTop_ + visible) dropdownTop_ = dropdownIndex_ - visible + 1;+ const Rect& row = rows[settingsRow_];+ Rect panel{row.x + row.w - kListW, row.y + row.h + 8, kListW, visible * kItemH + 16};+ if (panel.y + panel.h > kH - 100) panel.y = std::max(120, kH - 100 - panel.h);+ c.fillRect({panel.x + 6, panel.y + 10, panel.w, panel.h}, rgba(0, 0, 0, 120), 18); // shadow+ c.fillRect(panel, rgba(38, 38, 38), 18);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 18);+ for (int k = 0; k < visible; ++k) {+ int i = dropdownTop_ + k;+ Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};+ bool on = i == dropdownIndex_;+ if (on) c.fillRect(item, kWhite, 12);+ Color text = on ? kBg : (i == sel ? kWhite : kGray);+ if (settingsRow_ == 5)+ drawFaceButton(c, fonts_.bold, i == 1 ? kIconCircle : kIconCross, item.x + 44.0f, item.y + item.h / 2.0f, 20);+ else+ fonts_.semibold.draw(c, options[static_cast<size_t>(i)], item.x + 24,+ fonts_.semibold.centeredY(item.y, item.h, 26), 26, text);+ if (settingsRow_ == 6 && i == 1)+ c.fillCircle(item.x + item.w - 84.0f, item.y + item.h / 2.0f, 12, settings_.lightBarColour);+ if (i == sel) { // a check mark on the current choice+ float cx = static_cast<float>(item.x + item.w - 36), cy = static_cast<float>(item.y + item.h / 2);+ c.line(cx - 10, cy, cx - 3, cy + 7, 3, on ? kBg : kGreen);+ c.line(cx - 3, cy + 7, cx + 10, cy - 7, 3, on ? kBg : kGreen);+ }+ }+ // Scroll hints: more choices above / below.+ if (dropdownTop_ > 0) {+ float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y - 14);+ c.line(cx - 10, cy + 4, cx, cy - 4, 3, kGray);+ c.line(cx, cy - 4, cx + 10, cy + 4, 3, kGray);+ }+ if (dropdownTop_ + visible < n) {+ float cx = static_cast<float>(panel.x + panel.w / 2), cy = static_cast<float>(panel.y + panel.h + 14);+ c.line(cx - 10, cy - 4, cx, cy + 4, 3, kGray);+ c.line(cx, cy + 4, cx + 10, cy - 4, 3, kGray);+ }+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});+ } else {+ if (settingsRow_ == 23) {+ drawHints(c, {{kIconCross, tr(Str::HoldToReset)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});+ } else if (settingsRow_ == 16) {+ drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconSquare, tr(Str::TestSound)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});+ } else if (settingsRow_ == 10) {+ drawHints(c, {{kIconDpadLR, tr(Str::Adjust)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});+ } else {+ drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});+ }+ }+}++Rect AppUi::drawModal(Canvas& c, int w, int h, const std::string& title) {+ c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));+ Rect panel{(kW - w) / 2, (kH - h) / 2 - 30, w, h};+ c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow+ c.fillRect(panel, kPanel, 24);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);+ fonts_.bold.draw(c, title, panel.x + 56, panel.y + 44, 40, kWhite);+ c.fillRect({0, kH - 80, kW, 80}, kBg); // Settings' hints, under the panel's+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});+ return panel;+}++void AppUi::drawStickTester(Canvas& c) {+ Rect panel = drawModal(c, 1240, 740, tr(Str::Deadzone));+ constexpr int R = 180;+ const Color raw = rgba(170, 170, 170), game = rgba(90, 220, 110);+ for (int s = 0; s < 2; ++s) {+ const float dz = settings_.deadzone[s] / 100.0f;+ const bool chosen = s == testerStick_;+ const float cx = panel.x + (s ? 930.0f : 310.0f), cy = panel.y + 170.0f + R;+ // Its dead zone above it, in white on the stick being adjusted.+ std::string value = std::to_string(settings_.deadzone[s]) + " %";+ fonts_.bold.draw(c, value, static_cast<int>(cx) - fonts_.bold.measure(value, 34) / 2, static_cast<int>(cy) - R - 56, 34,+ chosen ? kWhite : kDim);+ c.fillCircle(cx, cy, R, rgba(255, 255, 255, chosen ? 22 : 10));+ c.line(cx - R, cy, cx + R, cy, 1, rgba(255, 255, 255, 30));+ c.line(cx, cy - R, cx, cy + R, 1, rgba(255, 255, 255, 30));+ c.strokeArc(cx, cy, R, chosen ? 4.0f : 2.0f, 0, 6.2832f, chosen ? kWhite : rgba(255, 255, 255, 70));+ // The dead zone: nothing reaches the game in there.+ if (dz > 0) {+ c.fillCircle(cx, cy, dz * R, rgba(230, 70, 70, 60));+ c.strokeArc(cx, cy, dz * R, 2, 0, 6.2832f, rgba(230, 90, 90, 180));+ }+ float x = testSticks_[2 * s], y = testSticks_[2 * s + 1], gx = x, gy = y;+ input::radialDeadzone(gx, gy, dz);+ c.fillCircle(cx + x * R, cy + y * R, 9, raw);+ c.fillCircle(cx + gx * R, cy + gy * R, 12, game);+ const char* name = tr(s ? Str::StickRight : Str::StickLeft);+ fonts_.semibold.draw(c, name, static_cast<int>(cx) - fonts_.semibold.measure(name, 26) / 2, static_cast<int>(cy) + R + 22,+ 26, kWhite);+ // How far each one is, in percent of the travel.+ auto pct = [](float a, float b) { return std::to_string(static_cast<int>(std::lround(std::min(1.0f, std::hypot(a, b)) * 100))) + " %"; };+ std::string line = pct(x, y) + " \xE2\x86\x92 " + pct(gx, gy);+ int tw = fonts_.regular.measure(line, 24);+ fonts_.regular.draw(c, line, static_cast<int>(cx) - tw / 2, static_cast<int>(cy) + R + 58, 24, kGray);+ }+ // The legend, then the help.+ int ly = panel.y + panel.h - 92, lx = panel.x + 56;+ c.fillCircle(lx + 9.0f, ly + 13.0f, 9, raw);+ fonts_.regular.draw(c, tr(Str::StickPosition), lx + 28, ly, 24, kGray);+ lx += 28 + fonts_.regular.measure(tr(Str::StickPosition), 24) + 48;+ c.fillCircle(lx + 12.0f, ly + 13.0f, 12, game);+ fonts_.regular.draw(c, tr(Str::StickGameGets), lx + 32, ly, 24, kGray);+ fonts_.regular.draw(c, tr(Str::StickTestHelp), panel.x + 56, ly + 44, 22, kDim);+}++void AppUi::drawTriggerTester(Canvas& c) {+ // Without adaptive triggers, no resistance, style or profile rows: the panel shorter by them.+ const int rows = triggerTesterRows(), lessY = (5 - rows) * 84;+ Rect panel = drawModal(c, 1100, 890 - lessY, tr(Str::TriggerRumble));+ // The choices, as Settings' rows: up / down picks one, left / right changes it.+ const char* strengths[] = {tr(Str::Deactivated), tr(Str::TriggerLight), tr(Str::TriggerMedium), tr(Str::TriggerStrong),+ tr(Str::TriggerMax)};+ const char* freqs[] = {tr(Str::FrequencyLow), tr(Str::TriggerMedium), tr(Str::FrequencyHigh)};+ static constexpr Str kProfileStrs[] = {Str::TriggerProfileStd, Str::TriggerProfileShooter, Str::TriggerProfileRacing};+ const char* labels[] = {tr(Str::TriggerIntensity), tr(Str::TriggerFrequency), tr(Str::TriggerResistance),+ tr(Str::TriggerStyle), tr(Str::TriggerProfile)};+ // Pulses go at their own, slower rates.+ int hz = settings_.triggerPulses ? input::kTriggerPulseHz[settings_.triggerHz] : input::kTriggerHz[settings_.triggerHz];+ int prof = std::clamp(settings_.triggerProfile, 0, 2);+ const std::string values[] = {strengths[settings_.triggerStrength],+ std::string(freqs[settings_.triggerHz]) + " (" + std::to_string(hz) + " Hz)",+ strengths[settings_.triggerResistance], // off, light, medium, strong+ tr(settings_.triggerPulses ? Str::StylePulses : Str::StyleVibration),+ tr(kProfileStrs[prof])};+ for (int i = 0; i < rows; ++i) {+ Rect r{panel.x + 56, panel.y + 120 + i * 84, panel.w - 112, 70};+ bool on = i == testerRow_;+ c.fillRect(r, on ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 16);+ if (on) c.strokeRect({r.x - 5, r.y - 5, r.w + 10, r.h + 10}, kWhite, 3, 20);+ fonts_.semibold.draw(c, labels[i], r.x + 36, fonts_.semibold.centeredY(r.y, r.h, 30), 30, kWhite);+ std::string v = "\xE2\x80\xB9 " + values[i] + " \xE2\x80\xBA"; // ‹ value ›+ int w = fonts_.regular.measure(v, 30);+ fonts_.regular.draw(c, v, r.x + r.w - 36 - w, fonts_.regular.centeredY(r.y, r.h, 30), 30, on ? kWhite : kGray);+ }+ // L2 and R2: how far each is pressed, and the level it sends to the trigger.+ const float pressed[2] = {testL2_, testR2_};+ for (int t = 0; t < 2; ++t) {+ constexpr int kBarW = 90, kBarH = 150;+ int bx = panel.x + panel.w / 2 + (t ? 80 : -80 - kBarW), by = panel.y + 560 - lessY;+ c.fillRect({bx, by, kBarW, kBarH}, rgba(255, 255, 255, 20), 16);+ int fill = static_cast<int>(kBarH * std::clamp(pressed[t], 0.0f, 1.0f));+ int level = input::triggerAmplitude(static_cast<uint8_t>(std::lround(pressed[t] * 255)), settings_.triggerStrength);+ if (fill > 0) c.fillRect({bx, by + kBarH - fill, kBarW, fill}, level ? rgba(90, 220, 110) : rgba(120, 120, 120), 16);+ std::string name = buttonName(g_glyphStyle, t ? PadButton::R2 : PadButton::L2);+ fonts_.bold.draw(c, name, bx + (kBarW - fonts_.bold.measure(name, 26)) / 2, by + kBarH + 14, 26, kWhite);+ std::string lv = trf(Str::TriggerLevel, std::to_string(level) + " / 8");+ fonts_.regular.draw(c, lv, bx + (kBarW - fonts_.regular.measure(lv, 22)) / 2, by + kBarH + 48, 22, kGray);+ }+ auto help = fonts_.regular.wrap(tr(Str::TriggerTestHelp), 22, panel.w - 112, 2);+ for (size_t i = 0; i < help.size(); ++i)+ fonts_.regular.draw(c, help[i], panel.x + 56, panel.y + panel.h - 70 + static_cast<int>(i) * 30, 22, kDim);+}++void AppUi::drawPadTester(Canvas& c) {+ Rect panel = drawModal(c, 1500, 860, tr(Str::ControllerButtons));++ // Top tab selector: [ Botões ] [ Touchpad ]+ if (caps_.touchpad) {+ int tabW = 280, tabH = 38, tabGap = 20;+ int totalTabsW = 2 * tabW + tabGap;+ int tabStartX = panel.x + (panel.w - totalTabsW) / 2;+ int tabY = panel.y + 60;++ auto shoulder = [&](const char* name, int cx) {+ Rect r{cx - 22, tabY + 5, 44, 28};+ c.fillRect(r, rgba(255, 255, 255, 40), 8);+ fonts_.bold.draw(c, name, cx - fonts_.bold.measure(name, 16) / 2, fonts_.bold.centeredY(r.y, r.h, 16), 16, kGray);+ };+ shoulder(g_keyboardHints ? "Q" : buttonName(g_glyphStyle, PadButton::L1), tabStartX - 32);++ for (int t = 0; t < 2; ++t) {+ Rect trRect{tabStartX + t * (tabW + tabGap), tabY, tabW, tabH};+ bool active = (padTesterTab_ == t);+ c.fillRect(trRect, active ? rgba(255, 255, 255, 40) : rgba(255, 255, 255, 14), 12);+ if (active) c.strokeRect(trRect, kWhite, 2, 12);+ const char* tabLabel = t == 0 ? tr(Str::ControllerButtons) : tr(Str::TouchpadShortcuts);+ int tw = fonts_.semibold.measure(tabLabel, 22);+ fonts_.semibold.draw(c, tabLabel, trRect.x + (trRect.w - tw) / 2,+ fonts_.semibold.centeredY(trRect.y, trRect.h, 22), 22, active ? kWhite : kGray);+ }++ shoulder(g_keyboardHints ? "E" : buttonName(g_glyphStyle, PadButton::R1), tabStartX + totalTabsW + 32);+ }++ if (padTesterTab_ == 1) {+ constexpr int kTouchRowH = 56, kTouchGap = 8;+ const input::TouchpadAction vals[6] = {+ touchpadWork_.swipeUp, touchpadWork_.swipeDown,+ touchpadWork_.swipeLeft, touchpadWork_.swipeRight,+ touchpadWork_.clickLeft, touchpadWork_.clickRight,+ };+ int y = panel.y + 116;+ for (int i = 0; i < 6; ++i) {+ Rect r{panel.x + 80, y, panel.w - 160, kTouchRowH};+ bool on = (touchpadRow_ == i);+ c.fillRect(r, on ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);+ if (on && !touchpadDropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 2, 18);+ int ty = fonts_.semibold.centeredY(r.y, r.h, 26);+ fonts_.semibold.draw(c, touchpadTriggerLabel(i), r.x + 32, ty, 26, kWhite);++ float cx = static_cast<float>(r.x + r.w - 40), cy = static_cast<float>(r.y + r.h / 2);+ c.line(cx - 8, cy - 3, cx, cy + 4, 2.5f, on ? kWhite : kGray);+ c.line(cx, cy + 4, cx + 8, cy - 3, 2.5f, on ? kWhite : kGray);++ std::string val = touchpadActionLabel(static_cast<int>(vals[i]));+ int vw = fonts_.regular.measure(val, 26);+ int vx = r.x + r.w - 68;+ fonts_.regular.draw(c, val, vx - vw, fonts_.regular.centeredY(r.y, r.h, 26), 26, on ? kWhite : kGray);++ y += kTouchRowH + kTouchGap;+ }++ Rect reset{panel.x + 80, y + 8, panel.w - 160, kTouchRowH};+ bool resetOn = (touchpadRow_ == 6);+ c.fillRect(reset, resetOn ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);+ if (resetOn && !touchpadDropdownOpen_) c.strokeRect({reset.x - 4, reset.y - 4, reset.w + 8, reset.h + 8}, kWhite, 2, 18);+ const char* resetLabel = tr(Str::ResetToDefault);+ fonts_.semibold.draw(c, resetLabel, reset.x + (reset.w - fonts_.semibold.measure(resetLabel, 24)) / 2,+ fonts_.semibold.centeredY(reset.y, reset.h, 24), 24, resetOn ? kWhite : rgba(240, 100, 100));++ int hy = reset.y + kTouchRowH + 22;+ auto help = fonts_.regular.wrap(tr(Str::SettingDescTouchpadShortcuts), 22, panel.w - 160, 2);+ for (size_t i = 0; i < help.size(); ++i)+ fonts_.regular.draw(c, help[i], panel.x + 80, hy + static_cast<int>(i) * 28, 22, kDim);++ if (touchpadDropdownOpen_) {+ constexpr int kListW = 500, kItemH = 46, kMaxVisible = 8;+ constexpr int n = input::kTouchpadActions;+ int visible = std::min(n, kMaxVisible);+ int anchorY = panel.y + 116 + touchpadRow_ * (kTouchRowH + kTouchGap);+ Rect dropPanel{panel.x + panel.w - 80 - kListW, anchorY + kTouchRowH + 6, kListW, visible * kItemH + 16};+ if (dropPanel.y + dropPanel.h > kH - 100) dropPanel.y = std::max(120, anchorY - dropPanel.h - 6);+ c.fillRect({dropPanel.x + 6, dropPanel.y + 10, dropPanel.w, dropPanel.h}, rgba(0, 0, 0, 160), 18);+ c.fillRect(dropPanel, rgba(38, 38, 38), 18);+ c.strokeRect(dropPanel, rgba(255, 255, 255, 60), 2, 18);+ int curAction = static_cast<int>(touchpadWork_.get(touchpadRow_));+ for (int k = 0; k < visible; ++k) {+ int itemIdx = touchpadDropdownTop_ + k;+ if (itemIdx >= n) break;+ Rect item{dropPanel.x + 8, dropPanel.y + 8 + k * kItemH, dropPanel.w - 16, kItemH};+ bool isFocused = (itemIdx == touchpadDropdownIndex_);+ bool isSelected = (itemIdx == curAction);+ if (isFocused) c.fillRect(item, kWhite, 12);+ Color textCol = isFocused ? kBg : (isSelected ? kWhite : kGray);+ std::string itemText = touchpadActionLabel(itemIdx);+ fonts_.semibold.draw(c, itemText, item.x + 24, fonts_.semibold.centeredY(item.y, item.h, 24), 24, textCol);+ if (isSelected) {+ float markX = static_cast<float>(item.x + item.w - 36), markY = static_cast<float>(item.y + item.h / 2);+ c.line(markX - 10, markY, markX - 3, markY + 7, 3, isFocused ? kBg : kGreen);+ c.line(markX - 3, markY + 7, markX + 10, markY - 7, 3, isFocused ? kBg : kGreen);+ }+ }+ if (touchpadDropdownTop_ > 0) {+ float scx = static_cast<float>(dropPanel.x + dropPanel.w / 2), scy = static_cast<float>(dropPanel.y - 14);+ c.line(scx - 10, scy + 4, scx, scy - 4, 3, kGray);+ c.line(scx, scy - 4, scx + 10, scy + 4, 3, kGray);+ }+ if (touchpadDropdownTop_ + visible < n) {+ float scx = static_cast<float>(dropPanel.x + dropPanel.w / 2), scy = static_cast<float>(dropPanel.y + dropPanel.h + 14);+ c.line(scx - 10, scy - 4, scx, scy + 4, 3, kGray);+ c.line(scx, scy + 4, scx + 10, scy - 4, 3, kGray);+ }+ }++ c.fillRect({0, kH - 80, kW, 80}, kBg);+ if (touchpadDropdownOpen_)+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});+ else if (resetOn)+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconSquare, tr(Str::ClearKey)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});+ return;+ }++ // Each Xbox button the game gets (as an Xbox pad shows it), then the+ // button on this pad that plays it (in the pad's own glyphs). Left+ // column the face buttons, shoulders and triggers; right the rest.+ constexpr int kPerColumn = input::kPadFns / 2;+ constexpr int kRowH = 52, kGap = 8, kChipW = 300, kColGap = 40;+ constexpr const char* kArrows[4] = {" \xE2\x86\x91", " \xE2\x86\x93", " \xE2\x86\x90", " \xE2\x86\x92"};+ static constexpr PadButton kButtons[12] = {PadButton::Cross, PadButton::Circle, PadButton::Square, PadButton::Triangle,+ PadButton::L1, PadButton::R1, PadButton::L2, PadButton::R2,+ PadButton::L3, PadButton::R3, PadButton::Touchpad, PadButton::Options};+ const GlyphStyle style = g_glyphStyle;+ const bool mapSwap = gameSettingsOpen_ ? activeGameProfile_.circleConfirms : settings_.circleConfirms;+ const bool capturing = padCaptureSince_ != 0;+ const std::string dpad = tr(Str::DPad);+ // A button (a PadFn index) drawn at (x, cy), left-aligned, in `s`'s glyphs.+ auto drawButton = [&](int i, GlyphStyle s, int x, int cy, Color color) {+ const int ty = fonts_.semibold.centeredY(cy - kRowH / 2, kRowH, 24);+ if (i >= 12) {+ fonts_.semibold.draw(c, dpad + kArrows[i - 12], x, ty, 24, color);+ } else if (i < 4) {+ ui::drawFaceButton(c, fonts_.bold, s, kButtons[i], x + 16.0f, static_cast<float>(cy), 16);+ if (s == GlyphStyle::PlayStation)+ fonts_.semibold.draw(c, buttonName(s, kButtons[i]), x + 44, ty, 24, color);+ } else {+ fonts_.semibold.draw(c, buttonName(s, kButtons[i]), x, ty, 24, color);+ }+ };+ const int colW = (panel.w - 112 - kColGap) / 2;+ for (int f = 0; f < input::kPadFns; ++f) {+ const int col = f / kPerColumn, row = f % kPerColumn;+ Rect r{panel.x + 56 + col * (colW + kColGap), panel.y + 106 + row * (kRowH + kGap), colW, kRowH};+ const bool on = row == padRow_ && col == padCol_;+ const int cy = r.y + r.h / 2;+ c.fillRect(r, on ? rgba(255, 255, 255, 30) : rgba(255, 255, 255, 12), 14);+ if (on && !capturing) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 2, 18);+ drawButton(f, GlyphStyle::Xbox, r.x + 22, cy, kWhite);+ Rect chip{r.x + r.w - 10 - kChipW, r.y + 7, kChipW, r.h - 14};+ fonts_.regular.draw(c, "\xE2\x86\x90", chip.x - 44, fonts_.regular.centeredY(r.y, r.h, 24), 24, kDim);+ const uint8_t src = padWork_[static_cast<size_t>(f)];+ const bool none = src >= input::kPadFns, changed = src != f;+ c.fillRect(chip, none ? rgba(240, 100, 100, 40) : changed ? rgba(90, 170, 255, 60) : rgba(255, 255, 255, 26), 10);+ if (on && capturing) {+ c.strokeRect({chip.x - 4, chip.y - 4, chip.w + 8, chip.h + 8}, rgba(90, 220, 110), 3, 13);+ fonts_.semibold.draw(c, "...", chip.x + 20, fonts_.semibold.centeredY(chip.y, chip.h, 24), 24, kWhite);+ } else if (none) {+ fonts_.semibold.draw(c, "\xE2\x80\x94", chip.x + 20, fonts_.semibold.centeredY(chip.y, chip.h, 24), 24,+ rgba(240, 100, 100));+ } else {+ drawButton(input::physicalSource(src, mapSwap), style, chip.x + 16, cy, kWhite);+ }+ }+ // Reset to default and Discard changes, side by side under the columns.+ const int by = panel.y + 106 + kPerColumn * (kRowH + kGap) + 8;+ for (int col = 0; col < 2; ++col) {+ Rect b{panel.x + 56 + col * (colW + kColGap), by, colW, kRowH};+ const bool on = padRow_ == kPerColumn && padCol_ == col;+ c.fillRect(b, on ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);+ if (on) c.strokeRect({b.x - 4, b.y - 4, b.w + 8, b.h + 8}, kWhite, 2, 18);+ const char* label = tr(col == 0 ? Str::ResetToDefault : Str::DiscardChanges);+ fonts_.semibold.draw(c, label, b.x + (b.w - fonts_.semibold.measure(label, 24)) / 2,+ fonts_.semibold.centeredY(b.y, b.h, 24), 24, on ? kWhite : rgba(240, 100, 100));+ }+ // Waiting for a press: say for what. Else what's missing (Circle won't+ // leave then), or the help.+ int hy = by + kRowH + 34;+ const uint32_t missing = input::padMapMissing(padWork_);+ if (capturing) {+ const auto fn = static_cast<input::PadFn>(padCol_ * kPerColumn + std::min(padRow_, kPerColumn - 1));+ std::string ask = trf(Str::PadPressButton, input::padFnName(fn));+ fonts_.bold.draw(c, ask, panel.x + (panel.w - fonts_.bold.measure(ask, 28)) / 2, hy, 28, kWhite);+ } else if (missing || !input::padMapValid(padWork_)) {+ std::string names;+ for (int f = 0; f < input::kPadFns; ++f)+ if (missing & (1u << f)) names += (names.empty() ? "" : ", ") + std::string(input::padFnName(static_cast<input::PadFn>(f)));+ auto lines = fonts_.semibold.wrap(trf(Str::PadMissing, names), 24, panel.w - 112, 2);+ for (size_t i = 0; i < lines.size(); ++i)+ fonts_.semibold.draw(c, lines[i], panel.x + 56, hy + static_cast<int>(i) * 32, 24, rgba(240, 100, 100));+ } else {+ auto help = fonts_.regular.wrap(tr(Str::PadHelp), 22, panel.w - 112, 2);+ for (size_t i = 0; i < help.size(); ++i)+ fonts_.regular.draw(c, help[i], panel.x + 56, hy + static_cast<int>(i) * 30, 22, kDim);+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg); // its own hints over drawModal's+ if (capturing)+ return;+ if (padRow_ == kPerColumn)+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCross, tr(Str::ChangeKey)}, {kIconSquare, tr(Str::ClearKey)}, {kIconL1R1, tr(Str::Sections)}, {kIconCircle, tr(Str::Back)}});+}++void AppUi::drawTouchpadTester(Canvas& c) {+ padTesterTab_ = 1;+ drawPadTester(c);+}++void AppUi::drawSignInCheck(Canvas& c, uint64_t nowMs) {+ Rect panel = drawModal(c, 1180, 680, tr(Str::CheckSignIn));+ if (signInCheck_.running) {+ drawSpinner(c, static_cast<float>(panel.x + panel.w - 76), static_cast<float>(panel.y + 64), 14.0f, nowMs);+ animating_ = true;+ }+ int y = panel.y + 115;+ constexpr int kRowH = 62, kGap = 8;+ for (size_t i = 0; i < signInCheck_.stages.size() && i < 6; ++i) {+ const auto& st = signInCheck_.stages[i];+ Rect r{panel.x + 56, y, panel.w - 112, kRowH};+ c.fillRect(r, rgba(255, 255, 255, 14), 14);+ float cx = static_cast<float>(r.x + 36), cy = static_cast<float>(r.y + r.h / 2);+ if (st.pending) {+ drawSpinner(c, cx, cy, 12.0f, nowMs);+ animating_ = true;+ } else if (st.ok) {+ c.fillCircle(cx, cy, 14.0f, kGreen);+ c.line(cx - 6, cy, cx - 2, cy + 5, 2.5f, kWhite);+ c.line(cx - 2, cy + 5, cx + 7, cy - 5, 2.5f, kWhite);+ } else {+ c.fillCircle(cx, cy, 14.0f, rgba(220, 65, 65));+ c.line(cx - 5, cy - 5, cx + 5, cy + 5, 2.5f, kWhite);+ c.line(cx - 5, cy + 5, cx + 5, cy - 5, 2.5f, kWhite);+ }+ int ty = fonts_.semibold.centeredY(r.y, r.h, 24);+ fonts_.semibold.draw(c, st.name, r.x + 70, ty, 24, kWhite);+ if (!st.detail.empty()) {+ int maxW = r.w - 380;+ std::string det = fonts_.regular.fit(st.detail, 22, maxW);+ int dw = fonts_.regular.measure(det, 22);+ Color detCol = st.pending ? kDim : (st.ok ? kGray : rgba(255, 130, 130));+ fonts_.regular.draw(c, det, r.x + r.w - 28 - dw, fonts_.regular.centeredY(r.y, r.h, 22), 22, detCol);+ }+ y += kRowH + kGap;+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg);+ if (signInCheck_.running)+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconCircle, tr(Str::Back)}});+}++void AppUi::drawNetworkTest(Canvas& c, uint64_t nowMs) {+ Rect panel = drawModal(c, 1180, 740, tr(Str::NetworkTest));+ if (networkTest_.running) {+ drawSpinner(c, static_cast<float>(panel.x + panel.w - 76), static_cast<float>(panel.y + 64), 14.0f, nowMs);+ animating_ = true;+ }+ Rect natBox{panel.x + 56, panel.y + 114, panel.w - 112, 56};+ c.fillRect(natBox, rgba(255, 255, 255, 18), 14);+ fonts_.semibold.draw(c, "UDP / STUN (NAT)", natBox.x + 28, fonts_.semibold.centeredY(natBox.y, natBox.h, 24), 24, kWhite);+ std::string natVal = networkTest_.natStatus.empty() ? "..." : networkTest_.natStatus;+ int nw = fonts_.regular.measure(natVal, 24);+ Color natCol = natVal.find("OK") != std::string::npos || natVal.find("Reachable") != std::string::npos+ ? rgba(110, 225, 120)+ : (networkTest_.running ? kDim : rgba(255, 180, 90));+ fonts_.regular.draw(c, natVal, natBox.x + natBox.w - 28 - nw, fonts_.regular.centeredY(natBox.y, natBox.h, 24), 24, natCol);++ int y = panel.y + 188;+ constexpr int kRowH = 54, kGap = 8;+ for (size_t i = 0; i < networkTest_.regions.size() && i < 8; ++i) {+ const auto& reg = networkTest_.regions[i];+ Rect r{panel.x + 56, y, panel.w - 112, kRowH};+ c.fillRect(r, i == 0 && reg.rttMs >= 0 ? rgba(16, 124, 16, 45) : rgba(255, 255, 255, 12), 12);+ std::string label = prettyRegion(reg.name);+ if (i == 0 && reg.rttMs >= 0) label += " \xE2\x98\x85";+ fonts_.semibold.draw(c, label, r.x + 28, fonts_.semibold.centeredY(r.y, r.h, 24), 24, kWhite);+ std::string val;+ Color valCol = kDim;+ if (reg.rttMs >= 0) {+ val = "RTT " + std::to_string(reg.rttMs) + " ms \xC2\xB7 Jitter " ++ std::to_string(std::max(0, reg.jitterMs)) + " ms";+ valCol = reg.rttMs < 60 ? rgba(110, 225, 120) : (reg.rttMs < 120 ? rgba(255, 200, 80) : rgba(255, 120, 120));+ } else {+ val = networkTest_.running ? "..." : "--";+ }+ int vw = fonts_.regular.measure(val, 22);+ fonts_.regular.draw(c, val, r.x + r.w - 28 - vw, fonts_.regular.centeredY(r.y, r.h, 22), 22, valCol);+ y += kRowH + kGap;+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg);+ if (networkTest_.running)+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconCircle, tr(Str::Back)}});+}++void AppUi::drawDonationModal(Canvas& c) {+ Rect panel = drawModal(c, 1260, 680, tr(Str::SupportTitle));++ // Calculate dimensions for QR code (larger target = 420px)+ constexpr int kQrTarget = 420;+ int qrTotalH = 460;+ int contentTop = panel.y + 90;+ int contentH = panel.h - 110;+ int centerY = contentTop + contentH / 2;++ int qrTop = centerY - qrTotalH / 2;+ Rect qrBox = drawQr(c, "https://ko-fi.com/RafaelNGP", panel.x + panel.w - 60, qrTop, kQrTarget, qrcodegen_Ecc_MEDIUM);+ if (qrBox.w > 0) {+ std::string scanText = tr(Str::ScanToDonate);+ int tw = fonts_.semibold.measure(scanText, 22);+ fonts_.semibold.draw(c, scanText, qrBox.x + (qrBox.w - tw) / 2, qrBox.y + qrBox.h + 16, 22, kWhite);+ }++ // Left column: message and link vertically centered aligned with QR code+ int textW = 600;+ int textX = panel.x + 60;+ auto lines = fonts_.regular.wrap(tr(Str::SupportMessage), 26, textW, 10);+ constexpr int kLineH = 38;+ int textContentH = static_cast<int>(lines.size()) * kLineH + 24 + 26;+ int textY = centerY - textContentH / 2;++ for (const auto& line : lines) {+ fonts_.regular.draw(c, line, textX, textY, 26, rgba(230, 230, 230));+ textY += kLineH;+ }++ textY += 24;+ fonts_.semibold.draw(c, "https://ko-fi.com/RafaelNGP", textX, textY, 24, rgba(255, 215, 80));++ c.fillRect({0, kH - 80, kW, 80}, kBg);+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+}++void AppUi::drawKeysTester(Canvas& c) {+ Rect panel = drawModal(c, 1500, 860, tr(Str::KeyboardKeys));+ // Each input: its name (the PlayStation button, the Xbox one beside),+ // then its two keys. Left column the sticks, D-pad, A and B; right the rest.+ constexpr const char* kUp = " \xE2\x86\x91", *kDown = " \xE2\x86\x93", *kLeft = " \xE2\x86\x90", *kRight = " \xE2\x86\x92";+ const std::string stick = tr(Str::StickLeft), dpad = tr(Str::DPad);+ const std::string names[input::kKeyActions] = {+ stick + kUp, stick + kDown, stick + kLeft, stick + kRight, dpad + kUp, dpad + kDown, dpad + kLeft, dpad + kRight,+ "A", "B", "X", "Y", "L1 (LB)", "R1 (RB)", "L2 (LT)", "R2 (RT)", "L3", "R3", "View", "Menu"};+ const int faceIcon[4] = {kIconCross, kIconCircle, kIconSquare, kIconTriangle}; // A B X Y+ // An Xbox pad: its own names alone.+ const bool xbox = g_glyphStyle == GlyphStyle::Xbox;+ std::string xboxNames[input::kKeyActions];+ if (xbox) {+ static constexpr PadButton kShoulders[6] = {PadButton::L1, PadButton::R1, PadButton::L2,+ PadButton::R2, PadButton::L3, PadButton::R3};+ for (int i = 0; i < 6; ++i)+ xboxNames[static_cast<int>(input::KeyAction::LB) + i] = buttonName(GlyphStyle::Xbox, kShoulders[i]);+ }+ constexpr int kRowH = 52, kGap = 8, kChipW = 170, kColGap = 40;+ const int colW = (panel.w - 112 - kColGap) / 2;+ const bool capturing = captureSince_ != 0;+ for (int a = 0; a < input::kKeyActions; ++a) {+ const int col = a / kKeysPerColumn, row = a % kKeysPerColumn;+ Rect r{panel.x + 56 + col * (colW + kColGap), panel.y + 106 + row * (kRowH + kGap), colW, kRowH};+ const bool rowOn = row == keysRow_ && col == keysCol_ / 2;+ c.fillRect(r, rowOn ? rgba(255, 255, 255, 30) : rgba(255, 255, 255, 12), 14);+ int ty = fonts_.semibold.centeredY(r.y, r.h, 24);+ if (a >= static_cast<int>(input::KeyAction::A) && a <= static_cast<int>(input::KeyAction::Y)) {+ int k = a - static_cast<int>(input::KeyAction::A);+ drawFaceButton(c, fonts_.bold, faceIcon[k], r.x + 38.0f, r.y + r.h / 2.0f, 16);+ if (!xbox) fonts_.semibold.draw(c, "(" + names[a] + ")", r.x + 66, ty, 24, kGray);+ } else {+ fonts_.semibold.draw(c, xbox && !xboxNames[a].empty() ? xboxNames[a] : names[a], r.x + 22, ty, 24, kWhite);+ }+ for (int slot = 0; slot < 2; ++slot) {+ Rect chip{r.x + r.w - 10 - (2 - slot) * kChipW - (1 - slot) * 10, r.y + 7, kChipW, r.h - 14};+ const bool on = rowOn && keysCol_ % 2 == slot;+ uint8_t code = settings_.keyMap[static_cast<size_t>(a)][static_cast<size_t>(slot)];+ std::string text = on && capturing ? "..." : code ? input::keyName(code) : "\xE2\x80\x94"; // an em dash: none+ c.fillRect(chip, on ? kWhite : rgba(255, 255, 255, code ? 26 : 10), 10);+ if (on && capturing) c.strokeRect({chip.x - 4, chip.y - 4, chip.w + 8, chip.h + 8}, rgba(90, 220, 110), 3, 13);+ int tw = fonts_.semibold.measure(text, 22);+ fonts_.semibold.draw(c, text, chip.x + (chip.w - tw) / 2, fonts_.semibold.centeredY(chip.y, chip.h, 22), 22,+ on ? kBg : code ? kWhite : kDim);+ }+ }+ // Reset to default, across both columns.+ Rect reset{panel.x + 56, panel.y + 106 + kKeysPerColumn * (kRowH + kGap) + 8, panel.w - 112, kRowH};+ const bool resetOn = keysRow_ == kKeysPerColumn;+ c.fillRect(reset, resetOn ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);+ if (resetOn) c.strokeRect({reset.x - 4, reset.y - 4, reset.w + 8, reset.h + 8}, kWhite, 2, 18);+ const char* resetLabel = tr(Str::ResetToDefault);+ fonts_.semibold.draw(c, resetLabel, reset.x + (reset.w - fonts_.semibold.measure(resetLabel, 24)) / 2,+ fonts_.semibold.centeredY(reset.y, reset.h, 24), 24, resetOn ? kWhite : rgba(240, 100, 100));+ // Waiting for a key: say so (and why a key was refused); else the help.+ int hy = panel.y + panel.h - 74;+ if (capturing) {+ std::string ask = tr(Str::PressKey);+ fonts_.bold.draw(c, ask, panel.x + (panel.w - fonts_.bold.measure(ask, 28)) / 2, hy - 4, 28, kWhite);+ if (keyRefused_) {+ std::string why = trf(Str::KeyReserved, input::keyName(keyRefused_));+ fonts_.regular.draw(c, why, panel.x + (panel.w - fonts_.regular.measure(why, 22)) / 2, hy + 34, 22,+ rgba(240, 100, 100));+ }+ } else {+ auto help = fonts_.regular.wrap(tr(Str::KeysHelp), 22, panel.w - 112, 2);+ for (size_t i = 0; i < help.size(); ++i)+ fonts_.regular.draw(c, help[i], panel.x + 56, hy + static_cast<int>(i) * 30, 22, kDim);+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg); // its own hints over drawModal's+ if (capturing)+ drawHints(c, {{kIconCircle, tr(Str::Cancel)}});+ else if (resetOn)+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});+ else+ drawHints(c, {{kIconCross, tr(Str::ChangeKey)}, {kIconSquare, tr(Str::ClearKey)}, {kIconCircle, tr(Str::Back)}});+}++void AppUi::drawColourPicker(Canvas& c) {+ c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));+ constexpr int kPanelW = 1000, kPanelH = 540;+ Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 20, kPanelW, kPanelH};+ c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow+ c.fillRect(panel, kPanel, 24);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);+ fonts_.bold.draw(c, tr(Str::LightBarColour), panel.x + 56, panel.y + 44, 40, kWhite);++ // The wheel: angle = hue, distance from the centre = saturation, at the+ // brightness chosen (its pixels kept until that changes).+ const int R = kWheelR, cx = panel.x + 56 + R, cy = panel.y + 120 + R;+ if (wheelValue_ != pickValue_ || wheel_.empty()) {+ wheel_.assign(static_cast<size_t>(4 * R * R), 0);+ for (int y = 0; y < 2 * R; ++y)+ for (int x = 0; x < 2 * R; ++x) {+ float u = (x + 0.5f - R) / R, v = (y + 0.5f - R) / R, d = std::hypot(u, v);+ if (d > 1.0f + 1.0f / R) continue;+ float h = std::atan2(v, u) / 6.2832f;+ Color col = hsvColour(h < 0 ? h + 1 : h, std::min(1.0f, d), pickValue_);+ // Edge coverage, for a smooth rim.+ uint32_t a = static_cast<uint32_t>(std::clamp((1.0f - d) * R + 0.5f, 0.0f, 1.0f) * 255);+ wheel_[static_cast<size_t>(y * 2 * R + x)] = (col & 0x00FFFFFF) | a << 24;+ }+ wheelValue_ = pickValue_;+ }+ uint32_t* px = c.data();+ for (int y = 0; y < 2 * R; ++y)+ for (int x = 0; x < 2 * R; ++x) {+ uint32_t w = wheel_[static_cast<size_t>(y * 2 * R + x)], a = w >> 24;+ if (!a) continue;+ uint32_t& d = px[static_cast<size_t>((cy - R + y) * kW + (cx - R + x))];+ auto mix = [&](int shift) {+ uint32_t s = w >> shift & 0xFF, t = d >> shift & 0xFF;+ return ((s * a + t * (255 - a)) / 255) << shift;+ };+ d = mix(0) | mix(8) | mix(16) | 0xFF000000u;+ }+ float kx = cx + pickU_ * R, ky = cy + pickV_ * R; // the cursor+ c.strokeArc(kx, ky, 15, 3, 0, 6.2832f, rgba(0, 0, 0, 160));+ c.strokeArc(kx, ky, 12, 3, 0, 6.2832f, kWhite);++ // The colour chosen, and the brightness under it.+ const int sx = panel.x + 56 + 2 * R + 80, sw = panel.x + panel.w - 56 - sx;+ Color chosen = pickerColour();+ c.fillRect({sx, cy - R + 10, sw, 170}, chosen, 20);+ c.strokeRect({sx, cy - R + 10, sw, 170}, rgba(255, 255, 255, 60), 2, 20);+ Rect bar{sx, cy + 30, sw, 18};+ float h = std::atan2(pickV_, pickU_) / 6.2832f, s = std::min(1.0f, std::hypot(pickU_, pickV_));+ c.gradientH(bar, hsvColour(h < 0 ? h + 1 : h, s, kMinValue), hsvColour(h < 0 ? h + 1 : h, s, 1));+ float mx = bar.x + (pickValue_ - kMinValue) / (1 - kMinValue) * bar.w;+ c.fillCircle(mx, bar.y + bar.h / 2.0f, 14, kWhite);+ c.fillCircle(mx, bar.y + bar.h / 2.0f, 9, chosen);+ // The help, a line per control (its parts are four spaces apart).+ std::string help = tr(Str::ColourPickerHelp);+ int hy = cy + 90;+ for (size_t start = 0; start < help.size();) {+ size_t gap = help.find(" ", start);+ std::string part = help.substr(start, gap == std::string::npos ? std::string::npos : gap - start);+ for (const auto& line : fonts_.regular.wrap(part, 22, sw, 2)) {+ fonts_.regular.draw(c, line, sx, hy, 22, kGray);+ hy += 32;+ }+ if (gap == std::string::npos) break;+ start = help.find_first_not_of(' ', gap);+ if (start == std::string::npos) break;+ }++ c.fillRect({0, kH - 80, kW, 80}, kBg);+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::Back)}});+}++void AppUi::drawUpdating(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ drawLogo(c, kW / 2.0f, 330, 56);+ drawCentered(c, fonts_.bold, trf(Str::UpdatingTo, updatingTo_), 440, 48, kWhite);+ drawCentered(c, fonts_.regular, updateStatus_, 520, 28, kGray);+ if (updateFraction_ >= 0) {+ constexpr int kBarW = 720;+ Rect bar{(kW - kBarW) / 2, 590, kBarW, 12};+ c.fillRect(bar, rgba(255, 255, 255, 40), 6);+ c.fillRect({bar.x, bar.y, static_cast<int>(kBarW * std::min(1.0f, updateFraction_)), bar.h}, kGreen, 6);+ } else {+ drawSpinner(c, kW / 2.0f, 610, 24, nowMs);+ }+}++void AppUi::drawSignOutHold(Canvas& c, uint64_t nowMs) {+ if (!signOutHoldStart_) return;+ float progress = std::min(1.0f, static_cast<float>(nowMs - signOutHoldStart_) / kSignOutHoldMs);+ int secondsLeft = static_cast<int>((kSignOutHoldMs - std::min<uint64_t>(kSignOutHoldMs, nowMs - signOutHoldStart_) + 999) / 1000);+ std::string text = trf(Str::SigningOutIn, std::to_string(secondsLeft));+ int tw = fonts_.semibold.measure(text, 28);+ Rect panel{(kW - (tw + 170)) / 2, kH - 250, tw + 170, 110};+ c.fillRect(panel, rgba(30, 30, 30, 240), 55);+ c.strokeRect(panel, rgba(255, 255, 255, 60), 2, 55);+ float cx = panel.x + 62, cy = panel.y + panel.h / 2.0f;+ c.strokeArc(cx, cy, 30, 6, 0, 6.2832f, rgba(255, 255, 255, 50));+ // Progress ring from 12 o'clock, clockwise, in red as it nears the end.+ Color ring = progress < 0.8f ? kWhite : rgba(255, 110, 110);+ if (progress > 0.01f) c.strokeArc(cx, cy, 30, 6, -1.5708f, 6.2832f * progress, ring);+ fonts_.bold.draw(c, std::to_string(secondsLeft), static_cast<int>(cx) - fonts_.bold.measure(std::to_string(secondsLeft), 26) / 2,+ static_cast<int>(cy) - 16, 26, kWhite);+ fonts_.semibold.draw(c, text, panel.x + 120, panel.y + 38, 28, kWhite);+ animating_ = true;+}++void AppUi::drawGameSettings(Canvas& c) {+ if (tester_ == Tester::Sticks) {+ drawStickTester(c);+ return;+ }+ if (tester_ == Tester::Triggers) {+ drawTriggerTester(c);+ return;+ }+ if (tester_ == Tester::Keys) {+ drawKeysTester(c);+ return;+ }+ if (tester_ == Tester::Pad) {+ drawPadTester(c);+ return;+ }+ if (tester_ == Tester::Touchpad) {+ drawTouchpadTester(c);+ return;+ }+ std::string title = tr(Str::GameSettings);+ if (!detail_.name.empty()) {+ std::string full = title + " \xE2\x80\xA2 " + detail_.name;+ if (fonts_.bold.measure(full, 40) <= 960) {+ title = full;+ } else {+ std::string cut = detail_.name;+ while (!cut.empty() && fonts_.bold.measure(title + " \xE2\x80\xA2 " + cut + "...", 40) > 960) {+ do {+ cut.pop_back();+ } while (!cut.empty() && (static_cast<uint8_t>(cut.back()) & 0xC0) == 0x80);+ }+ title = title + " \xE2\x80\xA2 " + cut + "...";+ }+ }+ constexpr int kModalW = 1140, kModalH = 960;+ constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;+ // The rows caps_ allows; the panel loses the height of those it hides+ // (the same as ever with all of them, "Reset to default" or not).+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);+ const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);+ auto groups = [](const std::vector<SettingsRowPos>& v) {+ return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));+ };+ const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -+ (groups(all) - groups(most)) * kGroupGap;+ Rect panel = drawModal(c, kModalW, modalH, title);+ int y = panel.y + 92;++ for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {+ const int i = rows[static_cast<size_t>(pos)].row;+ if (rows[static_cast<size_t>(pos)].groupStart) y += kGroupGap;+ Rect r{panel.x + 50, y, panel.w - 100, kRowH};+ bool focused = (pos == gameSettingsRow_);+ c.fillRect(r, focused ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 14);+ if (focused) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 2, 18);++ int ty = fonts_.semibold.centeredY(r.y, r.h, 26);++ if (i == 10) {+ const char* resetLabel = tr(Str::ResetToDefault);+ int tw = fonts_.semibold.measure(resetLabel, 26);+ fonts_.semibold.draw(c, resetLabel, r.x + (r.w - tw) / 2, ty, 26, focused ? kWhite : rgba(240, 100, 100));+ y += kRowH + kGap;+ continue;+ }++ const char* label = "";+ std::string value;++ switch (i) {+ case 0:+ label = tr(Str::Profile);+ value = tr(activeGameHasCustom_ ? Str::ProfileCustom : Str::ProfileDefault);+ break;+ case 1:+ label = tr(Str::MenuUpscaler);+ value = activeGameProfile_.upscaler == 3 ? tr(Str::UpscalerAiClean)+ : activeGameProfile_.upscaler == 2 ? tr(Str::UpscalerFsrClean)+ : activeGameProfile_.upscaler == 1 ? tr(Str::UpscalerAi)+ : "FSR";+ break;+ case 2: {+ label = tr(Str::MenuSharpness);+ static constexpr Str kLevels[] = {Str::SharpOff, Str::SharpLow, Str::SharpMedium, Str::SharpHigh};+ value = tr(kLevels[std::clamp(activeGameProfile_.sharpness, 0, 3)]);+ break;+ }+ case 3: {+ label = tr(Str::MenuDeband);+ static constexpr Str kLevels[] = {Str::SharpOff, Str::SharpLow, Str::SharpHigh};+ value = activeGameProfile_.deband == 3 ? "Auto"+ : tr(kLevels[std::clamp(activeGameProfile_.deband, 0, 2)]);+ break;+ }+ case 4:+ label = tr(Str::Resolution);+ value = activeGameProfile_.resolution == 1 ? "720p" : activeGameProfile_.resolution == 2 ? tr(Str::ResBest) : "1080p";+ break;+ case 5:+ label = tr(Str::Deadzone);+ value = std::to_string(activeGameProfile_.deadzoneLeft) + " %";+ break;+ case 6: {+ label = tr(Str::TriggerRumble);+ static constexpr Str kStrengths[] = {Str::Deactivated, Str::TriggerLight, Str::TriggerMedium,+ Str::TriggerStrong, Str::TriggerMax};+ value = tr(kStrengths[std::clamp(activeGameProfile_.triggerStrength, 0, 4)]);+ break;+ }+ case 16: {+ label = tr(Str::AudioHaptics);+ static constexpr Str kHapticsLevels[] = {Str::Off, Str::SharpLow, Str::SharpMedium, Str::SharpHigh};+ value = tr(kHapticsLevels[std::clamp(activeGameProfile_.audioHaptics, 0, 3)]);+ break;+ }+ case 7:+ label = tr(Str::ConfirmButton);+ break;+ case 8:+ label = tr(Str::HighRefresh);+ value = tr(activeGameProfile_.highRefresh ? Str::HighRefreshOn : Str::Deactivated);+ break;+ case 9:+ label = tr(Str::KeyboardKeys);+ value = tr(activeGameProfile_.keyMap == input::defaultKeyMap() ? Str::ProfileDefault : Str::ProfileCustom);+ break;+ case 11:+ label = tr(Str::ControllerButtons);+ value = tr(activeGameProfile_.padMap == input::defaultPadMap() ? Str::ProfileDefault : Str::ProfileCustom);+ break;+ case 17:+ label = tr(Str::TouchpadShortcuts);+ value = tr(activeGameProfile_.touchpadShortcuts == input::defaultTouchpadShortcuts() ? Str::ProfileDefault : Str::ProfileCustom);+ break;+ case 12:+ label = tr(Str::Gyro);+ value = tr(activeGameProfile_.gyroMode == 1 ? Str::GyroAlways+ : activeGameProfile_.gyroMode == 2 ? Str::GyroAiming+ : Str::Off);+ break;+ case 13:+ label = tr(Str::TouchpadMouse);+ value = tr(activeGameProfile_.touchpadMouse ? Str::Activated : Str::Deactivated);+ break;+ case 14: {+ static const std::pair<const char*, const char*> kLocales[] = {+ {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},+ {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},+ {"it-IT", "Italiano"}, {"ja-JP", "日本語"}+ };+ label = tr(Str::GameLanguage);+ if (activeGameProfile_.locale.empty()) {+ value = tr(Str::ProfileDefault);+ } else {+ for (const auto& [code, name] : kLocales) {+ if (activeGameProfile_.locale == code) {+ value = name;+ break;+ }+ }+ if (value.empty()) value = activeGameProfile_.locale;+ }+ break;+ }+ case 15:+ label = tr(Str::VideoDecoder);+ value = activeGameProfile_.videoDecoder == 1 ? tr(Str::VideoDecoderSw) : tr(Str::VideoDecoderHw);+ break;+ default: break;+ }++ fonts_.semibold.draw(c, label, r.x + 28, ty, 26, kWhite);++ if (i == 7) {+ float cx = static_cast<float>(r.x + r.w - 50), cy = static_cast<float>(r.y + r.h / 2);+ if (focused) {+ fonts_.regular.draw(c, "\xE2\x80\xB9", static_cast<int>(cx) - 40, fonts_.regular.centeredY(r.y, r.h, 26), 26, kWhite);+ fonts_.regular.draw(c, "\xE2\x80\xBA", static_cast<int>(cx) + 28, fonts_.regular.centeredY(r.y, r.h, 26), 26, kWhite);+ }+ drawFaceButton(c, fonts_.bold, activeGameProfile_.circleConfirms ? kIconCircle : kIconCross, cx, cy, 16);+ } else {+ std::string disp = focused ? ("\xE2\x80\xB9 " + value + " \xE2\x80\xBA") : value;+ int vw = fonts_.regular.measure(disp, 26);+ fonts_.regular.draw(c, disp, r.x + r.w - 28 - vw, fonts_.regular.centeredY(r.y, r.h, 26), 26,+ focused ? kWhite : kGray);+ }++ y += kRowH + kGap;+ }+}++} // namespace xc::uidiff --git a/src/ui/canvas.cpp b/src/ui/canvas.cppindex 7df27b4..0bce569 100644--- a/src/ui/canvas.cpp+++ b/src/ui/canvas.cpp@@ -4,6 +4,7 @@#include <algorithm>#include <cmath>+#include <cstring>namespace xc::ui {@@ -162,15 +163,32 @@ void Canvas::gradientV(Rect r, Color top, Color bottom) {Color c = 0;for (int s = 0; s < 32; s += 8) c |= lerp8((top >> s) & 0xFF, (bottom >> s) & 0xFF, t) << s;uint32_t a = alphaOf(c);+ if (a == 0) continue;uint32_t* row = &px_[static_cast<size_t>(y) * w_];- for (int x = b.x; x < b.x + b.w; ++x) blend(row[x], c, a);+ if (a >= 255) {+ std::fill_n(&row[b.x], b.w, c | 0xFF000000u);+ } else {+ uint32_t sr = (c & 0xFF) * a;+ uint32_t sg = ((c >> 8) & 0xFF) * a;+ uint32_t sb = ((c >> 16) & 0xFF) * a;+ uint32_t inv = 255 - a;+ for (int x = b.x; x < b.x + b.w; ++x) {+ uint32_t d = row[x];+ uint32_t dr = (sr + (d & 0xFF) * inv + 127) / 255;+ uint32_t dg = (sg + ((d >> 8) & 0xFF) * inv + 127) / 255;+ uint32_t db = (sb + ((d >> 16) & 0xFF) * inv + 127) / 255;+ row[x] = 0xFF000000u | (db << 16) | (dg << 8) | dr;+ }+ }}}void Canvas::gradientH(Rect r, Color left, Color right) {Rect b = intersect(r, clip_);if (b.w <= 0 || b.h <= 0) return;- std::vector<Color> cols(static_cast<size_t>(b.w));+ Color stackCols[2048];+ std::vector<Color> heapCols;+ Color* cols = b.w <= 2048 ? stackCols : (heapCols.resize(static_cast<size_t>(b.w)), heapCols.data());for (int x = b.x; x < b.x + b.w; ++x) {uint32_t t = r.w > 1 ? static_cast<uint32_t>((x - r.x) * 255 / (r.w - 1)) : 0;Color c = 0;@@ -268,6 +286,10 @@ void Canvas::drawImage(const Image& img, int x, int y, uint8_t opacity, int radiuint32_t* row = &px_[static_cast<size_t>(yy) * w_];const uint32_t* src = &img.px[static_cast<size_t>(yy - y) * img.w];bool cornerRow = radius > 0 && (circle || yy < y + radius || yy >= y + img.h - radius);+ if (!cornerRow && opacity >= 255 && img.opaque) {+ std::memcpy(&row[b.x], &src[b.x - x], static_cast<size_t>(b.w) * sizeof(uint32_t));+ continue;+ }for (int xx = b.x; xx < b.x + b.w; ++xx) {uint32_t s = src[xx - x];uint32_t a = (alphaOf(s) * opacity + 127) / 255;diff --git a/src/ui/canvas.h b/src/ui/canvas.hindex 8bba225..a8dc133 100644--- a/src/ui/canvas.h+++ b/src/ui/canvas.h@@ -20,6 +20,7 @@ constexpr Color withAlpha(Color c, uint8_t a) { return (c & 0x00FFFFFFu) | (statstruct Image {int w = 0, h = 0;+ bool opaque = false;std::vector<uint32_t> px; // straight (not premultiplied) alphasize_t bytes() const { return px.size() * 4; }};@@ -39,6 +40,7 @@ public:void setClip(Rect r);void resetClip() { clip_ = {0, 0, w_, h_}; }+ void clearClip() { resetClip(); }void clear(Color c);// Alpha-blended, antialiased rounded corners when radius > 0.diff --git a/src/ui/font.cpp b/src/ui/font.cppindex 3eb21dd..290b9ae 100644--- a/src/ui/font.cpp+++ b/src/ui/font.cpp@@ -19,6 +19,8 @@ namespace xc::ui {struct Font::Impl {stbtt_fontinfo info{};int ascent = 0, descent = 0, lineGap = 0;+ int capY1 = 0;+ bool hasCapBox = false;};Font::Font() : impl_(std::make_unique<Impl>()) {}@@ -37,6 +39,9 @@ bool Font::load(const std::string& path) {return false;}stbtt_GetFontVMetrics(&impl_->info, &impl_->ascent, &impl_->descent, &impl_->lineGap);+ int x0 = 0, y0 = 0, x1 = 0, y1 = 0;+ impl_->hasCapBox = stbtt_GetCodepointBox(&impl_->info, 'H', &x0, &y0, &x1, &y1) != 0;+ impl_->capY1 = y1;{std::lock_guard<std::mutex> lock(mutex_);cache_.clear();@@ -54,10 +59,9 @@ bool Font::usable() const {int Font::centeredY(int boxY, int boxH, int px) const {if (!usable()) return boxY;- // Cap height from the "H" glyph's box, in font units.- int x0, y0, x1, y1;- float capH = stbtt_GetCodepointBox(&impl_->info, 'H', &x0, &y0, &x1, &y1) ? y1 * scale(px) : 0.7f * px;- float ascent = impl_->ascent * scale(px); // line top to baseline+ float s = scale(px);+ float capH = impl_->hasCapBox ? impl_->capY1 * s : 0.7f * px;+ float ascent = impl_->ascent * s; // line top to baseline// Cap top = y + ascent - capH; centre it: (boxH - capH) / 2 below boxY.return static_cast<int>(std::lround(boxY + (boxH - capH) / 2.0f - (ascent - capH)));}@@ -86,7 +90,7 @@ const Font::Glyph& Font::glyph(uint32_t cp, int px) const {static const Glyph kNone;if (!usable()) return kNone;std::lock_guard<std::mutex> lock(mutex_);- auto key = std::make_pair(cp, px);+ uint64_t key = (static_cast<uint64_t>(cp) << 32) | static_cast<uint32_t>(px);auto it = cache_.find(key);if (it != cache_.end()) return it->second;Glyph g;@@ -124,18 +128,28 @@ int Font::draw(Canvas& c, std::string_view text, int x, int y, int px, Color col}std::string Font::fit(std::string_view text, int px, int maxWidth) const {- if (measure(text, px) <= maxWidth) return std::string(text);const char* dots = "...";- int budget = maxWidth - measure(dots, px);- std::string out;- int w = 0;+ int dotsW = measure(dots, px);+ int budget = maxWidth - dotsW;+ int totalW = 0;+ size_t cutIdx = 0;+ bool cutSet = false;for (size_t i = 0; i < text.size();) {size_t start = i;int adv = glyph(nextCodepoint(text, i), px).advance;- if (w + adv > budget) break;- w += adv;- out.append(text.substr(start, i - start));+ if (!cutSet && totalW + adv > budget) {+ cutIdx = start;+ cutSet = true;+ }+ totalW += adv;+ if (totalW > maxWidth && cutSet) {+ std::string out(text.substr(0, cutIdx));+ while (!out.empty() && out.back() == ' ') out.pop_back();+ return out + dots;+ }}+ if (totalW <= maxWidth) return std::string(text);+ std::string out(text.substr(0, cutSet ? cutIdx : 0));while (!out.empty() && out.back() == ' ') out.pop_back();return out + dots;}diff --git a/src/ui/font.h b/src/ui/font.hindex bd76583..77bd9d2 100644--- a/src/ui/font.h+++ b/src/ui/font.h@@ -6,11 +6,11 @@#include "ui/canvas.h"-#include <map>#include <memory>#include <mutex>#include <string>#include <string_view>+#include <unordered_map>#include <vector>namespace xc::ui {@@ -57,7 +57,7 @@ private:std::vector<unsigned char> data_;bool loaded_ = false;mutable std::mutex mutex_;- mutable std::map<std::pair<uint32_t, int>, Glyph> cache_;+ mutable std::unordered_map<uint64_t, Glyph> cache_;};// The three weights the UI uses.diff --git a/src/ui/i18n/strings_de.inc b/src/ui/i18n/strings_de.incnew file mode 100644index 0000000..4e364b1--- /dev/null+++ b/src/ui/i18n/strings_de.inc@@ -0,0 +1,418 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+constexpr Column kGerman = {+ "PSBox Cloud Gaming",+ "PSBOX CLOUD GAMING",+ "Anmeldung läuft...",+ "Anmeldecode wird abgerufen...",+ "Deine Spiele werden geladen...",+ "Zum Spielen anmelden",+ "Rufe auf deinem Handy oder Computer",+ "auf und gib diesen Code ein",+ "Scannen, um die Seite zu öffnen, dann den Code eingeben",+ "Warte auf deine Anmeldung...",+ "Weiterspielen",+ "Spielen",+ "Zurück",+ "Auswählen",+ "Abmelden",+ "Abbrechen",+ "Erneut versuchen",+ "Dein Spiel wird vorbereitet",+ "Du bist in der Warteschlange. Geschätzte Wartezeit: %s",+ "Verbindung wird hergestellt...",+ "Streaming wird gestartet...",+ "Touchpad: ↓ dieses Menü · ↑ Xbox-Taste",+ "Streaming beendet",+ "Etwas ist schiefgelaufen",+ "Angemeldet als %s",+ "Noch keine Spiele vorhanden",+ "Von %s",+ "Einstellungen",+ "Sprache",+ "Streaming-Auflösung",+ "Serverregion",+ "Automatisch (%s)",+ "1080p (Full HD)",+ "720p (verbraucht weniger Daten)",+ "Beste (Auto)",+ "Auflösung und Region gelten ab dem nächsten gestarteten Spiel.",+ "Ändern",+ "Anpassen",+ "Halten zum Abmelden",+ "Weiter halten zum Abmelden (%s)",+ "Anmeldung fehlgeschlagen: %s",+ "Die Anmeldung im Browser wurde nicht abgeschlossen. Verwende ein persönliches Microsoft-Konto, schließe Sicherheitsabfragen/2FA ab und gewähre Zugriff.",+ "Die Spieleliste konnte nicht geladen werden: %s",+ "Das Streaming konnte nicht gestartet werden: %s",+ "Keine Aktivität: Die Verbindung wird in %s Sekunden getrennt",+ "Meine Spiele",+ "Für dein Konto nicht verfügbar",+ "Game Pass",+ "Suchen",+ "Gib den Namen eines Spiels ein",+ "Keine Spiele gefunden",+ "%s Ergebnisse",+ "Leerzeichen",+ "Löschen",+ "Leeren",+ "%s Spiele",+ "Tippen",+ "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 Meine Spiele.",+ "Scannen, um die Store-Seite zu öffnen",+ "Suchen in %s",+ "KOSTENLOS",+ "Ausblenden",+ "Einblenden",+ "Ausgeblendet",+ "\xE2\x96\xA1 blendet ein Spiel wieder ein",+ "Ausgeblendet: unter Ausgeblendet, am Ende dieses Tabs",+ "Wieder sichtbar",+ "Sortieren: %s",+ "Zuletzt gespielt",+ "A-Z",+ "Nach Konsole",+ "Sortieren",+ "Kostenlos",+ "Niedrigster Preis",+ "Alle Konsolen",+ "1 Spiel",+ "Abschnitte",+ "Spieleliste wird aktualisiert...",+ "Spielmenü",+ "Statistiken",+ "An",+ "Aus",+ "Stream-Auflösung",+ "Spiel verlassen",+ "Latenz",+ "Bitrate",+ "Bilder pro Sekunde",+ "Paketverlust",+ "Region",+ "Dekodierung",+ "Der Server behält eventuell die aktuelle Qualität bei",+ "Schärfe",+ "Aus",+ "Niedrig",+ "Mittel",+ "Hoch",+ "Stick-Totzone",+ "Trigger-Vibration",+ "Bestätigungstaste",+ "An",+ "Aus",+ "Version %s verfügbar",+ "Controller",+ "Controller %s verbunden",+ "Controller %s getrennt",+ "Blockglättung",+ "Auf dem Bildschirm nach",+ "Verbindung verloren: neu verbinden...",+ "Wieder verbunden",+ "Lichtleiste",+ "Hochskalierung",+ "KI (Anime4K)",+ "Free-to-play",+ "Einmal kostenlos auf xbox.com oder in der Xbox-App holen (Code mit dem Handy scannen), dann Spielen drücken.",+ "Scannen, um es kostenlos zu holen",+ "%s ist noch nicht in deinem Konto. Es ist kostenlos: Code auf seiner Seite scannen, Abrufen wählen und erneut versuchen (kann eine Minute dauern).",+ "Dein Konto kann %s nicht spielen: nicht in deinem Abo oder nicht gekauft.",+ "Meine Konsolen",+ "An",+ "Im Standby",+ "Aus",+ "Deine Konsolen werden gesucht...",+ "Noch keine Xbox gefunden",+ "Spiele hier auf deiner eigenen Xbox: ihr Bildschirm, ihre Spiele und Apps.",+ "Deine Xbox wird geweckt...",+ "%s hat nicht geantwortet. Prüfe, ob die Remotefunktionen aktiv sind und der Energiemodus Ruhezustand ist, oder schalte sie ein und versuche es erneut.",+ "Melde dich auf deiner Xbox mit genau diesem Microsoft-Konto an.",+ "Einstellungen > Geräte & Verbindungen > Remotefunktionen: Remotefunktionen aktivieren.",+ "Einstellungen > Allgemein > Energieoptionen: Ruhezustand wählen, damit sie von selbst aufwacht.",+ "Scannen für die Hilfe von Microsoft",+ "Erneut suchen",+ "Xbox-Taste",+ "Streaming beenden",+ "Das Streaming wurde auf der Xbox beendet",+ "Ein anderes Gerät hat das Streaming übernommen",+ "Die Xbox wurde ausgeschaltet",+ "%s hat die Anfrage erhalten, aber Remote Play ist nicht gestartet. Starte sie neu: Halte die Ein/Aus-Taste der Konsole 10 Sekunden gedrückt, schalte sie wieder ein und versuche es erneut.",+ "Touchpad: ↓ wischen für das Menü, ↑ für die Xbox-Taste",+ "FSR + Bereinigung",+ "KI + Bereinigung",+ "Auto (%s)",+ "Jetzt aktualisieren? Die App startet danach von selbst neu.",+ "Jetzt aktualisieren",+ "Nicht jetzt",+ "Updates",+ "Aktuell (%s)",+ "%s verfügbar: aktualisieren",+ "Wird geprüft...",+ "Aktualisierung auf %s",+ "Wird geladen... %s",+ "Signatur wird geprüft...",+ "Wird installiert...",+ "Aktualisiert. Neustart...",+ "PSBox aktualisiert: App erneut öffnen",+ "Update fehlgeschlagen: nichts wurde geändert",+ "Farbe des Spiels",+ "Eigene Farbe",+ "Farbe der Lichtleiste",+ "Linker Stick oder Steuerkreuz: Farbe L2 / R2: Helligkeit",+ "Leicht",+ "Mittel",+ "Stark",+ "Maximal",+ "Stärke",+ "Frequenz",+ "Tief",+ "Hoch",+ "L2 / R2 drücken zum Fühlen: je tiefer, desto stärker würde es das Spiel verlangen",+ "Stufe %s",+ "Linker Stick",+ "Rechter Stick",+ "Tatsächliche Position",+ "Was das Spiel bekommt",+ "L1 / R1: Stick wählen Steuerkreuz ← / →: einstellen Sticks bewegen zum Sehen",+ "Widerstand",+ "Stil",+ "Vibration",+ "Kraftimpulse",+ "Modus",+ "Genre",+ "Sprache",+ "Alle Modi",+ "Einzelspieler",+ "Online-Mehrspieler",+ "Online-Koop",+ "Lokal / geteilter Bildschirm",+ "Alle Genres",+ "Alle Sprachen",+ "Deutsch",+ "Untertitel: %s",+ "Sprachausgabe: %s",+ "Spieleinstellungen",+ "Profil",+ "Standard",+ "Benutzerdefiniert",+ "Auf Standard zurücksetzen",+ "Publisher",+ "Alle Publisher",+ "Indies & Andere",+ "Freunde spielen jetzt",+ "Mikrofon",+ "Stumm",+ "Aktiv",+ "Audioausgabe",+ "TV",+ "Controller-Lautsprecher",+ "Problem melden",+ "Mit dem Handy scannen: Das Fehlerformular auf GitHub öffnet sich ausgefüllt. Du prüfst es vor dem Senden.",+ "Enthalten sind die App-Version, der Fehler und Zeilen des Logs, ohne persönliche Daten.",+ "PSBox wurde beim letzten Mal unerwartet beendet",+ "Anmeldeland",+ "Aus (das der Konsole)",+ "Als anderes Land anmelden",+ "xCloud wird mitgeteilt, dass die Anmeldung aus dem gewählten Land kommt. Microsoft erlaubt das nicht: Nutzung auf eigenes Risiko. Spiele kommen dann eventuell von weit entfernten Servern, mit mehr Verzögerung. Später in den Einstellungen änderbar.",+ "xCloud hat die Anmeldung abgelehnt. Cloud Gaming wird in deinem Land vielleicht nicht angeboten, oder das Konto hat kein Game-Pass-Abo mit Cloud Gaming.",+ "xCloud hat die Anmeldung abgelehnt, auch mit %s. Das Konto hat wahrscheinlich kein Game-Pass-Abo mit Cloud Gaming.",+ "Brasilien",+ "Japan",+ "Südkorea",+ "Polen",+ "USA",+ "Sichere Verbindungen wurden abgelehnt, weil Datum und Uhrzeit der PS5 falsch zu sein scheinen (sie zeigt %s). Stelle sie unter Einstellungen > System > Datum und Uhrzeit ein und versuche es erneut.",+ "Eine sichere Verbindung wurde abgelehnt: Etwas im Netzwerk (DNS-Server, Proxy oder Filter) antwortet anstelle der Microsoft-Seiten. Versuche es ohne und dann erneut.",+ "Datum und Uhrzeit der PS5 scheinen falsch zu sein (%s): Einige Inhalte laden nicht. Stelle sie unter Einstellungen > System > Datum und Uhrzeit ein.",+ "Die Anmeldung konnte nicht auf der Konsole gespeichert werden und wird beim nächsten Mal erneut abgefragt. Bitte melde das (Einstellungen > △).",+ "Geschätzte Wartezeit: %s s", // QueueSeconds+ "Geschätzte Wartezeit: %s Min.", // QueueMinutes+ "120-Hz-Ausgabe (VRR)", // HighRefresh+ "An (in Spielen)", // HighRefreshOn+ "Instabile Verbindung", // ConnectionUnstable+ "Sitzung: %s", // SessionSummary+ "Maximale Bitrate", // BitrateCap+ "Automatisch", // BitrateAuto+ "Spiellautstärke", // GameVolume+ "Tastatur: F12 dieses Menü · Pos1 Xbox-Taste", // MenuKeyHint+ "Maus & Tastatur", // FilterMouseKeyboard+ "Maus und Tastatur", // MouseKeyboardSupport+ "Tastatur und Maus: Spieler %s", // KeyboardPlayer+ "Du bist in der Warteschlange.", // InQueueNoEstimate+ "Tastaturbelegung", // KeyboardKeys+ "Steuerkreuz", // DPad+ "Drücke eine Taste oder Maustaste", // PressKey+ "%s ist für die App reserviert", // KeyReserved+ "Ändern", // ChangeKey+ "Löschen", // ClearKey+ "Die Maus bewegt den rechten Stick, jede Rasterstufe des Mausrads drückt Dreieck. F12 (Menü), Pos1 (Xbox-Taste) und 1-4 (Spieler) sind für die App reserviert.", // KeysHelp+ "Gyro-Zielen", // Gyro+ "Immer", // GyroAlways+ "Beim Zielen (L2)", // GyroAiming+ "Gyro-Stärke", // GyroIntensity+ "Sichere Verbindungen wurden abgelehnt, weil Datum und Uhrzeit dieses Computers falsch zu sein scheinen (er zeigt %s). Korrigiere sie in den Systemeinstellungen und versuche es erneut.", // ClockWrongPc+ "Datum und Uhrzeit dieses Computers scheinen falsch zu sein (%s): Einige Inhalte laden nicht. Korrigiere sie in den Systemeinstellungen.", // ClockWrongNoticePc+ "Aus (das des Computers)", // LoginCountryOffPc+ "Im Browser öffnen", // OpenInBrowser+ "%s verfügbar: herunterladen", // UpdateReadyPc+ "Menü: START + BACK oder F12 · Xbox-Taste: Guide oder Pos1", // GestureHintButtons+ "START + BACK oder F12: dieses Menü · Guide oder Pos1: Xbox-Taste", // MenuButtonHint+ "Anzeigemodus", // DisplayMode+ "Fenster", // DisplayWindow+ "Vollbild", // DisplayFullscreen+ "PSBox beenden?", // QuitTitle+ "Beenden", // QuitConfirm+ "Controller-Tasten", // ControllerButtons+ "Drücke die Taste für %s", // PadPressButton+ "Ohne Taste: %s. Weise jeder Funktion eine zu, oder setze zurück bzw. verwirf die Änderungen.", // PadMissing+ "Änderungen verwerfen", // DiscardChanges+ "Gilt nur im Spiel: Die Menüs der App nutzen die Tasten, wie sie sind. Eine schon belegte Taste zu wählen tauscht die beiden.", // PadHelp+ "Abo", // FilterPlan+ "Mein Abo", // PlanMine+ "Alle Abos", // PlanAll+ "In Game Pass %s enthalten", // IncludedWithPlan+ "Touchpad als Maus", // TouchpadMouse+ "Favoriten", // Favorites+ "Zu Favoriten hinzufügen", // AddFavorite+ "Aus Favoriten entfernen", // RemoveFavorite+ "Zu Favoriten hinzugefügt", // AddedToFavorites+ "Aus Favoriten entfernt", // RemovedFromFavorites+ "Spiel-Sprache", // GameLanguage+ "Monatliches Cloud-Gaming-Limit erreicht", // MonthlyLimitExceeded+ "Verbleibende Spielzeit", // PlaytimeRemaining+ "%s Std. verbleibend", // HoursRemaining+ "Weniger als 2 Std. verbleibend", // PlaytimeWarning+ "Trigger-Profil", // TriggerProfile+ "Standard", // TriggerProfileStd+ "Shooter (Hair Trigger)", // TriggerProfileShooter+ "Rennen (ABS)", // TriggerProfileRacing+ "Speicher %s ist schreibgeschützt: Anmeldung und Einstellungen werden nicht gespeichert", // StorageNotWritable+ "FTP: 'chmod 777 %s' ausführen oder Ordner löschen und neu starten", // StorageFixHint+ "Indikatoren anpassen", // StatsCustomize+ "FPS und Auflösung", // StatsIndicatorFps+ "Bitrate", // StatsIndicatorBitrate+ "Latenz (RTT)", // StatsIndicatorLatency+ "Paketverlust", // StatsIndicatorLoss+ "Frametime-Diagramm", // StatsIndicatorGraph+ "Dekodier- und Anzeigelatenz", // StatsIndicatorDelay+ "Videoqualität (QP)", // StatsIndicatorQp+ "Mikrofonstatus", // StatsIndicatorMic+ "Scannen Sie den QR-Code mit dem Smartphone, um dies bei Microsoft zu beheben, und drücken Sie dann Kreuz zum Wiederholen", // ScanQrToResolve+ "Kostenlos holen", // ClaimFree+ "Kostenlose Lizenz wird angefordert...", // Claiming+ "Spiel erfolgreich zu Ihrem Konto hinzugefügt!", // ClaimSuccess+ "Kostenloses Spiel konnte nicht angefordert werden: %s", // ClaimFailed+ "Dieses Spiel ist im Store nicht kostenlos", // ProductNotFree+ "Kostenloses Spiel. Drücken Sie Kreuz, um es zu Ihrem Konto hinzuzufügen und zu spielen", // FreeAcquireHint+ "DNS-Auflösung für Microsoft-Server fehlgeschlagen. Stelle auf der PS5 sicher, dass NanoDNS läuft und der primäre DNS auf die lokale IP gesetzt ist, um Internetzugriff zu behalten.", // DnsBlockedNanoDns+ "Dieses Microsoft-Konto hat noch kein Xbox-Profil. Melde dich auf xbox.com auf dem Smartphone oder PC an, um deinen Gamertag zu erstellen, und versuche es erneut.", // XboxProfileMissing+ "Warteschlange bereit! Spiel wird gestartet...", // QueueReadyAlert+ "Signalton bei Warteschlangenende", // QueueReadyNotification+ "Gespielt: %s", // PlaytimePlayed+ "Aktualisieren", // RefreshLibrary+ "Bibliothek wird aktualisiert...", // RefreshingLibrary+ "Dieses Xbox-Konto ist gesperrt oder gebannt. Details unter enforcement.xbox.com.", // XboxAccountBanned+ "Xbox Live wird im Land oder in der Region dieses Kontos nicht angeboten.", // XboxRegionNotSupported+ "Altersprüfung oder Zustimmung zu den Bedingungen erforderlich. Melde dich im Browser auf xbox.com an und versuche es erneut.", // XboxAdultVerificationRequired+ "Kinderkonto: Ein Erwachsener muss dieses Konto unter account.microsoft.com/family zu einer Microsoft-Familie hinzufügen.", // XboxChildAccountFamily+ "Anmeldung prüfen", // CheckSignIn+ "Prüfen", // RunCheck+ "Netzwerktest", // NetworkTest+ "Testen", // RunTest+ "Erfolge", // Achievements+ "Keine Erfolge", // NoAchievements+ "Gesperrt", // AchievementLocked+ "Geheimer Erfolg", // SecretAchievement+ "Wunschliste", // Wishlist+ "Zur Wunschliste hinzufügen", // AddWishlist+ "Von Wunschliste entfernen", // RemoveWishlist+ "Zur Wunschliste hinzugefügt", // AddedToWishlist+ "Von Wunschliste entfernt", // RemovedFromWishlist+ "%s ist im Angebot!", // WishlistOnSale+ "%s ist jetzt im Game Pass!", // WishlistInGamePass+ "Projekt unterstützen", // SupportProject+ "PSBox-Entwicklung unterstützen", // SupportTitle+ "PSBox ist ein Open-Source-Projekt, das mit viel Engagement entwickelt wird, um das beste Xbox Cloud Gaming-Erlebnis auf die PlayStation 5 zu bringen. Wenn dir die App gefällt und du die Weiterentwicklung unterstützen möchtest, spendiere mir gerne einen Kaffee auf Ko-Fi!", // SupportMessage+ "Ko-fi", // SupportKoFi+ "Mit dem Smartphone scannen", // ScanToDonate+ "Ton testen", // TestSound+ "Wunschliste ist leer", // WishlistEmpty+ // Loading tips+ "Touchpad: ↓ wischen (oder Touchpad + Options) für das Menü, ↑ für die Xbox-Taste", // TipTouchpadMenu+ "USB-Tastatur und -Maus an der Konsole werden in unterstützten Cloud-Spielen unterstützt", // TipKeyboardMouse+ "Kostenlose Spiele, Demos und Store-Angebote direkt in der App-Bibliothek sichern", // TipFreeStore+ "Problem aufgetreten? Öffnen Sie 'Problem melden', um einen QR-Code mit Konsolenprotokollen zu scannen", // TipBugReportQr+ "Gefällt Ihnen das Projekt? Unterstützen Sie die Weiterentwicklung via Ko-fi in den Einstellungen!", // TipSupportKofi+ "120-Hz-Videoausgabe in den Einstellungen für geringere Anzeigelatenz und flüssigere Steuerung aktivieren", // Tip120HzVideo+ "Stick-Totzone in den Einstellungen kalibrieren, um Stick-Drift zu verhindern und Präzision zu verbessern", // TipAnalogDeadzone+ "Integriertes DualSense-Mikrofon für Party- und Multiplayer-Sprachchat verwenden", // TipDualSenseMic+ // Settings descriptions+ "Ändert die Sprache der Benutzeroberfläche sowie die bevorzugte Audio- und Untertitelsprache in Cloud-Spielen", // SettingDescLanguage+ "Legt die maximale Streaming-Auflösung fest (1080p, 720p oder Beste). Wird beim nächsten Spielstart wirksam", // SettingDescResolution+ "Wählt die Microsoft-Rechenzentrumsregion für das Streaming aus (Automatisch oder bestimmte Regionen)", // SettingDescRegion+ "Passt die innere Totzone der DualSense-Analogsticks an, um Drift und unbeabsichtigte Bewegungen zu vermeiden", // SettingDescDeadzone+ "Aktiviert oder deaktiviert die Impuls-Trigger-Vibration an den adaptiven DualSense-Triggern L2 und R2", // SettingDescTriggerRumble+ "Wechselt die Tastenbelegung für Bestätigen und Zurück zwischen Kreuz (westlich) und Kreis (japanisch)", // SettingDescConfirmButton+ "Konfiguriert Farbe und Verhalten der Lichtleiste des DualSense-Controllers beim Navigieren und Spielen", // SettingDescLightBar+ "Prüft und installiert offizielle App-Updates automatisch direkt auf der Konsole ohne PC", // SettingDescUpdates+ "Ermöglicht die Xbox-Konto-Anmeldung über eine andere Region für alternative Spielkataloge", // SettingDescLoginCountry+ "Aktiviert 120-Hz-Videoausgabe auf Ihrer Konsole für minimale Eingabelatenz und höhere Bildwiederholrate", // SettingDescHighRefresh+ "Legt die maximale Bitrate für das Videostreaming fest, um Bildqualität zu optimieren oder Daten zu sparen", // SettingDescBitrateCap+ "Regelt die Gesamtlautstärke während der Spielsitzungen im Cloud-Streaming", // SettingDescGameVolume+ "Weist Tasten der USB- oder Bluetooth-Tastatur den entsprechenden Xbox-Controller-Tasten beim Spielen zu", // SettingDescKeyboardKeys+ "Wechselt zwischen Fenster- und Vollbildmodus auf unterstützten Desktop-Plattformen", // SettingDescDisplayMode+ "Öffnet den Test- und Kalibrierungsbildschirm für alle Tasten und Achsen des angeschlossenen Controllers", // SettingDescControllerButtons+ "Nutzt die DualSense-Bewegungssensoren zur Unterstützung des analogen Zielens in Shooter- und Actionspielen", // SettingDescGyro+ "Spielt einen Signalton ab, wenn die Wartezeit in der xCloud-Warteschlange endet und das Spiel bereit ist", // SettingDescQueueReady+ "Führt eine Diagnose der Xbox Live-Anmeldung durch und prüft Zugriffstoken, Profil und Abonnements", // SettingDescCheckSignIn+ "Misst Ping (RTT) und Jitter zu Cloud-Gaming-Rechenzentren in mehreren weltweiten Regionen", // SettingDescNetworkTest+ "Zeigt einen QR-Code, um den Entwickler via Ko-fi zu unterstützen und die Pflege des Projekts zu sichern", // SettingDescSupportProject+ "Neuigkeiten", // WhatsNew+ "Neuigkeiten", // WhatsNewTitle+ "Controller-Lautsprecher", // PadSpeakerVolume+ "Stumm", // Mute+ "Web-Steuerung", // WebControlTitle+ "Über Smartphone verbinden", // WebControlSubtitle+ "Mit demselben WLAN verbinden, um zu suchen, Tasten zu belegen, das Smartphone als Controller zu nutzen, Fehler zu melden oder Logs anzusehen.", // WebControlDesc+ "Videodekodierung", // VideoDecoder+ "Hardware (Empfohlen)", // VideoDecoderHw+ "Software (CPU)", // VideoDecoderSw+ "Wählt Hardware-Dekodierung (libSceVideodec2 auf PS5, HWAccel auf Desktop) oder Software-Dekodierung (CPU)", // SettingDescVideoDecoder+ "Audio-zu-Haptik", // AudioHaptics+ "Wandelt tiefe Audiofrequenzen in DualSense-Haptik-Vibrationen um", // SettingDescAudioHaptics+ "Touchpad-Kurzbefehle", // TouchpadShortcuts+ "Konfiguriert Wischgesten sowie Links- und Rechtsklick auf dem DualSense-Touchpad", // SettingDescTouchpadShortcuts+ "Nach oben wischen (↑)", // TouchpadSwipeUp+ "Nach unten wischen (↓)", // TouchpadSwipeDown+ "Nach links wischen (←)", // TouchpadSwipeLeft+ "Nach rechts wischen (→)", // TouchpadSwipeRight+ "Linksklick", // TouchpadClickLeft+ "Rechtsklick", // TouchpadClickRight+ "Deaktiviert", // TouchpadActNone+ "Spielmenü", // TouchpadActGameMenu+ "Xbox-Taste", // TouchpadActXboxButton+ "Statistiken umschalten", // TouchpadActToggleStats+ "Mikrofon stumm/aktiv", // TouchpadActToggleMic+ "Gyro-Modus wechseln", // TouchpadActCycleGyro+ "Trigger-Profil wechseln", // TouchpadActCycleTrigger+ "Touchpad + Options öffnet immer das Spielmenü", // TouchpadHelp+ "Standardeinstellungen wiederherstellen", // ResetSettings+ "Setzt alle Einstellungen auf die Werkseinstellungen zurück. 5 Sekunden ✕ gedrückt halten zur Bestätigung.", // SettingDescResetSettings+ "Einstellungen auf Standardwerte zurückgesetzt.", // SettingsResetNotice+ "Halten zum Zurücksetzen", // HoldToReset+ "Bibliothek ist bereits aktuell", // LibraryUpToDate+ "Bibliothek aktualisiert (%s neue Spiele)", // LibraryUpdatedCount+ "Offline-Modus", // OfflineMode+ "Preview-Funktionen (xCloud)", // PreviewFeatures+ "Aktiviert Preview-Client-Funktionen und werbefinanziertes Free-to-Play-Cloud-Streaming für Konten ohne Game Pass.", // SettingDescPreviewFeatures+ "Erfordert Xbox Game Pass Ultimate für Cloud-Streaming", // GamePassRequired+ "In Warteschlange (Wartezeit unbestimmt • wartet seit %s)", // InQueueIndeterminate+ "In Warteschlange (geschätzte Wartezeit: %s • wartet seit %s)", // InQueueEstimated+ "Um kostenlose Spiele außer Fortnite ohne Game Pass zu streamen, aktivieren Sie 'Preview-Funktionen' in den App-Einstellungen und auf xbox.com/play.", // F2pPreviewRequiredDesc+ "Dieses Konto muss 'Preview-Funktionen' im Profil auf xbox.com/play aktivieren, um werbefinanziertes Free-to-Play-Streaming freizuschalten.", // F2pPreviewAccountNeededDesc+};diff --git a/src/ui/i18n/strings_en.inc b/src/ui/i18n/strings_en.incnew file mode 100644index 0000000..ac7e29d--- /dev/null+++ b/src/ui/i18n/strings_en.inc@@ -0,0 +1,418 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+constexpr Column kEnglish = {+ "PSBox Cloud Gaming", // AppName+ "PSBOX CLOUD GAMING", // CloudGaming+ "Signing in...", // SigningIn+ "Getting a sign-in code...", // RequestingCode+ "Loading your games...", // LoadingGames+ "Sign in to play", // SignInTitle+ "On your phone or computer, go to", // SignInStep1+ "and enter this code", // SignInStep2+ "Scan to open the page, then enter the code", // SignInScan+ "Waiting for you to sign in...", // SignInWaiting+ "Jump back in", // JumpBackIn+ "Play", // Play+ "Back", // Back+ "Select", // Select+ "Sign out", // SignOut+ "Cancel", // Cancel+ "Try again", // TryAgain+ "Getting your game ready", // GettingReady+ "You're in the queue. Estimated wait: %s", // InQueue+ "Connecting...", // Connecting+ "Starting the stream...", // StartingStream+ "Touchpad: ↓ this menu · ↑ Xbox button", // MenuGestureHint+ "Stream ended", // StreamEnded+ "Something went wrong", // ErrorTitle+ "Signed in as %s", // SignedInAs+ "No games to show yet", // NoGames+ "By %s", // PublisherBy+ "Settings", // Settings+ "Language", // Language+ "Stream resolution", // Resolution+ "Server region", // Region+ "Automatic (%s)", // RegionAuto+ "1080p (Full HD)", // Res1080+ "720p (uses less data)", // Res720+ "Best (Auto)", // ResBest+ "Resolution and region apply to the next game you start.", // SettingsNote+ "Change", // Change+ "Adjust", // Adjust+ "Hold to sign out", // HoldSignOut+ "Keep holding to sign out (%s)", // SigningOutIn+ "Sign-in failed: %s", // SignInFailed+ "Sign-in not completed in the browser. Use a personal Microsoft account, complete any security prompts/2FA, and grant access to the app.", // SignInInteractionRequired+ "Could not load the game list: %s", // LibraryFailed+ "Could not start the stream: %s", // StreamFailed+ "No input for a while: you will be disconnected in %s seconds", // IdleWarning+ "My games", // YourGames+ "Not available on your account", // NotPlayable+ "Game Pass", // TabGamePass+ "Search", // TabSearch+ "Type the name of a game", // SearchHint+ "No games found", // NoResults+ "%s results", // ResultsCount+ "Space", // KeySpace+ "Delete", // KeyDelete+ "Clear", // KeyClear+ "%s games", // GamesCount+ "Type", // KeyType+ "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 My games.", // BuyHint+ "Scan to open the store page", // ScanToBuy+ "Search in %s", // SearchIn+ "FREE", // Free+ "Hide", // Hide+ "Show", // Unhide+ "Hidden", // HiddenSection+ "Square shows a game again", // HiddenHint+ "Hidden: find it under Hidden, at the end of this tab", // HiddenToast+ "Shown again", // UnhiddenToast+ "Sort: %s", // SortLabel+ "Recent first", // SortRecent+ "A-Z", // SortAZ+ "By console", // SortConsole+ "Sort", // SortHint+ "Free", // FilterFree+ "Lowest price", // FilterCheapest+ "All consoles", // FilterAllConsoles+ "1 game", // OneGame+ "Sections", // Sections+ "Updating the game list...", // UpdatingList+ "Game menu", // MenuTitle+ "Statistics", // MenuStats+ "On", // On+ "Off", // Off+ "Stream resolution", // MenuResolution+ "Leave game", // MenuLeave+ "Latency", // StatLatency+ "Bitrate", // StatBitrate+ "Frame rate", // StatFrameRate+ "Packet loss", // StatLoss+ "Region", // StatRegion+ "Decoding", // StatDecode+ "The server may keep the current quality", // ResolutionNote+ "Sharpness", // MenuSharpness+ "Off", // SharpOff+ "Low", // SharpLow+ "Medium", // SharpMedium+ "High", // SharpHigh+ "Stick dead zone", // Deadzone+ "Trigger vibration", // TriggerRumble+ "Confirm button", // ConfirmButton+ "On", // Activated+ "Off", // Deactivated+ "Version %s available", // UpdateAvailable+ "Controllers", // Controllers+ "Controller %s connected", // PadConnected+ "Controller %s disconnected", // PadDisconnected+ "Block smoothing", // MenuDeband+ "On screen after", // StatOnScreen+ "Connection lost: reconnecting...", // Reconnecting+ "Reconnected", // Reconnected+ "Light bar", // LightBar+ "Upscaling", // MenuUpscaler+ "AI (Anime4K)", // UpscalerAi+ "Free to play", // FreeToPlay+ "Get it once, free, on xbox.com or in the Xbox app (scan the code with your phone), then press Play.", // FreeHint+ "Scan to get it free", // ScanToGet+ "%s is not on your account yet. It is free: scan the code on its page, choose Get, then try again (it can take a minute).", // NoEntitlementFree+ "Your account can't play %s: it is not in your subscription or not bought.", // NoEntitlement+ "My consoles", // TabConsoles+ "On", // ConsoleOn+ "Sleeping", // ConsoleSleeping+ "Off", // ConsoleOff+ "Looking for your consoles...", // ConsolesLoading+ "No Xbox found yet", // NoConsoles+ "Play your own Xbox here: its screen, games and apps.", // ConsolesHint+ "Waking up your Xbox...", // WakingConsole+ "%s did not answer. Check that Remote features are on and the power mode is Sleep, or turn it on, then try again.", // WakeFailed+ "On your Xbox, sign in with this same Microsoft account.", // ConsoleStep1+ "Settings > Devices & connections > Remote features: turn on remote features.", // ConsoleStep2+ "Settings > General > Power options: choose Sleep, so it wakes up by itself.", // ConsoleStep3+ "Scan for Microsoft's help", // ScanForHelp+ "Search again", // SearchAgain+ "Xbox button", // MenuXboxButton+ "End the stream", // MenuEndStream+ "The stream was ended on the Xbox", // EndedOnXbox+ "Another device took over the stream", // EndedByOtherDevice+ "The Xbox was turned off", // EndedXboxOff+ "%s got the request but its Remote Play didn't start. Restart it: hold the power button on the console for 10 seconds, turn it back on, then try again.", // StreamingStuck+ "Touchpad: swipe ↓ for the menu, ↑ for the Xbox button", // GestureHint+ "FSR + clean-up", // UpscalerFsrClean+ "AI + clean-up", // UpscalerAiClean+ "Auto (%s)", // DebandAuto+ "Update now? The app restarts by itself when it's done.", // UpdatePrompt+ "Update now", // UpdateNow+ "Not now", // NotNow+ "Updates", // Updates+ "Up to date (%s)", // UpToDate+ "%s available: update", // UpdateReady+ "Checking...", // UpdateChecking+ "Updating to %s", // UpdatingTo+ "Downloading... %s", // UpdateDownloading+ "Checking the signature...", // UpdateVerifying+ "Installing...", // UpdateInstalling+ "Updated. Restarting...", // UpdateRestarting+ "PSBox updated: open the app again", // UpdateReopen+ "Update failed: nothing was changed", // UpdateFailed+ "Game colour", // LightBarGame+ "Custom colour", // LightBarCustom+ "Light bar colour", // LightBarColour+ "Left stick or D-pad: colour L2 / R2: brightness", // ColourPickerHelp+ "Light", // TriggerLight+ "Medium", // TriggerMedium+ "Strong", // TriggerStrong+ "Max", // TriggerMax+ "Intensity", // TriggerIntensity+ "Frequency", // TriggerFrequency+ "Low", // FrequencyLow+ "High", // FrequencyHigh+ "Press L2 / R2 to feel it: the deeper, the stronger the game would ask", // TriggerTestHelp+ "Level %s", // TriggerLevel+ "Left stick", // StickLeft+ "Right stick", // StickRight+ "Stick position", // StickPosition+ "What the game gets", // StickGameGets+ "L1 / R1: choose the stick D-pad ← / →: adjust Move the sticks to see it", // StickTestHelp+ "Resistance", // TriggerResistance+ "Style", // TriggerStyle+ "Vibration", // StyleVibration+ "Force pulses", // StylePulses+ "Mode", // FilterMode+ "Genre", // FilterGenre+ "Language", // FilterLanguage+ "All modes", // ModeAll+ "Single player", // ModeSingle+ "Online multiplayer", // ModeOnlineMulti+ "Online co-op", // ModeOnlineCoop+ "Local / split screen", // ModeLocal+ "All genres", // GenreAll+ "Any language", // LanguageAll+ "English", // LanguageNoun+ "Subtitles in %s", // LangSubtitles+ "Audio in %s", // LangAudio+ "Game settings", // GameSettings+ "Profile", // Profile+ "Default", // ProfileDefault+ "Custom", // ProfileCustom+ "Reset to default", // ResetToDefault+ "Publisher", // FilterPublisher+ "All publishers", // PublisherAll+ "Indies & Others", // PublisherIndies+ "Friends playing now", // FriendsPlayingNow+ "Microphone", // MenuMicrophone+ "Muted", // MicMuted+ "Active", // MicActive+ "Audio output", // MenuAudioOutput+ "TV", // AudioRouteTv+ "DualSense Speaker", // AudioRoutePad+ "Report a problem", // ReportProblem+ "Scan it with your phone: GitHub's bug form opens, filled in. You review it before sending it.", // ReportScan+ "It includes the app's version, the error and lines of its log, without personal data.", // ReportIncludes+ "PSBox closed unexpectedly last time", // CrashedLastTime+ "Sign-in country", // LoginCountry+ "Off (this console's)", // LoginCountryOff+ "Sign in as another country", // TryOtherCountry+ "xCloud will be told the sign-in comes from the chosen country. Microsoft doesn't allow this: use it at your own risk. Games may then come from servers far away, with more delay. You can change it later in Settings.", // LoginCountryWarning+ "xCloud refused the sign-in. Cloud gaming may not be offered in your country, or the account may not have a Game Pass plan with cloud gaming.", // RegionRefused+ "xCloud refused the sign-in, even as %s. The account probably doesn't have a Game Pass plan with cloud gaming.", // RegionRefusedAs+ "Brazil", // CountryBR+ "Japan", // CountryJP+ "South Korea", // CountryKR+ "Poland", // CountryPL+ "United States", // CountryUS+ "Secure connections were refused because the PS5's date and time look wrong (it says %s). Set them in Settings > System > Date and Time, then try again.", // ClockWrong+ "A secure connection was refused: something on the network (a DNS server, proxy or filter) is answering for Microsoft's sites. Try without it, then try again.", // ConnectionIntercepted+ "PS5 date and time look wrong (%s): some content can't load. Set them in Settings > System > Date and Time.", // ClockWrongNotice+ "Your sign-in couldn't be saved on the console, so it will be asked again next time. Please report it (Settings > △).", // SignInNotSaved+ "Estimated wait: %s s", // QueueSeconds+ "Estimated wait: %s min", // QueueMinutes+ "120 Hz output (VRR)", // HighRefresh+ "On (in games)", // HighRefreshOn+ "Unstable connection", // ConnectionUnstable+ "Session: %s", // SessionSummary+ "Maximum bitrate", // BitrateCap+ "Automatic", // BitrateAuto+ "Game volume", // GameVolume+ "Keyboard: F12 this menu · Home Xbox button", // MenuKeyHint+ "Mouse & keyboard", // FilterMouseKeyboard+ "Mouse and keyboard", // MouseKeyboardSupport+ "Keyboard and mouse: player %s", // KeyboardPlayer+ "You're in the queue.", // InQueueNoEstimate+ "Keyboard keys", // KeyboardKeys+ "D-pad", // DPad+ "Press a key or mouse button", // PressKey+ "%s is kept by the app", // KeyReserved+ "Change", // ChangeKey+ "Clear", // ClearKey+ "The mouse moves the right stick and a wheel notch presses Triangle. F12 (menu), Home (Xbox button) and 1-4 (player) are kept by the app.", // KeysHelp+ "Gyro aiming", // Gyro+ "Always", // GyroAlways+ "While aiming (L2)", // GyroAiming+ "Gyro intensity", // GyroIntensity+ "Secure connections were refused because this computer's date and time look wrong (it says %s). Correct them in the system's settings, then try again.", // ClockWrongPc+ "This computer's date and time look wrong (%s): some content can't load. Correct them in the system's settings.", // ClockWrongNoticePc+ "Off (this computer's)", // LoginCountryOffPc+ "Open in the browser", // OpenInBrowser+ "%s available: download", // UpdateReadyPc+ "Menu: START + BACK or F12 · Xbox button: Guide or Home", // GestureHintButtons+ "START + BACK or F12: this menu · Guide or Home: Xbox button", // MenuButtonHint+ "Display mode", // DisplayMode+ "Window", // DisplayWindow+ "Fullscreen", // DisplayFullscreen+ "Quit PSBox?", // QuitTitle+ "Quit", // QuitConfirm+ "Controller buttons", // ControllerButtons+ "Press the button for %s", // PadPressButton+ "Missing a button: %s. Give each one a button, or reset or discard the changes.", // PadMissing+ "Discard changes", // DiscardChanges+ "Only the game sees this: the app's menus keep the buttons as they are. Picking a button used by another swaps the two.", // PadHelp+ "Plan", // FilterPlan+ "My plan", // PlanMine+ "All plans", // PlanAll+ "Included with Game Pass %s", // IncludedWithPlan+ "Touchpad as mouse", // TouchpadMouse+ "Favourites", // Favorites+ "Add to favourites", // AddFavorite+ "Remove from favourites", // RemoveFavorite+ "Added to favourites", // AddedToFavorites+ "Removed from favourites", // RemovedFromFavorites+ "Game language", // GameLanguage+ "Monthly cloud gaming limit reached", // MonthlyLimitExceeded+ "Playtime remaining", // PlaytimeRemaining+ "%s h remaining", // HoursRemaining+ "Less than 2 h remaining", // PlaytimeWarning+ "Trigger profile", // TriggerProfile+ "Standard", // TriggerProfileStd+ "Shooter (Hair Trigger)", // TriggerProfileShooter+ "Racing (ABS)", // TriggerProfileRacing+ "Storage %s is not writable: sign-in and settings will not be saved", // StorageNotWritable+ "FTP: run 'chmod 777 %s' or delete the folder and relaunch", // StorageFixHint+ "Customize indicators", // StatsCustomize+ "FPS & Resolution", // StatsIndicatorFps+ "Bitrate", // StatsIndicatorBitrate+ "Latency (RTT)", // StatsIndicatorLatency+ "Packet loss", // StatsIndicatorLoss+ "Frametime graph", // StatsIndicatorGraph+ "Decode & display latency", // StatsIndicatorDelay+ "Video quality (QP)", // StatsIndicatorQp+ "Microphone status", // StatsIndicatorMic+ "Scan the QR code on your phone to resolve this with Microsoft, then press Cross to try again", // ScanQrToResolve+ "Get Free", // ClaimFree+ "Claiming free license...", // Claiming+ "Game added to your account!", // ClaimSuccess+ "Failed to claim free game: %s", // ClaimFailed+ "This game is not free in the store", // ProductNotFree+ "Free game. Press Cross to add to your account and start playing", // FreeAcquireHint+ "DNS lookup failed for Microsoft servers. If you are blocking Sony updates on PS5, make sure you are running NanoDNS with Primary DNS set to your local IP to keep internet access.", // DnsBlockedNanoDns+ "This Microsoft account has no Xbox profile yet. Sign in to xbox.com on your phone or PC to set up your Gamertag, then try again.", // XboxProfileMissing+ "Queue ready! Starting game...", // QueueReadyAlert+ "Queue ready chime", // QueueReadyNotification+ "Played: %s", // PlaytimePlayed+ "Refresh", // RefreshLibrary+ "Refreshing library...", // RefreshingLibrary+ "This Xbox account is suspended or banned. Visit enforcement.xbox.com for details.", // XboxAccountBanned+ "Xbox Live is not offered in this account's country or region.", // XboxRegionNotSupported+ "Age verification or terms acceptance is required. Sign in to xbox.com in a browser, then try again.", // XboxAdultVerificationRequired+ "Child account: an adult must add this account to a Microsoft family at account.microsoft.com/family.", // XboxChildAccountFamily+ "Check my sign-in", // CheckSignIn+ "Run check", // RunCheck+ "Network test", // NetworkTest+ "Run test", // RunTest+ "Achievements", // Achievements+ "No achievements", // NoAchievements+ "Locked", // AchievementLocked+ "Secret achievement", // SecretAchievement+ "Wishlist", // Wishlist+ "Add to wishlist", // AddWishlist+ "Remove from wishlist", // RemoveWishlist+ "Added to wishlist", // AddedToWishlist+ "Removed from wishlist", // RemovedFromWishlist+ "%s is on sale!", // WishlistOnSale+ "%s joined Game Pass!", // WishlistInGamePass+ "Support the project", // SupportProject+ "Support PSBox Development", // SupportTitle+ "PSBox is an open-source project passionately maintained to bring the best Xbox Cloud Gaming experience to PlayStation 5. If you enjoy the app and would like to support ongoing development, frequent updates and new features, consider buying me a coffee on Ko-Fi!", // SupportMessage+ "Ko-fi", // SupportKoFi+ "Scan with your phone to support", // ScanToDonate+ "Test sound", // TestSound+ "Wishlist is empty", // WishlistEmpty+ // Loading tips+ "Touchpad: swipe ↓ (or Touchpad + Options) for the menu, ↑ for the Xbox button", // TipTouchpadMenu+ "USB keyboard and mouse plugged into the console are supported in enabled cloud games", // TipKeyboardMouse+ "Claim free games, trials, and discover store promotions directly from the app library", // TipFreeStore+ "Encountered an issue? Open Bug Report to scan a QR code with auto-attached console logs", // TipBugReportQr+ "Enjoying the project? Support future development via Ko-fi in the Settings tab!", // TipSupportKofi+ "Enable 120 Hz display output in Settings for reduced frame latency and smoother response", // Tip120HzVideo+ "Calibrate DualSense stick dead zones in Settings to eliminate stick drift and improve precision", // TipAnalogDeadzone+ "Use the DualSense built-in microphone for party and multiplayer game voice chat", // TipDualSenseMic+ // Settings descriptions+ "Changes the language of the application interface and the preferred audio and subtitles in cloud games", // SettingDescLanguage+ "Sets the maximum streaming video resolution (1080p, 720p, or Best available). Takes effect on the next launch", // SettingDescResolution+ "Selects the Microsoft datacenter region for streaming (Automatic or specific regions). Takes effect on the next launch", // SettingDescRegion+ "Adjusts the inner dead zone of DualSense analog sticks to prevent stick drift and unintended movement", // SettingDescDeadzone+ "Enables or disables impulse trigger vibration emulation on DualSense L2 and R2 adaptive triggers", // SettingDescTriggerRumble+ "Toggles the confirm and back button layout between Cross (Western style) and Circle (Japanese style)", // SettingDescConfirmButton+ "Configures the light bar color and behavior of your DualSense controller during browsing and gameplay", // SettingDescLightBar+ "Checks for and automatically installs official app updates directly on your console without needing a PC", // SettingDescUpdates+ "Allows signing in to your Xbox account via a different geographic region to access alternative catalogs", // SettingDescLoginCountry+ "Enables 120 Hz video output on your console for lower display lag and reduced input latency", // SettingDescHighRefresh+ "Sets the maximum bandwidth limit for video streaming, ensuring higher visual fidelity or saving network data", // SettingDescBitrateCap+ "Adjusts the master audio volume level played during game streaming sessions", // SettingDescGameVolume+ "Maps USB or Bluetooth keyboard keys to the corresponding Xbox controller buttons during gameplay", // SettingDescKeyboardKeys+ "Toggles between windowed and fullscreen display mode on supported desktop platforms", // SettingDescDisplayMode+ "Opens the response test and calibration screen for all buttons and axes on your connected controller", // SettingDescControllerButtons+ "Enables DualSense motion sensors to assist with analog aiming in shooter and action games", // SettingDescGyro+ "Plays a distinctive chime when your wait in the xCloud queue finishes and your game is ready", // SettingDescQueueReady+ "Runs a complete diagnostic on your Xbox Live sign-in, validating access tokens, profile, and subscriptions", // SettingDescCheckSignIn+ "Measures ping (RTT) and jitter to cloud gaming datacenters across multiple global regions", // SettingDescNetworkTest+ "Displays a QR Code to support the developer via Ko-fi and help keep the project actively maintained", // SettingDescSupportProject+ "What's New", // WhatsNew+ "What's New", // WhatsNewTitle+ "Controller speaker", // PadSpeakerVolume+ "Mute", // Mute+ "Web Control", // WebControlTitle+ "Connect from your phone", // WebControlSubtitle+ "Connect to the same Wi-Fi to type search, remap buttons, use your phone as a virtual controller, report issues or view logs.", // WebControlDesc+ "Video Decoder", // VideoDecoder+ "Hardware (Recommended)", // VideoDecoderHw+ "Software (CPU)", // VideoDecoderSw+ "Selects hardware decoding (libSceVideodec2 on PS5, HWAccel on Desktop) or CPU software decoding", // SettingDescVideoDecoder+ "Audio-to-Haptics", // AudioHaptics+ "Converts low-frequency game audio into DualSense haptic rumble kicks", // SettingDescAudioHaptics+ "Touchpad shortcuts", // TouchpadShortcuts+ "Configures swipe gestures and left/right click actions on the DualSense touchpad", // SettingDescTouchpadShortcuts+ "Swipe Up (↑)", // TouchpadSwipeUp+ "Swipe Down (↓)", // TouchpadSwipeDown+ "Swipe Left (←)", // TouchpadSwipeLeft+ "Swipe Right (→)", // TouchpadSwipeRight+ "Left Click", // TouchpadClickLeft+ "Right Click", // TouchpadClickRight+ "Disabled", // TouchpadActNone+ "In-game menu", // TouchpadActGameMenu+ "Xbox button", // TouchpadActXboxButton+ "Toggle stats", // TouchpadActToggleStats+ "Mute/unmute mic", // TouchpadActToggleMic+ "Cycle gyro mode", // TouchpadActCycleGyro+ "Cycle trigger profile", // TouchpadActCycleTrigger+ "Touchpad + Options always opens the in-game menu", // TouchpadHelp+ "Restore default settings", // ResetSettings+ "Restores all settings to factory defaults. Hold Cross for 5 seconds to confirm.", // SettingDescResetSettings+ "Settings restored to factory defaults.", // SettingsResetNotice+ "Hold to reset", // HoldToReset+ "Library is already up to date", // LibraryUpToDate+ "Library updated (%s new games)", // LibraryUpdatedCount+ "Offline mode", // OfflineMode+ "Preview features (xCloud)", // PreviewFeatures+ "Enables preview client features and ad-supported Free-to-Play cloud streaming for accounts without Game Pass.", // SettingDescPreviewFeatures+ "Requires Xbox Game Pass Ultimate for cloud streaming", // GamePassRequired+ "In queue (wait time indeterminate • waiting for %s)", // InQueueIndeterminate+ "In queue (estimated wait: %s • waiting for %s)", // InQueueEstimated+ "To stream free-to-play games beyond Fortnite without Game Pass, enable 'Preview Features' in app Settings and on xbox.com/play.", // F2pPreviewRequiredDesc+ "This account needs to enable 'Preview Features' in its profile on xbox.com/play to unlock ad-supported free-to-play streaming.", // F2pPreviewAccountNeededDesc+};diff --git a/src/ui/i18n/strings_es.inc b/src/ui/i18n/strings_es.incnew file mode 100644index 0000000..f96002e--- /dev/null+++ b/src/ui/i18n/strings_es.inc@@ -0,0 +1,418 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+constexpr Column kSpanish = {+ "PSBox Cloud Gaming",+ "PSBOX CLOUD GAMING",+ "Iniciando sesión...",+ "Obteniendo un código de inicio de sesión...",+ "Cargando tus juegos...",+ "Inicia sesión para jugar",+ "En tu teléfono u ordenador, ve a",+ "e introduce este código",+ "Escanea para abrir la página e introduce el código",+ "Esperando a que inicies sesión...",+ "Seguir jugando",+ "Jugar",+ "Atrás",+ "Seleccionar",+ "Cerrar sesión",+ "Cancelar",+ "Reintentar",+ "Preparando tu juego",+ "Estás en la cola. Espera estimada: %s",+ "Conectando...",+ "Iniciando el streaming...",+ "Panel táctil: ↓ este menú · ↑ botón Xbox",+ "Streaming finalizado",+ "Algo salió mal",+ "Sesión iniciada como %s",+ "Todavía no hay juegos para mostrar",+ "De %s",+ "Ajustes",+ "Idioma",+ "Resolución del streaming",+ "Región del servidor",+ "Automática (%s)",+ "1080p (Full HD)",+ "720p (usa menos datos)",+ "Mejor (Auto)",+ "La resolución y la región se aplican al próximo juego que inicies.",+ "Cambiar",+ "Ajustar",+ "Mantén para cerrar sesión",+ "Sigue manteniendo para cerrar sesión (%s)",+ "Error al iniciar sesión: %s",+ "El inicio de sesión no se completó en el navegador. Usa una cuenta personal de Microsoft, completa la verificación/2FA y autoriza la app.",+ "No se pudo cargar la lista de juegos: %s",+ "No se pudo iniciar el streaming: %s",+ "Sin actividad: se te desconectará en %s segundos",+ "Mis juegos",+ "No disponible en tu cuenta",+ "Game Pass",+ "Buscar",+ "Escribe el nombre de un juego",+ "No se encontraron juegos",+ "%s resultados",+ "Espacio",+ "Borrar",+ "Limpiar",+ "%s juegos",+ "Escribir",+ "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 Mis juegos.",+ "Escanea para abrir la página de la tienda",+ "Buscar en %s",+ "GRATIS",+ "Ocultar",+ "Mostrar",+ "Ocultos",+ "\xE2\x96\xA1 vuelve a mostrar un juego",+ "Oculto: está en Ocultos, al final de esta pestaña",+ "Visible de nuevo",+ "Ordenar: %s",+ "Recientes primero",+ "A-Z",+ "Por consola",+ "Ordenar",+ "Gratis",+ "Menor precio",+ "Todas las consolas",+ "1 juego",+ "Secciones",+ "Actualizando la lista de juegos...",+ "Menú del juego",+ "Estadísticas",+ "Activado",+ "Desactivado",+ "Resolución del stream",+ "Salir del juego",+ "Latencia",+ "Tasa de bits",+ "Fotogramas por segundo",+ "Pérdida de paquetes",+ "Región",+ "Decodificación",+ "El servidor puede mantener la calidad actual",+ "Nitidez",+ "Desactivada",+ "Baja",+ "Media",+ "Alta",+ "Zona muerta del stick",+ "Vibración en los gatillos",+ "Botón de confirmar",+ "Activada",+ "Desactivada",+ "Versión %s disponible",+ "Mandos",+ "Mando %s conectado",+ "Mando %s desconectado",+ "Suavizado de bloques",+ "En pantalla tras",+ "Conexión perdida: reconectando...",+ "Reconectado",+ "Barra de luz",+ "Escalado",+ "IA (Anime4K)",+ "Gratis para jugar",+ "Consíguelo una vez, gratis, en xbox.com o en la app de Xbox (escanea el código con el móvil) y luego pulsa Jugar.",+ "Escanea para conseguirlo gratis",+ "%s aún no está en tu cuenta. Es gratis: escanea el código en su página, elige Obtener y vuelve a intentarlo (puede tardar un minuto).",+ "Tu cuenta no puede jugar a %s: no está en tu suscripción o no lo has comprado.",+ "Mis consolas",+ "Encendida",+ "En reposo",+ "Apagada",+ "Buscando tus consolas...",+ "Aún no se encontró ninguna Xbox",+ "Juega en tu propia Xbox desde aquí: su pantalla, juegos y aplicaciones.",+ "Encendiendo tu Xbox...",+ "%s no respondió. Comprueba que las Funciones remotas estén activadas y el modo de energía sea Suspensión, o enciéndela, y vuelve a intentarlo.",+ "En tu Xbox, inicia sesión con esta misma cuenta Microsoft.",+ "Configuración > Dispositivos y conexiones > Funciones remotas: activa las funciones remotas.",+ "Configuración > General > Opciones de energía: elige Suspensión, para que se encienda sola.",+ "Escanea para ver la ayuda de Microsoft",+ "Buscar de nuevo",+ "Botón Xbox",+ "Terminar la transmisión",+ "La transmisión se terminó en la Xbox",+ "Otro dispositivo tomó la transmisión",+ "La Xbox se apagó",+ "%s recibió la solicitud, pero su juego remoto no se inició. Reiníciala: mantén pulsado el botón de encendido de la consola 10 segundos, enciéndela de nuevo y vuelve a intentarlo.",+ "Panel táctil: desliza ↓ para el menú, ↑ para el botón Xbox",+ "FSR + limpieza",+ "IA + limpieza",+ "Auto (%s)",+ "¿Actualizar ahora? La app se reinicia sola al terminar.",+ "Actualizar ahora",+ "Ahora no",+ "Actualizaciones",+ "Al día (%s)",+ "%s disponible: actualizar",+ "Comprobando...",+ "Actualizando a %s",+ "Descargando... %s",+ "Comprobando la firma...",+ "Instalando...",+ "Actualizado. Reiniciando...",+ "PSBox actualizado: abre la app de nuevo",+ "La actualización falló: no se cambió nada",+ "Color del juego",+ "Color personalizado",+ "Color de la barra de luz",+ "Stick izquierdo o cruceta: color L2 / R2: brillo",+ "Suave",+ "Media",+ "Fuerte",+ "Máxima",+ "Intensidad",+ "Frecuencia",+ "Grave",+ "Aguda",+ "Pulsa L2 / R2 para sentirlo: cuanto más a fondo, más fuerte lo pediría el juego",+ "Nivel %s",+ "Stick izquierdo",+ "Stick derecho",+ "Posición real",+ "Lo que recibe el juego",+ "L1 / R1: elegir el stick Cruceta ← / →: ajustar Mueve los sticks para verlo",+ "Resistencia",+ "Estilo",+ "Vibración",+ "Pulsos de fuerza",+ "Modo",+ "Género",+ "Idioma",+ "Todos los modos",+ "Un jugador",+ "Multijugador en línea",+ "Cooperativo en línea",+ "Local / pantalla dividida",+ "Todos los géneros",+ "Cualquier idioma",+ "español",+ "Subtítulos en %s",+ "Doblado al %s",+ "Ajustes del juego",+ "Perfil",+ "Predeterminado",+ "Personalizado",+ "Restaurar predeterminado",+ "Distribuidora",+ "Todas las distribuidoras",+ "Indies y otras",+ "Amigos jugando ahora",+ "Micrófono",+ "Silenciado",+ "Activo",+ "Salida de audio",+ "TV",+ "Altavoz del mando",+ "Informar de un problema",+ "Escanéalo con el móvil: se abre el formulario de errores de GitHub, ya rellenado. Lo revisas antes de enviarlo.",+ "Incluye la versión de la app, el error y líneas del registro, sin datos personales.",+ "PSBox se cerró inesperadamente la última vez",+ "País de inicio de sesión",+ "Desactivado (el de la consola)",+ "Entrar como otro país",+ "Se le dirá a xCloud que el inicio de sesión viene del país elegido. Microsoft no lo permite: úsalo bajo tu propio riesgo. Los juegos pueden venir de servidores lejanos, con más retraso. Puedes cambiarlo luego en Ajustes.",+ "xCloud rechazó el inicio de sesión. Puede que el juego en la nube no se ofrezca en tu país o que la cuenta no tenga un plan de Game Pass con juego en la nube.",+ "xCloud rechazó el inicio de sesión, incluso como %s. Probablemente la cuenta no tenga un plan de Game Pass con juego en la nube.",+ "Brasil",+ "Japón",+ "Corea del Sur",+ "Polonia",+ "Estados Unidos",+ "Se rechazaron las conexiones seguras porque la fecha y la hora de la PS5 parecen incorrectas (indica %s). Ajústalas en Ajustes > Sistema > Fecha y hora y vuelve a intentarlo.",+ "Se rechazó una conexión segura: algo en la red (un servidor DNS, proxy o filtro) responde en lugar de los sitios de Microsoft. Prueba sin él y vuelve a intentarlo.",+ "La fecha y la hora de la PS5 parecen incorrectas (%s): parte del contenido no carga. Ajústalas en Ajustes > Sistema > Fecha y hora.",+ "No se pudo guardar el inicio de sesión en la consola, así que se pedirá de nuevo la próxima vez. Infórmalo (Ajustes > △).",+ "Espera estimada: %s s", // QueueSeconds+ "Espera estimada: %s min", // QueueMinutes+ "Salida 120 Hz (VRR)", // HighRefresh+ "Activada (en los juegos)", // HighRefreshOn+ "Conexión inestable", // ConnectionUnstable+ "Sesión: %s", // SessionSummary+ "Bitrate máximo", // BitrateCap+ "Automático", // BitrateAuto+ "Volumen del juego", // GameVolume+ "Teclado: F12 este menú · Inicio botón Xbox", // MenuKeyHint+ "Teclado y ratón", // FilterMouseKeyboard+ "Teclado y ratón", // MouseKeyboardSupport+ "Teclado y ratón: jugador %s", // KeyboardPlayer+ "Estás en la cola.", // InQueueNoEstimate+ "Teclas del teclado", // KeyboardKeys+ "Cruceta", // DPad+ "Pulsa una tecla o un botón del ratón", // PressKey+ "La app reserva %s", // KeyReserved+ "Cambiar", // ChangeKey+ "Borrar", // ClearKey+ "El ratón mueve el stick derecho y cada paso de la rueda pulsa Triángulo. F12 (menú), Inicio (botón Xbox) y 1-4 (jugador) las reserva la app.", // KeysHelp+ "Apuntado con giroscopio", // Gyro+ "Siempre", // GyroAlways+ "Al apuntar (L2)", // GyroAiming+ "Intensidad del giroscopio", // GyroIntensity+ "Se rechazaron las conexiones seguras porque la fecha y la hora de este ordenador parecen incorrectas (indica %s). Corrígelas en los ajustes del sistema y vuelve a intentarlo.", // ClockWrongPc+ "La fecha y la hora de este ordenador parecen incorrectas (%s): parte del contenido no carga. Corrígelas en los ajustes del sistema.", // ClockWrongNoticePc+ "Desactivado (el del ordenador)", // LoginCountryOffPc+ "Abrir en el navegador", // OpenInBrowser+ "%s disponible: descargar", // UpdateReadyPc+ "Menú: START + BACK o F12 · Botón Xbox: Guide o Inicio", // GestureHintButtons+ "START + BACK o F12: este menú · Guide o Inicio: botón Xbox", // MenuButtonHint+ "Modo de pantalla", // DisplayMode+ "Ventana", // DisplayWindow+ "Pantalla completa", // DisplayFullscreen+ "¿Salir de PSBox?", // QuitTitle+ "Salir", // QuitConfirm+ "Botones del mando", // ControllerButtons+ "Pulsa el botón para %s", // PadPressButton+ "Falta botón para: %s. Asigna uno a cada función, o restablece o descarta los cambios.", // PadMissing+ "Descartar cambios", // DiscardChanges+ "Solo el juego lo ve: los menús de la app usan los botones tal cual. Elegir un botón ya usado intercambia los dos.", // PadHelp+ "Plan", // FilterPlan+ "Mi plan", // PlanMine+ "Todos los planes", // PlanAll+ "Incluido con Game Pass %s", // IncludedWithPlan+ "Panel táctil como ratón", // TouchpadMouse+ "Favoritos", // Favorites+ "Añadir a favoritos", // AddFavorite+ "Quitar de favoritos", // RemoveFavorite+ "Añadido a favoritos", // AddedToFavorites+ "Eliminado de favoritos", // RemovedFromFavorites+ "Idioma del juego", // GameLanguage+ "Límite mensual de juego en la nube alcanzado", // MonthlyLimitExceeded+ "Tiempo de juego restante", // PlaytimeRemaining+ "%s h restantes", // HoursRemaining+ "Menos de 2 h restantes", // PlaytimeWarning+ "Perfil de gatillos", // TriggerProfile+ "Estándar", // TriggerProfileStd+ "Disparos (Hair Trigger)", // TriggerProfileShooter+ "Carreras (ABS)", // TriggerProfileRacing+ "El almacenamiento %s no permite escritura: la sesión y ajustes no se guardarán", // StorageNotWritable+ "FTP: usa 'chmod 777 %s' o borra la carpeta y reinicia la app", // StorageFixHint+ "Personalizar indicadores", // StatsCustomize+ "FPS y resolución", // StatsIndicatorFps+ "Tasa de bits (Bitrate)", // StatsIndicatorBitrate+ "Latencia (RTT)", // StatsIndicatorLatency+ "Pérdida de paquetes", // StatsIndicatorLoss+ "Gráfico de frametime", // StatsIndicatorGraph+ "Retardo de decodificación y pantalla", // StatsIndicatorDelay+ "Calidad de vídeo (QP)", // StatsIndicatorQp+ "Estado del micrófono", // StatsIndicatorMic+ "Usa tu teléfono para escanear el código QR y resolver con Microsoft, luego presiona Cruz para reintentar", // ScanQrToResolve+ "Obtener Gratis", // ClaimFree+ "Obteniendo licencia gratuita...", // Claiming+ "¡Juego añadido a tu cuenta con éxito!", // ClaimSuccess+ "Error al adquirir el juego gratuito: %s", // ClaimFailed+ "Este juego no es gratuito en la tienda", // ProductNotFree+ "Juego gratuito. Presiona Cruz para añadirlo a tu cuenta y empezar a jugar", // FreeAcquireHint+ "Fallo de conexión DNS con los servidores de Microsoft. En PS5, asegúrate de ejecutar NanoDNS con el DNS primario configurado en tu IP local para mantener acceso a internet bloqueando a Sony.", // DnsBlockedNanoDns+ "Esta cuenta Microsoft aún no tiene un perfil de Xbox. Inicia sesión en xbox.com en tu móvil o PC para crear tu Gamertag y vuelve a intentarlo.", // XboxProfileMissing+ "¡Cola lista! Iniciando el juego...", // QueueReadyAlert+ "Aviso sonoro de cola lista", // QueueReadyNotification+ "Jugado: %s", // PlaytimePlayed+ "Actualizar", // RefreshLibrary+ "Actualizando biblioteca...", // RefreshingLibrary+ "Esta cuenta de Xbox está suspendida o bloqueada. Visita enforcement.xbox.com para más detalles.", // XboxAccountBanned+ "Xbox Live no se ofrece en el país o región de esta cuenta.", // XboxRegionNotSupported+ "Se requiere verificación de edad o aceptar los términos. Inicia sesión en xbox.com desde un navegador y vuelve a intentarlo.", // XboxAdultVerificationRequired+ "Cuenta infantil: un adulto debe añadir esta cuenta a una familia de Microsoft en account.microsoft.com/family.", // XboxChildAccountFamily+ "Comprobar mi inicio de sesión", // CheckSignIn+ "Comprobar", // RunCheck+ "Prueba de red", // NetworkTest+ "Probar", // RunTest+ "Logros", // Achievements+ "Sin logros", // NoAchievements+ "Bloqueado", // AchievementLocked+ "Logro secreto", // SecretAchievement+ "Lista de deseos", // Wishlist+ "Añadir a lista de deseos", // AddWishlist+ "Quitar de lista de deseos", // RemoveWishlist+ "Añadido a lista de deseos", // AddedToWishlist+ "Quitado de lista de deseos", // RemovedFromWishlist+ "¡%s está en oferta!", // WishlistOnSale+ "¡%s llegó a Game Pass!", // WishlistInGamePass+ "Apoya el proyecto", // SupportProject+ "Apoya el Desarrollo de PSBox", // SupportTitle+ "PSBox es un proyecto de código abierto desarrollado con dedicación para brindar la mejor experiencia de Xbox Cloud Gaming en PlayStation 5. Si disfrutas de la app y deseas apoyar el desarrollo continuo y nuevas funciones, ¡considera invitarme un café en Ko-Fi!", // SupportMessage+ "Ko-fi", // SupportKoFi+ "Escanea con tu teléfono para donar", // ScanToDonate+ "Probar sonido", // TestSound+ "La lista de deseos está vacía", // WishlistEmpty+ // Loading tips+ "Panel táctil: desliza ↓ (o Touchpad + Options) para el menú, ↑ para el botón Xbox", // TipTouchpadMenu+ "Teclado y ratón USB conectados a la consola son compatibles con juegos de la nube habilitados", // TipKeyboardMouse+ "Reclama juegos gratis, demos y descubre promociones de la tienda directamente desde la aplicación", // TipFreeStore+ "¿Encontraste un problema? Abre Notificar problema para escanear un QR con registros de la consola", // TipBugReportQr+ "¿Disfrutas del proyecto? ¡Apoya su desarrollo futuro a través de Ko-fi en Configuración!", // TipSupportKofi+ "Activa salida de vídeo a 120 Hz en Configuración para menor latencia y respuesta más fluida", // Tip120HzVideo+ "Calibra la zona muerta de los sticks en Configuración para eliminar deriva y mejorar la precisión", // TipAnalogDeadzone+ "Usa el micrófono integrado del DualSense para chat de voz en grupos y partidas multijugador", // TipDualSenseMic+ // Settings descriptions+ "Cambia el idioma de la interfaz de la aplicación y la preferencia de audio y subtítulos en juegos en la nube", // SettingDescLanguage+ "Establece la resolución máxima del stream de vídeo (1080p, 720p o Mejor disponible). Se aplica en el próximo juego", // SettingDescResolution+ "Selecciona la región de servidores de Microsoft para streaming (Automático o regiones específicas). Se aplica en el próximo juego", // SettingDescRegion+ "Ajusta la zona muerta interna de los sticks analógicos para evitar deriva y movimientos no deseados", // SettingDescDeadzone+ "Activa o desactiva la vibración de gatillos adaptativos L2 y R2 en juegos compatibles", // SettingDescTriggerRumble+ "Alterna la función de confirmar y volver entre Cruz (estilo occidental) y Círculo (estilo japonés)", // SettingDescConfirmButton+ "Configura el color y comportamiento de la barra luminosa del DualSense en menús y durante el juego", // SettingDescLightBar+ "Comprueba e instala automáticamente actualizaciones oficiales de la aplicación directamente en la consola", // SettingDescUpdates+ "Permite iniciar sesión en tu cuenta de Xbox mediante otra región geográfica para acceder a catálogos alternativos", // SettingDescLoginCountry+ "Activa salida de vídeo a 120 Hz en tu consola para reducir el retardo de pantalla y la latencia de entrada", // SettingDescHighRefresh+ "Define el límite máximo de tasa de bits para streaming de vídeo, asegurando calidad visual o ahorrando red", // SettingDescBitrateCap+ "Ajusta el volumen general del audio reproducido durante las sesiones de juego en la nube", // SettingDescGameVolume+ "Asigna teclas del teclado USB o Bluetooth a los botones correspondientes del mando de Xbox durante el juego", // SettingDescKeyboardKeys+ "Alterna entre modo ventana y pantalla completa en plataformas de escritorio compatibles", // SettingDescDisplayMode+ "Abre la pantalla de prueba de respuesta y calibración de todos los botones y ejes del mando conectado", // SettingDescControllerButtons+ "Permite que los sensores de movimiento del DualSense asistan al apuntado analógico en juegos de disparos", // SettingDescGyro+ "Reproduce un aviso sonoro cuando termina la espera en cola de xCloud y el juego está listo", // SettingDescQueueReady+ "Ejecuta un diagnóstico completo del inicio de sesión de Xbox Live, validando tokens, perfil y suscripciones", // SettingDescCheckSignIn+ "Mide el ping (RTT) y la fluctuación (jitter) a centros de datos de juegos en la nube en múltiples regiones", // SettingDescNetworkTest+ "Muestra un código QR para apoyar al desarrollador mediante Ko-fi y mantener el proyecto activo", // SettingDescSupportProject+ "Novedades", // WhatsNew+ "Novedades", // WhatsNewTitle+ "Altavoz del mando", // PadSpeakerVolume+ "Silenciado", // Mute+ "Control Web", // WebControlTitle+ "Conectar desde el móvil", // WebControlSubtitle+ "Conéctate al mismo Wi-Fi para buscar, reasignar botones, usar el celular como control virtual, reportar problemas o ver registros.", // WebControlDesc+ "Decodificación de vídeo", // VideoDecoder+ "Hardware (Recomendado)", // VideoDecoderHw+ "Software (CPU)", // VideoDecoderSw+ "Selecciona decodificación por hardware (libSceVideodec2 en PS5, HWAccel en Desktop) o software (CPU)", // SettingDescVideoDecoder+ "Audio a Vibración Háptica", // AudioHaptics+ "Convierte frecuencias graves del audio en vibración háptica en DualSense", // SettingDescAudioHaptics+ "Atajos del panel táctil", // TouchpadShortcuts+ "Configura gestos de deslizamiento y clics izquierdo y derecho en el panel táctil DualSense", // SettingDescTouchpadShortcuts+ "Deslizar arriba (↑)", // TouchpadSwipeUp+ "Deslizar abajo (↓)", // TouchpadSwipeDown+ "Deslizar izquierda (←)", // TouchpadSwipeLeft+ "Deslizar derecha (→)", // TouchpadSwipeRight+ "Clic izquierdo", // TouchpadClickLeft+ "Clic derecho", // TouchpadClickRight+ "Desactivado", // TouchpadActNone+ "Menú del juego", // TouchpadActGameMenu+ "Botón Xbox", // TouchpadActXboxButton+ "Alternar estadísticas", // TouchpadActToggleStats+ "Silenciar/activar micrófono", // TouchpadActToggleMic+ "Alternar giroscopio", // TouchpadActCycleGyro+ "Alternar perfil de gatillo", // TouchpadActCycleTrigger+ "Touchpad + Options siempre abre el menú del juego", // TouchpadHelp+ "Restablecer ajustes predeterminados", // ResetSettings+ "Restablece todos los ajustes a los valores de fábrica. Mantén ✕ durante 5 segundos para confirmar.", // SettingDescResetSettings+ "Ajustes restablecidos a los valores predeterminados.", // SettingsResetNotice+ "Mantén para restablecer", // HoldToReset+ "La biblioteca ya está actualizada", // LibraryUpToDate+ "Biblioteca actualizada (%s nuevos juegos)", // LibraryUpdatedCount+ "Modo sin conexión", // OfflineMode+ "Funciones Preview (xCloud)", // PreviewFeatures+ "Activa la identificación de cliente preview y streaming de juegos Free-to-Play con anuncios para cuentas sin Game Pass.", // SettingDescPreviewFeatures+ "Requiere suscripción a Xbox Game Pass Ultimate para jugar en la nube", // GamePassRequired+ "En cola (tiempo indeterminado • esperando desde hace %s)", // InQueueIndeterminate+ "En cola (tiempo estimado: %s • esperando desde hace %s)", // InQueueEstimated+ "Para transmitir juegos gratuitos además de Fortnite en cuentas sin Game Pass, activa 'Funciones Preview' en Ajustes y en xbox.com/play.", // F2pPreviewRequiredDesc+ "Esta cuenta necesita habilitar 'Funciones Preview' en su perfil en xbox.com/play para desbloquear el streaming con anuncios de juegos gratuitos.", // F2pPreviewAccountNeededDesc+};diff --git a/src/ui/i18n/strings_fr.inc b/src/ui/i18n/strings_fr.incnew file mode 100644index 0000000..d988ae0--- /dev/null+++ b/src/ui/i18n/strings_fr.inc@@ -0,0 +1,418 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+constexpr Column kFrench = {+ "PSBox Cloud Gaming",+ "PSBOX CLOUD GAMING",+ "Connexion...",+ "Obtention d'un code de connexion...",+ "Chargement de vos jeux...",+ "Connectez-vous pour jouer",+ "Sur votre téléphone ou ordinateur, allez sur",+ "et saisissez ce code",+ "Scannez pour ouvrir la page, puis saisissez le code",+ "En attente de votre connexion...",+ "Reprendre",+ "Jouer",+ "Retour",+ "Sélectionner",+ "Se déconnecter",+ "Annuler",+ "Réessayer",+ "Préparation de votre jeu",+ "Vous êtes dans la file d'attente. Attente estimée : %s",+ "Connexion...",+ "Démarrage du streaming...",+ "Pavé tactile : ↓ ce menu · ↑ bouton Xbox",+ "Streaming terminé",+ "Un problème est survenu",+ "Connecté en tant que %s",+ "Aucun jeu à afficher pour le moment",+ "Par %s",+ "Paramètres",+ "Langue",+ "Résolution du streaming",+ "Région du serveur",+ "Automatique (%s)",+ "1080p (Full HD)",+ "720p (consomme moins de données)",+ "Meilleure (Auto)",+ "La résolution et la région s'appliquent au prochain jeu lancé.",+ "Modifier",+ "Ajuster",+ "Maintenez pour vous déconnecter",+ "Continuez à maintenir pour vous déconnecter (%s)",+ "Échec de la connexion : %s",+ "La connexion dans le navigateur n'a pas été finalisée. Utilisez un compte Microsoft personnel, effectuez les vérifications/2FA et autorisez l'app.",+ "Impossible de charger la liste des jeux : %s",+ "Impossible de démarrer le streaming : %s",+ "Aucune activité : vous serez déconnecté dans %s secondes",+ "Mes jeux",+ "Indisponible sur votre compte",+ "Game Pass",+ "Rechercher",+ "Tapez le nom d'un jeu",+ "Aucun jeu trouvé",+ "%s résultats",+ "Espace",+ "Effacer",+ "Tout effacer",+ "%s jeux",+ "Taper",+ "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 Mes jeux.",+ "Scannez pour ouvrir la page du magasin",+ "Rechercher dans %s",+ "GRATUIT",+ "Masquer",+ "Afficher",+ "Masqués",+ "\xE2\x96\xA1 réaffiche un jeu",+ "Masqué : voir Masqués, à la fin de cet onglet",+ "De nouveau visible",+ "Trier : %s",+ "Récents d'abord",+ "A-Z",+ "Par console",+ "Trier",+ "Gratuit",+ "Prix croissant",+ "Toutes les consoles",+ "1 jeu",+ "Sections",+ "Mise \xC3\xA0 jour de la liste des jeux...",+ "Menu du jeu",+ "Statistiques",+ "Activé",+ "Désactivé",+ "Résolution du stream",+ "Quitter le jeu",+ "Latence",+ "Débit",+ "Images par seconde",+ "Perte de paquets",+ "Région",+ "Décodage",+ "Le serveur peut conserver la qualité actuelle",+ "Netteté",+ "Désactivée",+ "Faible",+ "Moyenne",+ "Élevée",+ "Zone morte du stick",+ "Vibration des gâchettes",+ "Bouton de validation",+ "Activée",+ "Désactivée",+ "Version %s disponible",+ "Manettes",+ "Manette %s connectée",+ "Manette %s déconnectée",+ "Lissage des blocs",+ "À l'écran après",+ "Connexion perdue : reconnexion...",+ "Reconnecté",+ "Barre lumineuse",+ "Mise à l'échelle",+ "IA (Anime4K)",+ "Gratuit",+ "Obtenez-le une fois, gratuitement, sur xbox.com ou dans l'app Xbox (scannez le code avec votre téléphone), puis appuyez sur Jouer.",+ "Scannez pour l'obtenir gratuitement",+ "%s n'est pas encore sur votre compte. Il est gratuit : scannez le code sur sa page, choisissez Obtenir, puis réessayez (cela peut prendre une minute).",+ "Votre compte ne peut pas jouer à %s : il n'est pas dans votre abonnement ou n'a pas été acheté.",+ "Mes consoles",+ "Allumée",+ "En veille",+ "Éteinte",+ "Recherche de vos consoles...",+ "Aucune Xbox trouvée pour l'instant",+ "Jouez sur votre propre Xbox d'ici : son écran, ses jeux et ses applications.",+ "Réveil de votre Xbox...",+ "%s n'a pas répondu. Vérifiez que les fonctionnalités à distance sont activées et le mode Veille choisi, ou allumez-la, puis réessayez.",+ "Sur votre Xbox, connectez-vous avec ce même compte Microsoft.",+ "Paramètres > Appareils et connexions > Fonctionnalités à distance : activez-les.",+ "Paramètres > Général > Options d'alimentation : choisissez Veille, pour qu'elle se réveille seule.",+ "Scannez pour l'aide de Microsoft",+ "Rechercher à nouveau",+ "Bouton Xbox",+ "Arrêter la diffusion",+ "La diffusion a été arrêtée sur la Xbox",+ "Un autre appareil a repris la diffusion",+ "La Xbox a été éteinte",+ "%s a reçu la demande, mais son jeu à distance n'a pas démarré. Redémarrez-la : maintenez le bouton d'alimentation de la console 10 secondes, rallumez-la, puis réessayez.",+ "Pavé tactile : glissez ↓ pour le menu, ↑ pour le bouton Xbox",+ "FSR + nettoyage",+ "IA + nettoyage",+ "Auto (%s)",+ "Mettre à jour maintenant ? L'app redémarre toute seule à la fin.",+ "Mettre à jour",+ "Plus tard",+ "Mises à jour",+ "À jour (%s)",+ "%s disponible : mettre à jour",+ "Vérification...",+ "Mise à jour vers %s",+ "Téléchargement... %s",+ "Vérification de la signature...",+ "Installation...",+ "Mis à jour. Redémarrage...",+ "PSBox mis à jour : rouvrez l'app",+ "Échec de la mise à jour : rien n'a changé",+ "Couleur du jeu",+ "Couleur personnalisée",+ "Couleur de la barre lumineuse",+ "Joystick gauche ou croix : couleur L2 / R2 : luminosité",+ "Légère",+ "Moyenne",+ "Forte",+ "Maximale",+ "Intensité",+ "Fréquence",+ "Grave",+ "Aiguë",+ "Appuyez sur L2 / R2 pour le sentir : plus vous enfoncez, plus le jeu le demanderait fort",+ "Niveau %s",+ "Joystick gauche",+ "Joystick droit",+ "Position réelle",+ "Ce que reçoit le jeu",+ "L1 / R1 : choisir le joystick Croix ← / → : régler Bougez les joysticks pour le voir",+ "Résistance",+ "Style",+ "Vibration",+ "Impulsions de force",+ "Mode",+ "Genre",+ "Langue",+ "Tous les modes",+ "Solo",+ "Multijoueur en ligne",+ "Coopération en ligne",+ "Local / écran partagé",+ "Tous les genres",+ "Toutes les langues",+ "français",+ "Sous-titres en %s",+ "Doublé en %s",+ "Paramètres du jeu",+ "Profil",+ "Par défaut",+ "Personnalisé",+ "Réinitialiser",+ "Éditeur",+ "Tous les éditeurs",+ "Indépendants et autres",+ "Amis en train de jouer",+ "Microphone",+ "Coupé",+ "Actif",+ "Sortie audio",+ "TV",+ "Haut-parleur de la manette",+ "Signaler un problème",+ "Scannez-le avec votre téléphone : le formulaire de bug de GitHub s'ouvre, déjà rempli. Vous le relisez avant de l'envoyer.",+ "Il contient la version de l'app, l'erreur et des lignes du journal, sans données personnelles.",+ "PSBox s'est fermé de façon inattendue la dernière fois",+ "Pays de connexion",+ "Désactivé (celui de la console)",+ "Se connecter depuis un autre pays",+ "xCloud sera informé que la connexion vient du pays choisi. Microsoft ne l'autorise pas : utilisez-le à vos risques. Les jeux peuvent alors venir de serveurs éloignés, avec plus de latence. Modifiable plus tard dans Paramètres.",+ "xCloud a refusé la connexion. Le jeu dans le cloud n'est peut-être pas proposé dans votre pays, ou le compte n'a pas d'abonnement Game Pass avec le jeu dans le cloud.",+ "xCloud a refusé la connexion, même en choisissant %s. Le compte n'a probablement pas d'abonnement Game Pass avec le jeu dans le cloud.",+ "Brésil",+ "Japon",+ "Corée du Sud",+ "Pologne",+ "États-Unis",+ "Les connexions sécurisées ont été refusées car la date et l'heure de la PS5 semblent fausses (elle indique %s). Réglez-les dans Paramètres > Système > Date et heure, puis réessayez.",+ "Une connexion sécurisée a été refusée : quelque chose sur le réseau (serveur DNS, proxy ou filtre) répond à la place des sites de Microsoft. Essayez sans, puis réessayez.",+ "La date et l'heure de la PS5 semblent fausses (%s) : une partie du contenu ne se charge pas. Réglez-les dans Paramètres > Système > Date et heure.",+ "Impossible d'enregistrer la connexion sur la console : elle sera redemandée la prochaine fois. Signalez-le (Paramètres > △).",+ "Attente estimée : %s s", // QueueSeconds+ "Attente estimée : %s min", // QueueMinutes+ "Sortie 120 Hz (VRR)", // HighRefresh+ "Activée (en jeu)", // HighRefreshOn+ "Connexion instable", // ConnectionUnstable+ "Session : %s", // SessionSummary+ "Débit maximal", // BitrateCap+ "Automatique", // BitrateAuto+ "Volume du jeu", // GameVolume+ "Clavier : F12 ce menu · Origine bouton Xbox", // MenuKeyHint+ "Clavier et souris", // FilterMouseKeyboard+ "Clavier et souris", // MouseKeyboardSupport+ "Clavier et souris : joueur %s", // KeyboardPlayer+ "Vous êtes dans la file d'attente.", // InQueueNoEstimate+ "Touches du clavier", // KeyboardKeys+ "Croix directionnelle", // DPad+ "Appuyez sur une touche ou un bouton de la souris", // PressKey+ "%s est réservée par l'app", // KeyReserved+ "Modifier", // ChangeKey+ "Effacer", // ClearKey+ "La souris déplace le joystick droit et chaque cran de la molette appuie sur Triangle. F12 (menu), Origine (bouton Xbox) et 1-4 (joueur) sont réservées par l'app.", // KeysHelp+ "Visée gyroscopique", // Gyro+ "Toujours", // GyroAlways+ "En visant (L2)", // GyroAiming+ "Intensité du gyroscope", // GyroIntensity+ "Les connexions sécurisées ont été refusées car la date et l'heure de cet ordinateur semblent fausses (il indique %s). Corrigez-les dans les paramètres du système, puis réessayez.", // ClockWrongPc+ "La date et l'heure de cet ordinateur semblent fausses (%s) : une partie du contenu ne se charge pas. Corrigez-les dans les paramètres du système.", // ClockWrongNoticePc+ "Désactivé (celui de l'ordinateur)", // LoginCountryOffPc+ "Ouvrir dans le navigateur", // OpenInBrowser+ "%s disponible : télécharger", // UpdateReadyPc+ "Menu : START + BACK ou F12 · Bouton Xbox : Guide ou Origine", // GestureHintButtons+ "START + BACK ou F12 : ce menu · Guide ou Origine : bouton Xbox", // MenuButtonHint+ "Mode d'affichage", // DisplayMode+ "Fenêtre", // DisplayWindow+ "Plein écran", // DisplayFullscreen+ "Quitter PSBox ?", // QuitTitle+ "Quitter", // QuitConfirm+ "Boutons de la manette", // ControllerButtons+ "Appuyez sur le bouton pour %s", // PadPressButton+ "Bouton manquant pour : %s. Attribuez-en un à chaque fonction, ou réinitialisez ou annulez les modifications.", // PadMissing+ "Annuler les modifications", // DiscardChanges+ "Seul le jeu est concerné : les menus de l'app gardent les boutons tels quels. Choisir un bouton déjà utilisé échange les deux.", // PadHelp+ "Forfait", // FilterPlan+ "Mon forfait", // PlanMine+ "Tous les forfaits", // PlanAll+ "Inclus avec Game Pass %s", // IncludedWithPlan+ "Pavé tactile comme souris", // TouchpadMouse+ "Favoris", // Favorites+ "Ajouter aux favoris", // AddFavorite+ "Retirer des favoris", // RemoveFavorite+ "Ajouté aux favoris", // AddedToFavorites+ "Retiré des favoris", // RemovedFromFavorites+ "Langue du jeu", // GameLanguage+ "Limite mensuelle de jeu dans le cloud atteinte", // MonthlyLimitExceeded+ "Temps de jeu restant", // PlaytimeRemaining+ "%s h restantes", // HoursRemaining+ "Moins de 2 h restantes", // PlaytimeWarning+ "Profil de gâchettes", // TriggerProfile+ "Standard", // TriggerProfileStd+ "Tir (Hair Trigger)", // TriggerProfileShooter+ "Course (ABS)", // TriggerProfileRacing+ "Le stockage %s n'est pas accessible en écriture : connexion et réglages non enregistrés", // StorageNotWritable+ "FTP : faites 'chmod 777 %s' ou supprimez le dossier et relancez", // StorageFixHint+ "Personnaliser les indicateurs", // StatsCustomize+ "IPS et résolution", // StatsIndicatorFps+ "Débit binaire (Bitrate)", // StatsIndicatorBitrate+ "Latence (RTT)", // StatsIndicatorLatency+ "Perte de paquets", // StatsIndicatorLoss+ "Graphique de frametime", // StatsIndicatorGraph+ "Latence de décodage et d'affichage", // StatsIndicatorDelay+ "Qualité vidéo (QP)", // StatsIndicatorQp+ "État du microphone", // StatsIndicatorMic+ "Scannez le code QR avec votre téléphone pour résoudre ceci chez Microsoft, puis appuyez sur Croix pour réessayer", // ScanQrToResolve+ "Obtenir gratuitement", // ClaimFree+ "Obtention de la licence gratuite...", // Claiming+ "Jeu ajouté à votre compte avec succès !", // ClaimSuccess+ "Échec de l'obtention du jeu gratuit : %s", // ClaimFailed+ "Ce jeu n'est pas gratuit sur le store", // ProductNotFree+ "Jeu gratuit. Appuyez sur Croix pour l'ajouter à votre compte et jouer", // FreeAcquireHint+ "Échec de résolution DNS pour les serveurs Microsoft. Sur PS5, veillez à exécuter NanoDNS et à définir le DNS primaire sur votre IP locale pour garder l'accès Internet tout en bloquant Sony.", // DnsBlockedNanoDns+ "Ce compte Microsoft n'a pas encore de profil Xbox. Connectez-vous sur xbox.com sur mobile ou PC pour créer votre Gamertag, puis réessayez.", // XboxProfileMissing+ "File d'attente prête ! Lancement du jeu...", // QueueReadyAlert+ "Alerte sonore de file prête", // QueueReadyNotification+ "Joué : %s", // PlaytimePlayed+ "Actualiser", // RefreshLibrary+ "Actualisation de la bibliothèque...", // RefreshingLibrary+ "Ce compte Xbox est suspendu ou banni. Consultez enforcement.xbox.com pour plus de détails.", // XboxAccountBanned+ "Xbox Live n'est pas proposé dans le pays ou la région de ce compte.", // XboxRegionNotSupported+ "Vérification d'âge ou acceptation des conditions requise. Connectez-vous sur xbox.com dans un navigateur, puis réessayez.", // XboxAdultVerificationRequired+ "Compte enfant : un adulte doit ajouter ce compte à une famille Microsoft sur account.microsoft.com/family.", // XboxChildAccountFamily+ "Vérifier ma connexion", // CheckSignIn+ "Vérifier", // RunCheck+ "Test réseau", // NetworkTest+ "Tester", // RunTest+ "Succès", // Achievements+ "Aucun succès", // NoAchievements+ "Verrouillé", // AchievementLocked+ "Succès secret", // SecretAchievement+ "Liste d'envies", // Wishlist+ "Ajouter aux envies", // AddWishlist+ "Retirer des envies", // RemoveWishlist+ "Ajouté aux envies", // AddedToWishlist+ "Retiré des envies", // RemovedFromWishlist+ "%s est en promotion !", // WishlistOnSale+ "%s a rejoint le Game Pass !", // WishlistInGamePass+ "Soutenir le projet", // SupportProject+ "Soutenir le Développement de PSBox", // SupportTitle+ "PSBox est un projet open source développé avec passion pour offrir la meilleure expérience Xbox Cloud Gaming sur PlayStation 5. Si vous appréciez l'application et souhaitez soutenir les mises à jour et les nouveautés, pensez à m'offrir un café sur Ko-Fi !", // SupportMessage+ "Ko-fi", // SupportKoFi+ "Scannez avec votre téléphone", // ScanToDonate+ "Tester le son", // TestSound+ "La liste de souhaits est vide", // WishlistEmpty+ // Loading tips+ "Pavé tactile : glissez ↓ (ou Pavé tactile + Options) pour le menu, ↑ pour le bouton Xbox", // TipTouchpadMenu+ "Clavier et souris USB branchés sur la console sont pris en charge dans les jeux du cloud compatibles", // TipKeyboardMouse+ "Obtenez des jeux gratuits, démos et promotions du magasin directement depuis l'application", // TipFreeStore+ "Un problème ? Ouvrez Signaler un problème pour scanner un code QR avec les journaux de la console", // TipBugReportQr+ "Vous appréciez le projet ? Soutenez son développement via Ko-fi dans les Paramètres !", // TipSupportKofi+ "Activez la sortie vidéo 120 Hz dans les Paramètres pour réduire la latence d'affichage et de contrôle", // Tip120HzVideo+ "Calibrez la zone morte des sticks dans les Paramètres pour éliminer le drift et améliorer la précision", // TipAnalogDeadzone+ "Utilisez le microphone intégré de la DualSense pour le chat vocal dans les groupes et jeux multijoueurs", // TipDualSenseMic+ // Settings descriptions+ "Modifie la langue de l'interface de l'application et les préférences audio et sous-titres dans les jeux du cloud", // SettingDescLanguage+ "Définit la résolution vidéo maximale (1080p, 720p ou Meilleure disponible). Prend effet au prochain lancement", // SettingDescResolution+ "Sélectionne la région des serveurs Microsoft pour le streaming (Automatique ou spécifique). Prend effet au prochain lancement", // SettingDescRegion+ "Ajuste la zone morte intérieure des sticks analogiques DualSense pour éviter le drift et les mouvements involontaires", // SettingDescDeadzone+ "Active ou désactive l'émulation des vibrations sur les gâchettes adaptatives L2 et R2 dans les jeux compatibles", // SettingDescTriggerRumble+ "Bascule la disposition des boutons de confirmation et retour entre Croix (occidental) et Rond (japonais)", // SettingDescConfirmButton+ "Configure la couleur et le comportement de la barre lumineuse de votre manette DualSense", // SettingDescLightBar+ "Vérifie et installe automatiquement les mises à jour officielles de l'application directement sur votre console", // SettingDescUpdates+ "Permet de vous connecter à votre compte Xbox via une autre région pour accéder à d'autres catalogues", // SettingDescLoginCountry+ "Active la sortie vidéo 120 Hz sur votre console pour une réactivité accrue et une latence réduite", // SettingDescHighRefresh+ "Définit la limite maximale de débit binaire pour le streaming vidéo, optimisant la qualité ou préservant le réseau", // SettingDescBitrateCap+ "Ajuste le niveau du volume audio principal pendant les sessions de jeu en streaming", // SettingDescGameVolume+ "Associe les touches du clavier USB ou Bluetooth aux boutons correspondants de la manette Xbox en jeu", // SettingDescKeyboardKeys+ "Bascule entre mode fenêtré et plein écran sur les plates-formes de bureau compatibles", // SettingDescDisplayMode+ "Ouvre l'écran de test de réponse et de calibrage de tous les boutons et axes de votre manette connectée", // SettingDescControllerButtons+ "Active les capteurs de mouvement DualSense pour assister la visée analogique dans les jeux de tir", // SettingDescGyro+ "Joue un signal sonore distinctif lorsque l'attente dans la file xCloud est terminée et que le jeu est prêt", // SettingDescQueueReady+ "Exécute un diagnostic complet de la connexion Xbox Live, validant jetons d'accès, profil et abonnements", // SettingDescCheckSignIn+ "Mesure le ping (RTT) et la gigue (jitter) vers les centres de données de jeux en nuage de plusieurs régions", // SettingDescNetworkTest+ "Affiche un code QR pour soutenir le développeur via Ko-fi et contribuer à la maintenance active du projet", // SettingDescSupportProject+ "Nouveautés", // WhatsNew+ "Nouveautés", // WhatsNewTitle+ "Haut-parleur de la manette", // PadSpeakerVolume+ "Muet", // Mute+ "Contrôle Web", // WebControlTitle+ "Connexion mobile", // WebControlSubtitle+ "Connectez-vous au même Wi-Fi pour chercher, remapper, utiliser le mobile comme manette virtuelle, signaler des soucis ou voir les logs.", // WebControlDesc+ "Décodage vidéo", // VideoDecoder+ "Matériel (Recommandé)", // VideoDecoderHw+ "Logiciel (CPU)", // VideoDecoderSw+ "Sélectionne le décodage matériel (libSceVideodec2 sur PS5, HWAccel sur Desktop) ou logiciel (CPU)", // SettingDescVideoDecoder+ "Audio vers vibration haptique", // AudioHaptics+ "Convertit les basses fréquences audio en vibrations haptiques sur DualSense", // SettingDescAudioHaptics+ "Raccourcis du pavé tactile", // TouchpadShortcuts+ "Configure les gestes de glissement et les clics gauche/droit sur le pavé tactile DualSense", // SettingDescTouchpadShortcuts+ "Glisser vers le haut (↑)", // TouchpadSwipeUp+ "Glisser vers le bas (↓)", // TouchpadSwipeDown+ "Glisser vers la gauche (←)", // TouchpadSwipeLeft+ "Glisser vers la droite (→)", // TouchpadSwipeRight+ "Clic gauche", // TouchpadClickLeft+ "Clic droit", // TouchpadClickRight+ "Désactivé", // TouchpadActNone+ "Menu du jeu", // TouchpadActGameMenu+ "Bouton Xbox", // TouchpadActXboxButton+ "Afficher/masquer les stats", // TouchpadActToggleStats+ "Couper/activer le micro", // TouchpadActToggleMic+ "Changer le mode gyro", // TouchpadActCycleGyro+ "Changer le profil de gâchette", // TouchpadActCycleTrigger+ "Pavé tactile + Options ouvre toujours le menu du jeu", // TouchpadHelp+ "Restaurer les paramètres par défaut", // ResetSettings+ "Restaure tous les paramètres aux valeurs d'usine. Maintenez ✕ pendant 5 secondes pour confirmer.", // SettingDescResetSettings+ "Paramètres réinitialisés aux valeurs par défaut.", // SettingsResetNotice+ "Maintenir pour réinitialiser", // HoldToReset+ "La bibliothèque est déjà à jour", // LibraryUpToDate+ "Bibliothèque mise à jour (%s nouveaux jeux)", // LibraryUpdatedCount+ "Mode hors ligne", // OfflineMode+ "Fonctionnalités Preview (xCloud)", // PreviewFeatures+ "Active les fonctionnalités client preview et le streaming Free-to-Play avec publicités pour les comptes sans Game Pass.", // SettingDescPreviewFeatures+ "Nécessite un abonnement Xbox Game Pass Ultimate pour le cloud gaming", // GamePassRequired+ "En file d'attente (temps indéterminé • attente depuis %s)", // InQueueIndeterminate+ "En file d'attente (temps estimé : %s • attente depuis %s)", // InQueueEstimated+ "Pour jouer aux jeux gratuits autres que Fortnite sans Game Pass, activez les 'Fonctionnalités Preview' dans les Paramètres et sur xbox.com/play.", // F2pPreviewRequiredDesc+ "Ce compte doit activer les 'Fonctionnalités Preview' sur son profil sur xbox.com/play pour débloquer le streaming gratuit avec publicités.", // F2pPreviewAccountNeededDesc+};diff --git a/src/ui/i18n/strings_it.inc b/src/ui/i18n/strings_it.incnew file mode 100644index 0000000..3b53f8b--- /dev/null+++ b/src/ui/i18n/strings_it.inc@@ -0,0 +1,418 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+constexpr Column kItalian = {+ "PSBox Cloud Gaming",+ "PSBOX CLOUD GAMING",+ "Accesso in corso...",+ "Richiesta di un codice di accesso...",+ "Caricamento dei tuoi giochi...",+ "Accedi per giocare",+ "Sul telefono o sul computer, vai su",+ "e inserisci questo codice",+ "Scansiona per aprire la pagina, poi inserisci il codice",+ "In attesa del tuo accesso...",+ "Riprendi a giocare",+ "Gioca",+ "Indietro",+ "Seleziona",+ "Esci",+ "Annulla",+ "Riprova",+ "Preparazione del gioco",+ "Sei in coda. Attesa stimata: %s",+ "Connessione...",+ "Avvio dello streaming...",+ "Touchpad: ↓ questo menu · ↑ pulsante Xbox",+ "Streaming terminato",+ "Si è verificato un problema",+ "Accesso effettuato come %s",+ "Ancora nessun gioco da mostrare",+ "Di %s",+ "Impostazioni",+ "Lingua",+ "Risoluzione dello streaming",+ "Regione del server",+ "Automatica (%s)",+ "1080p (Full HD)",+ "720p (usa meno dati)",+ "Migliore (Auto)",+ "Risoluzione e regione valgono dal prossimo gioco avviato.",+ "Cambia",+ "Regola",+ "Tieni premuto per uscire",+ "Continua a tenere premuto per uscire (%s)",+ "Accesso non riuscito: %s",+ "L'accesso nel browser non è stato completato. Utilizza un account Microsoft personale, completa le verifiche/2FA e autorizza l'app.",+ "Impossibile caricare l'elenco dei giochi: %s",+ "Impossibile avviare lo streaming: %s",+ "Nessuna attività: verrai disconnesso tra %s secondi",+ "I miei giochi",+ "Non disponibile sul tuo account",+ "Game Pass",+ "Cerca",+ "Scrivi il nome di un gioco",+ "Nessun gioco trovato",+ "%s risultati",+ "Spazio",+ "Cancella",+ "Svuota",+ "%s giochi",+ "Scrivi",+ "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 miei giochi.",+ "Scansiona per aprire la pagina dello store",+ "Cerca in %s",+ "GRATIS",+ "Nascondi",+ "Mostra",+ "Nascosti",+ "\xE2\x96\xA1 mostra di nuovo un gioco",+ "Nascosto: lo trovi in Nascosti, in fondo a questa scheda",+ "Di nuovo visibile",+ "Ordina: %s",+ "Recenti prima",+ "A-Z",+ "Per console",+ "Ordina",+ "Gratis",+ "Prezzo più basso",+ "Tutte le console",+ "1 gioco",+ "Sezioni",+ "Aggiornamento dell'elenco dei giochi...",+ "Menu di gioco",+ "Statistiche",+ "Attivo",+ "Disattivo",+ "Risoluzione dello stream",+ "Esci dal gioco",+ "Latenza",+ "Bitrate",+ "Fotogrammi al secondo",+ "Perdita di pacchetti",+ "Regione",+ "Decodifica",+ "Il server potrebbe mantenere la qualità attuale",+ "Nitidezza",+ "Disattivata",+ "Bassa",+ "Media",+ "Alta",+ "Zona morta dello stick",+ "Vibrazione dei grilletti",+ "Tasto di conferma",+ "Attivata",+ "Disattivata",+ "Versione %s disponibile",+ "Controller",+ "Controller %s connesso",+ "Controller %s disconnesso",+ "Attenuazione blocchi",+ "Sullo schermo dopo",+ "Connessione persa: riconnessione...",+ "Riconnesso",+ "Barra luminosa",+ "Upscaling",+ "IA (Anime4K)",+ "Free to play",+ "Ottienilo una volta, gratis, su xbox.com o nell'app Xbox (scansiona il codice con il telefono), poi premi Gioca.",+ "Scansiona per ottenerlo gratis",+ "%s non è ancora nel tuo account. È gratis: scansiona il codice nella sua pagina, scegli Ottieni e riprova (può volerci un minuto).",+ "Il tuo account non può giocare a %s: non è nel tuo abbonamento o non è stato acquistato.",+ "Le mie console",+ "Accesa",+ "In standby",+ "Spenta",+ "Ricerca delle tue console...",+ "Nessuna Xbox trovata per ora",+ "Gioca sulla tua Xbox da qui: il suo schermo, i giochi e le app.",+ "Accensione della tua Xbox...",+ "%s non ha risposto. Controlla che le Funzionalità remote siano attive e la modalità sia Sospensione, oppure accendila, e riprova.",+ "Sulla tua Xbox, accedi con questo stesso account Microsoft.",+ "Impostazioni > Dispositivi e connessioni > Funzionalità remote: attiva le funzionalità remote.",+ "Impostazioni > Generale > Opzioni di alimentazione: scegli Sospensione, così si accende da sola.",+ "Scansiona per l'aiuto di Microsoft",+ "Cerca di nuovo",+ "Pulsante Xbox",+ "Termina lo streaming",+ "Lo streaming è stato terminato sulla Xbox",+ "Un altro dispositivo ha preso lo streaming",+ "La Xbox è stata spenta",+ "%s ha ricevuto la richiesta, ma il gioco remoto non è partito. Riavviala: tieni premuto il pulsante di accensione della console per 10 secondi, riaccendila e riprova.",+ "Touchpad: scorri ↓ per il menu, ↑ per il pulsante Xbox",+ "FSR + pulizia",+ "IA + pulizia",+ "Auto (%s)",+ "Aggiornare ora? L'app si riavvia da sola alla fine.",+ "Aggiorna ora",+ "Non ora",+ "Aggiornamenti",+ "Aggiornato (%s)",+ "%s disponibile: aggiorna",+ "Verifica...",+ "Aggiornamento a %s",+ "Download... %s",+ "Verifica della firma...",+ "Installazione...",+ "Aggiornato. Riavvio...",+ "PSBox aggiornato: riapri l'app",+ "Aggiornamento non riuscito: nulla è cambiato",+ "Colore del gioco",+ "Colore personalizzato",+ "Colore della barra luminosa",+ "Levetta sinistra o croce: colore L2 / R2: luminosità",+ "Leggera",+ "Media",+ "Forte",+ "Massima",+ "Intensità",+ "Frequenza",+ "Bassa",+ "Alta",+ "Premi L2 / R2 per sentirlo: più a fondo, più forte lo chiederebbe il gioco",+ "Livello %s",+ "Levetta sinistra",+ "Levetta destra",+ "Posizione reale",+ "Ciò che riceve il gioco",+ "L1 / R1: scegliere la levetta Croce ← / →: regolare Muovi le levette per vederlo",+ "Resistenza",+ "Stile",+ "Vibrazione",+ "Impulsi di forza",+ "Modalità",+ "Genere",+ "Lingua",+ "Tutte le modalità",+ "Giocatore singolo",+ "Multigiocatore online",+ "Cooperativa online",+ "Locale / schermo condiviso",+ "Tutti i generi",+ "Qualsiasi lingua",+ "italiano",+ "Sottotitoli in %s",+ "Doppiato in %s",+ "Impostazioni di gioco",+ "Profilo",+ "Predefinito",+ "Personalizzato",+ "Ripristina predefiniti",+ "Editore",+ "Tutti gli editori",+ "Indie e altri",+ "Amici che giocano ora",+ "Microfono",+ "Disattivato",+ "Attivo",+ "Uscita audio",+ "TV",+ "Altoparlante del controller",+ "Segnala un problema",+ "Inquadralo con il telefono: si apre il modulo dei bug di GitHub già compilato. Lo controlli prima di inviarlo.",+ "Include la versione dell'app, l'errore e righe del log, senza dati personali.",+ "PSBox si è chiuso inaspettatamente l'ultima volta",+ "Paese di accesso",+ "Disattivato (quello della console)",+ "Accedi come un altro paese",+ "A xCloud verrà detto che l'accesso arriva dal paese scelto. Microsoft non lo consente: usalo a tuo rischio. I giochi potrebbero arrivare da server lontani, con più ritardo. Puoi cambiarlo poi in Impostazioni.",+ "xCloud ha rifiutato l'accesso. Il cloud gaming potrebbe non essere offerto nel tuo paese, oppure l'account non ha un abbonamento Game Pass con il cloud gaming.",+ "xCloud ha rifiutato l'accesso, anche scegliendo %s. Probabilmente l'account non ha un abbonamento Game Pass con il cloud gaming.",+ "Brasile",+ "Giappone",+ "Corea del Sud",+ "Polonia",+ "Stati Uniti",+ "Le connessioni sicure sono state rifiutate perché la data e l'ora della PS5 sembrano errate (indica %s). Impostale in Impostazioni > Sistema > Data e ora, poi riprova.",+ "Una connessione sicura è stata rifiutata: qualcosa nella rete (un server DNS, proxy o filtro) risponde al posto dei siti Microsoft. Prova senza e riprova.",+ "La data e l'ora della PS5 sembrano errate (%s): alcuni contenuti non si caricano. Impostale in Impostazioni > Sistema > Data e ora.",+ "Impossibile salvare l'accesso sulla console: verrà richiesto di nuovo la prossima volta. Segnalalo (Impostazioni > △).",+ "Attesa stimata: %s s", // QueueSeconds+ "Attesa stimata: %s min", // QueueMinutes+ "Uscita 120 Hz (VRR)", // HighRefresh+ "Attiva (nei giochi)", // HighRefreshOn+ "Connessione instabile", // ConnectionUnstable+ "Sessione: %s", // SessionSummary+ "Bitrate massimo", // BitrateCap+ "Automatico", // BitrateAuto+ "Volume del gioco", // GameVolume+ "Tastiera: F12 questo menu · Home pulsante Xbox", // MenuKeyHint+ "Tastiera e mouse", // FilterMouseKeyboard+ "Tastiera e mouse", // MouseKeyboardSupport+ "Tastiera e mouse: giocatore %s", // KeyboardPlayer+ "Sei in coda.", // InQueueNoEstimate+ "Tasti della tastiera", // KeyboardKeys+ "Croce direzionale", // DPad+ "Premi un tasto o un pulsante del mouse", // PressKey+ "%s è riservato all'app", // KeyReserved+ "Cambia", // ChangeKey+ "Cancella", // ClearKey+ "Il mouse muove la levetta destra e ogni scatto della rotella preme Triangolo. F12 (menu), Home (tasto Xbox) e 1-4 (giocatore) sono riservati all'app.", // KeysHelp+ "Mira giroscopica", // Gyro+ "Sempre", // GyroAlways+ "Mirando (L2)", // GyroAiming+ "Intensità giroscopio", // GyroIntensity+ "Le connessioni sicure sono state rifiutate perché la data e l'ora di questo computer sembrano errate (indica %s). Correggile nelle impostazioni di sistema, poi riprova.", // ClockWrongPc+ "La data e l'ora di questo computer sembrano errate (%s): alcuni contenuti non si caricano. Correggile nelle impostazioni di sistema.", // ClockWrongNoticePc+ "Disattivato (quello del computer)", // LoginCountryOffPc+ "Apri nel browser", // OpenInBrowser+ "%s disponibile: scarica", // UpdateReadyPc+ "Menu: START + BACK o F12 · Pulsante Xbox: Guide o Home", // GestureHintButtons+ "START + BACK o F12: questo menu · Guide o Home: pulsante Xbox", // MenuButtonHint+ "Modalità schermo", // DisplayMode+ "Finestra", // DisplayWindow+ "Schermo intero", // DisplayFullscreen+ "Uscire da PSBox?", // QuitTitle+ "Esci", // QuitConfirm+ "Pulsanti del controller", // ControllerButtons+ "Premi il pulsante per %s", // PadPressButton+ "Manca un pulsante per: %s. Assegnane uno a ogni funzione, oppure ripristina o annulla le modifiche.", // PadMissing+ "Annulla modifiche", // DiscardChanges+ "Vale solo nel gioco: i menu dell'app usano i pulsanti così come sono. Scegliere un pulsante già usato scambia i due.", // PadHelp+ "Piano", // FilterPlan+ "Il mio piano", // PlanMine+ "Tutti i piani", // PlanAll+ "Incluso con Game Pass %s", // IncludedWithPlan+ "Touchpad come mouse", // TouchpadMouse+ "Preferiti", // Favorites+ "Aggiungi ai preferiti", // AddFavorite+ "Rimuovi dai preferiti", // RemoveFavorite+ "Aggiunto ai preferiti", // AddedToFavorites+ "Rimosso dai preferiti", // RemovedFromFavorites+ "Lingua del gioco", // GameLanguage+ "Limite mensile di gioco su cloud raggiunto", // MonthlyLimitExceeded+ "Tempo di gioco rimanente", // PlaytimeRemaining+ "%s ore rimanenti", // HoursRemaining+ "Meno di 2 ore rimanenti", // PlaytimeWarning+ "Profilo grilletti", // TriggerProfile+ "Standard", // TriggerProfileStd+ "Sparatutto (Hair Trigger)", // TriggerProfileShooter+ "Corsa (ABS)", // TriggerProfileRacing+ "La memoria %s non è scrivibile: accesso e impostazioni non verranno salvati", // StorageNotWritable+ "FTP: esegui 'chmod 777 %s' o elimina la cartella e riavvia", // StorageFixHint+ "Personalizza indicatori", // StatsCustomize+ "FPS e risoluzione", // StatsIndicatorFps+ "Bitrate", // StatsIndicatorBitrate+ "Latenza (RTT)", // StatsIndicatorLatency+ "Perdita pacchetti", // StatsIndicatorLoss+ "Grafico frametime", // StatsIndicatorGraph+ "Latenza di decodifica e visualizzazione", // StatsIndicatorDelay+ "Qualità video (QP)", // StatsIndicatorQp+ "Stato microfono", // StatsIndicatorMic+ "Inquadra il codice QR con lo smartphone per risolvere con Microsoft, poi premi Croce per riprovare", // ScanQrToResolve+ "Ottieni gratis", // ClaimFree+ "Acquisizione licenza gratuita in corso...", // Claiming+ "Gioco aggiunto al tuo account con successo!", // ClaimSuccess+ "Impossibile ottenere il gioco gratuito: %s", // ClaimFailed+ "Questo gioco non è gratuito nello store", // ProductNotFree+ "Gioco gratuito. Premi Croce per aggiungerlo al tuo account e iniziare a giocare", // FreeAcquireHint+ "Risoluzione DNS non riuscita per i server Microsoft. Su PS5, assicurati di eseguire NanoDNS e impostare il DNS primario sull'IP locale per bloccare Sony mantenendo l'accesso a Internet.", // DnsBlockedNanoDns+ "Questo account Microsoft non ha ancora un profilo Xbox. Accedi a xbox.com su smartphone o PC per creare il tuo Gamertag, quindi riprova.", // XboxProfileMissing+ "Coda pronta! Avvio del gioco...", // QueueReadyAlert+ "Segnale acustico di fine coda", // QueueReadyNotification+ "Giocato: %s", // PlaytimePlayed+ "Aggiorna", // RefreshLibrary+ "Aggiornamento libreria...", // RefreshingLibrary+ "Questo account Xbox è sospeso o bloccato. Visita enforcement.xbox.com per i dettagli.", // XboxAccountBanned+ "Xbox Live non è offerto nel paese o nella regione di questo account.", // XboxRegionNotSupported+ "È richiesta la verifica dell'età o l'accettazione dei termini. Accedi a xbox.com in un browser, poi riprova.", // XboxAdultVerificationRequired+ "Account bambino: un adulto deve aggiungere questo account a una famiglia Microsoft su account.microsoft.com/family.", // XboxChildAccountFamily+ "Verifica il mio accesso", // CheckSignIn+ "Verifica", // RunCheck+ "Test di rete", // NetworkTest+ "Testa", // RunTest+ "Obiettivi", // Achievements+ "Nessun obiettivo", // NoAchievements+ "Bloccato", // AchievementLocked+ "Obiettivo segreto", // SecretAchievement+ "Lista dei desideri", // Wishlist+ "Aggiungi ai desideri", // AddWishlist+ "Rimuovi dai desideri", // RemoveWishlist+ "Aggiunto ai desideri", // AddedToWishlist+ "Rimosso dai desideri", // RemovedFromWishlist+ "%s è in saldo!", // WishlistOnSale+ "%s è arrivato su Game Pass!", // WishlistInGamePass+ "Supporta il progetto", // SupportProject+ "Supporta lo Sviluppo di PSBox", // SupportTitle+ "PSBox è un progetto open source sviluppato con passione per portare la migliore esperienza di Xbox Cloud Gaming su PlayStation 5. Se ti piace l'app e vuoi sostenere lo sviluppo continuo e le nuove funzionalità, considera di offrirmi un caffè su Ko-Fi!", // SupportMessage+ "Ko-fi", // SupportKoFi+ "Inquadra con lo smartphone", // ScanToDonate+ "Prova suono", // TestSound+ "La lista dei desideri è vuota", // WishlistEmpty+ // Loading tips+ "Touchpad: scorri ↓ (o Touchpad + Options) per il menu, ↑ per il pulsante Xbox", // TipTouchpadMenu+ "Tastiera e mouse USB collegati alla console sono supportati nei giochi cloud compatibili", // TipKeyboardMouse+ "Ottieni giochi gratuiti, demo e promozioni del negozio direttamente dalla libreria dell'app", // TipFreeStore+ "Hai riscontrato un problema? Apri Segnala problema per scansionare un QR code con i log della console", // TipBugReportQr+ "Ti piace il progetto? Sostieni lo sviluppo futuro tramite Ko-fi nella scheda Impostazioni!", // TipSupportKofi+ "Abilita l'uscita video a 120 Hz nelle Impostazioni per una latenza di visualizzazione ridotta", // Tip120HzVideo+ "Calibra la zona morta delle levette nelle Impostazioni per eliminare il drift e migliorare la precisione", // TipAnalogDeadzone+ "Usa il microfono integrato del DualSense per la chat vocale nei gruppi e nelle partite multigiocatore", // TipDualSenseMic+ // Settings descriptions+ "Modifica la lingua dell'interfaccia dell'applicazione e le preferenze di audio e sottotitoli nei giochi cloud", // SettingDescLanguage+ "Imposta la risoluzione video massima (1080p, 720p o Migliore disponibile). Ha effetto al prossimo avvio", // SettingDescResolution+ "Seleziona la regione dei server Microsoft per lo streaming (Automatica o specifica). Ha effetto al prossimo avvio", // SettingDescRegion+ "Regola la zona morta interna delle levette analogiche DualSense per evitare drift e movimenti involontari", // SettingDescDeadzone+ "Abilita o disabilita l'emulazione della vibrazione sui grilletti adattivi L2 e R2 nei giochi compatibili", // SettingDescTriggerRumble+ "Alterna la configurazione dei tasti conferma e indietro tra Croce (occidentale) e Cerchio (giapponese)", // SettingDescConfirmButton+ "Configura il colore e il comportamento della barra luminosa del DualSense nei menu e durante il gioco", // SettingDescLightBar+ "Verifica e installa automaticamente gli aggiornamenti ufficiali dell'app direttamente sulla console", // SettingDescUpdates+ "Consente di accedere al proprio account Xbox tramite un'altra regione per accedere a cataloghi alternativi", // SettingDescLoginCountry+ "Abilita l'uscita video a 120 Hz sulla console per un ritardo di visualizzazione e latenza di input ridotti", // SettingDescHighRefresh+ "Imposta il limite massimo di bitrate per lo streaming video, garantendo alta fedeltà o risparmio dati", // SettingDescBitrateCap+ "Regola il livello del volume audio principale durante le sessioni di gioco in streaming", // SettingDescGameVolume+ "Mappa i tasti della tastiera USB o Bluetooth sui pulsanti corrispondenti del controller Xbox durante il gioco", // SettingDescKeyboardKeys+ "Alterna tra modalità finestra e schermo intero sulle piattaforme desktop supportate", // SettingDescDisplayMode+ "Apre la schermata di test e calibrazione di tutti i pulsanti e gli assi del controller collegato", // SettingDescControllerButtons+ "Abilita i sensori di movimento DualSense per assistere la mira analogica negli sparatutto e giochi d'azione", // SettingDescGyro+ "Riproduce un segnale sonoro caratteristico quando l'attesa nella coda di xCloud termina e il gioco è pronto", // SettingDescQueueReady+ "Esegue una diagnostica completa dell'accesso a Xbox Live, convalidando token di accesso, profilo e abbonamenti", // SettingDescCheckSignIn+ "Misura il ping (RTT) e il jitter verso i data center di gioco in cloud in diverse regioni globali", // SettingDescNetworkTest+ "Mostra un codice QR per supportare lo sviluppatore tramite Ko-fi e contribuire a mantenere il progetto attivo", // SettingDescSupportProject+ "Novità", // WhatsNew+ "Novità", // WhatsNewTitle+ "Altoparlante del controller", // PadSpeakerVolume+ "Muto", // Mute+ "Controllo Web", // WebControlTitle+ "Connetti dallo smartphone", // WebControlSubtitle+ "Connettiti allo stesso Wi-Fi per cercare, rimappare pulsanti, usare il telefono come controller virtuale, segnalare problemi o visualizzare i log.", // WebControlDesc+ "Decodifica video", // VideoDecoder+ "Hardware (Consigliato)", // VideoDecoderHw+ "Software (CPU)", // VideoDecoderSw+ "Seleziona decodifica hardware (libSceVideodec2 su PS5, HWAccel su Desktop) o software (CPU)", // SettingDescVideoDecoder+ "Audio a vibrazione aptica", // AudioHaptics+ "Converte le basse frequenze audio in vibrazioni aptiche su DualSense", // SettingDescAudioHaptics+ "Scorciatoie del touchpad", // TouchpadShortcuts+ "Configura i gesti di scorrimento e i clic sinistro/destro sul touchpad DualSense", // SettingDescTouchpadShortcuts+ "Scorri in alto (↑)", // TouchpadSwipeUp+ "Scorri in basso (↓)", // TouchpadSwipeDown+ "Scorri a sinistra (←)", // TouchpadSwipeLeft+ "Scorri a destra (→)", // TouchpadSwipeRight+ "Clic sinistro", // TouchpadClickLeft+ "Clic destro", // TouchpadClickRight+ "Disattivato", // TouchpadActNone+ "Menu di gioco", // TouchpadActGameMenu+ "Pulsante Xbox", // TouchpadActXboxButton+ "Mostra/nascondi statistiche", // TouchpadActToggleStats+ "Disattiva/attiva microfono", // TouchpadActToggleMic+ "Cambia modalità giroscopio", // TouchpadActCycleGyro+ "Cambia profilo grilletto", // TouchpadActCycleTrigger+ "Touchpad + Options apre sempre il menu di gioco", // TouchpadHelp+ "Ripristina impostazioni predefinite", // ResetSettings+ "Ripristina tutte le impostazioni ai valori di fabbrica. Tieni premuto ✕ per 5 secondi per confermare.", // SettingDescResetSettings+ "Impostazioni ripristinate ai valori predefiniti.", // SettingsResetNotice+ "Tieni premuto per ripristinare", // HoldToReset+ "La libreria è già aggiornata", // LibraryUpToDate+ "Libreria aggiornata (%s nuovi giochi)", // LibraryUpdatedCount+ "Modalità non in linea", // OfflineMode+ "Funzionalità Preview (xCloud)", // PreviewFeatures+ "Abilita le funzioni client preview e lo streaming Free-to-Play con annunci per account senza Game Pass.", // SettingDescPreviewFeatures+ "Richiede abbonamento Xbox Game Pass Ultimate per il gioco nel cloud", // GamePassRequired+ "In coda (tempo stimato indeterminato • in attesa da %s)", // InQueueIndeterminate+ "In coda (tempo stimato: %s • in attesa da %s)", // InQueueEstimated+ "Per giocare a titoli gratuiti oltre a Fortnite senza Game Pass, abilita 'Funzionalità Preview' nelle Impostazioni e su xbox.com/play.", // F2pPreviewRequiredDesc+ "Questo account deve abilitare le 'Funzionalità Preview' nel profilo su xbox.com/play per sbloccare lo streaming gratuito supportato da annunci.", // F2pPreviewAccountNeededDesc+};diff --git a/src/ui/i18n/strings_pt_br.inc b/src/ui/i18n/strings_pt_br.incnew file mode 100644index 0000000..eefcf56--- /dev/null+++ b/src/ui/i18n/strings_pt_br.inc@@ -0,0 +1,418 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+constexpr Column kPortugueseBR = {+ "PSBox Cloud Gaming",+ "PSBOX CLOUD GAMING",+ "Entrando...",+ "Gerando um código de login...",+ "Carregando seus jogos...",+ "Entre para jogar",+ "No celular ou computador, acesse",+ "e digite este código",+ "Escaneie para abrir a página e digite o código",+ "Aguardando você entrar...",+ "Continue jogando",+ "Jogar",+ "Voltar",+ "Selecionar",+ "Sair da conta",+ "Cancelar",+ "Tentar de novo",+ "Preparando seu jogo",+ "Você está na fila. Espera estimada: %s",+ "Conectando...",+ "Iniciando o streaming...",+ "Touchpad: ↓ este menu · ↑ botão Xbox",+ "Streaming encerrado",+ "Algo deu errado",+ "Conectado como %s",+ "Nenhum jogo para mostrar ainda",+ "Por %s",+ "Configurações",+ "Idioma",+ "Resolução do streaming",+ "Região do servidor",+ "Automática (%s)",+ "1080p (Full HD)",+ "720p (usa menos dados)",+ "Melhor (Auto)",+ "A resolução e a região valem a partir do próximo jogo.",+ "Alterar",+ "Ajustar",+ "Segure para sair da conta",+ "Continue segurando para sair da conta (%s)",+ "Falha ao entrar: %s",+ "O login no navegador não foi concluído. Use uma conta pessoal da Microsoft, conclua verificações de segurança/2FA e autorize o app.",+ "Não foi possível carregar a lista de jogos: %s",+ "Não foi possível iniciar o streaming: %s",+ "Sem atividade: você será desconectado em %s segundos",+ "Meus jogos",+ "Indisponível na sua conta",+ "Game Pass",+ "Pesquisar",+ "Digite o nome de um jogo",+ "Nenhum jogo encontrado",+ "%s resultados",+ "Espaço",+ "Apagar",+ "Limpar",+ "%s jogos",+ "Digitar",+ "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 Meus jogos.",+ "Escaneie para abrir a página da loja",+ "Pesquisar em %s",+ "GRÁTIS",+ "Ocultar",+ "Mostrar",+ "Ocultos",+ "\xE2\x96\xA1 mostra o jogo de novo",+ "Oculto: veja em Ocultos, no fim desta aba",+ "Visível de novo",+ "Ordenar: %s",+ "Recentes primeiro",+ "A-Z",+ "Por console",+ "Ordenar",+ "Grátis",+ "Menor preço",+ "Todos os consoles",+ "1 jogo",+ "Seções",+ "Atualizando a lista de jogos...",+ "Menu do jogo",+ "Estatísticas",+ "Ligado",+ "Desligado",+ "Resolução do stream",+ "Sair do jogo",+ "Latência",+ "Taxa de bits",+ "Quadros por segundo",+ "Perda de pacotes",+ "Região",+ "Decodificação",+ "O servidor pode manter a qualidade atual",+ "Nitidez",+ "Desligada",+ "Baixa",+ "Média",+ "Alta",+ "Zona morta do analógico",+ "Vibração nos gatilhos",+ "Botão de confirmar",+ "Ativada",+ "Desativada",+ "Versão %s disponível",+ "Controles",+ "Controle %s conectado",+ "Controle %s desconectado",+ "Suavização de blocos",+ "Na tela após",+ "Conexão perdida: reconectando...",+ "Reconectado",+ "Barra de luz",+ "Ampliação",+ "IA (Anime4K)",+ "Grátis para jogar",+ "Pegue uma vez, de graça, no xbox.com ou no app Xbox (escaneie o código com o celular) e depois aperte Jogar.",+ "Escaneie para pegar grátis",+ "%s ainda não está na sua conta. É grátis: escaneie o código na página do jogo, escolha Obter e tente de novo (pode levar um minuto).",+ "Sua conta não pode jogar %s: não está na sua assinatura ou não foi comprado.",+ "Meus consoles",+ "Ligado",+ "Em espera",+ "Desligado",+ "Procurando seus consoles...",+ "Nenhum Xbox encontrado ainda",+ "Jogue no seu próprio Xbox por aqui: a tela, os jogos e os apps dele.",+ "Ligando o seu Xbox...",+ "%s não respondeu. Confira se os Recursos remotos estão ativos e o modo de energia é Suspensão, ou ligue o console, e tente de novo.",+ "No seu Xbox, entre com esta mesma conta Microsoft.",+ "Configurações > Dispositivos e conexões > Recursos remotos: ative os recursos remotos.",+ "Configurações > Geral > Opções de energia: escolha Suspensão, para ele acordar sozinho.",+ "Escaneie para a ajuda da Microsoft",+ "Procurar de novo",+ "Botão Xbox",+ "Encerrar transmissão",+ "A transmissão foi encerrada no Xbox",+ "Outro aparelho assumiu a transmissão",+ "O Xbox foi desligado",+ "%s recebeu o pedido, mas o jogo remoto dele não iniciou. Reinicie o console: segure o botão de ligar do Xbox por 10 segundos, ligue de novo e tente outra vez.",+ "Touchpad: deslize ↓ para o menu, ↑ para o botão Xbox",+ "FSR + limpeza",+ "IA + limpeza",+ "Auto (%s)",+ "Atualizar agora? O app reinicia sozinho ao terminar.",+ "Atualizar agora",+ "Agora não",+ "Atualizações",+ "Atualizado (%s)",+ "%s disponível: atualizar",+ "Verificando...",+ "Atualizando para %s",+ "Baixando... %s",+ "Conferindo a assinatura...",+ "Instalando...",+ "Atualizado. Reiniciando...",+ "PSBox atualizado: abra o app de novo",+ "A atualização falhou: nada foi alterado",+ "Cor do jogo",+ "Cor personalizada",+ "Cor da barra de luz",+ "Analógico esquerdo ou direcional: cor L2 / R2: brilho",+ "Leve",+ "Média",+ "Forte",+ "Máxima",+ "Intensidade",+ "Frequência",+ "Grave",+ "Aguda",+ "Aperte L2 / R2 para sentir: quanto mais fundo, mais forte o jogo pediria",+ "Nível %s",+ "Analógico esquerdo",+ "Analógico direito",+ "Posição real",+ "O que o jogo recebe",+ "L1 / R1: escolher o analógico Direcional ← / →: ajustar Mova os analógicos para ver",+ "Resistência",+ "Estilo",+ "Vibração",+ "Pulsos de força",+ "Modo",+ "Gênero",+ "Idioma",+ "Todos os modos",+ "Um jogador",+ "Multijogador online",+ "Cooperação online",+ "Local / tela dividida",+ "Todos os gêneros",+ "Qualquer idioma",+ "português",+ "Legendas em %s",+ "Dublado em %s",+ "Configurações do jogo",+ "Perfil",+ "Padrão",+ "Personalizado",+ "Restaurar padrão",+ "Editora",+ "Todas as editoras",+ "Indies & Outras",+ "Amigos jogando agora",+ "Microfone",+ "Mutado",+ "Ativo",+ "Saída de áudio",+ "TV",+ "Alto-falante do controle",+ "Relatar problema",+ "Escaneie com o celular: o formulário de bug do GitHub abre preenchido. Você revisa antes de enviar.",+ "Inclui a versão do app, o erro e linhas do log, sem dados pessoais.",+ "O PSBox fechou inesperadamente da última vez",+ "País do login",+ "Desativado (o do console)",+ "Entrar como outro país",+ "O xCloud será informado de que o login vem do país escolhido. A Microsoft não permite isso: use por sua conta e risco. Os jogos podem vir de servidores distantes, com mais atraso. Dá para mudar depois em Configurações.",+ "O xCloud recusou o login. O jogo na nuvem pode não ser oferecido no seu país, ou a conta pode não ter um plano do Game Pass com jogos na nuvem.",+ "O xCloud recusou o login, mesmo como %s. Provavelmente a conta não tem um plano do Game Pass com jogos na nuvem.",+ "Brasil",+ "Japão",+ "Coreia do Sul",+ "Polônia",+ "Estados Unidos",+ "As conexões seguras foram recusadas porque a data e a hora do PS5 parecem erradas (ele diz %s). Acerte em Configurações > Sistema > Data e hora e tente de novo.",+ "Uma conexão segura foi recusada: algo na rede (um servidor DNS, proxy ou filtro) está respondendo no lugar dos sites da Microsoft. Tente sem ele e tente de novo.",+ "A data e a hora do PS5 parecem erradas (%s): parte do conteúdo não carrega. Acerte em Configurações > Sistema > Data e hora.",+ "Não foi possível salvar o login no console, então ele será pedido de novo na próxima vez. Relate o problema (Configurações > △).",+ "Espera estimada: %s s", // QueueSeconds+ "Espera estimada: %s min", // QueueMinutes+ "Saída 120 Hz (VRR)", // HighRefresh+ "Ativada (nos jogos)", // HighRefreshOn+ "Conexão instável", // ConnectionUnstable+ "Sessão: %s", // SessionSummary+ "Bitrate máximo", // BitrateCap+ "Automático", // BitrateAuto+ "Volume do jogo", // GameVolume+ "Teclado: F12 este menu · Home botão Xbox", // MenuKeyHint+ "Teclado e mouse", // FilterMouseKeyboard+ "Teclado e mouse", // MouseKeyboardSupport+ "Teclado e mouse: jogador %s", // KeyboardPlayer+ "Você está na fila.", // InQueueNoEstimate+ "Teclas do teclado", // KeyboardKeys+ "Direcional", // DPad+ "Pressione uma tecla ou botão do mouse", // PressKey+ "%s é reservada pelo app", // KeyReserved+ "Alterar", // ChangeKey+ "Limpar", // ClearKey+ "O mouse move o analógico direito e cada clique da roda aperta Triângulo. F12 (menu), Home (botão Xbox) e 1-4 (jogador) são reservadas pelo app.", // KeysHelp+ "Mira por giroscópio", // Gyro+ "Sempre", // GyroAlways+ "Ao mirar (L2)", // GyroAiming+ "Intensidade do giroscópio", // GyroIntensity+ "As conexões seguras foram recusadas porque a data e a hora deste computador parecem erradas (ele diz %s). Acerte nas configurações do sistema e tente de novo.", // ClockWrongPc+ "A data e a hora deste computador parecem erradas (%s): parte do conteúdo não carrega. Acerte nas configurações do sistema.", // ClockWrongNoticePc+ "Desativado (o do computador)", // LoginCountryOffPc+ "Abrir no navegador", // OpenInBrowser+ "%s disponível: baixar", // UpdateReadyPc+ "Menu: START + BACK ou F12 · Botão Xbox: Guide ou Home", // GestureHintButtons+ "START + BACK ou F12: este menu · Guide ou Home: botão Xbox", // MenuButtonHint+ "Modo de exibição", // DisplayMode+ "Janela", // DisplayWindow+ "Tela cheia", // DisplayFullscreen+ "Sair do PSBox?", // QuitTitle+ "Sair", // QuitConfirm+ "Botões do controle", // ControllerButtons+ "Aperte o botão para %s", // PadPressButton+ "Falta botão para: %s. Dê um botão a cada um, ou restaure o padrão ou descarte as alterações.", // PadMissing+ "Descartar alterações", // DiscardChanges+ "Só o jogo vê isto: os menus do app usam os botões como são. Escolher um botão já usado troca os dois.", // PadHelp+ "Plano", // FilterPlan+ "Meu plano", // PlanMine+ "Todos os planos", // PlanAll+ "Incluído no Game Pass %s", // IncludedWithPlan+ "Touchpad como mouse", // TouchpadMouse+ "Favoritos", // Favorites+ "Adicionar aos favoritos", // AddFavorite+ "Remover dos favoritos", // RemoveFavorite+ "Adicionado aos favoritos", // AddedToFavorites+ "Removido dos favoritos", // RemovedFromFavorites+ "Idioma do jogo", // GameLanguage+ "Limite mensal de jogo em nuvem atingido", // MonthlyLimitExceeded+ "Tempo de jogo restante", // PlaytimeRemaining+ "%s h restantes", // HoursRemaining+ "Menos de 2 h restantes", // PlaytimeWarning+ "Perfil de gatilho", // TriggerProfile+ "Padrão", // TriggerProfileStd+ "Tiroteio (Hair Trigger)", // TriggerProfileShooter+ "Corrida (ABS)", // TriggerProfileRacing+ "Armazenamento %s não permite gravação: login e ajustes não serão salvos", // StorageNotWritable+ "FTP: use 'chmod 777 %s' ou exclua a pasta e reabra o app", // StorageFixHint+ "Personalizar indicadores", // StatsCustomize+ "FPS e resolução", // StatsIndicatorFps+ "Taxa de bits (Bitrate)", // StatsIndicatorBitrate+ "Latência (RTT)", // StatsIndicatorLatency+ "Perda de pacotes", // StatsIndicatorLoss+ "Gráfico de frametime", // StatsIndicatorGraph+ "Atraso de decodificação e exibição", // StatsIndicatorDelay+ "Qualidade do vídeo (QP)", // StatsIndicatorQp+ "Status do microfone", // StatsIndicatorMic+ "Use seu celular para ler o código QR ao lado e resolver na Microsoft, depois pressione Cruz para tentar novamente", // ScanQrToResolve+ "Adquirir Grátis", // ClaimFree+ "Adquirindo licença gratuita...", // Claiming+ "Jogo adicionado à sua conta com sucesso!", // ClaimSuccess+ "Falha ao adquirir o jogo gratuito: %s", // ClaimFailed+ "Este jogo não é gratuito na loja", // ProductNotFree+ "Jogo gratuito. Pressione Cruz para adicionar à sua conta e começar a jogar", // FreeAcquireHint+ "Falha de conexão DNS com os servidores da Microsoft. No PS5, certifique-se de estar rodando o NanoDNS com o DNS Primário configurado para o IP local para manter acesso à internet enquanto bloqueia a Sony.", // DnsBlockedNanoDns+ "Esta conta Microsoft ainda não possui um perfil Xbox. Entre em xbox.com pelo celular ou computador para criar sua Gamertag e tente novamente.", // XboxProfileMissing+ "Fila liberada! Iniciando o jogo...", // QueueReadyAlert+ "Aviso sonoro de fila pronta", // QueueReadyNotification+ "Jogado: %s", // PlaytimePlayed+ "Atualizar", // RefreshLibrary+ "Atualizando biblioteca...", // RefreshingLibrary+ "Esta conta Xbox está suspensa ou banida. Acesse enforcement.xbox.com para mais detalhes.", // XboxAccountBanned+ "O Xbox Live não é oferecido no país ou região desta conta.", // XboxRegionNotSupported+ "Verificação de idade ou aceite dos termos necessário. Entre em xbox.com pelo navegador e tente novamente.", // XboxAdultVerificationRequired+ "Conta infantil: um adulto precisa adicionar esta conta a uma família Microsoft em account.microsoft.com/family.", // XboxChildAccountFamily+ "Verificar meu login", // CheckSignIn+ "Verificar", // RunCheck+ "Teste de rede", // NetworkTest+ "Testar", // RunTest+ "Conquistas", // Achievements+ "Nenhuma conquista", // NoAchievements+ "Bloqueada", // AchievementLocked+ "Conquista secreta", // SecretAchievement+ "Lista de desejos", // Wishlist+ "Adicionar à lista de desejos", // AddWishlist+ "Remover da lista de desejos", // RemoveWishlist+ "Adicionado à lista de desejos", // AddedToWishlist+ "Removido da lista de desejos", // RemovedFromWishlist+ "%s está em promoção!", // WishlistOnSale+ "%s entrou no Game Pass!", // WishlistInGamePass+ "Apoie o projeto", // SupportProject+ "Apoie o Desenvolvimento do PSBox", // SupportTitle+ "O PSBox é um projeto de código aberto mantido com dedicação para trazer a melhor experiência do Xbox Cloud Gaming ao PlayStation 5. Se você curte o app e quer apoiar o desenvolvimento contínuo, atualizações e novos recursos, considere me pagar um café no Ko-Fi!", // SupportMessage+ "Ko-fi", // SupportKoFi+ "Aponte a câmera do seu celular", // ScanToDonate+ "Testar som", // TestSound+ "A lista de desejos está vazia", // WishlistEmpty+ // Loading tips+ "Touchpad: deslize ↓ (ou Touchpad + Options) para o menu, ↑ para o botão Xbox", // TipTouchpadMenu+ "Teclado e mouse USB conectados ao console são suportados em jogos compatíveis da nuvem", // TipKeyboardMouse+ "Adquira jogos gratuitos, demonstrações e confira promoções da loja direto pelo aplicativo", // TipFreeStore+ "Encontrou um problema? Abra Relatar Problema para escanear um QR code com logs do console", // TipBugReportQr+ "Gostando do app? Apoie o desenvolvimento contínuo via Ko-fi na aba de Configurações!", // TipSupportKofi+ "Ative a saída de vídeo em 120 Hz nas Configurações para menor latência e resposta mais rápida", // Tip120HzVideo+ "Ajuste a zona morta dos analógicos do DualSense nas Configurações para eliminar drift", // TipAnalogDeadzone+ "Use o microfone integrado do DualSense para bate-papo de voz em grupos e jogos multijogador", // TipDualSenseMic+ // Settings descriptions+ "Altera o idioma da interface do aplicativo e a preferência de áudio e legendas nos jogos da nuvem", // SettingDescLanguage+ "Define a resolução máxima do fluxo de vídeo transmitido (1080p, 720p ou Melhor). Vale a partir do próximo jogo", // SettingDescResolution+ "Seleciona a região de servidores Microsoft para streaming (Automático ou regiões específicas). Vale a partir do próximo jogo", // SettingDescRegion+ "Ajusta a sensibilidade inicial dos analógicos do DualSense para evitar drift ou comandos involuntários", // SettingDescDeadzone+ "Ativa ou desativa a simulação dos motores de vibração nos gatilhos adaptáveis L2 e R2 em jogos compatíveis", // SettingDescTriggerRumble+ "Alterna a função de confirmar e voltar entre Cruz (padrão ocidental) e Círculo (padrão japonês)", // SettingDescConfirmButton+ "Configura a cor e o comportamento da barra de luz do DualSense durante a navegação e a jogatina", // SettingDescLightBar+ "Verifica e instala automaticamente novas versões lançadas do aplicativo diretamente pelo console sem PC", // SettingDescUpdates+ "Permite autenticar sua conta Xbox através de outra região geográfica para acessar catálogos alternativos", // SettingDescLoginCountry+ "Ativa saída de vídeo em 120 Hz no console para menor atraso de exibição e redução da latência de comando", // SettingDescHighRefresh+ "Define o limite máximo de bitrate para o stream de vídeo, garantindo fidelidade visual ou economizando rede", // SettingDescBitrateCap+ "Ajusta o nível geral do volume de áudio reproduzido durante as sessões de streaming dos jogos", // SettingDescGameVolume+ "Mapeia as teclas do teclado USB ou Bluetooth para os botões correspondentes do controle Xbox no jogo", // SettingDescKeyboardKeys+ "Alterna entre modo de janela ou tela cheia em plataformas desktop suportadas", // SettingDescDisplayMode+ "Abre o painel de teste de resposta e calibração de todos os botões e eixos do controle conectado", // SettingDescControllerButtons+ "Permite usar os sensores de movimento do DualSense para auxiliar na mira em jogos de tiro e ação", // SettingDescGyro+ "Toca um aviso sonoro característico quando o tempo de espera na fila do xCloud terminar e o jogo iniciar", // SettingDescQueueReady+ "Realiza um diagnóstico completo da autenticação Xbox Live, validando tokens de acesso, perfil e assinaturas", // SettingDescCheckSignIn+ "Mede o ping (RTT) e a variação (jitter) para servidores de jogos em nuvem de várias regiões globais", // SettingDescNetworkTest+ "Exibe um QR Code para você apoiar o desenvolvedor via Ko-fi e ajudar a manter o projeto ativo e atualizado", // SettingDescSupportProject+ "Novidades", // WhatsNew+ "Novidades", // WhatsNewTitle+ "Alto-falante do controle", // PadSpeakerVolume+ "Mudo", // Mute+ "Configuração Web", // WebControlTitle+ "Acesse pelo celular", // WebControlSubtitle+ "Conecte no mesmo Wi-Fi para pesquisar, remapear botões, usar o celular como controle virtual, relatar problemas ou visualizar o log.", // WebControlDesc+ "Decodificação de Vídeo", // VideoDecoder+ "Hardware (Recomendado)", // VideoDecoderHw+ "Software (CPU)", // VideoDecoderSw+ "Seleciona decodificação por hardware (libSceVideodec2 no PS5, HWAccel no Desktop) ou por software (CPU)", // SettingDescVideoDecoder+ "Áudio para Vibração Háptica", // AudioHaptics+ "Converte graves do áudio em vibração háptica no DualSense", // SettingDescAudioHaptics+ "Atalhos do Touchpad", // TouchpadShortcuts+ "Configura gestos de deslize e cliques esquerdo e direito no Touchpad do DualSense", // SettingDescTouchpadShortcuts+ "Deslizar para Cima (↑)", // TouchpadSwipeUp+ "Deslizar para Baixo (↓)", // TouchpadSwipeDown+ "Deslizar para Esquerda (←)", // TouchpadSwipeLeft+ "Deslizar para Direita (→)", // TouchpadSwipeRight+ "Clique Esquerdo", // TouchpadClickLeft+ "Clique Direito", // TouchpadClickRight+ "Desativado", // TouchpadActNone+ "Menu do jogo", // TouchpadActGameMenu+ "Botão Xbox", // TouchpadActXboxButton+ "Alternar estatísticas", // TouchpadActToggleStats+ "Mutar/desmutar microfone", // TouchpadActToggleMic+ "Alternar giroscópio", // TouchpadActCycleGyro+ "Alternar perfil de gatilho", // TouchpadActCycleTrigger+ "Touchpad + Options sempre abre o menu do jogo", // TouchpadHelp+ "Restaurar configurações padrões", // ResetSettings+ "Restaura todas as configurações para os padrões de fábrica. Mantenha ✕ por 5 segundos para confirmar.", // SettingDescResetSettings+ "Configurações restauradas para os padrões.", // SettingsResetNotice+ "Segure para restaurar", // HoldToReset+ "Biblioteca já está atualizada", // LibraryUpToDate+ "Biblioteca atualizada (%s novos jogos)", // LibraryUpdatedCount+ "Modo offline", // OfflineMode+ "Recursos Preview (xCloud)", // PreviewFeatures+ "Ativa identificação de cliente preview e suporte a jogos Free-to-Play com anúncios para contas sem Game Pass.", // SettingDescPreviewFeatures+ "Requer assinatura Xbox Game Pass Ultimate para streaming na nuvem", // GamePassRequired+ "Na fila (tempo estimado indeterminado • aguardando há %s)", // InQueueIndeterminate+ "Na fila (tempo estimado: %s • aguardando há %s)", // InQueueEstimated+ "Para transmitir jogos gratuitos além de Fortnite em contas sem Game Pass, ative os 'Recursos Preview' nas Configurações do app e no site xbox.com/play.", // F2pPreviewRequiredDesc+ "Esta conta precisa habilitar os 'Recursos Preview' no perfil em xbox.com/play para liberar o streaming com anúncios de jogos gratuitos.", // F2pPreviewAccountNeededDesc+};diff --git a/src/ui/image_cache.cpp b/src/ui/image_cache.cppindex aa2fdbc..9f4d3f5 100644--- a/src/ui/image_cache.cpp+++ b/src/ui/image_cache.cpp@@ -36,6 +36,17 @@ bool decodeImage(const std::string& bytes, Image& out) {out.px.resize(static_cast<size_t>(w) * h);std::memcpy(out.px.data(), data, out.px.size() * 4);stbi_image_free(data);+ if (n < 4) {+ out.opaque = true;+ } else {+ out.opaque = true;+ for (uint32_t p : out.px) {+ if ((p >> 24) != 255) {+ out.opaque = false;+ break;+ }+ }+ }return true;}@@ -52,6 +63,13 @@ Image coverResize(const Image& src, int w, int h) {const auto* start = reinterpret_cast<const unsigned char*>(&src.px[static_cast<size_t>(cy) * src.w + cx]);stbir_resize_uint8_srgb(start, cw, ch, src.w * 4, reinterpret_cast<unsigned char*>(out.px.data()), w, h, w * 4,STBIR_RGBA);+ out.opaque = true;+ for (uint32_t p : out.px) {+ if ((p >> 24) != 255) {+ out.opaque = false;+ break;+ }+ }return out;}@@ -98,6 +116,13 @@ std::shared_ptr<const Image> ImageCache::get(const std::string& url, int w, intEntry& e = entries_[key];e.lastUse = ++clock_;if (!e.image && !e.loading && (!e.failed || (e.retryAt && platform::nowMs() >= e.retryAt))) {+ constexpr size_t kMaxPendingJobs = 48;+ while (jobs_.size() >= kMaxPendingJobs) {+ Job dropped = std::move(jobs_.back());+ jobs_.pop_back();+ auto dit = entries_.find(dropped.key);+ if (dit != entries_.end()) dit->second.loading = false;+ }e.loading = true;jobs_.push_front({key, url, w, h});cv_.notify_one();diff --git a/src/ui/image_cache.h b/src/ui/image_cache.hindex 65b7059..d96fd9e 100644--- a/src/ui/image_cache.h+++ b/src/ui/image_cache.h@@ -15,10 +15,10 @@#include <cstdint>#include <deque>#include <functional>-#include <map>#include <memory>#include <mutex>#include <string>+#include <unordered_map>#include <vector>namespace xc::ui {@@ -63,7 +63,7 @@ private:size_t diskBudget_;std::mutex mutex_;std::condition_variable cv_;- std::map<std::string, Entry> entries_;+ std::unordered_map<std::string, Entry> entries_;std::deque<Job> jobs_; // newest first: what is on screen now winssize_t bytes_ = 0;uint64_t clock_ = 0;diff --git a/src/ui/settings_choice.cpp b/src/ui/settings_choice.cppindex ee0be36..ec5f323 100644--- a/src/ui/settings_choice.cpp+++ b/src/ui/settings_choice.cpp@@ -33,6 +33,7 @@ SettingsChoice choiceFromSettings(const app::Settings& s) {c.maxBitrateMbps = s.maxBitrateMbps;c.gameVolume = s.gameVolume;c.queueReadyAlert = s.queueReadyAlert;+ c.previewFeatures = s.previewFeatures;c.keyMap = s.keyMap;c.padMap = s.padMap;c.gyroMode = s.gyroMode;@@ -69,6 +70,7 @@ void applyChoice(const SettingsChoice& c, app::Settings& s) {s.maxBitrateMbps = c.maxBitrateMbps;s.gameVolume = c.gameVolume;s.queueReadyAlert = c.queueReadyAlert;+ s.previewFeatures = c.previewFeatures;s.keyMap = c.keyMap;if (input::padMapValid(c.padMap)) s.padMap = c.padMap; // the screen only lets a complete one outs.gyroMode = c.gyroMode;diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex 36cf8e4..f3acdda 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -32,2465 +32,12 @@ constexpr std::array<LangInfo, kLangs> kInfo = {{using Column = std::array<const char*, kStrs>;-constexpr Column kEnglish = {- "PSBox Cloud Gaming", // AppName- "PSBOX CLOUD GAMING", // CloudGaming- "Signing in...", // SigningIn- "Getting a sign-in code...", // RequestingCode- "Loading your games...", // LoadingGames- "Sign in to play", // SignInTitle- "On your phone or computer, go to", // SignInStep1- "and enter this code", // SignInStep2- "Scan to open the page, then enter the code", // SignInScan- "Waiting for you to sign in...", // SignInWaiting- "Jump back in", // JumpBackIn- "Play", // Play- "Back", // Back- "Select", // Select- "Sign out", // SignOut- "Cancel", // Cancel- "Try again", // TryAgain- "Getting your game ready", // GettingReady- "You're in the queue. Estimated wait: %s", // InQueue- "Connecting...", // Connecting- "Starting the stream...", // StartingStream- "Touchpad: ↓ this menu · ↑ Xbox button", // MenuGestureHint- "Stream ended", // StreamEnded- "Something went wrong", // ErrorTitle- "Signed in as %s", // SignedInAs- "No games to show yet", // NoGames- "By %s", // PublisherBy- "Settings", // Settings- "Language", // Language- "Stream resolution", // Resolution- "Server region", // Region- "Automatic (%s)", // RegionAuto- "1080p (Full HD)", // Res1080- "720p (uses less data)", // Res720- "Best (Auto)", // ResBest- "Resolution and region apply to the next game you start.", // SettingsNote- "Change", // Change- "Adjust", // Adjust- "Hold to sign out", // HoldSignOut- "Keep holding to sign out (%s)", // SigningOutIn- "Sign-in failed: %s", // SignInFailed- "Sign-in not completed in the browser. Use a personal Microsoft account, complete any security prompts/2FA, and grant access to the app.", // SignInInteractionRequired- "Could not load the game list: %s", // LibraryFailed- "Could not start the stream: %s", // StreamFailed- "No input for a while: you will be disconnected in %s seconds", // IdleWarning- "My games", // YourGames- "Not available on your account", // NotPlayable- "Game Pass", // TabGamePass- "Search", // TabSearch- "Type the name of a game", // SearchHint- "No games found", // NoResults- "%s results", // ResultsCount- "Space", // KeySpace- "Delete", // KeyDelete- "Clear", // KeyClear- "%s games", // GamesCount- "Type", // KeyType- "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 My games.", // BuyHint- "Scan to open the store page", // ScanToBuy- "Search in %s", // SearchIn- "FREE", // Free- "Hide", // Hide- "Show", // Unhide- "Hidden", // HiddenSection- "Square shows a game again", // HiddenHint- "Hidden: find it under Hidden, at the end of this tab", // HiddenToast- "Shown again", // UnhiddenToast- "Sort: %s", // SortLabel- "Recent first", // SortRecent- "A-Z", // SortAZ- "By console", // SortConsole- "Sort", // SortHint- "Free", // FilterFree- "Lowest price", // FilterCheapest- "All consoles", // FilterAllConsoles- "1 game", // OneGame- "Sections", // Sections- "Updating the game list...", // UpdatingList- "Game menu", // MenuTitle- "Statistics", // MenuStats- "On", // On- "Off", // Off- "Stream resolution", // MenuResolution- "Leave game", // MenuLeave- "Latency", // StatLatency- "Bitrate", // StatBitrate- "Frame rate", // StatFrameRate- "Packet loss", // StatLoss- "Region", // StatRegion- "Decoding", // StatDecode- "The server may keep the current quality", // ResolutionNote- "Sharpness", // MenuSharpness- "Off", // SharpOff- "Low", // SharpLow- "Medium", // SharpMedium- "High", // SharpHigh- "Stick dead zone", // Deadzone- "Trigger vibration", // TriggerRumble- "Confirm button", // ConfirmButton- "On", // Activated- "Off", // Deactivated- "Version %s available", // UpdateAvailable- "Controllers", // Controllers- "Controller %s connected", // PadConnected- "Controller %s disconnected", // PadDisconnected- "Block smoothing", // MenuDeband- "On screen after", // StatOnScreen- "Connection lost: reconnecting...", // Reconnecting- "Reconnected", // Reconnected- "Light bar", // LightBar- "Upscaling", // MenuUpscaler- "AI (Anime4K)", // UpscalerAi- "Free to play", // FreeToPlay- "Get it once, free, on xbox.com or in the Xbox app (scan the code with your phone), then press Play.", // FreeHint- "Scan to get it free", // ScanToGet- "%s is not on your account yet. It is free: scan the code on its page, choose Get, then try again (it can take a minute).", // NoEntitlementFree- "Your account can't play %s: it is not in your subscription or not bought.", // NoEntitlement- "My consoles", // TabConsoles- "On", // ConsoleOn- "Sleeping", // ConsoleSleeping- "Off", // ConsoleOff- "Looking for your consoles...", // ConsolesLoading- "No Xbox found yet", // NoConsoles- "Play your own Xbox here: its screen, games and apps.", // ConsolesHint- "Waking up your Xbox...", // WakingConsole- "%s did not answer. Check that Remote features are on and the power mode is Sleep, or turn it on, then try again.", // WakeFailed- "On your Xbox, sign in with this same Microsoft account.", // ConsoleStep1- "Settings > Devices & connections > Remote features: turn on remote features.", // ConsoleStep2- "Settings > General > Power options: choose Sleep, so it wakes up by itself.", // ConsoleStep3- "Scan for Microsoft's help", // ScanForHelp- "Search again", // SearchAgain- "Xbox button", // MenuXboxButton- "End the stream", // MenuEndStream- "The stream was ended on the Xbox", // EndedOnXbox- "Another device took over the stream", // EndedByOtherDevice- "The Xbox was turned off", // EndedXboxOff- "%s got the request but its Remote Play didn't start. Restart it: hold the power button on the console for 10 seconds, turn it back on, then try again.", // StreamingStuck- "Touchpad: swipe ↓ for the menu, ↑ for the Xbox button", // GestureHint- "FSR + clean-up", // UpscalerFsrClean- "AI + clean-up", // UpscalerAiClean- "Auto (%s)", // DebandAuto- "Update now? The app restarts by itself when it's done.", // UpdatePrompt- "Update now", // UpdateNow- "Not now", // NotNow- "Updates", // Updates- "Up to date (%s)", // UpToDate- "%s available: update", // UpdateReady- "Checking...", // UpdateChecking- "Updating to %s", // UpdatingTo- "Downloading... %s", // UpdateDownloading- "Checking the signature...", // UpdateVerifying- "Installing...", // UpdateInstalling- "Updated. Restarting...", // UpdateRestarting- "PSBox updated: open the app again", // UpdateReopen- "Update failed: nothing was changed", // UpdateFailed- "Game colour", // LightBarGame- "Custom colour", // LightBarCustom- "Light bar colour", // LightBarColour- "Left stick or D-pad: colour L2 / R2: brightness", // ColourPickerHelp- "Light", // TriggerLight- "Medium", // TriggerMedium- "Strong", // TriggerStrong- "Max", // TriggerMax- "Intensity", // TriggerIntensity- "Frequency", // TriggerFrequency- "Low", // FrequencyLow- "High", // FrequencyHigh- "Press L2 / R2 to feel it: the deeper, the stronger the game would ask", // TriggerTestHelp- "Level %s", // TriggerLevel- "Left stick", // StickLeft- "Right stick", // StickRight- "Stick position", // StickPosition- "What the game gets", // StickGameGets- "L1 / R1: choose the stick D-pad ← / →: adjust Move the sticks to see it", // StickTestHelp- "Resistance", // TriggerResistance- "Style", // TriggerStyle- "Vibration", // StyleVibration- "Force pulses", // StylePulses- "Mode", // FilterMode- "Genre", // FilterGenre- "Language", // FilterLanguage- "All modes", // ModeAll- "Single player", // ModeSingle- "Online multiplayer", // ModeOnlineMulti- "Online co-op", // ModeOnlineCoop- "Local / split screen", // ModeLocal- "All genres", // GenreAll- "Any language", // LanguageAll- "English", // LanguageNoun- "Subtitles in %s", // LangSubtitles- "Audio in %s", // LangAudio- "Game settings", // GameSettings- "Profile", // Profile- "Default", // ProfileDefault- "Custom", // ProfileCustom- "Reset to default", // ResetToDefault- "Publisher", // FilterPublisher- "All publishers", // PublisherAll- "Indies & Others", // PublisherIndies- "Friends playing now", // FriendsPlayingNow- "Microphone", // MenuMicrophone- "Muted", // MicMuted- "Active", // MicActive- "Audio output", // MenuAudioOutput- "TV", // AudioRouteTv- "DualSense Speaker", // AudioRoutePad- "Report a problem", // ReportProblem- "Scan it with your phone: GitHub's bug form opens, filled in. You review it before sending it.", // ReportScan- "It includes the app's version, the error and lines of its log, without personal data.", // ReportIncludes- "PSBox closed unexpectedly last time", // CrashedLastTime- "Sign-in country", // LoginCountry- "Off (this console's)", // LoginCountryOff- "Sign in as another country", // TryOtherCountry- "xCloud will be told the sign-in comes from the chosen country. Microsoft doesn't allow this: use it at your own risk. Games may then come from servers far away, with more delay. You can change it later in Settings.", // LoginCountryWarning- "xCloud refused the sign-in. Cloud gaming may not be offered in your country, or the account may not have a Game Pass plan with cloud gaming.", // RegionRefused- "xCloud refused the sign-in, even as %s. The account probably doesn't have a Game Pass plan with cloud gaming.", // RegionRefusedAs- "Brazil", // CountryBR- "Japan", // CountryJP- "South Korea", // CountryKR- "Poland", // CountryPL- "United States", // CountryUS- "Secure connections were refused because the PS5's date and time look wrong (it says %s). Set them in Settings > System > Date and Time, then try again.", // ClockWrong- "A secure connection was refused: something on the network (a DNS server, proxy or filter) is answering for Microsoft's sites. Try without it, then try again.", // ConnectionIntercepted- "PS5 date and time look wrong (%s): some content can't load. Set them in Settings > System > Date and Time.", // ClockWrongNotice- "Your sign-in couldn't be saved on the console, so it will be asked again next time. Please report it (Settings > △).", // SignInNotSaved- "Estimated wait: %s s", // QueueSeconds- "Estimated wait: %s min", // QueueMinutes- "120 Hz output (VRR)", // HighRefresh- "On (in games)", // HighRefreshOn- "Unstable connection", // ConnectionUnstable- "Session: %s", // SessionSummary- "Maximum bitrate", // BitrateCap- "Automatic", // BitrateAuto- "Game volume", // GameVolume- "Keyboard: F12 this menu · Home Xbox button", // MenuKeyHint- "Mouse & keyboard", // FilterMouseKeyboard- "Mouse and keyboard", // MouseKeyboardSupport- "Keyboard and mouse: player %s", // KeyboardPlayer- "You're in the queue.", // InQueueNoEstimate- "Keyboard keys", // KeyboardKeys- "D-pad", // DPad- "Press a key or mouse button", // PressKey- "%s is kept by the app", // KeyReserved- "Change", // ChangeKey- "Clear", // ClearKey- "The mouse moves the right stick and a wheel notch presses Triangle. F12 (menu), Home (Xbox button) and 1-4 (player) are kept by the app.", // KeysHelp- "Gyro aiming", // Gyro- "Always", // GyroAlways- "While aiming (L2)", // GyroAiming- "Gyro intensity", // GyroIntensity- "Secure connections were refused because this computer's date and time look wrong (it says %s). Correct them in the system's settings, then try again.", // ClockWrongPc- "This computer's date and time look wrong (%s): some content can't load. Correct them in the system's settings.", // ClockWrongNoticePc- "Off (this computer's)", // LoginCountryOffPc- "Open in the browser", // OpenInBrowser- "%s available: download", // UpdateReadyPc- "Menu: START + BACK or F12 · Xbox button: Guide or Home", // GestureHintButtons- "START + BACK or F12: this menu · Guide or Home: Xbox button", // MenuButtonHint- "Display mode", // DisplayMode- "Window", // DisplayWindow- "Fullscreen", // DisplayFullscreen- "Quit PSBox?", // QuitTitle- "Quit", // QuitConfirm- "Controller buttons", // ControllerButtons- "Press the button for %s", // PadPressButton- "Missing a button: %s. Give each one a button, or reset or discard the changes.", // PadMissing- "Discard changes", // DiscardChanges- "Only the game sees this: the app's menus keep the buttons as they are. Picking a button used by another swaps the two.", // PadHelp- "Plan", // FilterPlan- "My plan", // PlanMine- "All plans", // PlanAll- "Included with Game Pass %s", // IncludedWithPlan- "Touchpad as mouse", // TouchpadMouse- "Favourites", // Favorites- "Add to favourites", // AddFavorite- "Remove from favourites", // RemoveFavorite- "Added to favourites", // AddedToFavorites- "Removed from favourites", // RemovedFromFavorites- "Game language", // GameLanguage- "Monthly cloud gaming limit reached", // MonthlyLimitExceeded- "Playtime remaining", // PlaytimeRemaining- "%s h remaining", // HoursRemaining- "Less than 2 h remaining", // PlaytimeWarning- "Trigger profile", // TriggerProfile- "Standard", // TriggerProfileStd- "Shooter (Hair Trigger)", // TriggerProfileShooter- "Racing (ABS)", // TriggerProfileRacing- "Storage %s is not writable: sign-in and settings will not be saved", // StorageNotWritable- "FTP: run 'chmod 777 %s' or delete the folder and relaunch", // StorageFixHint- "Customize indicators", // StatsCustomize- "FPS & Resolution", // StatsIndicatorFps- "Bitrate", // StatsIndicatorBitrate- "Latency (RTT)", // StatsIndicatorLatency- "Packet loss", // StatsIndicatorLoss- "Frametime graph", // StatsIndicatorGraph- "Decode & display latency", // StatsIndicatorDelay- "Video quality (QP)", // StatsIndicatorQp- "Microphone status", // StatsIndicatorMic- "Scan the QR code on your phone to resolve this with Microsoft, then press Cross to try again", // ScanQrToResolve- "Get Free", // ClaimFree- "Claiming free license...", // Claiming- "Game added to your account!", // ClaimSuccess- "Failed to claim free game: %s", // ClaimFailed- "This game is not free in the store", // ProductNotFree- "Free game. Press Cross to add to your account and start playing", // FreeAcquireHint- "DNS lookup failed for Microsoft servers. If you are blocking Sony updates on PS5, make sure you are running NanoDNS with Primary DNS set to your local IP to keep internet access.", // DnsBlockedNanoDns- "This Microsoft account has no Xbox profile yet. Sign in to xbox.com on your phone or PC to set up your Gamertag, then try again.", // XboxProfileMissing- "Queue ready! Starting game...", // QueueReadyAlert- "Queue ready chime", // QueueReadyNotification- "Played: %s", // PlaytimePlayed- "Refresh", // RefreshLibrary- "Refreshing library...", // RefreshingLibrary- "This Xbox account is suspended or banned. Visit enforcement.xbox.com for details.", // XboxAccountBanned- "Xbox Live is not offered in this account's country or region.", // XboxRegionNotSupported- "Age verification or terms acceptance is required. Sign in to xbox.com in a browser, then try again.", // XboxAdultVerificationRequired- "Child account: an adult must add this account to a Microsoft family at account.microsoft.com/family.", // XboxChildAccountFamily- "Check my sign-in", // CheckSignIn- "Run check", // RunCheck- "Network test", // NetworkTest- "Run test", // RunTest- "Achievements", // Achievements- "No achievements", // NoAchievements- "Locked", // AchievementLocked- "Secret achievement", // SecretAchievement- "Wishlist", // Wishlist- "Add to wishlist", // AddWishlist- "Remove from wishlist", // RemoveWishlist- "Added to wishlist", // AddedToWishlist- "Removed from wishlist", // RemovedFromWishlist- "%s is on sale!", // WishlistOnSale- "%s joined Game Pass!", // WishlistInGamePass- "Support the project", // SupportProject- "Support PSBox Development", // SupportTitle- "PSBox is an open-source project passionately maintained to bring the best Xbox Cloud Gaming experience to PlayStation 5. If you enjoy the app and would like to support ongoing development, frequent updates and new features, consider buying me a coffee on Ko-Fi!", // SupportMessage- "Ko-fi", // SupportKoFi- "Scan with your phone to support", // ScanToDonate- "Test sound", // TestSound- "Wishlist is empty", // WishlistEmpty- // Loading tips- "Touchpad: swipe ↓ (or Touchpad + Options) for the menu, ↑ for the Xbox button", // TipTouchpadMenu- "USB keyboard and mouse plugged into the console are supported in enabled cloud games", // TipKeyboardMouse- "Claim free games, trials, and discover store promotions directly from the app library", // TipFreeStore- "Encountered an issue? Open Bug Report to scan a QR code with auto-attached console logs", // TipBugReportQr- "Enjoying the project? Support future development via Ko-fi in the Settings tab!", // TipSupportKofi- "Enable 120 Hz display output in Settings for reduced frame latency and smoother response", // Tip120HzVideo- "Calibrate DualSense stick dead zones in Settings to eliminate stick drift and improve precision", // TipAnalogDeadzone- "Use the DualSense built-in microphone for party and multiplayer game voice chat", // TipDualSenseMic- // Settings descriptions- "Changes the language of the application interface and the preferred audio and subtitles in cloud games", // SettingDescLanguage- "Sets the maximum streaming video resolution (1080p, 720p, or Best available). Takes effect on the next launch", // SettingDescResolution- "Selects the Microsoft datacenter region for streaming (Automatic or specific regions). Takes effect on the next launch", // SettingDescRegion- "Adjusts the inner dead zone of DualSense analog sticks to prevent stick drift and unintended movement", // SettingDescDeadzone- "Enables or disables impulse trigger vibration emulation on DualSense L2 and R2 adaptive triggers", // SettingDescTriggerRumble- "Toggles the confirm and back button layout between Cross (Western style) and Circle (Japanese style)", // SettingDescConfirmButton- "Configures the light bar color and behavior of your DualSense controller during browsing and gameplay", // SettingDescLightBar- "Checks for and automatically installs official app updates directly on your console without needing a PC", // SettingDescUpdates- "Allows signing in to your Xbox account via a different geographic region to access alternative catalogs", // SettingDescLoginCountry- "Enables 120 Hz video output on your console for lower display lag and reduced input latency", // SettingDescHighRefresh- "Sets the maximum bandwidth limit for video streaming, ensuring higher visual fidelity or saving network data", // SettingDescBitrateCap- "Adjusts the master audio volume level played during game streaming sessions", // SettingDescGameVolume- "Maps USB or Bluetooth keyboard keys to the corresponding Xbox controller buttons during gameplay", // SettingDescKeyboardKeys- "Toggles between windowed and fullscreen display mode on supported desktop platforms", // SettingDescDisplayMode- "Opens the response test and calibration screen for all buttons and axes on your connected controller", // SettingDescControllerButtons- "Enables DualSense motion sensors to assist with analog aiming in shooter and action games", // SettingDescGyro- "Plays a distinctive chime when your wait in the xCloud queue finishes and your game is ready", // SettingDescQueueReady- "Runs a complete diagnostic on your Xbox Live sign-in, validating access tokens, profile, and subscriptions", // SettingDescCheckSignIn- "Measures ping (RTT) and jitter to cloud gaming datacenters across multiple global regions", // SettingDescNetworkTest- "Displays a QR Code to support the developer via Ko-fi and help keep the project actively maintained", // SettingDescSupportProject- "What's New", // WhatsNew- "What's New", // WhatsNewTitle- "Controller speaker", // PadSpeakerVolume- "Mute", // Mute- "Web Control", // WebControlTitle- "Connect from your phone", // WebControlSubtitle- "Connect to the same Wi-Fi to type search, remap buttons, use your phone as a virtual controller, report issues or view logs.", // WebControlDesc- "Video Decoder", // VideoDecoder- "Hardware (Recommended)", // VideoDecoderHw- "Software (CPU)", // VideoDecoderSw- "Selects hardware decoding (libSceVideodec2 on PS5, HWAccel on Desktop) or CPU software decoding", // SettingDescVideoDecoder- "Audio-to-Haptics", // AudioHaptics- "Converts low-frequency game audio into DualSense haptic rumble kicks", // SettingDescAudioHaptics- "Touchpad shortcuts", // TouchpadShortcuts- "Configures swipe gestures and left/right click actions on the DualSense touchpad", // SettingDescTouchpadShortcuts- "Swipe Up (↑)", // TouchpadSwipeUp- "Swipe Down (↓)", // TouchpadSwipeDown- "Swipe Left (←)", // TouchpadSwipeLeft- "Swipe Right (→)", // TouchpadSwipeRight- "Left Click", // TouchpadClickLeft- "Right Click", // TouchpadClickRight- "Disabled", // TouchpadActNone- "In-game menu", // TouchpadActGameMenu- "Xbox button", // TouchpadActXboxButton- "Toggle stats", // TouchpadActToggleStats- "Mute/unmute mic", // TouchpadActToggleMic- "Cycle gyro mode", // TouchpadActCycleGyro- "Cycle trigger profile", // TouchpadActCycleTrigger- "Touchpad + Options always opens the in-game menu", // TouchpadHelp- "Restore default settings", // ResetSettings- "Restores all settings to factory defaults. Hold Cross for 5 seconds to confirm.", // SettingDescResetSettings- "Settings restored to factory defaults.", // SettingsResetNotice- "Hold to reset", // HoldToReset- "Library is already up to date", // LibraryUpToDate- "Library updated (%s new games)", // LibraryUpdatedCount- "Offline mode", // OfflineMode-};--constexpr Column kPortugueseBR = {- "PSBox Cloud Gaming",- "PSBOX CLOUD GAMING",- "Entrando...",- "Gerando um código de login...",- "Carregando seus jogos...",- "Entre para jogar",- "No celular ou computador, acesse",- "e digite este código",- "Escaneie para abrir a página e digite o código",- "Aguardando você entrar...",- "Continue jogando",- "Jogar",- "Voltar",- "Selecionar",- "Sair da conta",- "Cancelar",- "Tentar de novo",- "Preparando seu jogo",- "Você está na fila. Espera estimada: %s",- "Conectando...",- "Iniciando o streaming...",- "Touchpad: ↓ este menu · ↑ botão Xbox",- "Streaming encerrado",- "Algo deu errado",- "Conectado como %s",- "Nenhum jogo para mostrar ainda",- "Por %s",- "Configurações",- "Idioma",- "Resolução do streaming",- "Região do servidor",- "Automática (%s)",- "1080p (Full HD)",- "720p (usa menos dados)",- "Melhor (Auto)",- "A resolução e a região valem a partir do próximo jogo.",- "Alterar",- "Ajustar",- "Segure para sair da conta",- "Continue segurando para sair da conta (%s)",- "Falha ao entrar: %s",- "O login no navegador não foi concluído. Use uma conta pessoal da Microsoft, conclua verificações de segurança/2FA e autorize o app.",- "Não foi possível carregar a lista de jogos: %s",- "Não foi possível iniciar o streaming: %s",- "Sem atividade: você será desconectado em %s segundos",- "Meus jogos",- "Indisponível na sua conta",- "Game Pass",- "Pesquisar",- "Digite o nome de um jogo",- "Nenhum jogo encontrado",- "%s resultados",- "Espaço",- "Apagar",- "Limpar",- "%s jogos",- "Digitar",- "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 Meus jogos.",- "Escaneie para abrir a página da loja",- "Pesquisar em %s",- "GRÁTIS",- "Ocultar",- "Mostrar",- "Ocultos",- "\xE2\x96\xA1 mostra o jogo de novo",- "Oculto: veja em Ocultos, no fim desta aba",- "Visível de novo",- "Ordenar: %s",- "Recentes primeiro",- "A-Z",- "Por console",- "Ordenar",- "Grátis",- "Menor preço",- "Todos os consoles",- "1 jogo",- "Seções",- "Atualizando a lista de jogos...",- "Menu do jogo",- "Estatísticas",- "Ligado",- "Desligado",- "Resolução do stream",- "Sair do jogo",- "Latência",- "Taxa de bits",- "Quadros por segundo",- "Perda de pacotes",- "Região",- "Decodificação",- "O servidor pode manter a qualidade atual",- "Nitidez",- "Desligada",- "Baixa",- "Média",- "Alta",- "Zona morta do analógico",- "Vibração nos gatilhos",- "Botão de confirmar",- "Ativada",- "Desativada",- "Versão %s disponível",- "Controles",- "Controle %s conectado",- "Controle %s desconectado",- "Suavização de blocos",- "Na tela após",- "Conexão perdida: reconectando...",- "Reconectado",- "Barra de luz",- "Ampliação",- "IA (Anime4K)",- "Grátis para jogar",- "Pegue uma vez, de graça, no xbox.com ou no app Xbox (escaneie o código com o celular) e depois aperte Jogar.",- "Escaneie para pegar grátis",- "%s ainda não está na sua conta. É grátis: escaneie o código na página do jogo, escolha Obter e tente de novo (pode levar um minuto).",- "Sua conta não pode jogar %s: não está na sua assinatura ou não foi comprado.",- "Meus consoles",- "Ligado",- "Em espera",- "Desligado",- "Procurando seus consoles...",- "Nenhum Xbox encontrado ainda",- "Jogue no seu próprio Xbox por aqui: a tela, os jogos e os apps dele.",- "Ligando o seu Xbox...",- "%s não respondeu. Confira se os Recursos remotos estão ativos e o modo de energia é Suspensão, ou ligue o console, e tente de novo.",- "No seu Xbox, entre com esta mesma conta Microsoft.",- "Configurações > Dispositivos e conexões > Recursos remotos: ative os recursos remotos.",- "Configurações > Geral > Opções de energia: escolha Suspensão, para ele acordar sozinho.",- "Escaneie para a ajuda da Microsoft",- "Procurar de novo",- "Botão Xbox",- "Encerrar transmissão",- "A transmissão foi encerrada no Xbox",- "Outro aparelho assumiu a transmissão",- "O Xbox foi desligado",- "%s recebeu o pedido, mas o jogo remoto dele não iniciou. Reinicie o console: segure o botão de ligar do Xbox por 10 segundos, ligue de novo e tente outra vez.",- "Touchpad: deslize ↓ para o menu, ↑ para o botão Xbox",- "FSR + limpeza",- "IA + limpeza",- "Auto (%s)",- "Atualizar agora? O app reinicia sozinho ao terminar.",- "Atualizar agora",- "Agora não",- "Atualizações",- "Atualizado (%s)",- "%s disponível: atualizar",- "Verificando...",- "Atualizando para %s",- "Baixando... %s",- "Conferindo a assinatura...",- "Instalando...",- "Atualizado. Reiniciando...",- "PSBox atualizado: abra o app de novo",- "A atualização falhou: nada foi alterado",- "Cor do jogo",- "Cor personalizada",- "Cor da barra de luz",- "Analógico esquerdo ou direcional: cor L2 / R2: brilho",- "Leve",- "Média",- "Forte",- "Máxima",- "Intensidade",- "Frequência",- "Grave",- "Aguda",- "Aperte L2 / R2 para sentir: quanto mais fundo, mais forte o jogo pediria",- "Nível %s",- "Analógico esquerdo",- "Analógico direito",- "Posição real",- "O que o jogo recebe",- "L1 / R1: escolher o analógico Direcional ← / →: ajustar Mova os analógicos para ver",- "Resistência",- "Estilo",- "Vibração",- "Pulsos de força",- "Modo",- "Gênero",- "Idioma",- "Todos os modos",- "Um jogador",- "Multijogador online",- "Cooperação online",- "Local / tela dividida",- "Todos os gêneros",- "Qualquer idioma",- "português",- "Legendas em %s",- "Dublado em %s",- "Configurações do jogo",- "Perfil",- "Padrão",- "Personalizado",- "Restaurar padrão",- "Editora",- "Todas as editoras",- "Indies & Outras",- "Amigos jogando agora",- "Microfone",- "Mutado",- "Ativo",- "Saída de áudio",- "TV",- "Alto-falante do controle",- "Relatar problema",- "Escaneie com o celular: o formulário de bug do GitHub abre preenchido. Você revisa antes de enviar.",- "Inclui a versão do app, o erro e linhas do log, sem dados pessoais.",- "O PSBox fechou inesperadamente da última vez",- "País do login",- "Desativado (o do console)",- "Entrar como outro país",- "O xCloud será informado de que o login vem do país escolhido. A Microsoft não permite isso: use por sua conta e risco. Os jogos podem vir de servidores distantes, com mais atraso. Dá para mudar depois em Configurações.",- "O xCloud recusou o login. O jogo na nuvem pode não ser oferecido no seu país, ou a conta pode não ter um plano do Game Pass com jogos na nuvem.",- "O xCloud recusou o login, mesmo como %s. Provavelmente a conta não tem um plano do Game Pass com jogos na nuvem.",- "Brasil",- "Japão",- "Coreia do Sul",- "Polônia",- "Estados Unidos",- "As conexões seguras foram recusadas porque a data e a hora do PS5 parecem erradas (ele diz %s). Acerte em Configurações > Sistema > Data e hora e tente de novo.",- "Uma conexão segura foi recusada: algo na rede (um servidor DNS, proxy ou filtro) está respondendo no lugar dos sites da Microsoft. Tente sem ele e tente de novo.",- "A data e a hora do PS5 parecem erradas (%s): parte do conteúdo não carrega. Acerte em Configurações > Sistema > Data e hora.",- "Não foi possível salvar o login no console, então ele será pedido de novo na próxima vez. Relate o problema (Configurações > △).",- "Espera estimada: %s s", // QueueSeconds- "Espera estimada: %s min", // QueueMinutes- "Saída 120 Hz (VRR)", // HighRefresh- "Ativada (nos jogos)", // HighRefreshOn- "Conexão instável", // ConnectionUnstable- "Sessão: %s", // SessionSummary- "Bitrate máximo", // BitrateCap- "Automático", // BitrateAuto- "Volume do jogo", // GameVolume- "Teclado: F12 este menu · Home botão Xbox", // MenuKeyHint- "Teclado e mouse", // FilterMouseKeyboard- "Teclado e mouse", // MouseKeyboardSupport- "Teclado e mouse: jogador %s", // KeyboardPlayer- "Você está na fila.", // InQueueNoEstimate- "Teclas do teclado", // KeyboardKeys- "Direcional", // DPad- "Pressione uma tecla ou botão do mouse", // PressKey- "%s é reservada pelo app", // KeyReserved- "Alterar", // ChangeKey- "Limpar", // ClearKey- "O mouse move o analógico direito e cada clique da roda aperta Triângulo. F12 (menu), Home (botão Xbox) e 1-4 (jogador) são reservadas pelo app.", // KeysHelp- "Mira por giroscópio", // Gyro- "Sempre", // GyroAlways- "Ao mirar (L2)", // GyroAiming- "Intensidade do giroscópio", // GyroIntensity- "As conexões seguras foram recusadas porque a data e a hora deste computador parecem erradas (ele diz %s). Acerte nas configurações do sistema e tente de novo.", // ClockWrongPc- "A data e a hora deste computador parecem erradas (%s): parte do conteúdo não carrega. Acerte nas configurações do sistema.", // ClockWrongNoticePc- "Desativado (o do computador)", // LoginCountryOffPc- "Abrir no navegador", // OpenInBrowser- "%s disponível: baixar", // UpdateReadyPc- "Menu: START + BACK ou F12 · Botão Xbox: Guide ou Home", // GestureHintButtons- "START + BACK ou F12: este menu · Guide ou Home: botão Xbox", // MenuButtonHint- "Modo de exibição", // DisplayMode- "Janela", // DisplayWindow- "Tela cheia", // DisplayFullscreen- "Sair do PSBox?", // QuitTitle- "Sair", // QuitConfirm- "Botões do controle", // ControllerButtons- "Aperte o botão para %s", // PadPressButton- "Falta botão para: %s. Dê um botão a cada um, ou restaure o padrão ou descarte as alterações.", // PadMissing- "Descartar alterações", // DiscardChanges- "Só o jogo vê isto: os menus do app usam os botões como são. Escolher um botão já usado troca os dois.", // PadHelp- "Plano", // FilterPlan- "Meu plano", // PlanMine- "Todos os planos", // PlanAll- "Incluído no Game Pass %s", // IncludedWithPlan- "Touchpad como mouse", // TouchpadMouse- "Favoritos", // Favorites- "Adicionar aos favoritos", // AddFavorite- "Remover dos favoritos", // RemoveFavorite- "Adicionado aos favoritos", // AddedToFavorites- "Removido dos favoritos", // RemovedFromFavorites- "Idioma do jogo", // GameLanguage- "Limite mensal de jogo em nuvem atingido", // MonthlyLimitExceeded- "Tempo de jogo restante", // PlaytimeRemaining- "%s h restantes", // HoursRemaining- "Menos de 2 h restantes", // PlaytimeWarning- "Perfil de gatilho", // TriggerProfile- "Padrão", // TriggerProfileStd- "Tiroteio (Hair Trigger)", // TriggerProfileShooter- "Corrida (ABS)", // TriggerProfileRacing- "Armazenamento %s não permite gravação: login e ajustes não serão salvos", // StorageNotWritable- "FTP: use 'chmod 777 %s' ou exclua a pasta e reabra o app", // StorageFixHint- "Personalizar indicadores", // StatsCustomize- "FPS e resolução", // StatsIndicatorFps- "Taxa de bits (Bitrate)", // StatsIndicatorBitrate- "Latência (RTT)", // StatsIndicatorLatency- "Perda de pacotes", // StatsIndicatorLoss- "Gráfico de frametime", // StatsIndicatorGraph- "Atraso de decodificação e exibição", // StatsIndicatorDelay- "Qualidade do vídeo (QP)", // StatsIndicatorQp- "Status do microfone", // StatsIndicatorMic- "Use seu celular para ler o código QR ao lado e resolver na Microsoft, depois pressione Cruz para tentar novamente", // ScanQrToResolve- "Adquirir Grátis", // ClaimFree- "Adquirindo licença gratuita...", // Claiming- "Jogo adicionado à sua conta com sucesso!", // ClaimSuccess- "Falha ao adquirir o jogo gratuito: %s", // ClaimFailed- "Este jogo não é gratuito na loja", // ProductNotFree- "Jogo gratuito. Pressione Cruz para adicionar à sua conta e começar a jogar", // FreeAcquireHint- "Falha de conexão DNS com os servidores da Microsoft. No PS5, certifique-se de estar rodando o NanoDNS com o DNS Primário configurado para o IP local para manter acesso à internet enquanto bloqueia a Sony.", // DnsBlockedNanoDns- "Esta conta Microsoft ainda não possui um perfil Xbox. Entre em xbox.com pelo celular ou computador para criar sua Gamertag e tente novamente.", // XboxProfileMissing- "Fila liberada! Iniciando o jogo...", // QueueReadyAlert- "Aviso sonoro de fila pronta", // QueueReadyNotification- "Jogado: %s", // PlaytimePlayed- "Atualizar", // RefreshLibrary- "Atualizando biblioteca...", // RefreshingLibrary- "Esta conta Xbox está suspensa ou banida. Acesse enforcement.xbox.com para mais detalhes.", // XboxAccountBanned- "O Xbox Live não é oferecido no país ou região desta conta.", // XboxRegionNotSupported- "Verificação de idade ou aceite dos termos necessário. Entre em xbox.com pelo navegador e tente novamente.", // XboxAdultVerificationRequired- "Conta infantil: um adulto precisa adicionar esta conta a uma família Microsoft em account.microsoft.com/family.", // XboxChildAccountFamily- "Verificar meu login", // CheckSignIn- "Verificar", // RunCheck- "Teste de rede", // NetworkTest- "Testar", // RunTest- "Conquistas", // Achievements- "Nenhuma conquista", // NoAchievements- "Bloqueada", // AchievementLocked- "Conquista secreta", // SecretAchievement- "Lista de desejos", // Wishlist- "Adicionar à lista de desejos", // AddWishlist- "Remover da lista de desejos", // RemoveWishlist- "Adicionado à lista de desejos", // AddedToWishlist- "Removido da lista de desejos", // RemovedFromWishlist- "%s está em promoção!", // WishlistOnSale- "%s entrou no Game Pass!", // WishlistInGamePass- "Apoie o projeto", // SupportProject- "Apoie o Desenvolvimento do PSBox", // SupportTitle- "O PSBox é um projeto de código aberto mantido com dedicação para trazer a melhor experiência do Xbox Cloud Gaming ao PlayStation 5. Se você curte o app e quer apoiar o desenvolvimento contínuo, atualizações e novos recursos, considere me pagar um café no Ko-Fi!", // SupportMessage- "Ko-fi", // SupportKoFi- "Aponte a câmera do seu celular", // ScanToDonate- "Testar som", // TestSound- "A lista de desejos está vazia", // WishlistEmpty- // Loading tips- "Touchpad: deslize ↓ (ou Touchpad + Options) para o menu, ↑ para o botão Xbox", // TipTouchpadMenu- "Teclado e mouse USB conectados ao console são suportados em jogos compatíveis da nuvem", // TipKeyboardMouse- "Adquira jogos gratuitos, demonstrações e confira promoções da loja direto pelo aplicativo", // TipFreeStore- "Encontrou um problema? Abra Relatar Problema para escanear um QR code com logs do console", // TipBugReportQr- "Gostando do app? Apoie o desenvolvimento contínuo via Ko-fi na aba de Configurações!", // TipSupportKofi- "Ative a saída de vídeo em 120 Hz nas Configurações para menor latência e resposta mais rápida", // Tip120HzVideo- "Ajuste a zona morta dos analógicos do DualSense nas Configurações para eliminar drift", // TipAnalogDeadzone- "Use o microfone integrado do DualSense para bate-papo de voz em grupos e jogos multijogador", // TipDualSenseMic- // Settings descriptions- "Altera o idioma da interface do aplicativo e a preferência de áudio e legendas nos jogos da nuvem", // SettingDescLanguage- "Define a resolução máxima do fluxo de vídeo transmitido (1080p, 720p ou Melhor). Vale a partir do próximo jogo", // SettingDescResolution- "Seleciona a região de servidores Microsoft para streaming (Automático ou regiões específicas). Vale a partir do próximo jogo", // SettingDescRegion- "Ajusta a sensibilidade inicial dos analógicos do DualSense para evitar drift ou comandos involuntários", // SettingDescDeadzone- "Ativa ou desativa a simulação dos motores de vibração nos gatilhos adaptáveis L2 e R2 em jogos compatíveis", // SettingDescTriggerRumble- "Alterna a função de confirmar e voltar entre Cruz (padrão ocidental) e Círculo (padrão japonês)", // SettingDescConfirmButton- "Configura a cor e o comportamento da barra de luz do DualSense durante a navegação e a jogatina", // SettingDescLightBar- "Verifica e instala automaticamente novas versões lançadas do aplicativo diretamente pelo console sem PC", // SettingDescUpdates- "Permite autenticar sua conta Xbox através de outra região geográfica para acessar catálogos alternativos", // SettingDescLoginCountry- "Ativa saída de vídeo em 120 Hz no console para menor atraso de exibição e redução da latência de comando", // SettingDescHighRefresh- "Define o limite máximo de bitrate para o stream de vídeo, garantindo fidelidade visual ou economizando rede", // SettingDescBitrateCap- "Ajusta o nível geral do volume de áudio reproduzido durante as sessões de streaming dos jogos", // SettingDescGameVolume- "Mapeia as teclas do teclado USB ou Bluetooth para os botões correspondentes do controle Xbox no jogo", // SettingDescKeyboardKeys- "Alterna entre modo de janela ou tela cheia em plataformas desktop suportadas", // SettingDescDisplayMode- "Abre o painel de teste de resposta e calibração de todos os botões e eixos do controle conectado", // SettingDescControllerButtons- "Permite usar os sensores de movimento do DualSense para auxiliar na mira em jogos de tiro e ação", // SettingDescGyro- "Toca um aviso sonoro característico quando o tempo de espera na fila do xCloud terminar e o jogo iniciar", // SettingDescQueueReady- "Realiza um diagnóstico completo da autenticação Xbox Live, validando tokens de acesso, perfil e assinaturas", // SettingDescCheckSignIn- "Mede o ping (RTT) e a variação (jitter) para servidores de jogos em nuvem de várias regiões globais", // SettingDescNetworkTest- "Exibe um QR Code para você apoiar o desenvolvedor via Ko-fi e ajudar a manter o projeto ativo e atualizado", // SettingDescSupportProject- "Novidades", // WhatsNew- "Novidades", // WhatsNewTitle- "Alto-falante do controle", // PadSpeakerVolume- "Mudo", // Mute- "Configuração Web", // WebControlTitle- "Acesse pelo celular", // WebControlSubtitle- "Conecte no mesmo Wi-Fi para pesquisar, remapear botões, usar o celular como controle virtual, relatar problemas ou visualizar o log.", // WebControlDesc- "Decodificação de Vídeo", // VideoDecoder- "Hardware (Recomendado)", // VideoDecoderHw- "Software (CPU)", // VideoDecoderSw- "Seleciona decodificação por hardware (libSceVideodec2 no PS5, HWAccel no Desktop) ou por software (CPU)", // SettingDescVideoDecoder- "Áudio para Vibração Háptica", // AudioHaptics- "Converte graves do áudio em vibração háptica no DualSense", // SettingDescAudioHaptics- "Atalhos do Touchpad", // TouchpadShortcuts- "Configura gestos de deslize e cliques esquerdo e direito no Touchpad do DualSense", // SettingDescTouchpadShortcuts- "Deslizar para Cima (↑)", // TouchpadSwipeUp- "Deslizar para Baixo (↓)", // TouchpadSwipeDown- "Deslizar para Esquerda (←)", // TouchpadSwipeLeft- "Deslizar para Direita (→)", // TouchpadSwipeRight- "Clique Esquerdo", // TouchpadClickLeft- "Clique Direito", // TouchpadClickRight- "Desativado", // TouchpadActNone- "Menu do jogo", // TouchpadActGameMenu- "Botão Xbox", // TouchpadActXboxButton- "Alternar estatísticas", // TouchpadActToggleStats- "Mutar/desmutar microfone", // TouchpadActToggleMic- "Alternar giroscópio", // TouchpadActCycleGyro- "Alternar perfil de gatilho", // TouchpadActCycleTrigger- "Touchpad + Options sempre abre o menu do jogo", // TouchpadHelp- "Restaurar configurações padrões", // ResetSettings- "Restaura todas as configurações para os padrões de fábrica. Mantenha ✕ por 5 segundos para confirmar.", // SettingDescResetSettings- "Configurações restauradas para os padrões.", // SettingsResetNotice- "Segure para restaurar", // HoldToReset- "Biblioteca já está atualizada", // LibraryUpToDate- "Biblioteca atualizada (%s novos jogos)", // LibraryUpdatedCount- "Modo offline", // OfflineMode-};--constexpr Column kSpanish = {- "PSBox Cloud Gaming",- "PSBOX CLOUD GAMING",- "Iniciando sesión...",- "Obteniendo un código de inicio de sesión...",- "Cargando tus juegos...",- "Inicia sesión para jugar",- "En tu teléfono u ordenador, ve a",- "e introduce este código",- "Escanea para abrir la página e introduce el código",- "Esperando a que inicies sesión...",- "Seguir jugando",- "Jugar",- "Atrás",- "Seleccionar",- "Cerrar sesión",- "Cancelar",- "Reintentar",- "Preparando tu juego",- "Estás en la cola. Espera estimada: %s",- "Conectando...",- "Iniciando el streaming...",- "Panel táctil: ↓ este menú · ↑ botón Xbox",- "Streaming finalizado",- "Algo salió mal",- "Sesión iniciada como %s",- "Todavía no hay juegos para mostrar",- "De %s",- "Ajustes",- "Idioma",- "Resolución del streaming",- "Región del servidor",- "Automática (%s)",- "1080p (Full HD)",- "720p (usa menos datos)",- "Mejor (Auto)",- "La resolución y la región se aplican al próximo juego que inicies.",- "Cambiar",- "Ajustar",- "Mantén para cerrar sesión",- "Sigue manteniendo para cerrar sesión (%s)",- "Error al iniciar sesión: %s",- "El inicio de sesión no se completó en el navegador. Usa una cuenta personal de Microsoft, completa la verificación/2FA y autoriza la app.",- "No se pudo cargar la lista de juegos: %s",- "No se pudo iniciar el streaming: %s",- "Sin actividad: se te desconectará en %s segundos",- "Mis juegos",- "No disponible en tu cuenta",- "Game Pass",- "Buscar",- "Escribe el nombre de un juego",- "No se encontraron juegos",- "%s resultados",- "Espacio",- "Borrar",- "Limpiar",- "%s juegos",- "Escribir",- "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 Mis juegos.",- "Escanea para abrir la página de la tienda",- "Buscar en %s",- "GRATIS",- "Ocultar",- "Mostrar",- "Ocultos",- "\xE2\x96\xA1 vuelve a mostrar un juego",- "Oculto: está en Ocultos, al final de esta pestaña",- "Visible de nuevo",- "Ordenar: %s",- "Recientes primero",- "A-Z",- "Por consola",- "Ordenar",- "Gratis",- "Menor precio",- "Todas las consolas",- "1 juego",- "Secciones",- "Actualizando la lista de juegos...",- "Menú del juego",- "Estadísticas",- "Activado",- "Desactivado",- "Resolución del stream",- "Salir del juego",- "Latencia",- "Tasa de bits",- "Fotogramas por segundo",- "Pérdida de paquetes",- "Región",- "Decodificación",- "El servidor puede mantener la calidad actual",- "Nitidez",- "Desactivada",- "Baja",- "Media",- "Alta",- "Zona muerta del stick",- "Vibración en los gatillos",- "Botón de confirmar",- "Activada",- "Desactivada",- "Versión %s disponible",- "Mandos",- "Mando %s conectado",- "Mando %s desconectado",- "Suavizado de bloques",- "En pantalla tras",- "Conexión perdida: reconectando...",- "Reconectado",- "Barra de luz",- "Escalado",- "IA (Anime4K)",- "Gratis para jugar",- "Consíguelo una vez, gratis, en xbox.com o en la app de Xbox (escanea el código con el móvil) y luego pulsa Jugar.",- "Escanea para conseguirlo gratis",- "%s aún no está en tu cuenta. Es gratis: escanea el código en su página, elige Obtener y vuelve a intentarlo (puede tardar un minuto).",- "Tu cuenta no puede jugar a %s: no está en tu suscripción o no lo has comprado.",- "Mis consolas",- "Encendida",- "En reposo",- "Apagada",- "Buscando tus consolas...",- "Aún no se encontró ninguna Xbox",- "Juega en tu propia Xbox desde aquí: su pantalla, juegos y aplicaciones.",- "Encendiendo tu Xbox...",- "%s no respondió. Comprueba que las Funciones remotas estén activadas y el modo de energía sea Suspensión, o enciéndela, y vuelve a intentarlo.",- "En tu Xbox, inicia sesión con esta misma cuenta Microsoft.",- "Configuración > Dispositivos y conexiones > Funciones remotas: activa las funciones remotas.",- "Configuración > General > Opciones de energía: elige Suspensión, para que se encienda sola.",- "Escanea para ver la ayuda de Microsoft",- "Buscar de nuevo",- "Botón Xbox",- "Terminar la transmisión",- "La transmisión se terminó en la Xbox",- "Otro dispositivo tomó la transmisión",- "La Xbox se apagó",- "%s recibió la solicitud, pero su juego remoto no se inició. Reiníciala: mantén pulsado el botón de encendido de la consola 10 segundos, enciéndela de nuevo y vuelve a intentarlo.",- "Panel táctil: desliza ↓ para el menú, ↑ para el botón Xbox",- "FSR + limpieza",- "IA + limpieza",- "Auto (%s)",- "¿Actualizar ahora? La app se reinicia sola al terminar.",- "Actualizar ahora",- "Ahora no",- "Actualizaciones",- "Al día (%s)",- "%s disponible: actualizar",- "Comprobando...",- "Actualizando a %s",- "Descargando... %s",- "Comprobando la firma...",- "Instalando...",- "Actualizado. Reiniciando...",- "PSBox actualizado: abre la app de nuevo",- "La actualización falló: no se cambió nada",- "Color del juego",- "Color personalizado",- "Color de la barra de luz",- "Stick izquierdo o cruceta: color L2 / R2: brillo",- "Suave",- "Media",- "Fuerte",- "Máxima",- "Intensidad",- "Frecuencia",- "Grave",- "Aguda",- "Pulsa L2 / R2 para sentirlo: cuanto más a fondo, más fuerte lo pediría el juego",- "Nivel %s",- "Stick izquierdo",- "Stick derecho",- "Posición real",- "Lo que recibe el juego",- "L1 / R1: elegir el stick Cruceta ← / →: ajustar Mueve los sticks para verlo",- "Resistencia",- "Estilo",- "Vibración",- "Pulsos de fuerza",- "Modo",- "Género",- "Idioma",- "Todos los modos",- "Un jugador",- "Multijugador en línea",- "Cooperativo en línea",- "Local / pantalla dividida",- "Todos los géneros",- "Cualquier idioma",- "español",- "Subtítulos en %s",- "Doblado al %s",- "Ajustes del juego",- "Perfil",- "Predeterminado",- "Personalizado",- "Restaurar predeterminado",- "Distribuidora",- "Todas las distribuidoras",- "Indies y otras",- "Amigos jugando ahora",- "Micrófono",- "Silenciado",- "Activo",- "Salida de audio",- "TV",- "Altavoz del mando",- "Informar de un problema",- "Escanéalo con el móvil: se abre el formulario de errores de GitHub, ya rellenado. Lo revisas antes de enviarlo.",- "Incluye la versión de la app, el error y líneas del registro, sin datos personales.",- "PSBox se cerró inesperadamente la última vez",- "País de inicio de sesión",- "Desactivado (el de la consola)",- "Entrar como otro país",- "Se le dirá a xCloud que el inicio de sesión viene del país elegido. Microsoft no lo permite: úsalo bajo tu propio riesgo. Los juegos pueden venir de servidores lejanos, con más retraso. Puedes cambiarlo luego en Ajustes.",- "xCloud rechazó el inicio de sesión. Puede que el juego en la nube no se ofrezca en tu país o que la cuenta no tenga un plan de Game Pass con juego en la nube.",- "xCloud rechazó el inicio de sesión, incluso como %s. Probablemente la cuenta no tenga un plan de Game Pass con juego en la nube.",- "Brasil",- "Japón",- "Corea del Sur",- "Polonia",- "Estados Unidos",- "Se rechazaron las conexiones seguras porque la fecha y la hora de la PS5 parecen incorrectas (indica %s). Ajústalas en Ajustes > Sistema > Fecha y hora y vuelve a intentarlo.",- "Se rechazó una conexión segura: algo en la red (un servidor DNS, proxy o filtro) responde en lugar de los sitios de Microsoft. Prueba sin él y vuelve a intentarlo.",- "La fecha y la hora de la PS5 parecen incorrectas (%s): parte del contenido no carga. Ajústalas en Ajustes > Sistema > Fecha y hora.",- "No se pudo guardar el inicio de sesión en la consola, así que se pedirá de nuevo la próxima vez. Infórmalo (Ajustes > △).",- "Espera estimada: %s s", // QueueSeconds- "Espera estimada: %s min", // QueueMinutes- "Salida 120 Hz (VRR)", // HighRefresh- "Activada (en los juegos)", // HighRefreshOn- "Conexión inestable", // ConnectionUnstable- "Sesión: %s", // SessionSummary- "Bitrate máximo", // BitrateCap- "Automático", // BitrateAuto- "Volumen del juego", // GameVolume- "Teclado: F12 este menú · Inicio botón Xbox", // MenuKeyHint- "Teclado y ratón", // FilterMouseKeyboard- "Teclado y ratón", // MouseKeyboardSupport- "Teclado y ratón: jugador %s", // KeyboardPlayer- "Estás en la cola.", // InQueueNoEstimate- "Teclas del teclado", // KeyboardKeys- "Cruceta", // DPad- "Pulsa una tecla o un botón del ratón", // PressKey- "La app reserva %s", // KeyReserved- "Cambiar", // ChangeKey- "Borrar", // ClearKey- "El ratón mueve el stick derecho y cada paso de la rueda pulsa Triángulo. F12 (menú), Inicio (botón Xbox) y 1-4 (jugador) las reserva la app.", // KeysHelp- "Apuntado con giroscopio", // Gyro- "Siempre", // GyroAlways- "Al apuntar (L2)", // GyroAiming- "Intensidad del giroscopio", // GyroIntensity- "Se rechazaron las conexiones seguras porque la fecha y la hora de este ordenador parecen incorrectas (indica %s). Corrígelas en los ajustes del sistema y vuelve a intentarlo.", // ClockWrongPc- "La fecha y la hora de este ordenador parecen incorrectas (%s): parte del contenido no carga. Corrígelas en los ajustes del sistema.", // ClockWrongNoticePc- "Desactivado (el del ordenador)", // LoginCountryOffPc- "Abrir en el navegador", // OpenInBrowser- "%s disponible: descargar", // UpdateReadyPc- "Menú: START + BACK o F12 · Botón Xbox: Guide o Inicio", // GestureHintButtons- "START + BACK o F12: este menú · Guide o Inicio: botón Xbox", // MenuButtonHint- "Modo de pantalla", // DisplayMode- "Ventana", // DisplayWindow- "Pantalla completa", // DisplayFullscreen- "¿Salir de PSBox?", // QuitTitle- "Salir", // QuitConfirm- "Botones del mando", // ControllerButtons- "Pulsa el botón para %s", // PadPressButton- "Falta botón para: %s. Asigna uno a cada función, o restablece o descarta los cambios.", // PadMissing- "Descartar cambios", // DiscardChanges- "Solo el juego lo ve: los menús de la app usan los botones tal cual. Elegir un botón ya usado intercambia los dos.", // PadHelp- "Plan", // FilterPlan- "Mi plan", // PlanMine- "Todos los planes", // PlanAll- "Incluido con Game Pass %s", // IncludedWithPlan- "Panel táctil como ratón", // TouchpadMouse- "Favoritos", // Favorites- "Añadir a favoritos", // AddFavorite- "Quitar de favoritos", // RemoveFavorite- "Añadido a favoritos", // AddedToFavorites- "Eliminado de favoritos", // RemovedFromFavorites- "Idioma del juego", // GameLanguage- "Límite mensual de juego en la nube alcanzado", // MonthlyLimitExceeded- "Tiempo de juego restante", // PlaytimeRemaining- "%s h restantes", // HoursRemaining- "Menos de 2 h restantes", // PlaytimeWarning- "Perfil de gatillos", // TriggerProfile- "Estándar", // TriggerProfileStd- "Disparos (Hair Trigger)", // TriggerProfileShooter- "Carreras (ABS)", // TriggerProfileRacing- "El almacenamiento %s no permite escritura: la sesión y ajustes no se guardarán", // StorageNotWritable- "FTP: usa 'chmod 777 %s' o borra la carpeta y reinicia la app", // StorageFixHint- "Personalizar indicadores", // StatsCustomize- "FPS y resolución", // StatsIndicatorFps- "Tasa de bits (Bitrate)", // StatsIndicatorBitrate- "Latencia (RTT)", // StatsIndicatorLatency- "Pérdida de paquetes", // StatsIndicatorLoss- "Gráfico de frametime", // StatsIndicatorGraph- "Retardo de decodificación y pantalla", // StatsIndicatorDelay- "Calidad de vídeo (QP)", // StatsIndicatorQp- "Estado del micrófono", // StatsIndicatorMic- "Usa tu teléfono para escanear el código QR y resolver con Microsoft, luego presiona Cruz para reintentar", // ScanQrToResolve- "Obtener Gratis", // ClaimFree- "Obteniendo licencia gratuita...", // Claiming- "¡Juego añadido a tu cuenta con éxito!", // ClaimSuccess- "Error al adquirir el juego gratuito: %s", // ClaimFailed- "Este juego no es gratuito en la tienda", // ProductNotFree- "Juego gratuito. Presiona Cruz para añadirlo a tu cuenta y empezar a jugar", // FreeAcquireHint- "Fallo de conexión DNS con los servidores de Microsoft. En PS5, asegúrate de ejecutar NanoDNS con el DNS primario configurado en tu IP local para mantener acceso a internet bloqueando a Sony.", // DnsBlockedNanoDns- "Esta cuenta Microsoft aún no tiene un perfil de Xbox. Inicia sesión en xbox.com en tu móvil o PC para crear tu Gamertag y vuelve a intentarlo.", // XboxProfileMissing- "¡Cola lista! Iniciando el juego...", // QueueReadyAlert- "Aviso sonoro de cola lista", // QueueReadyNotification- "Jugado: %s", // PlaytimePlayed- "Actualizar", // RefreshLibrary- "Actualizando biblioteca...", // RefreshingLibrary- "Esta cuenta de Xbox está suspendida o bloqueada. Visita enforcement.xbox.com para más detalles.", // XboxAccountBanned- "Xbox Live no se ofrece en el país o región de esta cuenta.", // XboxRegionNotSupported- "Se requiere verificación de edad o aceptar los términos. Inicia sesión en xbox.com desde un navegador y vuelve a intentarlo.", // XboxAdultVerificationRequired- "Cuenta infantil: un adulto debe añadir esta cuenta a una familia de Microsoft en account.microsoft.com/family.", // XboxChildAccountFamily- "Comprobar mi inicio de sesión", // CheckSignIn- "Comprobar", // RunCheck- "Prueba de red", // NetworkTest- "Probar", // RunTest- "Logros", // Achievements- "Sin logros", // NoAchievements- "Bloqueado", // AchievementLocked- "Logro secreto", // SecretAchievement- "Lista de deseos", // Wishlist- "Añadir a lista de deseos", // AddWishlist- "Quitar de lista de deseos", // RemoveWishlist- "Añadido a lista de deseos", // AddedToWishlist- "Quitado de lista de deseos", // RemovedFromWishlist- "¡%s está en oferta!", // WishlistOnSale- "¡%s llegó a Game Pass!", // WishlistInGamePass- "Apoya el proyecto", // SupportProject- "Apoya el Desarrollo de PSBox", // SupportTitle- "PSBox es un proyecto de código abierto desarrollado con dedicación para brindar la mejor experiencia de Xbox Cloud Gaming en PlayStation 5. Si disfrutas de la app y deseas apoyar el desarrollo continuo y nuevas funciones, ¡considera invitarme un café en Ko-Fi!", // SupportMessage- "Ko-fi", // SupportKoFi- "Escanea con tu teléfono para donar", // ScanToDonate- "Probar sonido", // TestSound- "La lista de deseos está vacía", // WishlistEmpty- // Loading tips- "Panel táctil: desliza ↓ (o Touchpad + Options) para el menú, ↑ para el botón Xbox", // TipTouchpadMenu- "Teclado y ratón USB conectados a la consola son compatibles con juegos de la nube habilitados", // TipKeyboardMouse- "Reclama juegos gratis, demos y descubre promociones de la tienda directamente desde la aplicación", // TipFreeStore- "¿Encontraste un problema? Abre Notificar problema para escanear un QR con registros de la consola", // TipBugReportQr- "¿Disfrutas del proyecto? ¡Apoya su desarrollo futuro a través de Ko-fi en Configuración!", // TipSupportKofi- "Activa salida de vídeo a 120 Hz en Configuración para menor latencia y respuesta más fluida", // Tip120HzVideo- "Calibra la zona muerta de los sticks en Configuración para eliminar deriva y mejorar la precisión", // TipAnalogDeadzone- "Usa el micrófono integrado del DualSense para chat de voz en grupos y partidas multijugador", // TipDualSenseMic- // Settings descriptions- "Cambia el idioma de la interfaz de la aplicación y la preferencia de audio y subtítulos en juegos en la nube", // SettingDescLanguage- "Establece la resolución máxima del stream de vídeo (1080p, 720p o Mejor disponible). Se aplica en el próximo juego", // SettingDescResolution- "Selecciona la región de servidores de Microsoft para streaming (Automático o regiones específicas). Se aplica en el próximo juego", // SettingDescRegion- "Ajusta la zona muerta interna de los sticks analógicos para evitar deriva y movimientos no deseados", // SettingDescDeadzone- "Activa o desactiva la vibración de gatillos adaptativos L2 y R2 en juegos compatibles", // SettingDescTriggerRumble- "Alterna la función de confirmar y volver entre Cruz (estilo occidental) y Círculo (estilo japonés)", // SettingDescConfirmButton- "Configura el color y comportamiento de la barra luminosa del DualSense en menús y durante el juego", // SettingDescLightBar- "Comprueba e instala automáticamente actualizaciones oficiales de la aplicación directamente en la consola", // SettingDescUpdates- "Permite iniciar sesión en tu cuenta de Xbox mediante otra región geográfica para acceder a catálogos alternativos", // SettingDescLoginCountry- "Activa salida de vídeo a 120 Hz en tu consola para reducir el retardo de pantalla y la latencia de entrada", // SettingDescHighRefresh- "Define el límite máximo de tasa de bits para streaming de vídeo, asegurando calidad visual o ahorrando red", // SettingDescBitrateCap- "Ajusta el volumen general del audio reproducido durante las sesiones de juego en la nube", // SettingDescGameVolume- "Asigna teclas del teclado USB o Bluetooth a los botones correspondientes del mando de Xbox durante el juego", // SettingDescKeyboardKeys- "Alterna entre modo ventana y pantalla completa en plataformas de escritorio compatibles", // SettingDescDisplayMode- "Abre la pantalla de prueba de respuesta y calibración de todos los botones y ejes del mando conectado", // SettingDescControllerButtons- "Permite que los sensores de movimiento del DualSense asistan al apuntado analógico en juegos de disparos", // SettingDescGyro- "Reproduce un aviso sonoro cuando termina la espera en cola de xCloud y el juego está listo", // SettingDescQueueReady- "Ejecuta un diagnóstico completo del inicio de sesión de Xbox Live, validando tokens, perfil y suscripciones", // SettingDescCheckSignIn- "Mide el ping (RTT) y la fluctuación (jitter) a centros de datos de juegos en la nube en múltiples regiones", // SettingDescNetworkTest- "Muestra un código QR para apoyar al desarrollador mediante Ko-fi y mantener el proyecto activo", // SettingDescSupportProject- "Novedades", // WhatsNew- "Novedades", // WhatsNewTitle- "Altavoz del mando", // PadSpeakerVolume- "Silenciado", // Mute- "Control Web", // WebControlTitle- "Conectar desde el móvil", // WebControlSubtitle- "Conéctate al mismo Wi-Fi para buscar, reasignar botones, usar el celular como control virtual, reportar problemas o ver registros.", // WebControlDesc- "Decodificación de vídeo", // VideoDecoder- "Hardware (Recomendado)", // VideoDecoderHw- "Software (CPU)", // VideoDecoderSw- "Selecciona decodificación por hardware (libSceVideodec2 en PS5, HWAccel en Desktop) o software (CPU)", // SettingDescVideoDecoder- "Audio a Vibración Háptica", // AudioHaptics- "Convierte frecuencias graves del audio en vibración háptica en DualSense", // SettingDescAudioHaptics- "Atajos del panel táctil", // TouchpadShortcuts- "Configura gestos de deslizamiento y clics izquierdo y derecho en el panel táctil DualSense", // SettingDescTouchpadShortcuts- "Deslizar arriba (↑)", // TouchpadSwipeUp- "Deslizar abajo (↓)", // TouchpadSwipeDown- "Deslizar izquierda (←)", // TouchpadSwipeLeft- "Deslizar derecha (→)", // TouchpadSwipeRight- "Clic izquierdo", // TouchpadClickLeft- "Clic derecho", // TouchpadClickRight- "Desactivado", // TouchpadActNone- "Menú del juego", // TouchpadActGameMenu- "Botón Xbox", // TouchpadActXboxButton- "Alternar estadísticas", // TouchpadActToggleStats- "Silenciar/activar micrófono", // TouchpadActToggleMic- "Alternar giroscopio", // TouchpadActCycleGyro- "Alternar perfil de gatillo", // TouchpadActCycleTrigger- "Touchpad + Options siempre abre el menú del juego", // TouchpadHelp- "Restablecer ajustes predeterminados", // ResetSettings- "Restablece todos los ajustes a los valores de fábrica. Mantén ✕ durante 5 segundos para confirmar.", // SettingDescResetSettings- "Ajustes restablecidos a los valores predeterminados.", // SettingsResetNotice- "Mantén para restablecer", // HoldToReset- "La biblioteca ya está actualizada", // LibraryUpToDate- "Biblioteca actualizada (%s nuevos juegos)", // LibraryUpdatedCount- "Modo sin conexión", // OfflineMode-};--constexpr Column kFrench = {- "PSBox Cloud Gaming",- "PSBOX CLOUD GAMING",- "Connexion...",- "Obtention d'un code de connexion...",- "Chargement de vos jeux...",- "Connectez-vous pour jouer",- "Sur votre téléphone ou ordinateur, allez sur",- "et saisissez ce code",- "Scannez pour ouvrir la page, puis saisissez le code",- "En attente de votre connexion...",- "Reprendre",- "Jouer",- "Retour",- "Sélectionner",- "Se déconnecter",- "Annuler",- "Réessayer",- "Préparation de votre jeu",- "Vous êtes dans la file d'attente. Attente estimée : %s",- "Connexion...",- "Démarrage du streaming...",- "Pavé tactile : ↓ ce menu · ↑ bouton Xbox",- "Streaming terminé",- "Un problème est survenu",- "Connecté en tant que %s",- "Aucun jeu à afficher pour le moment",- "Par %s",- "Paramètres",- "Langue",- "Résolution du streaming",- "Région du serveur",- "Automatique (%s)",- "1080p (Full HD)",- "720p (consomme moins de données)",- "Meilleure (Auto)",- "La résolution et la région s'appliquent au prochain jeu lancé.",- "Modifier",- "Ajuster",- "Maintenez pour vous déconnecter",- "Continuez à maintenir pour vous déconnecter (%s)",- "Échec de la connexion : %s",- "La connexion dans le navigateur n'a pas été finalisée. Utilisez un compte Microsoft personnel, effectuez les vérifications/2FA et autorisez l'app.",- "Impossible de charger la liste des jeux : %s",- "Impossible de démarrer le streaming : %s",- "Aucune activité : vous serez déconnecté dans %s secondes",- "Mes jeux",- "Indisponible sur votre compte",- "Game Pass",- "Rechercher",- "Tapez le nom d'un jeu",- "Aucun jeu trouvé",- "%s résultats",- "Espace",- "Effacer",- "Tout effacer",- "%s jeux",- "Taper",- "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 Mes jeux.",- "Scannez pour ouvrir la page du magasin",- "Rechercher dans %s",- "GRATUIT",- "Masquer",- "Afficher",- "Masqués",- "\xE2\x96\xA1 réaffiche un jeu",- "Masqué : voir Masqués, à la fin de cet onglet",- "De nouveau visible",- "Trier : %s",- "Récents d'abord",- "A-Z",- "Par console",- "Trier",- "Gratuit",- "Prix croissant",- "Toutes les consoles",- "1 jeu",- "Sections",- "Mise \xC3\xA0 jour de la liste des jeux...",- "Menu du jeu",- "Statistiques",- "Activé",- "Désactivé",- "Résolution du stream",- "Quitter le jeu",- "Latence",- "Débit",- "Images par seconde",- "Perte de paquets",- "Région",- "Décodage",- "Le serveur peut conserver la qualité actuelle",- "Netteté",- "Désactivée",- "Faible",- "Moyenne",- "Élevée",- "Zone morte du stick",- "Vibration des gâchettes",- "Bouton de validation",- "Activée",- "Désactivée",- "Version %s disponible",- "Manettes",- "Manette %s connectée",- "Manette %s déconnectée",- "Lissage des blocs",- "À l'écran après",- "Connexion perdue : reconnexion...",- "Reconnecté",- "Barre lumineuse",- "Mise à l'échelle",- "IA (Anime4K)",- "Gratuit",- "Obtenez-le une fois, gratuitement, sur xbox.com ou dans l'app Xbox (scannez le code avec votre téléphone), puis appuyez sur Jouer.",- "Scannez pour l'obtenir gratuitement",- "%s n'est pas encore sur votre compte. Il est gratuit : scannez le code sur sa page, choisissez Obtenir, puis réessayez (cela peut prendre une minute).",- "Votre compte ne peut pas jouer à %s : il n'est pas dans votre abonnement ou n'a pas été acheté.",- "Mes consoles",- "Allumée",- "En veille",- "Éteinte",- "Recherche de vos consoles...",- "Aucune Xbox trouvée pour l'instant",- "Jouez sur votre propre Xbox d'ici : son écran, ses jeux et ses applications.",- "Réveil de votre Xbox...",- "%s n'a pas répondu. Vérifiez que les fonctionnalités à distance sont activées et le mode Veille choisi, ou allumez-la, puis réessayez.",- "Sur votre Xbox, connectez-vous avec ce même compte Microsoft.",- "Paramètres > Appareils et connexions > Fonctionnalités à distance : activez-les.",- "Paramètres > Général > Options d'alimentation : choisissez Veille, pour qu'elle se réveille seule.",- "Scannez pour l'aide de Microsoft",- "Rechercher à nouveau",- "Bouton Xbox",- "Arrêter la diffusion",- "La diffusion a été arrêtée sur la Xbox",- "Un autre appareil a repris la diffusion",- "La Xbox a été éteinte",- "%s a reçu la demande, mais son jeu à distance n'a pas démarré. Redémarrez-la : maintenez le bouton d'alimentation de la console 10 secondes, rallumez-la, puis réessayez.",- "Pavé tactile : glissez ↓ pour le menu, ↑ pour le bouton Xbox",- "FSR + nettoyage",- "IA + nettoyage",- "Auto (%s)",- "Mettre à jour maintenant ? L'app redémarre toute seule à la fin.",- "Mettre à jour",- "Plus tard",- "Mises à jour",- "À jour (%s)",- "%s disponible : mettre à jour",- "Vérification...",- "Mise à jour vers %s",- "Téléchargement... %s",- "Vérification de la signature...",- "Installation...",- "Mis à jour. Redémarrage...",- "PSBox mis à jour : rouvrez l'app",- "Échec de la mise à jour : rien n'a changé",- "Couleur du jeu",- "Couleur personnalisée",- "Couleur de la barre lumineuse",- "Joystick gauche ou croix : couleur L2 / R2 : luminosité",- "Légère",- "Moyenne",- "Forte",- "Maximale",- "Intensité",- "Fréquence",- "Grave",- "Aiguë",- "Appuyez sur L2 / R2 pour le sentir : plus vous enfoncez, plus le jeu le demanderait fort",- "Niveau %s",- "Joystick gauche",- "Joystick droit",- "Position réelle",- "Ce que reçoit le jeu",- "L1 / R1 : choisir le joystick Croix ← / → : régler Bougez les joysticks pour le voir",- "Résistance",- "Style",- "Vibration",- "Impulsions de force",- "Mode",- "Genre",- "Langue",- "Tous les modes",- "Solo",- "Multijoueur en ligne",- "Coopération en ligne",- "Local / écran partagé",- "Tous les genres",- "Toutes les langues",- "français",- "Sous-titres en %s",- "Doublé en %s",- "Paramètres du jeu",- "Profil",- "Par défaut",- "Personnalisé",- "Réinitialiser",- "Éditeur",- "Tous les éditeurs",- "Indépendants et autres",- "Amis en train de jouer",- "Microphone",- "Coupé",- "Actif",- "Sortie audio",- "TV",- "Haut-parleur de la manette",- "Signaler un problème",- "Scannez-le avec votre téléphone : le formulaire de bug de GitHub s'ouvre, déjà rempli. Vous le relisez avant de l'envoyer.",- "Il contient la version de l'app, l'erreur et des lignes du journal, sans données personnelles.",- "PSBox s'est fermé de façon inattendue la dernière fois",- "Pays de connexion",- "Désactivé (celui de la console)",- "Se connecter depuis un autre pays",- "xCloud sera informé que la connexion vient du pays choisi. Microsoft ne l'autorise pas : utilisez-le à vos risques. Les jeux peuvent alors venir de serveurs éloignés, avec plus de latence. Modifiable plus tard dans Paramètres.",- "xCloud a refusé la connexion. Le jeu dans le cloud n'est peut-être pas proposé dans votre pays, ou le compte n'a pas d'abonnement Game Pass avec le jeu dans le cloud.",- "xCloud a refusé la connexion, même en choisissant %s. Le compte n'a probablement pas d'abonnement Game Pass avec le jeu dans le cloud.",- "Brésil",- "Japon",- "Corée du Sud",- "Pologne",- "États-Unis",- "Les connexions sécurisées ont été refusées car la date et l'heure de la PS5 semblent fausses (elle indique %s). Réglez-les dans Paramètres > Système > Date et heure, puis réessayez.",- "Une connexion sécurisée a été refusée : quelque chose sur le réseau (serveur DNS, proxy ou filtre) répond à la place des sites de Microsoft. Essayez sans, puis réessayez.",- "La date et l'heure de la PS5 semblent fausses (%s) : une partie du contenu ne se charge pas. Réglez-les dans Paramètres > Système > Date et heure.",- "Impossible d'enregistrer la connexion sur la console : elle sera redemandée la prochaine fois. Signalez-le (Paramètres > △).",- "Attente estimée : %s s", // QueueSeconds- "Attente estimée : %s min", // QueueMinutes- "Sortie 120 Hz (VRR)", // HighRefresh- "Activée (en jeu)", // HighRefreshOn- "Connexion instable", // ConnectionUnstable- "Session : %s", // SessionSummary- "Débit maximal", // BitrateCap- "Automatique", // BitrateAuto- "Volume du jeu", // GameVolume- "Clavier : F12 ce menu · Origine bouton Xbox", // MenuKeyHint- "Clavier et souris", // FilterMouseKeyboard- "Clavier et souris", // MouseKeyboardSupport- "Clavier et souris : joueur %s", // KeyboardPlayer- "Vous êtes dans la file d'attente.", // InQueueNoEstimate- "Touches du clavier", // KeyboardKeys- "Croix directionnelle", // DPad- "Appuyez sur une touche ou un bouton de la souris", // PressKey- "%s est réservée par l'app", // KeyReserved- "Modifier", // ChangeKey- "Effacer", // ClearKey- "La souris déplace le joystick droit et chaque cran de la molette appuie sur Triangle. F12 (menu), Origine (bouton Xbox) et 1-4 (joueur) sont réservées par l'app.", // KeysHelp- "Visée gyroscopique", // Gyro- "Toujours", // GyroAlways- "En visant (L2)", // GyroAiming- "Intensité du gyroscope", // GyroIntensity- "Les connexions sécurisées ont été refusées car la date et l'heure de cet ordinateur semblent fausses (il indique %s). Corrigez-les dans les paramètres du système, puis réessayez.", // ClockWrongPc- "La date et l'heure de cet ordinateur semblent fausses (%s) : une partie du contenu ne se charge pas. Corrigez-les dans les paramètres du système.", // ClockWrongNoticePc- "Désactivé (celui de l'ordinateur)", // LoginCountryOffPc- "Ouvrir dans le navigateur", // OpenInBrowser- "%s disponible : télécharger", // UpdateReadyPc- "Menu : START + BACK ou F12 · Bouton Xbox : Guide ou Origine", // GestureHintButtons- "START + BACK ou F12 : ce menu · Guide ou Origine : bouton Xbox", // MenuButtonHint- "Mode d'affichage", // DisplayMode- "Fenêtre", // DisplayWindow- "Plein écran", // DisplayFullscreen- "Quitter PSBox ?", // QuitTitle- "Quitter", // QuitConfirm- "Boutons de la manette", // ControllerButtons- "Appuyez sur le bouton pour %s", // PadPressButton- "Bouton manquant pour : %s. Attribuez-en un à chaque fonction, ou réinitialisez ou annulez les modifications.", // PadMissing- "Annuler les modifications", // DiscardChanges- "Seul le jeu est concerné : les menus de l'app gardent les boutons tels quels. Choisir un bouton déjà utilisé échange les deux.", // PadHelp- "Forfait", // FilterPlan- "Mon forfait", // PlanMine- "Tous les forfaits", // PlanAll- "Inclus avec Game Pass %s", // IncludedWithPlan- "Pavé tactile comme souris", // TouchpadMouse- "Favoris", // Favorites- "Ajouter aux favoris", // AddFavorite- "Retirer des favoris", // RemoveFavorite- "Ajouté aux favoris", // AddedToFavorites- "Retiré des favoris", // RemovedFromFavorites- "Langue du jeu", // GameLanguage- "Limite mensuelle de jeu dans le cloud atteinte", // MonthlyLimitExceeded- "Temps de jeu restant", // PlaytimeRemaining- "%s h restantes", // HoursRemaining- "Moins de 2 h restantes", // PlaytimeWarning- "Profil de gâchettes", // TriggerProfile- "Standard", // TriggerProfileStd- "Tir (Hair Trigger)", // TriggerProfileShooter- "Course (ABS)", // TriggerProfileRacing- "Le stockage %s n'est pas accessible en écriture : connexion et réglages non enregistrés", // StorageNotWritable- "FTP : faites 'chmod 777 %s' ou supprimez le dossier et relancez", // StorageFixHint- "Personnaliser les indicateurs", // StatsCustomize- "IPS et résolution", // StatsIndicatorFps- "Débit binaire (Bitrate)", // StatsIndicatorBitrate- "Latence (RTT)", // StatsIndicatorLatency- "Perte de paquets", // StatsIndicatorLoss- "Graphique de frametime", // StatsIndicatorGraph- "Latence de décodage et d'affichage", // StatsIndicatorDelay- "Qualité vidéo (QP)", // StatsIndicatorQp- "État du microphone", // StatsIndicatorMic- "Scannez le code QR avec votre téléphone pour résoudre ceci chez Microsoft, puis appuyez sur Croix pour réessayer", // ScanQrToResolve- "Obtenir gratuitement", // ClaimFree- "Obtention de la licence gratuite...", // Claiming- "Jeu ajouté à votre compte avec succès !", // ClaimSuccess- "Échec de l'obtention du jeu gratuit : %s", // ClaimFailed- "Ce jeu n'est pas gratuit sur le store", // ProductNotFree- "Jeu gratuit. Appuyez sur Croix pour l'ajouter à votre compte et jouer", // FreeAcquireHint- "Échec de résolution DNS pour les serveurs Microsoft. Sur PS5, veillez à exécuter NanoDNS et à définir le DNS primaire sur votre IP locale pour garder l'accès Internet tout en bloquant Sony.", // DnsBlockedNanoDns- "Ce compte Microsoft n'a pas encore de profil Xbox. Connectez-vous sur xbox.com sur mobile ou PC pour créer votre Gamertag, puis réessayez.", // XboxProfileMissing- "File d'attente prête ! Lancement du jeu...", // QueueReadyAlert- "Alerte sonore de file prête", // QueueReadyNotification- "Joué : %s", // PlaytimePlayed- "Actualiser", // RefreshLibrary- "Actualisation de la bibliothèque...", // RefreshingLibrary- "Ce compte Xbox est suspendu ou banni. Consultez enforcement.xbox.com pour plus de détails.", // XboxAccountBanned- "Xbox Live n'est pas proposé dans le pays ou la région de ce compte.", // XboxRegionNotSupported- "Vérification d'âge ou acceptation des conditions requise. Connectez-vous sur xbox.com dans un navigateur, puis réessayez.", // XboxAdultVerificationRequired- "Compte enfant : un adulte doit ajouter ce compte à une famille Microsoft sur account.microsoft.com/family.", // XboxChildAccountFamily- "Vérifier ma connexion", // CheckSignIn- "Vérifier", // RunCheck- "Test réseau", // NetworkTest- "Tester", // RunTest- "Succès", // Achievements- "Aucun succès", // NoAchievements- "Verrouillé", // AchievementLocked- "Succès secret", // SecretAchievement- "Liste d'envies", // Wishlist- "Ajouter aux envies", // AddWishlist- "Retirer des envies", // RemoveWishlist- "Ajouté aux envies", // AddedToWishlist- "Retiré des envies", // RemovedFromWishlist- "%s est en promotion !", // WishlistOnSale- "%s a rejoint le Game Pass !", // WishlistInGamePass- "Soutenir le projet", // SupportProject- "Soutenir le Développement de PSBox", // SupportTitle- "PSBox est un projet open source développé avec passion pour offrir la meilleure expérience Xbox Cloud Gaming sur PlayStation 5. Si vous appréciez l'application et souhaitez soutenir les mises à jour et les nouveautés, pensez à m'offrir un café sur Ko-Fi !", // SupportMessage- "Ko-fi", // SupportKoFi- "Scannez avec votre téléphone", // ScanToDonate- "Tester le son", // TestSound- "La liste de souhaits est vide", // WishlistEmpty- // Loading tips- "Pavé tactile : glissez ↓ (ou Pavé tactile + Options) pour le menu, ↑ pour le bouton Xbox", // TipTouchpadMenu- "Clavier et souris USB branchés sur la console sont pris en charge dans les jeux du cloud compatibles", // TipKeyboardMouse- "Obtenez des jeux gratuits, démos et promotions du magasin directement depuis l'application", // TipFreeStore- "Un problème ? Ouvrez Signaler un problème pour scanner un code QR avec les journaux de la console", // TipBugReportQr- "Vous appréciez le projet ? Soutenez son développement via Ko-fi dans les Paramètres !", // TipSupportKofi- "Activez la sortie vidéo 120 Hz dans les Paramètres pour réduire la latence d'affichage et de contrôle", // Tip120HzVideo- "Calibrez la zone morte des sticks dans les Paramètres pour éliminer le drift et améliorer la précision", // TipAnalogDeadzone- "Utilisez le microphone intégré de la DualSense pour le chat vocal dans les groupes et jeux multijoueurs", // TipDualSenseMic- // Settings descriptions- "Modifie la langue de l'interface de l'application et les préférences audio et sous-titres dans les jeux du cloud", // SettingDescLanguage- "Définit la résolution vidéo maximale (1080p, 720p ou Meilleure disponible). Prend effet au prochain lancement", // SettingDescResolution- "Sélectionne la région des serveurs Microsoft pour le streaming (Automatique ou spécifique). Prend effet au prochain lancement", // SettingDescRegion- "Ajuste la zone morte intérieure des sticks analogiques DualSense pour éviter le drift et les mouvements involontaires", // SettingDescDeadzone- "Active ou désactive l'émulation des vibrations sur les gâchettes adaptatives L2 et R2 dans les jeux compatibles", // SettingDescTriggerRumble- "Bascule la disposition des boutons de confirmation et retour entre Croix (occidental) et Rond (japonais)", // SettingDescConfirmButton- "Configure la couleur et le comportement de la barre lumineuse de votre manette DualSense", // SettingDescLightBar- "Vérifie et installe automatiquement les mises à jour officielles de l'application directement sur votre console", // SettingDescUpdates- "Permet de vous connecter à votre compte Xbox via une autre région pour accéder à d'autres catalogues", // SettingDescLoginCountry- "Active la sortie vidéo 120 Hz sur votre console pour une réactivité accrue et une latence réduite", // SettingDescHighRefresh- "Définit la limite maximale de débit binaire pour le streaming vidéo, optimisant la qualité ou préservant le réseau", // SettingDescBitrateCap- "Ajuste le niveau du volume audio principal pendant les sessions de jeu en streaming", // SettingDescGameVolume- "Associe les touches du clavier USB ou Bluetooth aux boutons correspondants de la manette Xbox en jeu", // SettingDescKeyboardKeys- "Bascule entre mode fenêtré et plein écran sur les plates-formes de bureau compatibles", // SettingDescDisplayMode- "Ouvre l'écran de test de réponse et de calibrage de tous les boutons et axes de votre manette connectée", // SettingDescControllerButtons- "Active les capteurs de mouvement DualSense pour assister la visée analogique dans les jeux de tir", // SettingDescGyro- "Joue un signal sonore distinctif lorsque l'attente dans la file xCloud est terminée et que le jeu est prêt", // SettingDescQueueReady- "Exécute un diagnostic complet de la connexion Xbox Live, validant jetons d'accès, profil et abonnements", // SettingDescCheckSignIn- "Mesure le ping (RTT) et la gigue (jitter) vers les centres de données de jeux en nuage de plusieurs régions", // SettingDescNetworkTest- "Affiche un code QR pour soutenir le développeur via Ko-fi et contribuer à la maintenance active du projet", // SettingDescSupportProject- "Nouveautés", // WhatsNew- "Nouveautés", // WhatsNewTitle- "Haut-parleur de la manette", // PadSpeakerVolume- "Muet", // Mute- "Contrôle Web", // WebControlTitle- "Connexion mobile", // WebControlSubtitle- "Connectez-vous au même Wi-Fi pour chercher, remapper, utiliser le mobile comme manette virtuelle, signaler des soucis ou voir les logs.", // WebControlDesc- "Décodage vidéo", // VideoDecoder- "Matériel (Recommandé)", // VideoDecoderHw- "Logiciel (CPU)", // VideoDecoderSw- "Sélectionne le décodage matériel (libSceVideodec2 sur PS5, HWAccel sur Desktop) ou logiciel (CPU)", // SettingDescVideoDecoder- "Audio vers vibration haptique", // AudioHaptics- "Convertit les basses fréquences audio en vibrations haptiques sur DualSense", // SettingDescAudioHaptics- "Raccourcis du pavé tactile", // TouchpadShortcuts- "Configure les gestes de glissement et les clics gauche/droit sur le pavé tactile DualSense", // SettingDescTouchpadShortcuts- "Glisser vers le haut (↑)", // TouchpadSwipeUp- "Glisser vers le bas (↓)", // TouchpadSwipeDown- "Glisser vers la gauche (←)", // TouchpadSwipeLeft- "Glisser vers la droite (→)", // TouchpadSwipeRight- "Clic gauche", // TouchpadClickLeft- "Clic droit", // TouchpadClickRight- "Désactivé", // TouchpadActNone- "Menu du jeu", // TouchpadActGameMenu- "Bouton Xbox", // TouchpadActXboxButton- "Afficher/masquer les stats", // TouchpadActToggleStats- "Couper/activer le micro", // TouchpadActToggleMic- "Changer le mode gyro", // TouchpadActCycleGyro- "Changer le profil de gâchette", // TouchpadActCycleTrigger- "Pavé tactile + Options ouvre toujours le menu du jeu", // TouchpadHelp- "Restaurer les paramètres par défaut", // ResetSettings- "Restaure tous les paramètres aux valeurs d'usine. Maintenez ✕ pendant 5 secondes pour confirmer.", // SettingDescResetSettings- "Paramètres réinitialisés aux valeurs par défaut.", // SettingsResetNotice- "Maintenir pour réinitialiser", // HoldToReset- "La bibliothèque est déjà à jour", // LibraryUpToDate- "Bibliothèque mise à jour (%s nouveaux jeux)", // LibraryUpdatedCount- "Mode hors ligne", // OfflineMode-};--constexpr Column kGerman = {- "PSBox Cloud Gaming",- "PSBOX CLOUD GAMING",- "Anmeldung läuft...",- "Anmeldecode wird abgerufen...",- "Deine Spiele werden geladen...",- "Zum Spielen anmelden",- "Rufe auf deinem Handy oder Computer",- "auf und gib diesen Code ein",- "Scannen, um die Seite zu öffnen, dann den Code eingeben",- "Warte auf deine Anmeldung...",- "Weiterspielen",- "Spielen",- "Zurück",- "Auswählen",- "Abmelden",- "Abbrechen",- "Erneut versuchen",- "Dein Spiel wird vorbereitet",- "Du bist in der Warteschlange. Geschätzte Wartezeit: %s",- "Verbindung wird hergestellt...",- "Streaming wird gestartet...",- "Touchpad: ↓ dieses Menü · ↑ Xbox-Taste",- "Streaming beendet",- "Etwas ist schiefgelaufen",- "Angemeldet als %s",- "Noch keine Spiele vorhanden",- "Von %s",- "Einstellungen",- "Sprache",- "Streaming-Auflösung",- "Serverregion",- "Automatisch (%s)",- "1080p (Full HD)",- "720p (verbraucht weniger Daten)",- "Beste (Auto)",- "Auflösung und Region gelten ab dem nächsten gestarteten Spiel.",- "Ändern",- "Anpassen",- "Halten zum Abmelden",- "Weiter halten zum Abmelden (%s)",- "Anmeldung fehlgeschlagen: %s",- "Die Anmeldung im Browser wurde nicht abgeschlossen. Verwende ein persönliches Microsoft-Konto, schließe Sicherheitsabfragen/2FA ab und gewähre Zugriff.",- "Die Spieleliste konnte nicht geladen werden: %s",- "Das Streaming konnte nicht gestartet werden: %s",- "Keine Aktivität: Die Verbindung wird in %s Sekunden getrennt",- "Meine Spiele",- "Für dein Konto nicht verfügbar",- "Game Pass",- "Suchen",- "Gib den Namen eines Spiels ein",- "Keine Spiele gefunden",- "%s Ergebnisse",- "Leerzeichen",- "Löschen",- "Leeren",- "%s Spiele",- "Tippen",- "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 Meine Spiele.",- "Scannen, um die Store-Seite zu öffnen",- "Suchen in %s",- "KOSTENLOS",- "Ausblenden",- "Einblenden",- "Ausgeblendet",- "\xE2\x96\xA1 blendet ein Spiel wieder ein",- "Ausgeblendet: unter Ausgeblendet, am Ende dieses Tabs",- "Wieder sichtbar",- "Sortieren: %s",- "Zuletzt gespielt",- "A-Z",- "Nach Konsole",- "Sortieren",- "Kostenlos",- "Niedrigster Preis",- "Alle Konsolen",- "1 Spiel",- "Abschnitte",- "Spieleliste wird aktualisiert...",- "Spielmenü",- "Statistiken",- "An",- "Aus",- "Stream-Auflösung",- "Spiel verlassen",- "Latenz",- "Bitrate",- "Bilder pro Sekunde",- "Paketverlust",- "Region",- "Dekodierung",- "Der Server behält eventuell die aktuelle Qualität bei",- "Schärfe",- "Aus",- "Niedrig",- "Mittel",- "Hoch",- "Stick-Totzone",- "Trigger-Vibration",- "Bestätigungstaste",- "An",- "Aus",- "Version %s verfügbar",- "Controller",- "Controller %s verbunden",- "Controller %s getrennt",- "Blockglättung",- "Auf dem Bildschirm nach",- "Verbindung verloren: neu verbinden...",- "Wieder verbunden",- "Lichtleiste",- "Hochskalierung",- "KI (Anime4K)",- "Free-to-play",- "Einmal kostenlos auf xbox.com oder in der Xbox-App holen (Code mit dem Handy scannen), dann Spielen drücken.",- "Scannen, um es kostenlos zu holen",- "%s ist noch nicht in deinem Konto. Es ist kostenlos: Code auf seiner Seite scannen, Abrufen wählen und erneut versuchen (kann eine Minute dauern).",- "Dein Konto kann %s nicht spielen: nicht in deinem Abo oder nicht gekauft.",- "Meine Konsolen",- "An",- "Im Standby",- "Aus",- "Deine Konsolen werden gesucht...",- "Noch keine Xbox gefunden",- "Spiele hier auf deiner eigenen Xbox: ihr Bildschirm, ihre Spiele und Apps.",- "Deine Xbox wird geweckt...",- "%s hat nicht geantwortet. Prüfe, ob die Remotefunktionen aktiv sind und der Energiemodus Ruhezustand ist, oder schalte sie ein und versuche es erneut.",- "Melde dich auf deiner Xbox mit genau diesem Microsoft-Konto an.",- "Einstellungen > Geräte & Verbindungen > Remotefunktionen: Remotefunktionen aktivieren.",- "Einstellungen > Allgemein > Energieoptionen: Ruhezustand wählen, damit sie von selbst aufwacht.",- "Scannen für die Hilfe von Microsoft",- "Erneut suchen",- "Xbox-Taste",- "Streaming beenden",- "Das Streaming wurde auf der Xbox beendet",- "Ein anderes Gerät hat das Streaming übernommen",- "Die Xbox wurde ausgeschaltet",- "%s hat die Anfrage erhalten, aber Remote Play ist nicht gestartet. Starte sie neu: Halte die Ein/Aus-Taste der Konsole 10 Sekunden gedrückt, schalte sie wieder ein und versuche es erneut.",- "Touchpad: ↓ wischen für das Menü, ↑ für die Xbox-Taste",- "FSR + Bereinigung",- "KI + Bereinigung",- "Auto (%s)",- "Jetzt aktualisieren? Die App startet danach von selbst neu.",- "Jetzt aktualisieren",- "Nicht jetzt",- "Updates",- "Aktuell (%s)",- "%s verfügbar: aktualisieren",- "Wird geprüft...",- "Aktualisierung auf %s",- "Wird geladen... %s",- "Signatur wird geprüft...",- "Wird installiert...",- "Aktualisiert. Neustart...",- "PSBox aktualisiert: App erneut öffnen",- "Update fehlgeschlagen: nichts wurde geändert",- "Farbe des Spiels",- "Eigene Farbe",- "Farbe der Lichtleiste",- "Linker Stick oder Steuerkreuz: Farbe L2 / R2: Helligkeit",- "Leicht",- "Mittel",- "Stark",- "Maximal",- "Stärke",- "Frequenz",- "Tief",- "Hoch",- "L2 / R2 drücken zum Fühlen: je tiefer, desto stärker würde es das Spiel verlangen",- "Stufe %s",- "Linker Stick",- "Rechter Stick",- "Tatsächliche Position",- "Was das Spiel bekommt",- "L1 / R1: Stick wählen Steuerkreuz ← / →: einstellen Sticks bewegen zum Sehen",- "Widerstand",- "Stil",- "Vibration",- "Kraftimpulse",- "Modus",- "Genre",- "Sprache",- "Alle Modi",- "Einzelspieler",- "Online-Mehrspieler",- "Online-Koop",- "Lokal / geteilter Bildschirm",- "Alle Genres",- "Alle Sprachen",- "Deutsch",- "Untertitel: %s",- "Sprachausgabe: %s",- "Spieleinstellungen",- "Profil",- "Standard",- "Benutzerdefiniert",- "Auf Standard zurücksetzen",- "Publisher",- "Alle Publisher",- "Indies & Andere",- "Freunde spielen jetzt",- "Mikrofon",- "Stumm",- "Aktiv",- "Audioausgabe",- "TV",- "Controller-Lautsprecher",- "Problem melden",- "Mit dem Handy scannen: Das Fehlerformular auf GitHub öffnet sich ausgefüllt. Du prüfst es vor dem Senden.",- "Enthalten sind die App-Version, der Fehler und Zeilen des Logs, ohne persönliche Daten.",- "PSBox wurde beim letzten Mal unerwartet beendet",- "Anmeldeland",- "Aus (das der Konsole)",- "Als anderes Land anmelden",- "xCloud wird mitgeteilt, dass die Anmeldung aus dem gewählten Land kommt. Microsoft erlaubt das nicht: Nutzung auf eigenes Risiko. Spiele kommen dann eventuell von weit entfernten Servern, mit mehr Verzögerung. Später in den Einstellungen änderbar.",- "xCloud hat die Anmeldung abgelehnt. Cloud Gaming wird in deinem Land vielleicht nicht angeboten, oder das Konto hat kein Game-Pass-Abo mit Cloud Gaming.",- "xCloud hat die Anmeldung abgelehnt, auch mit %s. Das Konto hat wahrscheinlich kein Game-Pass-Abo mit Cloud Gaming.",- "Brasilien",- "Japan",- "Südkorea",- "Polen",- "USA",- "Sichere Verbindungen wurden abgelehnt, weil Datum und Uhrzeit der PS5 falsch zu sein scheinen (sie zeigt %s). Stelle sie unter Einstellungen > System > Datum und Uhrzeit ein und versuche es erneut.",- "Eine sichere Verbindung wurde abgelehnt: Etwas im Netzwerk (DNS-Server, Proxy oder Filter) antwortet anstelle der Microsoft-Seiten. Versuche es ohne und dann erneut.",- "Datum und Uhrzeit der PS5 scheinen falsch zu sein (%s): Einige Inhalte laden nicht. Stelle sie unter Einstellungen > System > Datum und Uhrzeit ein.",- "Die Anmeldung konnte nicht auf der Konsole gespeichert werden und wird beim nächsten Mal erneut abgefragt. Bitte melde das (Einstellungen > △).",- "Geschätzte Wartezeit: %s s", // QueueSeconds- "Geschätzte Wartezeit: %s Min.", // QueueMinutes- "120-Hz-Ausgabe (VRR)", // HighRefresh- "An (in Spielen)", // HighRefreshOn- "Instabile Verbindung", // ConnectionUnstable- "Sitzung: %s", // SessionSummary- "Maximale Bitrate", // BitrateCap- "Automatisch", // BitrateAuto- "Spiellautstärke", // GameVolume- "Tastatur: F12 dieses Menü · Pos1 Xbox-Taste", // MenuKeyHint- "Maus & Tastatur", // FilterMouseKeyboard- "Maus und Tastatur", // MouseKeyboardSupport- "Tastatur und Maus: Spieler %s", // KeyboardPlayer- "Du bist in der Warteschlange.", // InQueueNoEstimate- "Tastaturbelegung", // KeyboardKeys- "Steuerkreuz", // DPad- "Drücke eine Taste oder Maustaste", // PressKey- "%s ist für die App reserviert", // KeyReserved- "Ändern", // ChangeKey- "Löschen", // ClearKey- "Die Maus bewegt den rechten Stick, jede Rasterstufe des Mausrads drückt Dreieck. F12 (Menü), Pos1 (Xbox-Taste) und 1-4 (Spieler) sind für die App reserviert.", // KeysHelp- "Gyro-Zielen", // Gyro- "Immer", // GyroAlways- "Beim Zielen (L2)", // GyroAiming- "Gyro-Stärke", // GyroIntensity- "Sichere Verbindungen wurden abgelehnt, weil Datum und Uhrzeit dieses Computers falsch zu sein scheinen (er zeigt %s). Korrigiere sie in den Systemeinstellungen und versuche es erneut.", // ClockWrongPc- "Datum und Uhrzeit dieses Computers scheinen falsch zu sein (%s): Einige Inhalte laden nicht. Korrigiere sie in den Systemeinstellungen.", // ClockWrongNoticePc- "Aus (das des Computers)", // LoginCountryOffPc- "Im Browser öffnen", // OpenInBrowser- "%s verfügbar: herunterladen", // UpdateReadyPc- "Menü: START + BACK oder F12 · Xbox-Taste: Guide oder Pos1", // GestureHintButtons- "START + BACK oder F12: dieses Menü · Guide oder Pos1: Xbox-Taste", // MenuButtonHint- "Anzeigemodus", // DisplayMode- "Fenster", // DisplayWindow- "Vollbild", // DisplayFullscreen- "PSBox beenden?", // QuitTitle- "Beenden", // QuitConfirm- "Controller-Tasten", // ControllerButtons- "Drücke die Taste für %s", // PadPressButton- "Ohne Taste: %s. Weise jeder Funktion eine zu, oder setze zurück bzw. verwirf die Änderungen.", // PadMissing- "Änderungen verwerfen", // DiscardChanges- "Gilt nur im Spiel: Die Menüs der App nutzen die Tasten, wie sie sind. Eine schon belegte Taste zu wählen tauscht die beiden.", // PadHelp- "Abo", // FilterPlan- "Mein Abo", // PlanMine- "Alle Abos", // PlanAll- "In Game Pass %s enthalten", // IncludedWithPlan- "Touchpad als Maus", // TouchpadMouse- "Favoriten", // Favorites- "Zu Favoriten hinzufügen", // AddFavorite- "Aus Favoriten entfernen", // RemoveFavorite- "Zu Favoriten hinzugefügt", // AddedToFavorites- "Aus Favoriten entfernt", // RemovedFromFavorites- "Spiel-Sprache", // GameLanguage- "Monatliches Cloud-Gaming-Limit erreicht", // MonthlyLimitExceeded- "Verbleibende Spielzeit", // PlaytimeRemaining- "%s Std. verbleibend", // HoursRemaining- "Weniger als 2 Std. verbleibend", // PlaytimeWarning- "Trigger-Profil", // TriggerProfile- "Standard", // TriggerProfileStd- "Shooter (Hair Trigger)", // TriggerProfileShooter- "Rennen (ABS)", // TriggerProfileRacing- "Speicher %s ist schreibgeschützt: Anmeldung und Einstellungen werden nicht gespeichert", // StorageNotWritable- "FTP: 'chmod 777 %s' ausführen oder Ordner löschen und neu starten", // StorageFixHint- "Indikatoren anpassen", // StatsCustomize- "FPS und Auflösung", // StatsIndicatorFps- "Bitrate", // StatsIndicatorBitrate- "Latenz (RTT)", // StatsIndicatorLatency- "Paketverlust", // StatsIndicatorLoss- "Frametime-Diagramm", // StatsIndicatorGraph- "Dekodier- und Anzeigelatenz", // StatsIndicatorDelay- "Videoqualität (QP)", // StatsIndicatorQp- "Mikrofonstatus", // StatsIndicatorMic- "Scannen Sie den QR-Code mit dem Smartphone, um dies bei Microsoft zu beheben, und drücken Sie dann Kreuz zum Wiederholen", // ScanQrToResolve- "Kostenlos holen", // ClaimFree- "Kostenlose Lizenz wird angefordert...", // Claiming- "Spiel erfolgreich zu Ihrem Konto hinzugefügt!", // ClaimSuccess- "Kostenloses Spiel konnte nicht angefordert werden: %s", // ClaimFailed- "Dieses Spiel ist im Store nicht kostenlos", // ProductNotFree- "Kostenloses Spiel. Drücken Sie Kreuz, um es zu Ihrem Konto hinzuzufügen und zu spielen", // FreeAcquireHint- "DNS-Auflösung für Microsoft-Server fehlgeschlagen. Stelle auf der PS5 sicher, dass NanoDNS läuft und der primäre DNS auf die lokale IP gesetzt ist, um Internetzugriff zu behalten.", // DnsBlockedNanoDns- "Dieses Microsoft-Konto hat noch kein Xbox-Profil. Melde dich auf xbox.com auf dem Smartphone oder PC an, um deinen Gamertag zu erstellen, und versuche es erneut.", // XboxProfileMissing- "Warteschlange bereit! Spiel wird gestartet...", // QueueReadyAlert- "Signalton bei Warteschlangenende", // QueueReadyNotification- "Gespielt: %s", // PlaytimePlayed- "Aktualisieren", // RefreshLibrary- "Bibliothek wird aktualisiert...", // RefreshingLibrary- "Dieses Xbox-Konto ist gesperrt oder gebannt. Details unter enforcement.xbox.com.", // XboxAccountBanned- "Xbox Live wird im Land oder in der Region dieses Kontos nicht angeboten.", // XboxRegionNotSupported- "Altersprüfung oder Zustimmung zu den Bedingungen erforderlich. Melde dich im Browser auf xbox.com an und versuche es erneut.", // XboxAdultVerificationRequired- "Kinderkonto: Ein Erwachsener muss dieses Konto unter account.microsoft.com/family zu einer Microsoft-Familie hinzufügen.", // XboxChildAccountFamily- "Anmeldung prüfen", // CheckSignIn- "Prüfen", // RunCheck- "Netzwerktest", // NetworkTest- "Testen", // RunTest- "Erfolge", // Achievements- "Keine Erfolge", // NoAchievements- "Gesperrt", // AchievementLocked- "Geheimer Erfolg", // SecretAchievement- "Wunschliste", // Wishlist- "Zur Wunschliste hinzufügen", // AddWishlist- "Von Wunschliste entfernen", // RemoveWishlist- "Zur Wunschliste hinzugefügt", // AddedToWishlist- "Von Wunschliste entfernt", // RemovedFromWishlist- "%s ist im Angebot!", // WishlistOnSale- "%s ist jetzt im Game Pass!", // WishlistInGamePass- "Projekt unterstützen", // SupportProject- "PSBox-Entwicklung unterstützen", // SupportTitle- "PSBox ist ein Open-Source-Projekt, das mit viel Engagement entwickelt wird, um das beste Xbox Cloud Gaming-Erlebnis auf die PlayStation 5 zu bringen. Wenn dir die App gefällt und du die Weiterentwicklung unterstützen möchtest, spendiere mir gerne einen Kaffee auf Ko-Fi!", // SupportMessage- "Ko-fi", // SupportKoFi- "Mit dem Smartphone scannen", // ScanToDonate- "Ton testen", // TestSound- "Wunschliste ist leer", // WishlistEmpty- // Loading tips- "Touchpad: ↓ wischen (oder Touchpad + Options) für das Menü, ↑ für die Xbox-Taste", // TipTouchpadMenu- "USB-Tastatur und -Maus an der Konsole werden in unterstützten Cloud-Spielen unterstützt", // TipKeyboardMouse- "Kostenlose Spiele, Demos und Store-Angebote direkt in der App-Bibliothek sichern", // TipFreeStore- "Problem aufgetreten? Öffnen Sie 'Problem melden', um einen QR-Code mit Konsolenprotokollen zu scannen", // TipBugReportQr- "Gefällt Ihnen das Projekt? Unterstützen Sie die Weiterentwicklung via Ko-fi in den Einstellungen!", // TipSupportKofi- "120-Hz-Videoausgabe in den Einstellungen für geringere Anzeigelatenz und flüssigere Steuerung aktivieren", // Tip120HzVideo- "Stick-Totzone in den Einstellungen kalibrieren, um Stick-Drift zu verhindern und Präzision zu verbessern", // TipAnalogDeadzone- "Integriertes DualSense-Mikrofon für Party- und Multiplayer-Sprachchat verwenden", // TipDualSenseMic- // Settings descriptions- "Ändert die Sprache der Benutzeroberfläche sowie die bevorzugte Audio- und Untertitelsprache in Cloud-Spielen", // SettingDescLanguage- "Legt die maximale Streaming-Auflösung fest (1080p, 720p oder Beste). Wird beim nächsten Spielstart wirksam", // SettingDescResolution- "Wählt die Microsoft-Rechenzentrumsregion für das Streaming aus (Automatisch oder bestimmte Regionen)", // SettingDescRegion- "Passt die innere Totzone der DualSense-Analogsticks an, um Drift und unbeabsichtigte Bewegungen zu vermeiden", // SettingDescDeadzone- "Aktiviert oder deaktiviert die Impuls-Trigger-Vibration an den adaptiven DualSense-Triggern L2 und R2", // SettingDescTriggerRumble- "Wechselt die Tastenbelegung für Bestätigen und Zurück zwischen Kreuz (westlich) und Kreis (japanisch)", // SettingDescConfirmButton- "Konfiguriert Farbe und Verhalten der Lichtleiste des DualSense-Controllers beim Navigieren und Spielen", // SettingDescLightBar- "Prüft und installiert offizielle App-Updates automatisch direkt auf der Konsole ohne PC", // SettingDescUpdates- "Ermöglicht die Xbox-Konto-Anmeldung über eine andere Region für alternative Spielkataloge", // SettingDescLoginCountry- "Aktiviert 120-Hz-Videoausgabe auf Ihrer Konsole für minimale Eingabelatenz und höhere Bildwiederholrate", // SettingDescHighRefresh- "Legt die maximale Bitrate für das Videostreaming fest, um Bildqualität zu optimieren oder Daten zu sparen", // SettingDescBitrateCap- "Regelt die Gesamtlautstärke während der Spielsitzungen im Cloud-Streaming", // SettingDescGameVolume- "Weist Tasten der USB- oder Bluetooth-Tastatur den entsprechenden Xbox-Controller-Tasten beim Spielen zu", // SettingDescKeyboardKeys- "Wechselt zwischen Fenster- und Vollbildmodus auf unterstützten Desktop-Plattformen", // SettingDescDisplayMode- "Öffnet den Test- und Kalibrierungsbildschirm für alle Tasten und Achsen des angeschlossenen Controllers", // SettingDescControllerButtons- "Nutzt die DualSense-Bewegungssensoren zur Unterstützung des analogen Zielens in Shooter- und Actionspielen", // SettingDescGyro- "Spielt einen Signalton ab, wenn die Wartezeit in der xCloud-Warteschlange endet und das Spiel bereit ist", // SettingDescQueueReady- "Führt eine Diagnose der Xbox Live-Anmeldung durch und prüft Zugriffstoken, Profil und Abonnements", // SettingDescCheckSignIn- "Misst Ping (RTT) und Jitter zu Cloud-Gaming-Rechenzentren in mehreren weltweiten Regionen", // SettingDescNetworkTest- "Zeigt einen QR-Code, um den Entwickler via Ko-fi zu unterstützen und die Pflege des Projekts zu sichern", // SettingDescSupportProject- "Neuigkeiten", // WhatsNew- "Neuigkeiten", // WhatsNewTitle- "Controller-Lautsprecher", // PadSpeakerVolume- "Stumm", // Mute- "Web-Steuerung", // WebControlTitle- "Über Smartphone verbinden", // WebControlSubtitle- "Mit demselben WLAN verbinden, um zu suchen, Tasten zu belegen, das Smartphone als Controller zu nutzen, Fehler zu melden oder Logs anzusehen.", // WebControlDesc- "Videodekodierung", // VideoDecoder- "Hardware (Empfohlen)", // VideoDecoderHw- "Software (CPU)", // VideoDecoderSw- "Wählt Hardware-Dekodierung (libSceVideodec2 auf PS5, HWAccel auf Desktop) oder Software-Dekodierung (CPU)", // SettingDescVideoDecoder- "Audio-zu-Haptik", // AudioHaptics- "Wandelt tiefe Audiofrequenzen in DualSense-Haptik-Vibrationen um", // SettingDescAudioHaptics- "Touchpad-Kurzbefehle", // TouchpadShortcuts- "Konfiguriert Wischgesten sowie Links- und Rechtsklick auf dem DualSense-Touchpad", // SettingDescTouchpadShortcuts- "Nach oben wischen (↑)", // TouchpadSwipeUp- "Nach unten wischen (↓)", // TouchpadSwipeDown- "Nach links wischen (←)", // TouchpadSwipeLeft- "Nach rechts wischen (→)", // TouchpadSwipeRight- "Linksklick", // TouchpadClickLeft- "Rechtsklick", // TouchpadClickRight- "Deaktiviert", // TouchpadActNone- "Spielmenü", // TouchpadActGameMenu- "Xbox-Taste", // TouchpadActXboxButton- "Statistiken umschalten", // TouchpadActToggleStats- "Mikrofon stumm/aktiv", // TouchpadActToggleMic- "Gyro-Modus wechseln", // TouchpadActCycleGyro- "Trigger-Profil wechseln", // TouchpadActCycleTrigger- "Touchpad + Options öffnet immer das Spielmenü", // TouchpadHelp- "Standardeinstellungen wiederherstellen", // ResetSettings- "Setzt alle Einstellungen auf die Werkseinstellungen zurück. 5 Sekunden ✕ gedrückt halten zur Bestätigung.", // SettingDescResetSettings- "Einstellungen auf Standardwerte zurückgesetzt.", // SettingsResetNotice- "Halten zum Zurücksetzen", // HoldToReset- "Bibliothek ist bereits aktuell", // LibraryUpToDate- "Bibliothek aktualisiert (%s neue Spiele)", // LibraryUpdatedCount- "Offline-Modus", // OfflineMode-};--constexpr Column kItalian = {- "PSBox Cloud Gaming",- "PSBOX CLOUD GAMING",- "Accesso in corso...",- "Richiesta di un codice di accesso...",- "Caricamento dei tuoi giochi...",- "Accedi per giocare",- "Sul telefono o sul computer, vai su",- "e inserisci questo codice",- "Scansiona per aprire la pagina, poi inserisci il codice",- "In attesa del tuo accesso...",- "Riprendi a giocare",- "Gioca",- "Indietro",- "Seleziona",- "Esci",- "Annulla",- "Riprova",- "Preparazione del gioco",- "Sei in coda. Attesa stimata: %s",- "Connessione...",- "Avvio dello streaming...",- "Touchpad: ↓ questo menu · ↑ pulsante Xbox",- "Streaming terminato",- "Si è verificato un problema",- "Accesso effettuato come %s",- "Ancora nessun gioco da mostrare",- "Di %s",- "Impostazioni",- "Lingua",- "Risoluzione dello streaming",- "Regione del server",- "Automatica (%s)",- "1080p (Full HD)",- "720p (usa meno dati)",- "Migliore (Auto)",- "Risoluzione e regione valgono dal prossimo gioco avviato.",- "Cambia",- "Regola",- "Tieni premuto per uscire",- "Continua a tenere premuto per uscire (%s)",- "Accesso non riuscito: %s",- "L'accesso nel browser non è stato completato. Utilizza un account Microsoft personale, completa le verifiche/2FA e autorizza l'app.",- "Impossibile caricare l'elenco dei giochi: %s",- "Impossibile avviare lo streaming: %s",- "Nessuna attività: verrai disconnesso tra %s secondi",- "I miei giochi",- "Non disponibile sul tuo account",- "Game Pass",- "Cerca",- "Scrivi il nome di un gioco",- "Nessun gioco trovato",- "%s risultati",- "Spazio",- "Cancella",- "Svuota",- "%s giochi",- "Scrivi",- "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 miei giochi.",- "Scansiona per aprire la pagina dello store",- "Cerca in %s",- "GRATIS",- "Nascondi",- "Mostra",- "Nascosti",- "\xE2\x96\xA1 mostra di nuovo un gioco",- "Nascosto: lo trovi in Nascosti, in fondo a questa scheda",- "Di nuovo visibile",- "Ordina: %s",- "Recenti prima",- "A-Z",- "Per console",- "Ordina",- "Gratis",- "Prezzo più basso",- "Tutte le console",- "1 gioco",- "Sezioni",- "Aggiornamento dell'elenco dei giochi...",- "Menu di gioco",- "Statistiche",- "Attivo",- "Disattivo",- "Risoluzione dello stream",- "Esci dal gioco",- "Latenza",- "Bitrate",- "Fotogrammi al secondo",- "Perdita di pacchetti",- "Regione",- "Decodifica",- "Il server potrebbe mantenere la qualità attuale",- "Nitidezza",- "Disattivata",- "Bassa",- "Media",- "Alta",- "Zona morta dello stick",- "Vibrazione dei grilletti",- "Tasto di conferma",- "Attivata",- "Disattivata",- "Versione %s disponibile",- "Controller",- "Controller %s connesso",- "Controller %s disconnesso",- "Attenuazione blocchi",- "Sullo schermo dopo",- "Connessione persa: riconnessione...",- "Riconnesso",- "Barra luminosa",- "Upscaling",- "IA (Anime4K)",- "Free to play",- "Ottienilo una volta, gratis, su xbox.com o nell'app Xbox (scansiona il codice con il telefono), poi premi Gioca.",- "Scansiona per ottenerlo gratis",- "%s non è ancora nel tuo account. È gratis: scansiona il codice nella sua pagina, scegli Ottieni e riprova (può volerci un minuto).",- "Il tuo account non può giocare a %s: non è nel tuo abbonamento o non è stato acquistato.",- "Le mie console",- "Accesa",- "In standby",- "Spenta",- "Ricerca delle tue console...",- "Nessuna Xbox trovata per ora",- "Gioca sulla tua Xbox da qui: il suo schermo, i giochi e le app.",- "Accensione della tua Xbox...",- "%s non ha risposto. Controlla che le Funzionalità remote siano attive e la modalità sia Sospensione, oppure accendila, e riprova.",- "Sulla tua Xbox, accedi con questo stesso account Microsoft.",- "Impostazioni > Dispositivi e connessioni > Funzionalità remote: attiva le funzionalità remote.",- "Impostazioni > Generale > Opzioni di alimentazione: scegli Sospensione, così si accende da sola.",- "Scansiona per l'aiuto di Microsoft",- "Cerca di nuovo",- "Pulsante Xbox",- "Termina lo streaming",- "Lo streaming è stato terminato sulla Xbox",- "Un altro dispositivo ha preso lo streaming",- "La Xbox è stata spenta",- "%s ha ricevuto la richiesta, ma il gioco remoto non è partito. Riavviala: tieni premuto il pulsante di accensione della console per 10 secondi, riaccendila e riprova.",- "Touchpad: scorri ↓ per il menu, ↑ per il pulsante Xbox",- "FSR + pulizia",- "IA + pulizia",- "Auto (%s)",- "Aggiornare ora? L'app si riavvia da sola alla fine.",- "Aggiorna ora",- "Non ora",- "Aggiornamenti",- "Aggiornato (%s)",- "%s disponibile: aggiorna",- "Verifica...",- "Aggiornamento a %s",- "Download... %s",- "Verifica della firma...",- "Installazione...",- "Aggiornato. Riavvio...",- "PSBox aggiornato: riapri l'app",- "Aggiornamento non riuscito: nulla è cambiato",- "Colore del gioco",- "Colore personalizzato",- "Colore della barra luminosa",- "Levetta sinistra o croce: colore L2 / R2: luminosità",- "Leggera",- "Media",- "Forte",- "Massima",- "Intensità",- "Frequenza",- "Bassa",- "Alta",- "Premi L2 / R2 per sentirlo: più a fondo, più forte lo chiederebbe il gioco",- "Livello %s",- "Levetta sinistra",- "Levetta destra",- "Posizione reale",- "Ciò che riceve il gioco",- "L1 / R1: scegliere la levetta Croce ← / →: regolare Muovi le levette per vederlo",- "Resistenza",- "Stile",- "Vibrazione",- "Impulsi di forza",- "Modalità",- "Genere",- "Lingua",- "Tutte le modalità",- "Giocatore singolo",- "Multigiocatore online",- "Cooperativa online",- "Locale / schermo condiviso",- "Tutti i generi",- "Qualsiasi lingua",- "italiano",- "Sottotitoli in %s",- "Doppiato in %s",- "Impostazioni di gioco",- "Profilo",- "Predefinito",- "Personalizzato",- "Ripristina predefiniti",- "Editore",- "Tutti gli editori",- "Indie e altri",- "Amici che giocano ora",- "Microfono",- "Disattivato",- "Attivo",- "Uscita audio",- "TV",- "Altoparlante del controller",- "Segnala un problema",- "Inquadralo con il telefono: si apre il modulo dei bug di GitHub già compilato. Lo controlli prima di inviarlo.",- "Include la versione dell'app, l'errore e righe del log, senza dati personali.",- "PSBox si è chiuso inaspettatamente l'ultima volta",- "Paese di accesso",- "Disattivato (quello della console)",- "Accedi come un altro paese",- "A xCloud verrà detto che l'accesso arriva dal paese scelto. Microsoft non lo consente: usalo a tuo rischio. I giochi potrebbero arrivare da server lontani, con più ritardo. Puoi cambiarlo poi in Impostazioni.",- "xCloud ha rifiutato l'accesso. Il cloud gaming potrebbe non essere offerto nel tuo paese, oppure l'account non ha un abbonamento Game Pass con il cloud gaming.",- "xCloud ha rifiutato l'accesso, anche scegliendo %s. Probabilmente l'account non ha un abbonamento Game Pass con il cloud gaming.",- "Brasile",- "Giappone",- "Corea del Sud",- "Polonia",- "Stati Uniti",- "Le connessioni sicure sono state rifiutate perché la data e l'ora della PS5 sembrano errate (indica %s). Impostale in Impostazioni > Sistema > Data e ora, poi riprova.",- "Una connessione sicura è stata rifiutata: qualcosa nella rete (un server DNS, proxy o filtro) risponde al posto dei siti Microsoft. Prova senza e riprova.",- "La data e l'ora della PS5 sembrano errate (%s): alcuni contenuti non si caricano. Impostale in Impostazioni > Sistema > Data e ora.",- "Impossibile salvare l'accesso sulla console: verrà richiesto di nuovo la prossima volta. Segnalalo (Impostazioni > △).",- "Attesa stimata: %s s", // QueueSeconds- "Attesa stimata: %s min", // QueueMinutes- "Uscita 120 Hz (VRR)", // HighRefresh- "Attiva (nei giochi)", // HighRefreshOn- "Connessione instabile", // ConnectionUnstable- "Sessione: %s", // SessionSummary- "Bitrate massimo", // BitrateCap- "Automatico", // BitrateAuto- "Volume del gioco", // GameVolume- "Tastiera: F12 questo menu · Home pulsante Xbox", // MenuKeyHint- "Tastiera e mouse", // FilterMouseKeyboard- "Tastiera e mouse", // MouseKeyboardSupport- "Tastiera e mouse: giocatore %s", // KeyboardPlayer- "Sei in coda.", // InQueueNoEstimate- "Tasti della tastiera", // KeyboardKeys- "Croce direzionale", // DPad- "Premi un tasto o un pulsante del mouse", // PressKey- "%s è riservato all'app", // KeyReserved- "Cambia", // ChangeKey- "Cancella", // ClearKey- "Il mouse muove la levetta destra e ogni scatto della rotella preme Triangolo. F12 (menu), Home (tasto Xbox) e 1-4 (giocatore) sono riservati all'app.", // KeysHelp- "Mira giroscopica", // Gyro- "Sempre", // GyroAlways- "Mirando (L2)", // GyroAiming- "Intensità giroscopio", // GyroIntensity- "Le connessioni sicure sono state rifiutate perché la data e l'ora di questo computer sembrano errate (indica %s). Correggile nelle impostazioni di sistema, poi riprova.", // ClockWrongPc- "La data e l'ora di questo computer sembrano errate (%s): alcuni contenuti non si caricano. Correggile nelle impostazioni di sistema.", // ClockWrongNoticePc- "Disattivato (quello del computer)", // LoginCountryOffPc- "Apri nel browser", // OpenInBrowser- "%s disponibile: scarica", // UpdateReadyPc- "Menu: START + BACK o F12 · Pulsante Xbox: Guide o Home", // GestureHintButtons- "START + BACK o F12: questo menu · Guide o Home: pulsante Xbox", // MenuButtonHint- "Modalità schermo", // DisplayMode- "Finestra", // DisplayWindow- "Schermo intero", // DisplayFullscreen- "Uscire da PSBox?", // QuitTitle- "Esci", // QuitConfirm- "Pulsanti del controller", // ControllerButtons- "Premi il pulsante per %s", // PadPressButton- "Manca un pulsante per: %s. Assegnane uno a ogni funzione, oppure ripristina o annulla le modifiche.", // PadMissing- "Annulla modifiche", // DiscardChanges- "Vale solo nel gioco: i menu dell'app usano i pulsanti così come sono. Scegliere un pulsante già usato scambia i due.", // PadHelp- "Piano", // FilterPlan- "Il mio piano", // PlanMine- "Tutti i piani", // PlanAll- "Incluso con Game Pass %s", // IncludedWithPlan- "Touchpad come mouse", // TouchpadMouse- "Preferiti", // Favorites- "Aggiungi ai preferiti", // AddFavorite- "Rimuovi dai preferiti", // RemoveFavorite- "Aggiunto ai preferiti", // AddedToFavorites- "Rimosso dai preferiti", // RemovedFromFavorites- "Lingua del gioco", // GameLanguage- "Limite mensile di gioco su cloud raggiunto", // MonthlyLimitExceeded- "Tempo di gioco rimanente", // PlaytimeRemaining- "%s ore rimanenti", // HoursRemaining- "Meno di 2 ore rimanenti", // PlaytimeWarning- "Profilo grilletti", // TriggerProfile- "Standard", // TriggerProfileStd- "Sparatutto (Hair Trigger)", // TriggerProfileShooter- "Corsa (ABS)", // TriggerProfileRacing- "La memoria %s non è scrivibile: accesso e impostazioni non verranno salvati", // StorageNotWritable- "FTP: esegui 'chmod 777 %s' o elimina la cartella e riavvia", // StorageFixHint- "Personalizza indicatori", // StatsCustomize- "FPS e risoluzione", // StatsIndicatorFps- "Bitrate", // StatsIndicatorBitrate- "Latenza (RTT)", // StatsIndicatorLatency- "Perdita pacchetti", // StatsIndicatorLoss- "Grafico frametime", // StatsIndicatorGraph- "Latenza di decodifica e visualizzazione", // StatsIndicatorDelay- "Qualità video (QP)", // StatsIndicatorQp- "Stato microfono", // StatsIndicatorMic- "Inquadra il codice QR con lo smartphone per risolvere con Microsoft, poi premi Croce per riprovare", // ScanQrToResolve- "Ottieni gratis", // ClaimFree- "Acquisizione licenza gratuita in corso...", // Claiming- "Gioco aggiunto al tuo account con successo!", // ClaimSuccess- "Impossibile ottenere il gioco gratuito: %s", // ClaimFailed- "Questo gioco non è gratuito nello store", // ProductNotFree- "Gioco gratuito. Premi Croce per aggiungerlo al tuo account e iniziare a giocare", // FreeAcquireHint- "Risoluzione DNS non riuscita per i server Microsoft. Su PS5, assicurati di eseguire NanoDNS e impostare il DNS primario sull'IP locale per bloccare Sony mantenendo l'accesso a Internet.", // DnsBlockedNanoDns- "Questo account Microsoft non ha ancora un profilo Xbox. Accedi a xbox.com su smartphone o PC per creare il tuo Gamertag, quindi riprova.", // XboxProfileMissing- "Coda pronta! Avvio del gioco...", // QueueReadyAlert- "Segnale acustico di fine coda", // QueueReadyNotification- "Giocato: %s", // PlaytimePlayed- "Aggiorna", // RefreshLibrary- "Aggiornamento libreria...", // RefreshingLibrary- "Questo account Xbox è sospeso o bloccato. Visita enforcement.xbox.com per i dettagli.", // XboxAccountBanned- "Xbox Live non è offerto nel paese o nella regione di questo account.", // XboxRegionNotSupported- "È richiesta la verifica dell'età o l'accettazione dei termini. Accedi a xbox.com in un browser, poi riprova.", // XboxAdultVerificationRequired- "Account bambino: un adulto deve aggiungere questo account a una famiglia Microsoft su account.microsoft.com/family.", // XboxChildAccountFamily- "Verifica il mio accesso", // CheckSignIn- "Verifica", // RunCheck- "Test di rete", // NetworkTest- "Testa", // RunTest- "Obiettivi", // Achievements- "Nessun obiettivo", // NoAchievements- "Bloccato", // AchievementLocked- "Obiettivo segreto", // SecretAchievement- "Lista dei desideri", // Wishlist- "Aggiungi ai desideri", // AddWishlist- "Rimuovi dai desideri", // RemoveWishlist- "Aggiunto ai desideri", // AddedToWishlist- "Rimosso dai desideri", // RemovedFromWishlist- "%s è in saldo!", // WishlistOnSale- "%s è arrivato su Game Pass!", // WishlistInGamePass- "Supporta il progetto", // SupportProject- "Supporta lo Sviluppo di PSBox", // SupportTitle- "PSBox è un progetto open source sviluppato con passione per portare la migliore esperienza di Xbox Cloud Gaming su PlayStation 5. Se ti piace l'app e vuoi sostenere lo sviluppo continuo e le nuove funzionalità, considera di offrirmi un caffè su Ko-Fi!", // SupportMessage- "Ko-fi", // SupportKoFi- "Inquadra con lo smartphone", // ScanToDonate- "Prova suono", // TestSound- "La lista dei desideri è vuota", // WishlistEmpty- // Loading tips- "Touchpad: scorri ↓ (o Touchpad + Options) per il menu, ↑ per il pulsante Xbox", // TipTouchpadMenu- "Tastiera e mouse USB collegati alla console sono supportati nei giochi cloud compatibili", // TipKeyboardMouse- "Ottieni giochi gratuiti, demo e promozioni del negozio direttamente dalla libreria dell'app", // TipFreeStore- "Hai riscontrato un problema? Apri Segnala problema per scansionare un QR code con i log della console", // TipBugReportQr- "Ti piace il progetto? Sostieni lo sviluppo futuro tramite Ko-fi nella scheda Impostazioni!", // TipSupportKofi- "Abilita l'uscita video a 120 Hz nelle Impostazioni per una latenza di visualizzazione ridotta", // Tip120HzVideo- "Calibra la zona morta delle levette nelle Impostazioni per eliminare il drift e migliorare la precisione", // TipAnalogDeadzone- "Usa il microfono integrato del DualSense per la chat vocale nei gruppi e nelle partite multigiocatore", // TipDualSenseMic- // Settings descriptions- "Modifica la lingua dell'interfaccia dell'applicazione e le preferenze di audio e sottotitoli nei giochi cloud", // SettingDescLanguage- "Imposta la risoluzione video massima (1080p, 720p o Migliore disponibile). Ha effetto al prossimo avvio", // SettingDescResolution- "Seleziona la regione dei server Microsoft per lo streaming (Automatica o specifica). Ha effetto al prossimo avvio", // SettingDescRegion- "Regola la zona morta interna delle levette analogiche DualSense per evitare drift e movimenti involontari", // SettingDescDeadzone- "Abilita o disabilita l'emulazione della vibrazione sui grilletti adattivi L2 e R2 nei giochi compatibili", // SettingDescTriggerRumble- "Alterna la configurazione dei tasti conferma e indietro tra Croce (occidentale) e Cerchio (giapponese)", // SettingDescConfirmButton- "Configura il colore e il comportamento della barra luminosa del DualSense nei menu e durante il gioco", // SettingDescLightBar- "Verifica e installa automaticamente gli aggiornamenti ufficiali dell'app direttamente sulla console", // SettingDescUpdates- "Consente di accedere al proprio account Xbox tramite un'altra regione per accedere a cataloghi alternativi", // SettingDescLoginCountry- "Abilita l'uscita video a 120 Hz sulla console per un ritardo di visualizzazione e latenza di input ridotti", // SettingDescHighRefresh- "Imposta il limite massimo di bitrate per lo streaming video, garantendo alta fedeltà o risparmio dati", // SettingDescBitrateCap- "Regola il livello del volume audio principale durante le sessioni di gioco in streaming", // SettingDescGameVolume- "Mappa i tasti della tastiera USB o Bluetooth sui pulsanti corrispondenti del controller Xbox durante il gioco", // SettingDescKeyboardKeys- "Alterna tra modalità finestra e schermo intero sulle piattaforme desktop supportate", // SettingDescDisplayMode- "Apre la schermata di test e calibrazione di tutti i pulsanti e gli assi del controller collegato", // SettingDescControllerButtons- "Abilita i sensori di movimento DualSense per assistere la mira analogica negli sparatutto e giochi d'azione", // SettingDescGyro- "Riproduce un segnale sonoro caratteristico quando l'attesa nella coda di xCloud termina e il gioco è pronto", // SettingDescQueueReady- "Esegue una diagnostica completa dell'accesso a Xbox Live, convalidando token di accesso, profilo e abbonamenti", // SettingDescCheckSignIn- "Misura il ping (RTT) e il jitter verso i data center di gioco in cloud in diverse regioni globali", // SettingDescNetworkTest- "Mostra un codice QR per supportare lo sviluppatore tramite Ko-fi e contribuire a mantenere il progetto attivo", // SettingDescSupportProject- "Novità", // WhatsNew- "Novità", // WhatsNewTitle- "Altoparlante del controller", // PadSpeakerVolume- "Muto", // Mute- "Controllo Web", // WebControlTitle- "Connetti dallo smartphone", // WebControlSubtitle- "Connettiti allo stesso Wi-Fi per cercare, rimappare pulsanti, usare il telefono come controller virtuale, segnalare problemi o visualizzare i log.", // WebControlDesc- "Decodifica video", // VideoDecoder- "Hardware (Consigliato)", // VideoDecoderHw- "Software (CPU)", // VideoDecoderSw- "Seleziona decodifica hardware (libSceVideodec2 su PS5, HWAccel su Desktop) o software (CPU)", // SettingDescVideoDecoder- "Audio a vibrazione aptica", // AudioHaptics- "Converte le basse frequenze audio in vibrazioni aptiche su DualSense", // SettingDescAudioHaptics- "Scorciatoie del touchpad", // TouchpadShortcuts- "Configura i gesti di scorrimento e i clic sinistro/destro sul touchpad DualSense", // SettingDescTouchpadShortcuts- "Scorri in alto (↑)", // TouchpadSwipeUp- "Scorri in basso (↓)", // TouchpadSwipeDown- "Scorri a sinistra (←)", // TouchpadSwipeLeft- "Scorri a destra (→)", // TouchpadSwipeRight- "Clic sinistro", // TouchpadClickLeft- "Clic destro", // TouchpadClickRight- "Disattivato", // TouchpadActNone- "Menu di gioco", // TouchpadActGameMenu- "Pulsante Xbox", // TouchpadActXboxButton- "Mostra/nascondi statistiche", // TouchpadActToggleStats- "Disattiva/attiva microfono", // TouchpadActToggleMic- "Cambia modalità giroscopio", // TouchpadActCycleGyro- "Cambia profilo grilletto", // TouchpadActCycleTrigger- "Touchpad + Options apre sempre il menu di gioco", // TouchpadHelp- "Ripristina impostazioni predefinite", // ResetSettings- "Ripristina tutte le impostazioni ai valori di fabbrica. Tieni premuto ✕ per 5 secondi per confermare.", // SettingDescResetSettings- "Impostazioni ripristinate ai valori predefiniti.", // SettingsResetNotice- "Tieni premuto per ripristinare", // HoldToReset- "La libreria è già aggiornata", // LibraryUpToDate- "Libreria aggiornata (%s nuovi giochi)", // LibraryUpdatedCount- "Modalità non in linea", // OfflineMode-};+#include "ui/i18n/strings_en.inc"+#include "ui/i18n/strings_pt_br.inc"+#include "ui/i18n/strings_es.inc"+#include "ui/i18n/strings_fr.inc"+#include "ui/i18n/strings_de.inc"+#include "ui/i18n/strings_it.inc"constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,&kFrench, &kGerman, &kItalian};@@ -2538,6 +85,15 @@ std::string trf(Str id, const std::string& arg) {return s;}+std::string trf(Str id, const std::string& arg1, const std::string& arg2) {+ std::string s = tr(id);+ size_t at = s.find("%s");+ if (at != std::string::npos) s.replace(at, 2, arg1);+ at = s.find("%s");+ if (at != std::string::npos) s.replace(at, 2, arg2);+ return s;+}+std::string touchpadActionLabel(int actionIndex) {switch (actionIndex) {case 0: return tr(Str::TouchpadActNone);diff --git a/src/ui/strings.h b/src/ui/strings.hindex 7e4f847..fb212a6 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -417,6 +417,13 @@ enum class Str {LibraryUpToDate,LibraryUpdatedCount,OfflineMode,+ PreviewFeatures,+ SettingDescPreviewFeatures,+ GamePassRequired,+ InQueueIndeterminate,+ InQueueEstimated,+ F2pPreviewRequiredDesc,+ F2pPreviewAccountNeededDesc,Count};@@ -437,6 +444,8 @@ const char* gameLocale();const char* tr(Str id);// tr() with one "%s" substituted.std::string trf(Str id, const std::string& arg);+// tr() with two "%s" substituted in order.+std::string trf(Str id, const std::string& arg1, const std::string& arg2);std::string touchpadActionLabel(int actionIndex);const char* touchpadTriggerLabel(int triggerIndex);diff --git a/src/xcloud/catalog.cpp b/src/xcloud/catalog.cppindex 8421d2a..f8743f3 100644--- a/src/xcloud/catalog.cpp+++ b/src/xcloud/catalog.cpp@@ -190,6 +190,12 @@ bool fetchProducts(const std::vector<std::string>& ids, const std::string& markeif (prod.heroUrl.empty()) prod.heroUrl = existing->second.heroUrl;if (prod.description.empty()) prod.description = existing->second.description;if (prod.xcloudTitleId.empty()) prod.xcloudTitleId = existing->second.xcloudTitleId;+ if (prod.ratingAge.empty()) prod.ratingAge = existing->second.ratingAge;+ if (prod.ratingSystem.empty()) prod.ratingSystem = existing->second.ratingSystem;+ if (prod.ratingDescriptors.empty()) prod.ratingDescriptors = existing->second.ratingDescriptors;+ if (prod.publisher.empty()) prod.publisher = existing->second.publisher;+ if (prod.categories.empty()) prod.categories = existing->second.categories;+ if (prod.xboxTitleId.empty()) prod.xboxTitleId = existing->second.xboxTitleId;prod.isPcOnly = prod.isPcOnly || existing->second.isPcOnly;if (!prod.detailed && existing->second.detailed) {prod.detailed = existing->second.detailed;diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cppindex d50b182..36a59b9 100644--- a/src/xcloud/gssv.cpp+++ b/src/xcloud/gssv.cpp@@ -23,13 +23,13 @@ constexpr int kLoginTries = 6; // xCloud login: tries on a 5xx / no answer// Sent like the Windows Xbox app does: "Windows" plus a 1080p display is what// gets a 1080p stream; an Android device with a 720p display gets 720p.-const std::string& deviceInfo(Resolution res) {- auto build = [](bool hd, int w = 1920, int h = 1080) {+const std::string& deviceInfo(Resolution res, bool preview = true) {+ auto build = [](bool hd, bool prev, int w = 1920, int h = 1080) {json::Value env = json::Value::object();- env.set("clientAppId", "Microsoft.GamingApp");- env.set("clientAppType", "native");- env.set("clientAppVersion", "2203.1001.4.0");- env.set("clientSdkVersion", "8.5.2");+ env.set("clientAppId", prev ? "play.xbox.com" : "Microsoft.GamingApp");+ env.set("clientAppType", prev ? "browser" : "native");+ env.set("clientAppVersion", prev ? "26.1.97" : "2203.1001.4.0");+ env.set("clientSdkVersion", prev ? "10.3.7" : "8.5.2");env.set("httpEnvironment", "prod");env.set("sdkInstallId", "");json::Value app = json::Value::object();@@ -37,7 +37,7 @@ const std::string& deviceInfo(Resolution res) {json::Value hw = json::Value::object();hw.set("make", hd ? "Microsoft" : "Google");hw.set("model", hd ? "Surface Pro" : "Pixel");- hw.set("sdktype", "native");+ hw.set("sdktype", prev ? "web" : "native");json::Value os = json::Value::object();os.set("name", hd ? "Windows 11" : "Android");os.set("ver", hd ? "22631.2715" : "14");@@ -62,9 +62,9 @@ const std::string& deviceInfo(Resolution res) {};// 1440p: the xbox.com web client (SDK 10.6.62) in Edge on a 1440p display,// field for field as its X-MS-Device-Info interceptor builds it.- static const std::string qhd = [] {+ auto makeQhd = [](bool prev) {json::Value env = json::Value::object();- env.set("clientAppId", "www.xbox.com");+ env.set("clientAppId", prev ? "play.xbox.com" : "www.xbox.com");env.set("clientAppType", "browser");env.set("clientAppVersion", "1.0.2610.0201");env.set("clientSdkVersion", "10.6.65");@@ -111,12 +111,12 @@ const std::string& deviceInfo(Resolution res) {v.set("appInfo", app);v.set("dev", dev);return v.dump();- }();+ };// 1080p HQ: the web client on a Tizen TV with a 4K panel, as Better// xCloud sends it.- static const std::string tv = [] {+ auto makeTv = [](bool prev) {json::Value env = json::Value::object();- env.set("clientAppId", "www.xbox.com");+ env.set("clientAppId", prev ? "play.xbox.com" : "www.xbox.com");env.set("clientAppType", "browser");env.set("clientAppVersion", "26.1.97");env.set("clientSdkVersion", "10.3.7");@@ -153,13 +153,16 @@ const std::string& deviceInfo(Resolution res) {v.set("appInfo", app);v.set("dev", dev);return v.dump();- }();- static const std::string hd = build(true), sd = build(false);+ };+ static const std::string qhd_p = makeQhd(true), qhd_np = makeQhd(false);+ static const std::string tv_p = makeTv(true), tv_np = makeTv(false);+ static const std::string hd_p = build(true, true), hd_np = build(true, false);+ static const std::string sd_p = build(false, true), sd_np = build(false, false);switch (res) {- case Resolution::P720: return sd;- case Resolution::P1440: return qhd;- case Resolution::P1080HQ: return tv;- default: return hd;+ case Resolution::P720: return preview ? sd_p : sd_np;+ case Resolution::P1440: return preview ? qhd_p : qhd_np;+ case Resolution::P1080HQ: return preview ? tv_p : tv_np;+ default: return preview ? hd_p : hd_np;}}@@ -215,7 +218,7 @@ std::string GssvClient::sessionUrl(const std::string& suffix) const {return region_.baseUri + p + suffix;}-static net::Request authed(Resolution res, const GssvLogin& l, std::string method, std::string url,+static net::Request authed(Resolution res, bool preview, const GssvLogin& l, std::string method, std::string url,std::string body = {}) {net::Request req;req.method = std::move(method);@@ -223,7 +226,7 @@ static net::Request authed(Resolution res, const GssvLogin& l, std::string methoreq.body = std::move(body);req.headers = {{"Authorization", "Bearer " + l.gsToken},{"x-gssv-client", kClientHeader},- {"X-MS-Device-Info", deviceInfo(res)}};+ {"X-MS-Device-Info", deviceInfo(res, preview)}};if (!req.body.empty() || req.method == "POST") req.headers.emplace_back("Content-Type", "application/json");return req;}@@ -329,7 +332,7 @@ bool GssvClient::listTitles(std::vector<Title>& out, std::string& err, bool recedo {std::string path = recentOnly ? "/v2/titles/mru?mr=25" : "/v2/titles?mr=200";if (!continuation.empty()) path += "&ct=" + net::urlEncode(continuation);- auto r = net::perform(authed(resolution_, login_, "GET", url(path)));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", url(path)));auto j = json::parse(r.body);if (!r.ok() || !j) {err = "title list failed: " + describe(r);@@ -434,7 +437,7 @@ bool GssvClient::hydrateTitles(std::vector<Title>& titles, const std::string& mabool GssvClient::listConsoles(std::vector<Console>& out, std::string& err) {out.clear();- auto r = net::perform(authed(resolution_, login_, "GET", url("/v6/servers/home")));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", url("/v6/servers/home")));auto j = json::parse(r.body);if (!r.ok() || !j) {err = "console list failed: " + describe(r);@@ -495,7 +498,7 @@ bool GssvClient::startSession(const std::string& titleId, const std::string& locbody.set("fallbackRegionNames", json::Value::array());std::string kind = offering_ == "xhome" ? "home" : "cloud";- auto r = net::perform(authed(resolution_, login_, "POST", url("/v5/sessions/" + kind + "/play"), body.dump()));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", url("/v5/sessions/" + kind + "/play"), body.dump()));if (status) *status = r.status;auto j = json::parse(r.body);if (!r.ok() || !j || !(*j)["sessionPath"].isString()) {@@ -508,7 +511,7 @@ bool GssvClient::startSession(const std::string& titleId, const std::string& loc}bool GssvClient::sessionState(SessionStatus& out, std::string& err) {- auto r = net::perform(authed(resolution_, login_, "GET", sessionUrl("/state")));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", sessionUrl("/state")));auto j = json::parse(r.body);if (!r.ok() || !j) {err = "session state failed: " + describe(r);@@ -523,7 +526,7 @@ bool GssvClient::sessionState(SessionStatus& out, std::string& err) {int GssvClient::titleWaitSeconds(const std::string& titleId) {if (titleId.empty() || login_.gsToken.empty()) return -1;- auto r = net::perform(authed(resolution_, login_, "GET", url("/v1/waittime/" + titleId)));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", url("/v1/waittime/" + titleId)));auto j = json::parse(r.body);if (!r.ok() || !j) return -1;return static_cast<int>((*j)["estimatedTotalWaitTimeInSeconds"].asInt(-1));@@ -532,7 +535,7 @@ int GssvClient::titleWaitSeconds(const std::string& titleId) {bool GssvClient::connect(const std::string& msaTransferToken, std::string& err) {json::Value body = json::Value::object();body.set("userToken", msaTransferToken);- auto r = net::perform(authed(resolution_, login_, "POST", sessionUrl("/connect"), body.dump()));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/connect"), body.dump()));if (!r.ok()) {err = "session connect failed: " + describe(r);return false;@@ -569,7 +572,7 @@ bool GssvClient::sendSdpOffer(const std::string& sdp, std::string& err) {body.set("sdp", sdp);body.set("requestId", "1");body.set("configuration", cfg);- auto r = net::perform(authed(resolution_, login_, "POST", sessionUrl("/sdp"), body.dump()));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/sdp"), body.dump()));if (!r.ok()) {err = "SDP offer failed: " + describe(r);return false;@@ -579,7 +582,7 @@ bool GssvClient::sendSdpOffer(const std::string& sdp, std::string& err) {bool GssvClient::pollSdpAnswer(std::string& answer, std::string& err) {answer.clear();- auto r = net::perform(authed(resolution_, login_, "GET", sessionUrl("/sdp")));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", sessionUrl("/sdp")));if (r.status == 204) return true; // not ready yetauto j = json::parse(r.body);if (!r.ok() || !j) {@@ -608,7 +611,7 @@ bool GssvClient::sendIceCandidates(const std::vector<IceCandidate>& candidates,json::Value body = json::Value::object();body.set("messageType", "iceCandidate");body.set("candidate", list);- auto r = net::perform(authed(resolution_, login_, "POST", sessionUrl("/ice"), body.dump()));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/ice"), body.dump()));if (!r.ok()) {err = "ICE upload failed: " + describe(r);return false;@@ -618,7 +621,7 @@ bool GssvClient::sendIceCandidates(const std::vector<IceCandidate>& candidates,bool GssvClient::pollIceCandidates(std::vector<IceCandidate>& out, std::string& err) {out.clear();- auto r = net::perform(authed(resolution_, login_, "GET", sessionUrl("/ice")));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", sessionUrl("/ice")));if (r.status == 204) return true;auto j = json::parse(r.body);if (!r.ok() || !j) {@@ -638,7 +641,7 @@ bool GssvClient::pollIceCandidates(std::vector<IceCandidate>& out, std::string&}bool GssvClient::keepalive(std::string& err) {- auto r = net::perform(authed(resolution_, login_, "POST", sessionUrl("/keepalive")));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/keepalive")));if (!r.ok()) {err = "keepalive failed: " + describe(r);return false;@@ -648,7 +651,7 @@ bool GssvClient::keepalive(std::string& err) {void GssvClient::stopSession() {if (sessionPath_.empty()) return;- auto r = net::perform(authed(resolution_, login_, "DELETE", sessionUrl("")));+ auto r = net::perform(authed(resolution_, previewFeatures_, login_, "DELETE", sessionUrl("")));XC_LOGI("session stopped (%s)", r.ok() ? "ok" : describe(r).c_str());sessionPath_.clear();}diff --git a/src/xcloud/gssv.h b/src/xcloud/gssv.hindex 6b8076c..74ff2d4 100644--- a/src/xcloud/gssv.h+++ b/src/xcloud/gssv.h@@ -109,6 +109,8 @@ public:const GssvLogin& session() const { return login_; }void setRegion(const Region& r) { region_ = r; }void setResolution(Resolution r) { resolution_ = r; }+ void setPreviewFeatures(bool preview) { previewFeatures_ = preview; }+ bool previewFeatures() const { return previewFeatures_; }Resolution resolution() const { return resolution_; }const Region& region() const { return region_; }bool isHome() const { return offering_ == "xhome"; }@@ -153,6 +155,7 @@ private:GssvLogin login_;Region region_;std::string sessionPath_;+ bool previewFeatures_ = true;};const char* toString(SessionState s);diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 738ff0d..e2f8972 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -551,6 +551,7 @@ static void testPlaytimeLimit() {ui::Fonts fonts;ui::ImageCache images([] {});ui::AppUi app(fonts, images);+ app.setSubscription("GamePass");ui::GameTile tile;tile.titleId = "TEST_TITLE_1";tile.productId = "TEST_PROD_1";@@ -569,6 +570,107 @@ static void testPlaytimeLimit() {CHECK(ev.game.titleId == "TEST_TITLE_1");}+static void testFreeAccountPlayability() {+ ui::Fonts fonts;+ ui::ImageCache images([] {});+ ui::AppUi app(fonts, images);+ app.setSubscription(""); // Free account (no Game Pass)+ CHECK(app.isFreeAccount());++ ui::GameTile paidTile;+ paidTile.titleId = "PAID_TITLE";+ paidTile.productId = "PAID_PROD";+ paidTile.playable = true;+ paidTile.freeInStore = false;++ ui::GameTile f2pTile;+ f2pTile.titleId = "Fortnite";+ f2pTile.productId = "9NBLGGH52538";+ f2pTile.playable = true;+ f2pTile.freeInStore = true;++ ui::GameRow row;+ row.title = "Games";+ row.tiles = {paidTile, f2pTile};+ app.setRows({row});+ app.showHome();++ // Paid game on free account: cannot launch+ ui::NavInput in;+ in.accept = true;+ app.handle(in); // Home -> Details+ ui::UiEvent evPaid = app.handle(in);+ CHECK(evPaid.action != ui::Action::Play);++ // Back to home, select F2P game (index 1)+ ui::NavInput back;+ back.back = true;+ app.handle(back); // Details -> Home+ ui::NavInput right;+ right.right = true;+ app.handle(right); // Move to F2P game+ app.handle(in); // Home -> Details+ ui::UiEvent evF2p = app.handle(in);+ CHECK(evF2p.action == ui::Action::Play);+ CHECK(evF2p.game.titleId == "Fortnite");+}++static void testDetailsHydrationAndPlaytimeBadge() {+ ui::Fonts fonts;+ ui::ImageCache images([] {});+ ui::AppUi app(fonts, images);+ app.setSubscription("GamePass");+ CHECK(!app.isFreeAccount());++ // Tile on home row with only titleId and productId (no description, no rating)+ ui::GameTile lightTile;+ lightTile.titleId = "GAME_WITH_FULL_DATA";+ lightTile.productId = "PROD_FULL_DATA";+ lightTile.name = "My Full Game";+ lightTile.playable = true;++ // Detailed tile in gamePassPool+ ui::GameTile fullTile = lightTile;+ fullTile.description = "Full detailed description of the game.";+ fullTile.heroUrl = "https://example.com/hero.jpg";+ fullTile.publisher = "Awesome Studio";+ fullTile.categories = {"Action", "Adventure"};+ fullTile.ratingAge = "14+";+ fullTile.ratingSystem = "ClassInd";+ fullTile.ratingDescriptors = {"Violência"};++ app.setSearchPools({fullTile}, {});++ ui::GameRow row;+ row.title = "Jump Back In";+ row.tiles = {lightTile};+ app.setRows({row});+ app.showHome();++ // Set playtime in settings+ ui::SettingsChoice c = app.settings();+ c.titlePlaytime[lightTile.productId] = 3600; // 1 hour+ app.setSettings(c);++ // Open details+ ui::NavInput in;+ in.accept = true;+ app.handle(in); // Opens Details++ // Detail tile must have description, rating, publisher, categories, heroUrl hydrated!+ ui::NavInput acceptInDetails;+ acceptInDetails.accept = true;+ ui::UiEvent ev = app.handle(acceptInDetails);+ CHECK(ev.action == ui::Action::Play);+ CHECK(ev.game.description == "Full detailed description of the game.");+ CHECK(ev.game.publisher == "Awesome Studio");+ CHECK(ev.game.ratingAge == "14+");+ CHECK(ev.game.ratingSystem == "ClassInd");+ CHECK(ev.game.heroUrl == "https://example.com/hero.jpg");+ CHECK(!ev.game.ratingDescriptors.empty());+ CHECK(ev.game.ratingDescriptors[0] == "Violência");+}+static void testSplashInputBlocking() {ui::Fonts fonts;ui::ImageCache images([] {});@@ -2072,21 +2174,21 @@ static void testVisibleSettingsRows() {};const ui::UiCaps ps5;auto all = ui::visibleSettingsRows(ps5);- CHECK((ids(all) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 19, 7, 23}));- CHECK((groups(all) == std::vector<bool>{false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, true, false, true}));+ CHECK((ids(all) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 22, 19, 7, 23}));+ CHECK((groups(all) == std::vector<bool>{false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, true, false, true}));ui::UiCaps pc;pc.lightBar = pc.triggerRumble = pc.adaptiveTriggers = pc.gyro = pc.touchpad = false;pc.upscalers = pc.sharpen = pc.deband = pc.highRefresh = pc.console = pc.selfUpdate = false;pc.openUrl = true;auto desk = ui::visibleSettingsRows(pc);- CHECK((ids(desk) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 10, 14, 12, 3, 5, 16, 19, 7, 23}));- CHECK((groups(desk) == std::vector<bool>{false, false, false, false, false, true, false, false, true, false, false, false, false, true, false, true}));+ CHECK((ids(desk) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 10, 14, 12, 3, 5, 16, 22, 19, 7, 23}));+ CHECK((groups(desk) == std::vector<bool>{false, false, false, false, false, true, false, false, true, false, false, false, false, false, true, false, true}));// The desktop app's window: Display mode after the resolution, in the stream's group.ui::UiCaps win = pc;win.desktopWindow = true;auto w = ui::visibleSettingsRows(win);- CHECK((ids(w) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 13, 10, 14, 12, 3, 5, 16, 19, 7, 23}));- CHECK((groups(w) == std::vector<bool>{false, false, false, false, false, true, false, false, false, true, false, false, false, false, true, false, true}));+ CHECK((ids(w) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 13, 10, 14, 12, 3, 5, 16, 22, 19, 7, 23}));+ CHECK((groups(w) == std::vector<bool>{false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, true, false, true}));ui::UiCaps xbox = pc; // an Xbox pad: impulse triggers, no light barxbox.triggerRumble = true;auto x = ids(ui::visibleSettingsRows(xbox));@@ -2108,8 +2210,8 @@ static void testVisibleSettingsRows() {CHECK(ui::settingsRowPosition(ps5, 16) == 17);CHECK(ui::settingsRowPosition(ps5, 5) == 15 && ui::settingsRowPosition(ps5, 6) == 16);CHECK(ui::settingsRowPosition(ps5, 12) == 10 && ui::settingsRowPosition(ps5, 14) == 9);- CHECK(ui::settingsRowPosition(ps5, 22) == -1);- CHECK(ui::settingsRowPosition(ps5, 7) == 19 && ui::settingsRowPosition(ps5, 19) == 18 && ui::settingsRowPosition(ps5, 2) == 1);+ CHECK(ui::settingsRowPosition(ps5, 22) == 18);+ CHECK(ui::settingsRowPosition(ps5, 7) == 20 && ui::settingsRowPosition(ps5, 19) == 19 && ui::settingsRowPosition(ps5, 2) == 1);CHECK(ui::settingsRowPosition(ps5, 21) == 14);CHECK(ui::settingsRowPosition(pc, 5) == 11 && ui::settingsRowPosition(pc, 6) == -1 && ui::settingsRowPosition(pc, 4) == -1);}@@ -4027,7 +4129,14 @@ static void testDesktopMouseNav() {CHECK(uiApp.detailWanted(100).empty());}- // 6. Mouse wheel scrolling+ // 6. Clicking or hovering in the top bar area (y < 140) must not hit cards+ {+ auto evTop = uiApp.onMouseDown(120.0f, 100.0f, 1);+ CHECK(evTop.action == ui::Action::None);+ CHECK(uiApp.detailWanted(100).empty());+ }++ // 7. Mouse wheel scrolling{auto evWheel = uiApp.onMouseWheel(0.0f, 2.0f);CHECK(evWheel.action == ui::Action::None);@@ -6085,7 +6194,7 @@ static void testBlock4OwnershipAndRecents() {CHECK(t.name == "Just Dance 2026");CHECK(t.playable);CHECK(!t.purchasable);- CHECK(!t.freeInStore);+ CHECK(t.freeInStore);break;}}@@ -6158,6 +6267,7 @@ static void testBlock4OwnershipAndRecents() {jdFound = true;CHECK(t.playable);CHECK(!t.purchasable);+ CHECK(t.freeInStore);break;}}@@ -6181,6 +6291,7 @@ static void testBlock4OwnershipAndRecents() {auto owned = bootLib.owned();CHECK(owned.size() == 2);CHECK(owned[0].productId == "9P368QBR2C5S");+ CHECK(owned[0].freeInStore);CHECK(owned[1].productId == "PROD_OWNED1");bool bootFoundStore1 = false;bool bootFoundJdInPurchasable = false;@@ -6246,6 +6357,9 @@ static void testBlock4OwnershipAndRecents() {ui::Fonts dummyFonts;ui::ImageCache images([] {});ui::AppUi appUi(dummyFonts, images);+ appUi.setSubscription("Free");+ appUi.setMembership(false);+ui::GameTile t1, t2;t1.productId = "PID_OWNED";t1.titleId = "TID_OWNED";@@ -6271,19 +6385,175 @@ static void testBlock4OwnershipAndRecents() {// Claim 9P368QBR2C5SappUi.markTileOwned("9P368QBR2C5S", "TID_JD");- // Now 9P368QBR2C5S should be in owned, playable, and not purchasable+ // Now 9P368QBR2C5S should be in owned, playable, not purchasable, and still freeInStore so Free accounts can play it!CHECK(!appUi.purchasableAt(0, out)); // purchasable is now empty!CHECK(appUi.findTile("TID_JD", out));CHECK(out.productId == "9P368QBR2C5S");CHECK(out.playable);CHECK(!out.purchasable);- CHECK(!out.freeInStore);+ CHECK(out.freeInStore);+ CHECK(appUi.isEffectivePlayable(out));}std::system(("rm -rf " + testDir).c_str());}+void testPhase1BugFixesAndPhase2Optimizations() {+ // 1. GssvClient previewFeatures header propagation across authenticated requests+ {+ std::string lastDeviceInfo;+ net::setTestTransport([&](const net::Request& req) {+ for (const auto& [k, v] : req.headers) {+ if (k == "X-MS-Device-Info" || k == "x-ms-device-info") lastDeviceInfo = v;+ }+ net::Response r;+ r.status = 200;+ if (req.url.find("/v2/login/user") != std::string::npos) {+ r.body = R"({"gsToken":"tok","market":"US","offeringSettings":{"regions":[{"name":"EASTUS","baseUri":"https://eastus.gssv.com","isDefault":true}]}})";+ } else if (req.url.find("/v2/titles") != std::string::npos) {+ r.body = R"({"results":[]})";+ }+ return r;+ });+ xcloud::GssvClient gssv;+ gssv.setPreviewFeatures(true);+ std::string err;+ auth::XblToken xblTok;+ xblTok.token = "xbl_tok";+ CHECK(gssv.login(xblTok, err));++ lastDeviceInfo.clear();+ std::vector<xcloud::Title> titles;+ CHECK(gssv.listTitles(titles, err));+ CHECK(lastDeviceInfo.find("play.xbox.com") != std::string::npos);++ gssv.setPreviewFeatures(false);+ lastDeviceInfo.clear();+ CHECK(gssv.listTitles(titles, err));+ CHECK(lastDeviceInfo.find("Microsoft.GamingApp") != std::string::npos);+ net::setTestTransport({});+ }++ // 2. ProductId isolation when sharing titleId (Bug 1.5) & markUnclaimable (Bug 2.1)+ {+ ui::Fonts fonts;+ fonts.load("assets/fonts");+ ui::ImageCache images([] {});+ ui::AppUi ui(fonts, images);++ ui::GameTile baseEd, deluxeEd;+ baseEd.productId = "PROD_BASE_01";+ baseEd.titleId = "SHARED_TID";+ baseEd.name = "Base Edition";+ baseEd.playable = true;+ baseEd.freeInStore = true;++ deluxeEd.productId = "PROD_DELUXE1";+ deluxeEd.titleId = "SHARED_TID";+ deluxeEd.name = "Deluxe Edition";+ deluxeEd.playable = false;+ deluxeEd.purchasable = true;++ ui::GameRow row;+ row.title = "Row";+ row.tiles = {baseEd, deluxeEd};+ ui.setCatalogState({row}, {baseEd}, {deluxeEd}, true, true, {baseEd}, {deluxeEd}, false, 0, 0);++ ui.setDetailInfo("PROD_BASE_01", "Base description only", "BasePub", {}, "https://example.com/base_hero.jpg");++ ui.showDetails(deluxeEd);+ CHECK(ui.detailTile().productId == "PROD_DELUXE1");+ CHECK(ui.detailTile().description.empty());+ CHECK(ui.detailTile().heroUrl.empty());++ // markUnclaimable clears freeInStore across cached lists+ ui.markUnclaimable("PROD_BASE_01");+ ui::GameTile found;+ CHECK(ui.findTile("SHARED_TID", found));+ CHECK(!found.freeInStore);+ }++ // 3. Mouse hit-testing on Details (only inside button rect) and Settings rows 10 & 22 + right-click save+ {+ ui::Fonts fonts;+ fonts.load("assets/fonts");+ ui::ImageCache images([] {});+ ui::AppUi ui(fonts, images);+ ui::UiCaps caps;+ caps.desktopWindow = true;+ caps.touchpad = true;+ ui.setCaps(caps);++ ui::GameTile freeTile;+ freeTile.productId = "9P_FREE_GAME";+ freeTile.titleId = "TID_FREE";+ freeTile.name = "Free Game";+ freeTile.playable = false;+ freeTile.freeInStore = true;++ ui.showDetails(freeTile);+ ui::Canvas c(1920, 1080);+ ui.render(c, 1000);++ // Clicking outside the ClaimFree button must NOT trigger ClaimFreeGame+ auto evOutside = ui.onMouseDown(1500.0f, 200.0f, 1);+ CHECK(evOutside.action == ui::Action::None);++ // Open Settings and test Row 10 (Bitrate) accept and Row 22 (PreviewFeatures) click+ ui.showHome();+ ui.handle(ui::NavInput{.options = true});+ CHECK(ui.screen() == ui::Screen::Settings);++ // Navigate to row 10 (BitrateCap) and press accept+ while (ui.settingsFocus() != 10) {+ ui.handle(ui::NavInput{.down = true});+ }+ auto evBitrate = ui.handle(ui::NavInput{.accept = true});+ CHECK(evBitrate.action == ui::Action::SettingsChanged);++ // Right-click in Settings saves and exits to Home+ auto evRightClick = ui.onMouseDown(500.0f, 500.0f, 3);+ CHECK(ui.screen() == ui::Screen::Home);+ CHECK(evRightClick.action == ui::Action::SettingsChanged);+ }++ // 4. Canvas fast paths (opaque drawImage, gradientV, gradientH, setClip/clearClip)+ {+ ui::Canvas c(64, 64);+ c.gradientV({0, 0, 64, 64}, ui::rgba(20, 30, 40, 255), ui::rgba(10, 15, 20, 255));+ c.gradientH({0, 0, 64, 64}, ui::rgba(0, 0, 0, 128), ui::rgba(0, 0, 0, 0));++ ui::Image img;+ img.w = 16;+ img.h = 16;+ img.opaque = true;+ img.px.assign(16 * 16, ui::rgba(100, 150, 200, 255));++ c.setClip({8, 8, 8, 8});+ c.drawImage(img, 0, 0, 255, 0);+ c.clearClip();+ // Outside clip at (2, 2) should NOT be img color; inside clip at (10, 10) SHOULD be img color+ CHECK(c.data()[2 * 64 + 2] != ui::rgba(100, 150, 200, 255));+ CHECK(c.data()[10 * 64 + 10] == ui::rgba(100, 150, 200, 255));+ }++ // 5. Screen::SignIn redirect on sign-in completion+ {+ ui::Fonts fonts;+ fonts.load("assets/fonts");+ ui::ImageCache images([] {});+ ui::AppUi ui(fonts, images);+ ui.showSignIn("ABCD-1234", "https://www.microsoft.com/link");+ CHECK(ui.screen() == ui::Screen::SignIn);+ ui.showSplash("Carregando jogos...");+ CHECK(ui.screen() == ui::Screen::Splash);+ ui.showHome();+ CHECK(ui.screen() == ui::Screen::Home);+ }+}+int main() {+ testPhase1BugFixesAndPhase2Optimizations();testBlock4OwnershipAndRecents();testBloco3Corrections();testBloco2Corrections();@@ -6368,6 +6638,8 @@ int main() {testPlayerSwitchAndUnresolvedTiles();testWebReportAndGamepadLayout();testCodSearchRomanAndSettingsReset();+ testFreeAccountPlayability();+ testDetailsHydrationAndPlaytimeBadge();if (g_failures) {std::fprintf(stderr, "%d failure(s)\n", g_failures);return 1;