Xbox Cloud Gaming app for PS5 Homebrew
C
WIP: keyboard keys remap screen (general and per game), Settings rows grouped
Rafael Abud Ferreirad11c95970298
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 5895c51..98a4bc3 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -36,6 +36,7 @@ add_library(xcloud_core STATICsrc/xcloud/prices.cppsrc/input/kbm.cppsrc/input/kbm_map.cpp+ src/input/key_map.cppsrc/input/keyboard_nav.cppsrc/xcloud/social.cppsrc/platform/posix_common.cppdiff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex 4e91964..30dd8ff 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -29,6 +29,7 @@ namespace {// The home screen was saved: the tests that start from it may go.bool uiSaved = false;bool settingsShot = false; // "settingstest": save the screen now+const char* keysShot = nullptr; // "keystest": the screen to save nowuint64_t homeSince = 0, launchSince = 0;bool launchSaved = false;const char* pickerShot = nullptr;@@ -75,6 +76,7 @@ void loadAutoplay() {if (opt == "consoles") g_autoplay.consoles = true;if (opt == "consolestab") g_autoplay.consolesTab = true;if (opt == "settingstest") g_autoplay.settingsTest = true;+ if (opt == "keystest") g_autoplay.keysTest = true;if (opt == "badca") g_autoplay.badCa = true;if (opt == "consolesempty") g_autoplay.consolesTab = g_autoplay.consolesEmpty = true;if (opt == "librarytest") g_autoplay.libraryTest = true;@@ -456,6 +458,43 @@ void autoplayNav(ui::NavInput& nav, bool& menuCombo, uint64_t now) {}}+ if (g_autoplay.keysTest && uiSaved) {+ // Settings down to the keyboard keys, their screen, a reserved key+ // and then G chosen for the D-pad down's first key; back to the+ // default keys before leaving (Settings saves them).+ static uint64_t since = 0;+ static int step = 0;+ if (!since) since = now;+ struct Step { uint64_t at; int what; };+ enum { Options, Down, Up, Accept, Back, Shot, Reserved, KeyG, End };+ static const Step steps[] = {+ {500, Options}, {1500, Down}, {1800, Down}, {2100, Down}, {2400, Down}, {2700, Down}, {3000, Down},+ {3300, Down}, {3600, Down}, {3900, Down}, {4200, Down}, {4500, Down}, {5200, Shot},+ {5800, Accept}, {7000, Shot}, {7500, Down}, {8000, Accept}, {8600, Reserved}, {9400, Shot},+ {10000, KeyG}, {10800, Shot}, {11400, Up}, {11800, Up}, {12400, Accept}, {13000, Back},+ {14000, Shot}, {14600, Back}, {15200, End}};+ static const char* shots[] = {"keys_settings.ppm", "keys.ppm", "keys_capture.ppm", "keys_after.ppm",+ "keys_settings_after.ppm"};+ static int shot = 0;+ if (step < static_cast<int>(std::size(steps)) && now - since >= steps[step].at) {+ switch (steps[step].what) {+ case Options: nav.options = true; break;+ case Down: nav.down = true; break;+ case Up: nav.up = true; break;+ case Accept: nav.accept = true; break;+ case Back: nav.back = true; break;+ case Shot: keysShot = shots[shot++]; break;+ case Reserved: g_ui->captureKey(0x7B); break;+ case KeyG: g_ui->captureKey('G'); break;+ case End:+ g_autoplay.keysTest = false;+ XC_LOGI("AUTOPLAY END: keys test");+ break;+ }+ ++step;+ }+ }+if (g_autoplay.settingsTest && uiSaved) {// Settings, down to the resolution, open its list; saved 2 s later.static uint64_t since = 0;@@ -573,6 +612,10 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {XC_LOGI("AUTOPLAY END: detail test");}}+ if (keysShot) {+ saveCanvas(keysShot);+ keysShot = nullptr;+ }if (settingsShot) {settingsShot = false;saveCanvas("settings.ppm");diff --git a/src/app/autoplay.h b/src/app/autoplay.hindex 53de437..dbceeda 100644--- a/src/app/autoplay.h+++ b/src/app/autoplay.h@@ -38,6 +38,7 @@ struct Autoplay {bool consolesTab = false; // "consolestab": open My consoles, save consoles.ppmbool consolesEmpty = false; // with "consolestab": as if none were foundbool settingsTest = false; // "settingstest": open the resolution list, save settings.ppm+ bool keysTest = false; // "keystest": Settings' groups, the keyboard keys' screen, a key chosen (keys*.ppm)bool badCa = false; // "badca": a missing CA bundle: the built-in copy must be usedbool consoles = false; // "consoles": log the account's own consoles (xhome)bool pad = false; // "pad": the physical pad stays in use, its buttons loggeddiff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex bbb56d0..e43dacd 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -128,6 +128,7 @@ bool saveSettings(const ui::SettingsChoice& choice) {g_settings.highRefresh = choice.highRefresh;g_settings.maxBitrateMbps = choice.maxBitrateMbps;g_settings.gameVolume = choice.gameVolume;+ g_settings.keyMap = choice.keyMap;g_settings.save(settingsPath()); // warns itselfXC_LOGI("settings saved: language %s, %s, region %s", code.c_str(), g_settings.resolution.c_str(),g_settings.region.empty() ? "auto" : g_settings.region.c_str());@@ -259,6 +260,7 @@ int main(int argc, char** argv) {choice.highRefresh = g_settings.highRefresh;choice.maxBitrateMbps = g_settings.maxBitrateMbps;choice.gameVolume = g_settings.gameVolume;+ choice.keyMap = g_settings.keyMap;g_ui->setAllow1440(allow1440Locked());g_ui->setUpdateState(XC_APP_VERSION, {}, false); // Settings shows this version before any checkg_ui->setSettings(choice);@@ -286,6 +288,8 @@ int main(int argc, char** argv) {// Never return from main: the app is closed from the home screen.input::ControllerState prev{}, pad{};bool appMenuKeyBefore = false, homeKeyBefore = false; // F12 / Home held at the last pass+ uint8_t mouseButtonsBefore = 0; // the mouse buttons at the last pass (a press chooses a key)+ std::vector<uint8_t> swallowedKeys; // keys pressed to be chosen, kept from the screens until let gobool kbmConnected = false; // a USB keyboard or mouse in useuint64_t keyboardActiveAt = 0; // when a key or the mouse was last used (ms)// The slot showing the keyboard (-1 none): the keyboard's player, while@@ -389,7 +393,19 @@ int main(int argc, char** argv) {// Keys 1-4 (off a game, or with the app's menu open in one): the// player the keyboard and mouse play as. 1 native with player 1;// 2-4 that player's controller (3 or 4 with two players: just its slot).- if (!inGame || streamScreen.menuOpen()) {+ // The keyboard keys' screen waiting for a key: the next key or mouse+ // button pressed is the one chosen (not a move through the screens);+ // keys pressed for it stay out of the screens until let go.+ bool capturing = g_ui->capturingKey();+ if (capturing) {+ for (const auto& k : kbm.keys)+ 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));+ }+ mouseButtonsBefore = kbm.buttons;+ std::erase_if(swallowedKeys, [&](uint8_t vk) { return !std::binary_search(kbm.held.begin(), kbm.held.end(), vk); });+ if ((!inGame || streamScreen.menuOpen()) && !capturing) {for (const auto& k : kbm.keys) {if (!k.pressed || k.vk < '1' || k.vk > '4') continue;int player = k.vk - '1';@@ -410,7 +426,12 @@ int main(int argc, char** argv) {bool appMenuKey = std::binary_search(kbm.held.begin(), kbm.held.end(), input::kVkAppMenu);bool appMenuPressed = appMenuKey && !appMenuKeyBefore;appMenuKeyBefore = appMenuKey;- if (!inGame || streamScreen.menuOpen()) input::keyboardToPad(kbm.held, pad);+ if ((!inGame || streamScreen.menuOpen()) && !capturing) {+ std::vector<uint8_t> navKeys;+ for (uint8_t vk : kbm.held)+ if (std::find(swallowedKeys.begin(), swallowedKeys.end(), vk) == swallowedKeys.end()) navKeys.push_back(vk);+ input::keyboardToPad(navKeys, pad);+ }kbmConnected = kbm.keyboard || kbm.mouse || g_autoplay.kbHints;if (int shown = keyboardIconSlot(); shown != keyboardIconShown) {keyboardIconShown = shown;diff --git a/src/app/settings.cpp b/src/app/settings.cppindex dca0469..60aadfc 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -12,6 +12,28 @@namespace xc::app {+namespace {++// "keyMap": each input's two keys, in KeyAction order (flat). Anything else+// (an older file, another count) keeps `fallback`.+input::KeyMap readKeyMap(const json::Value& v, const input::KeyMap& fallback) {+ const auto& items = v.items();+ if (items.size() != static_cast<size_t>(input::kKeyActions) * 2) return fallback;+ input::KeyMap m{};+ for (size_t i = 0; i < items.size(); ++i)+ m[i / 2][i % 2] = static_cast<uint8_t>(std::clamp<int64_t>(items[i].asInt(0), 0, 255));+ return m;+}++json::Value keyMapJson(const input::KeyMap& m) {+ json::Value v = json::Value::array();+ for (const auto& keys : m)+ for (uint8_t k : keys) v.push(static_cast<int>(k));+ return v;+}++} // namespace+bool Settings::load(const std::string& path) {std::string text;if (!platform::readFile(path, text)) return false;@@ -53,6 +75,7 @@ bool Settings::load(const std::string& path) {highRefresh = (*j)["highRefresh"].asBool(highRefresh);maxBitrateMbps = static_cast<int>(std::clamp<int64_t>((*j)["maxBitrateMbps"].asInt(maxBitrateMbps), 0, 40));gameVolume = static_cast<int>(std::clamp<int64_t>((*j)["gameVolume"].asInt(gameVolume), 0, 200));+ keyMap = readKeyMap((*j)["keyMap"], input::defaultKeyMap());keyboardPlayer = static_cast<int>(std::clamp<int64_t>((*j)["keyboardPlayer"].asInt(keyboardPlayer), 0, 3));micGain = static_cast<int>(std::clamp<int64_t>((*j)["micGain"].asInt(micGain), 0, 2));audioRoute = static_cast<int>(std::clamp<int64_t>((*j)["audioRoute"].asInt(audioRoute), 0, 1));@@ -88,6 +111,7 @@ bool Settings::load(const std::string& path) {p.triggerPulses = obj["triggerPulses"].asBool(triggerPulses);p.circleConfirms = obj["circleConfirms"].asBool(circleConfirms);p.highRefresh = obj["highRefresh"].asBool(highRefresh);+ p.keyMap = readKeyMap(obj["keyMap"], keyMap);perGame[id] = p;}return true;@@ -107,6 +131,7 @@ GameProfile Settings::defaultProfile() const {p.triggerPulses = triggerPulses;p.circleConfirms = circleConfirms;p.highRefresh = highRefresh;+ p.keyMap = keyMap;return p;}@@ -163,6 +188,7 @@ bool Settings::save(const std::string& path) const {v.set("highRefresh", highRefresh);v.set("maxBitrateMbps", maxBitrateMbps);v.set("gameVolume", gameVolume);+ v.set("keyMap", keyMapJson(keyMap));v.set("keyboardPlayer", keyboardPlayer);v.set("micGain", micGain);v.set("audioRoute", audioRoute);@@ -186,6 +212,7 @@ bool Settings::save(const std::string& path) const {obj.set("triggerPulses", p.triggerPulses);obj.set("circleConfirms", p.circleConfirms);obj.set("highRefresh", p.highRefresh);+ obj.set("keyMap", keyMapJson(p.keyMap));pg.set(id, obj);}v.set("perGame", pg);diff --git a/src/app/settings.h b/src/app/settings.hindex ad7263b..02f74bf 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -3,6 +3,8 @@// User settings, kept in <dataDir>/settings.json.#pragma once+#include "input/key_map.h"+#include <cstdint>#include <map>#include <string>@@ -25,6 +27,8 @@ struct GameProfile {bool circleConfirms = false;// Displaybool highRefresh = false; // 120 Hz output (VRR) while streaming+ // Keyboard and mouse as a controller: which keys play what+ input::KeyMap keyMap = input::defaultKeyMap();};// Key to identify a game profile: productId first, else titleId.@@ -74,6 +78,7 @@ struct Settings {bool highRefresh = false; // 119.88 Hz output (VRR where the console turns it on) while streamingint maxBitrateMbps = 0; // the stream's bitrate cap: 0 automatic (the tier's), else 20, 15, 10 or 5int gameVolume = 100; // percent: 25, 50, 75, 100 or 150+ input::KeyMap keyMap = input::defaultKeyMap(); // the keys when the keyboard is a player's controllerint keyboardPlayer = 0; // the player a USB keyboard and mouse play as (0..3; keys 1-4): 0 native with player 1, else that player's controllerint micGain = 1; // 0: 50%, 1: 100%, 2: 150%int audioRoute = 0; // 0: TV/HDMI (Main), 1: DualSense Speaker / Headset (Pad)diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cppindex cf131c0..8945b72 100644--- a/src/app/stream_screen.cpp+++ b/src/app/stream_screen.cpp@@ -121,6 +121,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, btriggerStrength_ = prof.triggerStrength;deadzone_ = prof.deadzoneLeft;circleConfirms_ = prof.circleConfirms;+ keyMap_ = prof.keyMap;input::setDeadzone(prof.deadzoneLeft / 100.0f, prof.deadzoneRight / 100.0f);input::setTriggerFeel(prof.triggerStrength, prof.triggerHz, prof.triggerResistance, prof.triggerPulses);input::setCircleConfirms(prof.circleConfirms);@@ -203,6 +204,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, bp.circleConfirms = circleConfirms_;auto had = g_settings.perGame.find(gameKey_); // not set from this menu: keptp.highRefresh = had != g_settings.perGame.end() ? had->second.highRefresh : g_settings.highRefresh;+ p.keyMap = had != g_settings.perGame.end() ? had->second.keyMap : g_settings.keyMap;g_settings.perGame[gameKey_] = p;} else {g_settings.perGame.erase(gameKey_);@@ -213,6 +215,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, bstreamResolution_ = def.resolution;deadzone_ = def.deadzoneLeft;triggerStrength_ = def.triggerStrength;+ keyMap_ = def.keyMap;circleConfirms_ = def.circleConfirms;display::setSharpness(kSharpAmount[sharpness_]);applyDeband_();@@ -350,7 +353,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b// in the slot by itself.int kbSlot = keyboardPadSlot(kbm_.keyboard || kbm_.mouse);kbPad_ = input::ControllerState{};- if (kbSlot >= 0 && !menu_.isOpen()) input::keyboardAsGamepad(kbm_, mouseStick_, kbPad_);+ if (kbSlot >= 0 && !menu_.isOpen()) input::keyboardAsGamepad(kbm_, mouseStick_, kbPad_, keyMap_);int alone = kbSlot >= 0 && !input::padConnected(kbSlot) ? kbSlot : -1;if (alone != kbSlotAttached_) {if (kbSlotAttached_ >= 0 && !input::padConnected(kbSlotAttached_)) g_player->setPadConnected(kbSlotAttached_, false);diff --git a/src/app/stream_screen.h b/src/app/stream_screen.hindex 77af067..43ed1b6 100644--- a/src/app/stream_screen.h+++ b/src/app/stream_screen.h@@ -70,6 +70,7 @@ private:int triggerStrength_ = 2;int deadzone_ = 15;bool circleConfirms_ = false;+ input::KeyMap keyMap_ = input::defaultKeyMap(); // this game's keys (the keyboard as a controller)bool highRefresh_ = false; // 120 Hz turned on for this streaminput::KbmInput kbm_;int kbSlotAttached_ = -1; // the keyboard's slot as a controller, announceddiff --git a/src/app/worker.cpp b/src/app/worker.cppindex 964d6a6..1103412 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -655,7 +655,7 @@ void loadLibrary(xcloud::GssvClient& gssv) {});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.consolesTab && !g_autoplay.settingsTest && !g_autoplay.keysTest &&!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) {diff --git a/src/input/key_map.cpp b/src/input/key_map.cppnew file mode 100644index 0000000..8a75141--- /dev/null+++ b/src/input/key_map.cpp@@ -0,0 +1,110 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "input/key_map.h"++#include <cstdio>++namespace xc::input {++KeyMap defaultKeyMap() {+ KeyMap m{};+ auto set = [&](KeyAction a, uint8_t k1, uint8_t k2 = 0) { m[static_cast<size_t>(a)] = {k1, k2}; };+ set(KeyAction::LeftUp, 'W');+ set(KeyAction::LeftDown, 'S');+ set(KeyAction::LeftLeft, 'A');+ set(KeyAction::LeftRight, 'D');+ set(KeyAction::DpadUp, 0x26);+ set(KeyAction::DpadDown, 0x28);+ set(KeyAction::DpadLeft, 0x25);+ set(KeyAction::DpadRight, 0x27);+ set(KeyAction::A, 0x20);+ set(KeyAction::B, 'C');+ set(KeyAction::X, 'R');+ set(KeyAction::Y, 'E');+ set(KeyAction::LB, 'Q');+ set(KeyAction::RB, 'F');+ set(KeyAction::LT, kMouseRight);+ set(KeyAction::RT, kMouseLeft);+ set(KeyAction::L3, 0x10); // shift+ set(KeyAction::R3, 'V', kMouseMiddle);+ set(KeyAction::View, 0x09); // tab+ set(KeyAction::Menu, 0x1B); // escape+ return m;+}++std::string keyName(uint8_t k) {+ if ((k >= 'A' && k <= 'Z') || (k >= '0' && k <= '9')) return std::string(1, static_cast<char>(k));+ char buf[16];+ if (k >= 0x70 && k <= 0x87) {+ std::snprintf(buf, sizeof buf, "F%d", k - 0x70 + 1);+ return buf;+ }+ if (k >= 0x60 && k <= 0x69) {+ std::snprintf(buf, sizeof buf, "Num %d", k - 0x60);+ return buf;+ }+ switch (k) {+ case 0: return "";+ case kMouseLeft: return "Mouse L";+ case kMouseRight: return "Mouse R";+ case kMouseMiddle: return "Mouse M";+ case kMouseBack: return "Mouse 4";+ case kMouseForward: return "Mouse 5";+ case 0x08: return "Backspace";+ case 0x09: return "Tab";+ case 0x0D: return "Enter";+ case 0x10: return "Shift";+ case 0x11: return "Ctrl";+ case 0x12: return "Alt";+ case 0x13: return "Pause";+ case 0x14: return "Caps Lock";+ case 0x1B: return "Esc";+ case 0x20: return "Space";+ case 0x21: return "Page Up";+ case 0x22: return "Page Down";+ case 0x23: return "End";+ case 0x24: return "Home";+ case 0x25: return "Left";+ case 0x26: return "Up";+ case 0x27: return "Right";+ case 0x28: return "Down";+ case 0x2C: return "Print Screen";+ case 0x2D: return "Insert";+ case 0x2E: return "Delete";+ case 0x5B: return "Win";+ case 0x5C: return "Win R";+ case 0x5D: return "Menu";+ case 0x6A: return "Num *";+ case 0x6B: return "Num +";+ case 0x6D: return "Num -";+ case 0x6E: return "Num .";+ case 0x6F: return "Num /";+ case 0x90: return "Num Lock";+ case 0x91: return "Scroll Lock";+ case 0xBA: return ";";+ case 0xBB: return "=";+ case 0xBC: return ",";+ case 0xBD: return "-";+ case 0xBE: return ".";+ case 0xBF: return "/";+ case 0xC0: return "`";+ case 0xDB: return "[";+ case 0xDC: return "\\";+ case 0xDD: return "]";+ case 0xDE: return "'";+ case 0xE2: return "\\ (ISO)";+ default: std::snprintf(buf, sizeof buf, "0x%02X", k); return buf;+ }+}++bool isReservedKey(uint8_t k) { return k == 0x7B || k == 0x24 || (k >= '1' && k <= '4'); }++void assignKey(KeyMap& map, KeyAction a, int slot, uint8_t code) {+ if (code)+ for (auto& keys : map)+ for (auto& k : keys)+ if (k == code) k = 0;+ map[static_cast<size_t>(a)][static_cast<size_t>(slot & 1)] = code;+}++} // namespace xc::inputdiff --git a/src/input/key_map.h b/src/input/key_map.hnew file mode 100644index 0000000..670b2ef--- /dev/null+++ b/src/input/key_map.h@@ -0,0 +1,42 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// Which keys (and mouse buttons) play which controller input when the+// keyboard and mouse are a player's controller: two per input, chosen in+// Settings (and per game). The mouse itself stays the right stick and a+// wheel notch a press of Y.+#pragma once++#include <array>+#include <cstdint>+#include <string>++namespace xc::input {++enum class KeyAction : uint8_t {+ LeftUp, LeftDown, LeftLeft, LeftRight, // the left stick+ DpadUp, DpadDown, DpadLeft, DpadRight,+ A, B, X, Y, LB, RB, LT, RT, L3, R3, View, Menu,+ Count+};+constexpr int kKeyActions = static_cast<int>(KeyAction::Count);++// Mouse buttons in a key's place: codes no keyboard sends (Windows keeps+// 0xF1..0xF5 for OEM keys). KbmInput::buttons bit b is kMouseLeft + b.+constexpr uint8_t kMouseLeft = 0xF1, kMouseRight = 0xF2, kMouseMiddle = 0xF3, kMouseBack = 0xF4, kMouseForward = 0xF5;++// Each input's two keys (0: none).+using KeyMap = std::array<std::array<uint8_t, 2>, kKeyActions>;++// W A S D the left stick, the arrows the D-pad; Space A, C B, R X, E Y, Q LB,+// F RB, the mouse's right / left buttons LT / RT, Shift and V or the middle+// button the sticks' clicks, Tab View, Esc Menu.+KeyMap defaultKeyMap();+// A key or mouse button as it is written on it ("W", "Space", "Mouse L").+std::string keyName(uint8_t code);+// Keys the app keeps for itself: F12 (its menu), Home (the Xbox button),+// 1-4 (which player the keyboard is).+bool isReservedKey(uint8_t code);+// Puts `code` in action `a`'s slot, taking it off any other input first.+void assignKey(KeyMap& map, KeyAction a, int slot, uint8_t code);++} // namespace xc::inputdiff --git a/src/input/keyboard_nav.cpp b/src/input/keyboard_nav.cppindex 515f039..0b9f5c0 100644--- a/src/input/keyboard_nav.cpp+++ b/src/input/keyboard_nav.cpp@@ -7,32 +7,37 @@namespace xc::input {-void keyboardAsGamepad(const KbmInput& in, MouseStick& stick, ControllerState& out) {+void keyboardAsGamepad(const KbmInput& in, MouseStick& stick, ControllerState& out, const KeyMap& map) {out = ControllerState{};out.connected = in.keyboard || in.mouse;- auto down = [&](std::initializer_list<uint8_t> vks) {- for (uint8_t vk : vks)- if (std::binary_search(in.held.begin(), in.held.end(), vk)) return true;+ auto down = [&](KeyAction a) {+ for (uint8_t k : map[static_cast<size_t>(a)]) {+ if (k >= kMouseLeft && k <= kMouseForward) {+ if (in.buttons & (1u << (k - kMouseLeft))) return true;+ } else if (k && std::binary_search(in.held.begin(), in.held.end(), k)) {+ return true;+ }+ }return false;};- out.leftStickX = (down({'D'}) ? 1.0f : 0.0f) - (down({'A'}) ? 1.0f : 0.0f);- out.leftStickY = (down({'S'}) ? 1.0f : 0.0f) - (down({'W'}) ? 1.0f : 0.0f); // pad convention: +down- out.dpadUp = down({0x26});- out.dpadDown = down({0x28});- out.dpadLeft = down({0x25});- out.dpadRight = down({0x27});- out.btnA = down({0x20});- out.btnB = down({'C'});- out.btnX = down({'R'});- out.btnY = down({'E'});- out.btnL1 = down({'Q'});- out.btnR1 = down({'F'});- out.btnL3 = down({0x10}); // shift- out.btnR3 = down({'V'}) || (in.buttons & 4);- out.btnTouchpad = down({0x09}); // View- out.btnOptions = down({0x1B}); // Menu- out.triggerL2 = (in.buttons & 2) ? 1.0f : 0.0f;- out.triggerR2 = (in.buttons & 1) ? 1.0f : 0.0f;+ out.leftStickX = (down(KeyAction::LeftRight) ? 1.0f : 0.0f) - (down(KeyAction::LeftLeft) ? 1.0f : 0.0f);+ out.leftStickY = (down(KeyAction::LeftDown) ? 1.0f : 0.0f) - (down(KeyAction::LeftUp) ? 1.0f : 0.0f); // pad convention: +down+ out.dpadUp = down(KeyAction::DpadUp);+ out.dpadDown = down(KeyAction::DpadDown);+ out.dpadLeft = down(KeyAction::DpadLeft);+ out.dpadRight = down(KeyAction::DpadRight);+ out.btnA = down(KeyAction::A);+ out.btnB = down(KeyAction::B);+ out.btnX = down(KeyAction::X);+ out.btnY = down(KeyAction::Y);+ out.btnL1 = down(KeyAction::LB);+ out.btnR1 = down(KeyAction::RB);+ out.btnL3 = down(KeyAction::L3);+ out.btnR3 = down(KeyAction::R3);+ out.btnTouchpad = down(KeyAction::View);+ out.btnOptions = down(KeyAction::Menu);+ out.triggerL2 = down(KeyAction::LT) ? 1.0f : 0.0f;+ out.triggerR2 = down(KeyAction::RT) ? 1.0f : 0.0f;// The mouse: about 12 counts a pass is the stick all the way; eased so// a still mouse lets the stick come back to the centre.constexpr float kFull = 12.0f, kEase = 0.45f;diff --git a/src/input/keyboard_nav.h b/src/input/keyboard_nav.hindex 9ce6d01..66210c4 100644--- a/src/input/keyboard_nav.h+++ b/src/input/keyboard_nav.h@@ -16,6 +16,7 @@#include "input/controller.h"#include "input/kbm.h"+#include "input/key_map.h"#include <cstdint>#include <vector>@@ -26,17 +27,17 @@ namespace xc::input {constexpr uint8_t kVkAppMenu = 0x7B;// The keyboard and mouse as a controller of their own (another player, so-// a second controller isn't needed): W A S D the left stick, the mouse the-// right stick, the arrows the D-pad; Space A, C B, R X, E Y, Q LB, F RB, the-// mouse's right / left buttons LT / RT, Shift and the middle button the-// sticks' clicks, Tab View, Esc Menu, a wheel notch a press of Y.+// a second controller isn't needed): the keys as `map` says (defaultKeyMap()+// unless changed in Settings), the mouse the right stick, a wheel notch a+// press of Y.struct MouseStick {float x = 0, y = 0; // the right stick, eased towards the mouse's speed// The wheel: each notch is a short press of Y (switch weapon in most// shooters): presses still to give, and where the current one is.int wheelPresses = 0, wheelPhase = 0;};-void keyboardAsGamepad(const KbmInput& in, MouseStick& stick, ControllerState& out);+void keyboardAsGamepad(const KbmInput& in, MouseStick& stick, ControllerState& out,+ const KeyMap& map = defaultKeyMap());// Adds `extra` (the keyboard as a controller) to `pad`: buttons pressed on// either, the stick or trigger pushed further.diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 6c29298..5f4950b 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -52,6 +52,25 @@ enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle, kIconTouchpad,// 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 and sign-in country; the+// stream (resolution, 120 Hz, bitrate, region); sound; the controller and+// keyboard; updates last. A group starts at each kSettingsGroupStart.+constexpr int kSettingsOrder[kSettingRows] = {0, 8, 1, 9, 10, 2, 11, 3, 4, 5, 6, 12, 7};+constexpr bool kSettingsGroupStart[kSettingRows] = {false, false, true, false, false, false, true,+ true, false, false, false, false, true};+int settingsPos(int row) {+ for (int i = 0; i < kSettingRows; ++i)+ if (kSettingsOrder[i] == row) return i;+ return 0;+}+// 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).+constexpr int kGameRowOrder[11] = {0, 4, 8, 1, 2, 3, 5, 6, 7, 9, 10};+constexpr bool kGameGroupStart[11] = {false, true, false, true, false, false, true, false, false, false, true};+// The keyboard keys' screen: two columns of inputs, then "Reset to default".+constexpr int kKeysPerColumn = input::kKeyActions / 2;// Grids ("Your games", search results): cards with the name below.constexpr int kGridPitchY = 300;@@ -978,12 +997,72 @@ void AppUi::openTester(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::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::Sticks) {// L1 / R1 pick the stick, the D-pad (only: the sticks are what is// being tried) changes its dead zone.@@ -1150,6 +1229,7 @@ void AppUi::openGameSettings() {activeGameProfile_.triggerPulses = settings_.triggerPulses;activeGameProfile_.circleConfirms = settings_.circleConfirms;activeGameProfile_.highRefresh = settings_.highRefresh;+ activeGameProfile_.keyMap = settings_.keyMap;}}@@ -1259,6 +1339,9 @@ std::vector<std::string> AppUi::settingOptions(int row) const {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 == 12) {+ // The keys' own screen changes them.+ out = {tr(settings_.keyMap == input::defaultKeyMap() ? Str::ProfileDefault : Str::ProfileCustom)};} else if (row == 8) {out.push_back(tr(Str::LoginCountryOff));@@ -1279,7 +1362,7 @@ int AppUi::settingSelected(int row) const {for (int i = 0; i < 3; ++i)if (kResolutionOrder[i] == settings_.resolution) return i;}- if (row == 3) return 0;+ if (row == 3 || row == 12) return 0;if (row == 4) return settings_.triggerStrength;if (row == 5) return settings_.circleConfirms ? 1 : 0;if (row == 6) return settings_.lightBarMode;@@ -1312,8 +1395,8 @@ void AppUi::applySetting(int row, int index) {setLanguage(static_cast<Language>(index)); // the UI switches right away} else if (row == 1) {settings_.resolution = kResolutionOrder[index];- } else if (row == 3) {- (void)index; // the tester sets each stick's+ } else if (row == 3 || row == 12) {+ (void)index; // the tester sets each stick's, the keys' screen the keys} else if (row == 4) {settings_.triggerStrength = index;} else if (row == 5) {@@ -1864,7 +1947,7 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {handleTester(in);return;}- int rowCount = activeGameHasCustom_ ? 10 : 9;+ int rowCount = activeGameHasCustom_ ? 11 : 10;if (in.up) {gameSettingsRow_ = (gameSettingsRow_ + rowCount - 1) % rowCount;dirty_ = true;@@ -1873,9 +1956,10 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {gameSettingsRow_ = (gameSettingsRow_ + 1) % rowCount;dirty_ = true;}+ const int rowId = kGameRowOrder[std::clamp(gameSettingsRow_, 0, 10)];if (in.left || in.right) {int dir = in.right ? 1 : -1;- switch (gameSettingsRow_) {+ switch (rowId) {case 0:activeGameHasCustom_ = !activeGameHasCustom_;dirty_ = true;@@ -1933,7 +2017,7 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {}}if (in.accept) {- switch (gameSettingsRow_) {+ switch (rowId) {case 0:activeGameHasCustom_ = !activeGameHasCustom_;dirty_ = true;@@ -1996,8 +2080,13 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {activeGameHasCustom_ = true;dirty_ = true;break;- case 9: // Reset to default+ case 9: // Keyboard keys: their own screen, on this game's+ openTester(Tester::Keys);+ settings_.keyMap = activeGameProfile_.keyMap;+ break;+ case 10: // Reset to defaultactiveGameHasCustom_ = false;+ activeGameProfile_.keyMap = settings_.keyMap;activeGameProfile_.sharpness = settings_.sharpness;activeGameProfile_.deband = settings_.deband;activeGameProfile_.upscaler = settings_.upscaler;@@ -2086,13 +2175,15 @@ UiEvent AppUi::handle(const NavInput& in) {dirty_ = true;break;}- if (in.down && settingsRow_ < kSettingRows - 1) ++settingsRow_, dirty_ = true;- if (in.up && settingsRow_ > 0) --settingsRow_, dirty_ = true;+ if (int pos = settingsPos(settingsRow_); in.down && pos < kSettingRows - 1)+ settingsRow_ = kSettingsOrder[pos + 1], dirty_ = true;+ else if (in.up && pos > 0)+ settingsRow_ = kSettingsOrder[pos - 1], dirty_ = true;if (in.right) changeSetting(+1);if (in.left) changeSetting(-1);- if (in.accept && (settingsRow_ == 3 || settingsRow_ == 4)) {- // Dead zone, trigger vibration: their testers instead of a list.- openTester(settingsRow_ == 3 ? Tester::Sticks : Tester::Triggers);+ 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_ == 7) {// Updates: a newer version is installed (the settings saved first).if (!updateAvailable_.empty() && !updateChecking_) {@@ -3259,26 +3350,29 @@ void AppUi::drawSettings(Canvas& c) {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)};- constexpr int kRowW = 1200, kRowH = 50, kGap = 6;- Rect rows[kSettingRows];- int y = 262;- for (int i = 0; i < kSettingRows; ++i) {+ tr(Str::HighRefresh), tr(Str::BitrateCap), tr(Str::GameVolume),+ tr(Str::KeyboardKeys)};+ constexpr int kRowW = 1200, kRowH = 46, kGap = 5, kGroupGap = 16;+ Rect rows[kSettingRows]; // by row id+ int y = 236;+ for (int pos = 0; pos < kSettingRows; ++pos) {+ const int i = kSettingsOrder[pos];+ if (kSettingsGroupStart[pos]) y += kGroupGap;Rect r{kMargin, y, kRowW, kRowH};rows[i] = r;bool focused = i == settingsRow_;c.fillRect(r, focused ? rgba(255, 255, 255, 36) : rgba(255, 255, 255, 14), 16);if (focused && !dropdownOpen_) c.strokeRect({r.x - 5, r.y - 5, r.w + 10, r.h + 10}, kWhite, 3, 20);- int ty = fonts_.semibold.centeredY(r.y, r.h, 30);- fonts_.semibold.draw(c, labels[i], r.x + 36, ty, 30, kWhite);+ int ty = fonts_.semibold.centeredY(r.y, r.h, 28);+ fonts_.semibold.draw(c, labels[i], r.x + 36, ty, 28, kWhite);if (i == 7) {// Updates: the state; Cross updates when there is a newer version.std::string value = updateChecking_ ? tr(Str::UpdateChecking): !updateAvailable_.empty() ? trf(Str::UpdateReady, updateAvailable_): trf(Str::UpToDate, "v" + updateCurrent_);Color color = !updateAvailable_.empty() && !updateChecking_ ? rgba(120, 220, 120) : focused ? kWhite : kGray;- int w = fonts_.regular.measure(value, 30);- fonts_.regular.draw(c, value, r.x + r.w - 44 - w, fonts_.regular.centeredY(r.y, r.h, 30), 30, color);+ int w = fonts_.regular.measure(value, 28);+ fonts_.regular.draw(c, value, r.x + r.w - 44 - w, fonts_.regular.centeredY(r.y, r.h, 28), 28, color);y += kRowH + kGap;continue;}@@ -3294,8 +3388,8 @@ void AppUi::drawSettings(Canvas& c) {// The confirm button, as the button itself.drawFaceButton(c, settings_.circleConfirms ? kIconCircle : kIconCross, vx - 20.0f, cy, 20);} else {- int w = fonts_.regular.measure(value, 30);- fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, 30), 30, focused ? kWhite : kGray);+ int w = fonts_.regular.measure(value, 28);+ fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, 28), 28, focused ? kWhite : kGray);if (i == 6 && settings_.lightBarMode == 1) { // the colour chosenc.fillCircle(vx - w - 30.0f, cy, 14, settings_.lightBarColour);c.strokeArc(vx - w - 30.0f, cy, 14, 2, 0, 6.2832f, rgba(255, 255, 255, 120));@@ -3314,6 +3408,7 @@ void AppUi::drawSettings(Canvas& c) {}if (tester_ == Tester::Sticks) return drawStickTester(c);if (tester_ == Tester::Triggers) return drawTriggerTester(c);+ if (tester_ == Tester::Keys) return drawKeysTester(c);if (dropdownOpen_) {// The list under (or, near the bottom, over) the row, right-aligned// with it; scrolls past kVisible choices.@@ -3546,6 +3641,76 @@ void AppUi::drawTriggerTester(Canvas& c) {fonts_.regular.draw(c, help[i], panel.x + 56, panel.y + panel.h - 70 + static_cast<int>(i) * 30, 22, kDim);}+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+ 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, faceIcon[k], r.x + 38.0f, r.y + r.h / 2.0f, 16);+ fonts_.semibold.draw(c, "(" + names[a] + ")", r.x + 66, ty, 24, kGray);+ } else {+ fonts_.semibold.draw(c, 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;@@ -3662,6 +3827,10 @@ void AppUi::drawGameSettings(Canvas& c) {drawTriggerTester(c);return;}+ if (tester_ == Tester::Keys) {+ drawKeysTester(c);+ return;+ }std::string title = tr(Str::GameSettings);if (!detail_.name.empty()) {std::string full = title + " \xE2\x80\xA2 " + detail_.name;@@ -3677,22 +3846,24 @@ void AppUi::drawGameSettings(Canvas& c) {title = title + " \xE2\x80\xA2 " + cut + "...";}}- constexpr int kModalW = 1140, kModalH = 800;+ constexpr int kModalW = 1140, kModalH = 860;Rect panel = drawModal(c, kModalW, kModalH, title);- int rowCount = activeGameHasCustom_ ? 10 : 9;- constexpr int kRowH = 52, kGap = 8;- int y = panel.y + 110;+ int rowCount = activeGameHasCustom_ ? 11 : 10;+ constexpr int kRowH = 52, kGap = 7, kGroupGap = 12;+ int y = panel.y + 106;- for (int i = 0; i < rowCount; ++i) {+ for (int pos = 0; pos < rowCount; ++pos) {+ const int i = kGameRowOrder[pos];+ if (kGameGroupStart[pos]) y += kGroupGap;Rect r{panel.x + 50, y, panel.w - 100, kRowH};- bool focused = (i == gameSettingsRow_);+ 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 == 9) {+ 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));@@ -3750,6 +3921,10 @@ void AppUi::drawGameSettings(Canvas& c) {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;default: break;}diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 0a092a5..88daa06 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -118,12 +118,13 @@ struct SettingsChoice {bool highRefresh = false; // 120 Hz output while a game streamsint maxBitrateMbps = 0; // 0 automatic, else 20 / 15 / 10 / 5int gameVolume = 100; // percent: 25 / 50 / 75 / 100 / 150+ input::KeyMap keyMap = input::defaultKeyMap(); // the keyboard as a player's controller};// The largest stick dead zone Settings offers, in percent of the travel.constexpr int kMaxDeadzone = 30;-constexpr int kSettingRows = 12; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,- // sign-in country, 120 Hz output, bitrate cap, game volume+constexpr int kSettingRows = 13; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,+ // sign-in country, 120 Hz output, bitrate cap, game volume, keyboard keys// The countries "Sign in as another country" offers (xcloud::loginCountryAddress).constexpr const char* kLoginCountries[] = {"br", "jp", "kr", "pl", "us"};@@ -301,6 +302,11 @@ public:// --- UI thread -----------------------------------------------------------UiEvent handle(const NavInput& in);+ // The keyboard keys' screen waits for a key: the main loop gives it the+ // next key or mouse button pressed (input::kMouseLeft..) instead of+ // moving through the screens with it.+ bool capturingKey() const;+ void captureKey(uint8_t code);bool needsRedraw(uint64_t nowMs) const;void render(Canvas& c, uint64_t nowMs);@@ -389,11 +395,13 @@ private:Color pickerColour() const;void drawColourPicker(Canvas& c);// The testers that Dead zone and Trigger vibration open in Settings.- enum class Tester { None, Sticks, Triggers };+ enum class Tester { None, Sticks, Triggers, Keys };void openTester(Tester t);void handleTester(const NavInput& in);void drawStickTester(Canvas& c);void drawTriggerTester(Canvas& c);+ void handleKeysTester(const NavInput& in);+ void drawKeysTester(Canvas& c);// A modal panel over Settings with its title; returns its rectangle.Rect drawModal(Canvas& c, int w, int h, const std::string& title);void drawUpdating(Canvas& c, uint64_t nowMs);@@ -490,6 +498,13 @@ private:Tester tester_ = Tester::None;SettingsChoice testerBackup_; // what Circle puts backint testerRow_ = 0; // the trigger tester's row: intensity, frequency, resistance, style+ // The keyboard keys' screen: the row (kKeysPerColumn: restore defaults),+ // the key across both columns (0, 1 the left column's two, 2, 3 the+ // right's), waiting for a key since (ms; 0 not), a key refused and until when.+ int keysRow_ = 0, keysCol_ = 0;+ uint64_t captureSince_ = 0;+ uint8_t keyRefused_ = 0;+ uint64_t keyRefusedUntil_ = 0;int testerStick_ = 0; // the stick tester: the one being adjusted (L1 / R1)float testSticks_[4] = {0, 0, 0, 0}, testL2_ = 0, testR2_ = 0;bool pickerOpen_ = false;diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex c46ab29..fd84d2b 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -274,6 +274,13 @@ constexpr Column kEnglish = {"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};constexpr Column kPortugueseBR = {@@ -518,6 +525,13 @@ constexpr Column kPortugueseBR = {"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};constexpr Column kSpanish = {@@ -762,6 +776,13 @@ constexpr Column kSpanish = {"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};constexpr Column kFrench = {@@ -1006,6 +1027,13 @@ constexpr Column kFrench = {"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};constexpr Column kGerman = {@@ -1250,6 +1278,13 @@ constexpr Column kGerman = {"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};constexpr Column kItalian = {@@ -1494,6 +1529,13 @@ constexpr Column kItalian = {"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};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex 328c020..f1e3cf9 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -251,6 +251,13 @@ enum class Str {MouseKeyboardSupport, // game page, beside the console and genresKeyboardPlayer, // notification: keys 1-4 chose the player the keyboard plays as (%s: 1..4)InQueueNoEstimate, // launching, in the queue, the service gives no estimate+ KeyboardKeys, // Settings / game settings row and its screen: the keys of the keyboard as a controller+ DPad, // keyboard keys: the D-pad (then an arrow)+ PressKey, // keyboard keys: waiting for the new key+ KeyReserved, // keyboard keys: F12, Home and 1-4 can't be chosen (%s: the key)+ ChangeKey, // keyboard keys hint: Cross changes the key+ ClearKey, // keyboard keys hint: Square takes it off+ KeysHelp, // keyboard keys: the mouse and the keys the app keepsCount};diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 3a1cdd2..ab6f3b7 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -989,6 +989,36 @@ static void testKeyboardAsGamepad() {CHECK(pad.btnA && pad.btnB && pad.leftStickX == -1.0f && pad.triggerR2 == 1.0f);}+// Keys chosen in Settings: one key moves off the input it was on.+static void testKeyMap() {+ using namespace xc::input;+ KeyMap map = defaultKeyMap();+ assignKey(map, KeyAction::A, 0, 'E'); // E was Y+ CHECK(map[static_cast<size_t>(KeyAction::A)][0] == 'E' && map[static_cast<size_t>(KeyAction::Y)][0] == 0);+ assignKey(map, KeyAction::Y, 1, kMouseBack);+ KbmInput in;+ in.keyboard = in.mouse = true;+ in.held = {'E'};+ in.buttons = 8; // back+ MouseStick stick;+ ControllerState out;+ keyboardAsGamepad(in, stick, out, map);+ CHECK(out.btnA && out.btnY && !out.triggerR2);+ CHECK(keyName(0x20) == "Space" && keyName('W') == "W" && keyName(kMouseLeft) == "Mouse L" && keyName(0x7B) == "F12");+ CHECK(isReservedKey(0x7B) && isReservedKey('2') && !isReservedKey('5'));+ // Saved and read back, in the settings and a game's profile.+ xc::app::Settings st;+ st.keyMap = map;+ st.perGame["g"] = st.defaultProfile();+ st.perGame["g"].keyMap[0] = {'I', 0};+ std::string path = std::string(std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp") + "/xc_keymap_test.json";+ CHECK(st.save(path));+ xc::app::Settings back;+ CHECK(back.load(path));+ CHECK(back.keyMap == map && back.perGame["g"].keyMap[0][0] == 'I');+ std::remove(path.c_str());+}+int main() {testReport();testCrashGuard();@@ -1020,6 +1050,7 @@ int main() {testHidToVk();testKeyboardNav();testKeyboardAsGamepad();+ testKeyMap();testTeredo();if (g_failures) {std::fprintf(stderr, "%d failure(s)\n", g_failures);