From 3a952bac66539171db62820da460cd27234514b0 Mon Sep 17 00:00:00 2001 From: narkotrxll Date: Fri, 16 Oct 2026 14:26:32 +0000 Subject: [PATCH] Controller presses keys in games without controller support --- native/common/hook_protocol.h | 24 ++- native/helper/main.cpp | 6 + native/hook/CMakeLists.txt | 1 + native/hook/activation_shield.cpp | 6 + native/hook/input_block.cpp | 8 + native/hook/key_emulation.cpp | 137 ++++++++++++++++ native/hook/modules.h | 6 + native/hook/tuning.cpp | 2 + native/hook/xinput_bridge.cpp | 10 ++ src/main/native/protocol.ts | 1 + .../src/components/GamepadKeysCard.vue | 149 ++++++++++++++++++ src/renderer/src/i18n/de.ts | 9 ++ src/renderer/src/i18n/en.ts | 9 ++ src/renderer/src/i18n/es.ts | 9 ++ src/renderer/src/i18n/fr.ts | 9 ++ src/renderer/src/i18n/ja.ts | 9 ++ src/renderer/src/i18n/pl.ts | 9 ++ src/renderer/src/i18n/pt-BR.ts | 9 ++ src/renderer/src/i18n/ru.ts | 9 ++ src/renderer/src/i18n/tr.ts | 9 ++ src/renderer/src/i18n/uk.ts | 9 ++ src/renderer/src/i18n/zh-CN.ts | 9 ++ src/renderer/src/views/ControllersView.vue | 2 + src/shared/defaults.ts | 13 ++ src/shared/domain.ts | 5 +- src/shared/key-names.ts | 46 ++++++ src/shared/tuning.test.ts | 19 +++ src/shared/tuning.ts | 32 +++- 28 files changed, 560 insertions(+), 6 deletions(-) create mode 100644 native/hook/key_emulation.cpp create mode 100644 src/renderer/src/components/GamepadKeysCard.vue create mode 100644 src/shared/key-names.ts diff --git a/native/common/hook_protocol.h b/native/common/hook_protocol.h index a20c7b1..7bca66e 100644 --- a/native/common/hook_protocol.h +++ b/native/common/hook_protocol.h @@ -16,9 +16,9 @@ namespace inputsplit::proto { constexpr uint32_t kMagic = 0x4C505349; // "ISPL" in little-endian -constexpr uint16_t kProtocolVersion = 5; // 2: DirectInput / Raw Input counters, 3: frame stats, +constexpr uint16_t kProtocolVersion = 7; // 2: DirectInput / Raw Input counters, 3: frame stats, // 4: tuning (dead zones, button remapping), - // 5: player order in tuning + // 5: player order in tuning, 7: keys in tuning // Pipe name prefix; the game PID (decimal) is appended. constexpr wchar_t kPipePrefix[] = L"\\\\.\\pipe\\InputSplit.Hook."; @@ -119,10 +119,28 @@ struct TuningMessage { // Without slot lock (the game reads every controller): the physical slot behind the // game's player 1..4. Identity (0, 1, 2, 3) = Windows' own order. uint8_t playerSlots[4]; + // Keys pressed in the game by the controller (games without controller support): a + // virtual-key code per KeyBinding, 0 = none. All zeros = off. + uint8_t keyMap[24]; uint32_t reserved2; }; constexpr uint8_t kButtonOff = 0xFF; +// Indexes into TuningMessage::keyMap: 0..15 are the XInput button bits, then these. +enum KeyBinding : uint8_t { + kKeyLeftTrigger = 16, + kKeyRightTrigger = 17, + kKeyStickUp = 18, + kKeyStickDown = 19, + kKeyStickLeft = 20, + kKeyStickRight = 21, + kKeyBindings = 22, +}; + +// Set in lParam of the keyboard messages InputSplit posts for those keys (a bit Windows +// leaves reserved), so the keyboard block lets them through. +constexpr uint32_t kSyntheticKeyBit = 1u << 25; + struct StatusMessage { Header header; uint32_t requested; // Feature bits currently requested @@ -165,7 +183,7 @@ static_assert(sizeof(Header) == 16, "Header layout changed"); static_assert(sizeof(HelloMessage) == 40, "HelloMessage layout changed"); static_assert(sizeof(ConfigureMessage) == 32, "ConfigureMessage layout changed"); static_assert(sizeof(FrameStatsMessage) == 24, "FrameStatsMessage layout changed"); -static_assert(sizeof(TuningMessage) == 48, "TuningMessage layout changed"); +static_assert(sizeof(TuningMessage) == 72, "TuningMessage layout changed"); static_assert(sizeof(StatusMessage) == 160, "StatusMessage layout changed"); static_assert(sizeof(LogMessage) == 504, "LogMessage layout changed"); diff --git a/native/helper/main.cpp b/native/helper/main.cpp index a6fb218..8d5dd1c 100644 --- a/native/helper/main.cpp +++ b/native/helper/main.cpp @@ -160,6 +160,12 @@ Json Handle(const std::string& method, const Json& params) { tuning.playerSlots[i] = slots[i].get(); } } + if (params.contains("keyMap")) { + const Json& keys = params["keyMap"]; + for (int i = 0; i < proto::kKeyBindings && i < static_cast(keys.size()); ++i) { + tuning.keyMap[i] = keys[i].get(); + } + } if (!SessionManager::Instance().SetTuning(params.at("sessionId").get(), tuning)) { throw HelperError{"sessionNotFound", "No such session."}; } diff --git a/native/hook/CMakeLists.txt b/native/hook/CMakeLists.txt index 1e6b437..9361114 100644 --- a/native/hook/CMakeLists.txt +++ b/native/hook/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(InputSplitHook SHARED detection.cpp frame_stats.cpp tuning.cpp + key_emulation.cpp minhook_util.cpp log.cpp hook.def) diff --git a/native/hook/activation_shield.cpp b/native/hook/activation_shield.cpp index 9607803..1df279d 100644 --- a/native/hook/activation_shield.cpp +++ b/native/hook/activation_shield.cpp @@ -76,6 +76,12 @@ LRESULT CALLBACK ShieldProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { return result; } + // Keys from the controller (key_emulation.cpp): delivered without the marker bit. + if (IsKeyboardMessage(msg) && (lParam & proto::kSyntheticKeyBit)) { + lParam &= ~static_cast(proto::kSyntheticKeyBit); + return callOriginal(); + } + LRESULT syncResult = 0; if (HandleRawInputSyncMessage(msg, syncResult)) return syncResult; diff --git a/native/hook/input_block.cpp b/native/hook/input_block.cpp index e0eaf69..7a24020 100644 --- a/native/hook/input_block.cpp +++ b/native/hook/input_block.cpp @@ -58,6 +58,9 @@ void FilterMessage(MSG* msg) { if (msg == nullptr) return; bool hide = false; if (IsKeyboardMessage(msg->message)) { + // Keys from the controller (key_emulation.cpp) pass; the window procedure removes the + // marker. TranslateMessage copies it into the WM_CHAR it makes, so those pass too. + if (msg->lParam & proto::kSyntheticKeyBit) return; hide = IsActive(proto::kFeatureBlockKeyboard); if (hide) Count(g_counters.blockedKeyboard); } else if (IsMouseMessage(msg->message)) { @@ -101,6 +104,7 @@ BOOL WINAPI DetourPeekMessageA(LPMSG msg, HWND hwnd, UINT min, UINT max, UINT re // --- 2. Key state polling --------------------------------------------------------------- SHORT WINAPI DetourGetAsyncKeyState(int vk) { + if (SyntheticKeyDown(vk)) return static_cast(0x8000); SHORT real = g_realGetAsyncKeyState(vk); if (real != 0 && ShouldHideKey(vk)) { Count(IsMouseButtonKey(vk) ? g_counters.blockedMouse : g_counters.blockedKeyboard); @@ -110,6 +114,7 @@ SHORT WINAPI DetourGetAsyncKeyState(int vk) { } SHORT WINAPI DetourGetKeyState(int vk) { + if (SyntheticKeyDown(vk)) return static_cast(0x8000); SHORT real = g_realGetKeyState(vk); if (real != 0 && ShouldHideKey(vk)) { return 0; // not counted: GetAsyncKeyState already counts real presses @@ -127,6 +132,9 @@ BOOL WINAPI DetourGetKeyboardState(PBYTE keys) { if (IsMouseButtonKey(vk) ? hideMouse : hideKeyboard) keys[vk] = 0; } } + for (int vk = 1; vk < 256; ++vk) { + if (SyntheticKeyDown(vk)) keys[vk] |= 0x80; + } } return result; } diff --git a/native/hook/key_emulation.cpp b/native/hook/key_emulation.cpp new file mode 100644 index 0000000..e21d0a7 --- /dev/null +++ b/native/hook/key_emulation.cpp @@ -0,0 +1,137 @@ +// key_emulation.cpp — the controller presses keys inside the game, for games that only +// understand a keyboard (InputSplit's own). +// +// A thread reads the game's controller about 125 times per second and, for every bound +// button, trigger or left-stick direction that changes, posts WM_KEYDOWN / WM_KEYUP to the +// game window. The messages carry kSyntheticKeyBit, so the keyboard block lets them through +// while the shared keyboard stays hidden (input_block.cpp, activation_shield.cpp). Key-state +// queries (GetAsyncKeyState & co.) report these keys as pressed. Nothing is sent to other +// programs: Windows' own input queue (SendInput) is never used. +// +// Not covered: games that read the keyboard through Raw Input or DirectInput. +#include "modules.h" + +#include + +#include "hook_state.h" +#include "log.h" + +namespace inputsplit::hook { +namespace { + +std::atomic g_keyMap[proto::kKeyBindings]; +std::atomic g_enabled{false}; +std::atomic g_down[256]; // keys this module holds down in the game +bool g_threadStarted = false; // pipe thread only + +constexpr int kTriggerOn = 64, kTriggerOff = 40; // 0..255 +constexpr int kStickOn = 16000, kStickOff = 11000; // thumb units + +bool IsExtendedKey(UINT vk) { + switch (vk) { + case VK_LEFT: case VK_RIGHT: case VK_UP: case VK_DOWN: + case VK_INSERT: case VK_DELETE: case VK_HOME: case VK_END: case VK_PRIOR: case VK_NEXT: + case VK_RCONTROL: case VK_RMENU: case VK_DIVIDE: case VK_NUMLOCK: + return true; + default: + return false; + } +} + +void PostKey(UINT vk, bool down) { + g_down[vk].store(down, std::memory_order_relaxed); + HWND game = GameWindow(); + if (game == nullptr) return; + LPARAM lParam = 1 | (static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) & 0xFF) << 16) | + static_cast(proto::kSyntheticKeyBit); + if (IsExtendedKey(vk)) lParam |= 1 << 24; + if (!down) lParam |= (static_cast(1) << 30) | (static_cast(1) << 31); + PostMessageW(game, down ? WM_KEYDOWN : WM_KEYUP, vk, lParam); +} + +void ReleaseAll() { + for (UINT vk = 1; vk < 256; ++vk) { + if (g_down[vk].load(std::memory_order_relaxed)) PostKey(vk, false); + } +} + +// Which bindings are held, with a gap between "press" and "release" so a stick resting +// near the threshold does not flicker the key. +void ReadBindings(const XINPUT_GAMEPAD& pad, bool held[proto::kKeyBindings]) { + for (int bit = 0; bit < 16; ++bit) held[bit] = (pad.wButtons & (1u << bit)) != 0; + auto over = [&](int index, int value, int on, int off) { + held[index] = value > (held[index] ? off : on); + }; + over(proto::kKeyLeftTrigger, pad.bLeftTrigger, kTriggerOn, kTriggerOff); + over(proto::kKeyRightTrigger, pad.bRightTrigger, kTriggerOn, kTriggerOff); + over(proto::kKeyStickUp, pad.sThumbLY, kStickOn, kStickOff); + over(proto::kKeyStickDown, -static_cast(pad.sThumbLY), kStickOn, kStickOff); + over(proto::kKeyStickLeft, -static_cast(pad.sThumbLX), kStickOn, kStickOff); + over(proto::kKeyStickRight, pad.sThumbLX, kStickOn, kStickOff); +} + +DWORD WINAPI Worker(LPVOID) { + bool held[proto::kKeyBindings] = {}; + for (;;) { + if (!g_enabled.load(std::memory_order_acquire) || g_active.load() == 0) { + for (bool& h : held) h = false; + ReleaseAll(); + Sleep(100); + continue; + } + XINPUT_STATE state{}; + if (ReadPlayerOnePad(&state)) { + ReadBindings(state.Gamepad, held); + } else { + for (bool& h : held) h = false; + } + bool want[256] = {}; + for (int i = 0; i < proto::kKeyBindings; ++i) { + const uint8_t vk = g_keyMap[i].load(std::memory_order_relaxed); + if (vk != 0 && held[i]) want[vk] = true; + } + for (UINT vk = 1; vk < 256; ++vk) { + if (want[vk] != g_down[vk].load(std::memory_order_relaxed)) PostKey(vk, want[vk]); + } + Sleep(8); + } +} + +} // namespace + +void SetKeyMap(const uint8_t (&keyMap)[24]) { + bool any = false; + for (int i = 0; i < proto::kKeyBindings; ++i) { + g_keyMap[i].store(keyMap[i], std::memory_order_relaxed); + any = any || keyMap[i] != 0; + } + g_enabled.store(any, std::memory_order_release); + // Key-state queries must report these keys even when the keyboard block is off. + if (any && !InstallInputBlockHooks()) Log(LogLevel::Warn, "Key-state hooks not available"); + if (any && !g_threadStarted) { + HANDLE thread = CreateThread(nullptr, 0, &Worker, nullptr, 0, nullptr); + if (thread == nullptr) { + Log(LogLevel::Error, "Could not start the controller-to-keys thread"); + return; + } + CloseHandle(thread); + g_threadStarted = true; + } + if (any) Log(LogLevel::Info, "Controller presses keys in the game"); +} + +void ClearKeyMap() { g_enabled.store(false, std::memory_order_release); } + +bool SyntheticKeyDown(int vk) { + if (vk <= 0 || vk > 255) return false; + if (g_down[vk].load(std::memory_order_relaxed)) return true; + // Games often ask for the left/right variant of a modifier the binding names generically. + switch (vk) { + case VK_LSHIFT: case VK_RSHIFT: return g_down[VK_SHIFT].load(std::memory_order_relaxed); + case VK_LCONTROL: case VK_RCONTROL: return g_down[VK_CONTROL].load(std::memory_order_relaxed); + case VK_LMENU: case VK_RMENU: return g_down[VK_MENU].load(std::memory_order_relaxed); + default: return false; + } +} + +} // namespace inputsplit::hook diff --git a/native/hook/modules.h b/native/hook/modules.h index f03ca1f..30a7f55 100644 --- a/native/hook/modules.h +++ b/native/hook/modules.h @@ -34,6 +34,12 @@ bool IsMouseMessage(UINT message); bool InstallXInputHooks(); void OnXInputBackgroundEnabled(); void OnXInputBackgroundDisabled(); +bool ReadPlayerOnePad(XINPUT_STATE* state); // the game's player 1, tuning applied + +// key_emulation.cpp (the controller presses keys in the game) +void SetKeyMap(const uint8_t (&keyMap)[24]); +void ClearKeyMap(); +bool SyntheticKeyDown(int vk); // a key the controller holds down in the game // directinput_bridge.cpp bool InstallDirectInputHooks(); diff --git a/native/hook/tuning.cpp b/native/hook/tuning.cpp index 7ba17bf..5f1bcbb 100644 --- a/native/hook/tuning.cpp +++ b/native/hook/tuning.cpp @@ -83,6 +83,7 @@ void SetTuning(const proto::TuningMessage& tuning) { Log(LogLevel::Info, "Player order: slots %u %u %u %u", tuning.playerSlots[0] + 1u, tuning.playerSlots[1] + 1u, tuning.playerSlots[2] + 1u, tuning.playerSlots[3] + 1u); } + SetKeyMap(tuning.keyMap); Log(LogLevel::Info, "Tuning %s: dead zones L=%d R=%d triggers=%d, buttons %s", enabled ? "on" : "off", left, right, trigger, identity ? "unchanged" : "remapped"); } @@ -90,6 +91,7 @@ void SetTuning(const proto::TuningMessage& tuning) { void ClearTuning() { g_enabled.store(false, std::memory_order_release); g_orderEnabled.store(false, std::memory_order_release); + ClearKeyMap(); } bool PlayerOrderSlot(DWORD userIndex, DWORD& physical) { diff --git a/native/hook/xinput_bridge.cpp b/native/hook/xinput_bridge.cpp index 38c7932..894da52 100644 --- a/native/hook/xinput_bridge.cpp +++ b/native/hook/xinput_bridge.cpp @@ -196,6 +196,16 @@ bool InstallXInputHooks() { return installed; } +bool ReadPlayerOnePad(XINPUT_STATE* state) { + if (g_real.getState == nullptr && !InstallXInputHooks()) return false; + DWORD physical = 0; + if (!MapUserIndex(0, physical) || g_real.getState(physical, state) != ERROR_SUCCESS) { + return false; + } + ApplyTuning(state); + return true; +} + void OnXInputBackgroundEnabled() { // The game may already have disabled XInput before isolation started. if (g_real.enable != nullptr) g_real.enable(TRUE); diff --git a/src/main/native/protocol.ts b/src/main/native/protocol.ts index a3d31b4..c0e1a27 100644 --- a/src/main/native/protocol.ts +++ b/src/main/native/protocol.ts @@ -89,6 +89,7 @@ export const helperMethods = { triggerDeadzone: z.number().int(), buttonMap: z.array(z.number().int()), playerSlots: z.array(z.number().int()).optional(), + keyMap: z.array(z.number().int()).optional(), }), result: empty, }, diff --git a/src/renderer/src/components/GamepadKeysCard.vue b/src/renderer/src/components/GamepadKeysCard.vue new file mode 100644 index 0000000..8e16110 --- /dev/null +++ b/src/renderer/src/components/GamepadKeysCard.vue @@ -0,0 +1,149 @@ + + + diff --git a/src/renderer/src/i18n/de.ts b/src/renderer/src/i18n/de.ts index f67d5eb..8fd61f6 100644 --- a/src/renderer/src/i18n/de.ts +++ b/src/renderer/src/i18n/de.ts @@ -338,6 +338,15 @@ export const de: Messages = { wired: 'Kabel', use: 'Für Spiel nutzen', inUse: 'Ausgewählt', + keys: { + title: 'Controller als Tastatur', + description: + 'Für Spiele ohne Controller-Unterstützung: Tasten, Trigger und linker Stick drücken Tasten im isolierten Spiel. Die gemeinsame Tastatur bleibt gesperrt, nur diese Tasten erreichen das Spiel. Funktioniert in Spielen, die Tasten aus Fensternachrichten lesen; Spiele, die die Tastatur über Raw Input oder DirectInput lesen, sehen sie nicht.', + preset: 'WASD-Vorlage', + clear: 'Leeren', + press: 'Taste drücken…', + stick: 'Stick', + }, tuning: { title: 'Sticks, Trigger und Tasten', description: diff --git a/src/renderer/src/i18n/en.ts b/src/renderer/src/i18n/en.ts index a259086..922d5e0 100644 --- a/src/renderer/src/i18n/en.ts +++ b/src/renderer/src/i18n/en.ts @@ -333,6 +333,15 @@ export const en = { wired: 'Wired', use: 'Use for game', inUse: 'Selected', + keys: { + title: 'Controller as keyboard', + description: + "For games without controller support: buttons, triggers and the left stick press keys inside the isolated game. The shared keyboard stays blocked; only these keys reach the game. Works in games that read keys from window messages; games that read the keyboard through Raw Input or DirectInput won't see them.", + preset: 'WASD preset', + clear: 'Clear', + press: 'Press a key…', + stick: 'Stick', + }, tuning: { title: 'Sticks, triggers and buttons', description: diff --git a/src/renderer/src/i18n/es.ts b/src/renderer/src/i18n/es.ts index 719a602..90f2282 100644 --- a/src/renderer/src/i18n/es.ts +++ b/src/renderer/src/i18n/es.ts @@ -337,6 +337,15 @@ export const es: Messages = { wired: 'Con cable', use: 'Usar en el juego', inUse: 'Elegido', + keys: { + title: 'Mando como teclado', + description: + 'Para juegos sin soporte de mando: los botones, gatillos y el stick izquierdo pulsan teclas dentro del juego aislado. El teclado compartido sigue bloqueado; solo estas teclas llegan al juego. Funciona en juegos que leen las teclas de los mensajes de ventana; los que leen el teclado con Raw Input o DirectInput no las verán.', + preset: 'Plantilla WASD', + clear: 'Borrar', + press: 'Pulsa una tecla…', + stick: 'Stick', + }, tuning: { title: 'Sticks, gatillos y botones', description: diff --git a/src/renderer/src/i18n/fr.ts b/src/renderer/src/i18n/fr.ts index 89f0ea9..d6df8b0 100644 --- a/src/renderer/src/i18n/fr.ts +++ b/src/renderer/src/i18n/fr.ts @@ -337,6 +337,15 @@ export const fr: Messages = { wired: 'Filaire', use: 'Utiliser pour le jeu', inUse: 'Choisie', + keys: { + title: 'Manette comme clavier', + description: + 'Pour les jeux sans prise en charge de la manette : boutons, gâchettes et stick gauche appuient sur des touches dans le jeu isolé. Le clavier partagé reste bloqué ; seules ces touches atteignent le jeu. Fonctionne dans les jeux qui lisent les touches via les messages de fenêtre ; ceux qui lisent le clavier via Raw Input ou DirectInput ne les verront pas.', + preset: 'Modèle WASD', + clear: 'Effacer', + press: 'Appuyez sur une touche…', + stick: 'Stick', + }, tuning: { title: 'Sticks, gâchettes et boutons', description: diff --git a/src/renderer/src/i18n/ja.ts b/src/renderer/src/i18n/ja.ts index ef98040..f2b2c08 100644 --- a/src/renderer/src/i18n/ja.ts +++ b/src/renderer/src/i18n/ja.ts @@ -341,6 +341,15 @@ export const ja: Messages = { wired: '有線', use: 'ゲームで使う', inUse: '選択済み', + keys: { + title: 'コントローラーをキーボードとして使う', + description: + 'コントローラー非対応のゲーム向け:ボタン、トリガー、左スティックで、分離したゲームの中でキーを押します。共有キーボードはブロックされたままで、ゲームに届くのはこれらのキーだけです。ウィンドウメッセージからキーを読むゲームで動作します。Raw Input や DirectInput でキーボードを読むゲームには届きません。', + preset: 'WASD プリセット', + clear: 'クリア', + press: 'キーを押してください…', + stick: 'スティック', + }, tuning: { title: 'スティック・トリガー・ボタン', description: diff --git a/src/renderer/src/i18n/pl.ts b/src/renderer/src/i18n/pl.ts index daf81d9..570eefc 100644 --- a/src/renderer/src/i18n/pl.ts +++ b/src/renderer/src/i18n/pl.ts @@ -331,6 +331,15 @@ export const pl: Messages = { wired: 'Przewodowy', use: 'Użyj w grze', inUse: 'Wybrany', + keys: { + title: 'Pad jako klawiatura', + description: + 'Dla gier bez obsługi pada: przyciski, spusty i lewa gałka naciskają klawisze w izolowanej grze. Wspólna klawiatura pozostaje zablokowana, do gry trafiają tylko te klawisze. Działa w grach, które czytają klawisze z komunikatów okna; gry czytające klawiaturę przez Raw Input lub DirectInput ich nie zobaczą.', + preset: 'Układ WASD', + clear: 'Wyczyść', + press: 'Naciśnij klawisz…', + stick: 'Gałka', + }, tuning: { title: 'Gałki, spusty i przyciski', description: diff --git a/src/renderer/src/i18n/pt-BR.ts b/src/renderer/src/i18n/pt-BR.ts index 4e43eaa..f77ac7f 100644 --- a/src/renderer/src/i18n/pt-BR.ts +++ b/src/renderer/src/i18n/pt-BR.ts @@ -333,6 +333,15 @@ export const ptBR: Messages = { wired: 'Com fio', use: 'Usar no jogo', inUse: 'Escolhido', + keys: { + title: 'Controle como teclado', + description: + 'Para jogos sem suporte a controle: botões, gatilhos e o analógico esquerdo pressionam teclas dentro do jogo isolado. O teclado compartilhado continua bloqueado; só essas teclas chegam ao jogo. Funciona em jogos que leem teclas das mensagens da janela; jogos que leem o teclado via Raw Input ou DirectInput não as verão.', + preset: 'Modelo WASD', + clear: 'Limpar', + press: 'Pressione uma tecla…', + stick: 'Analógico', + }, tuning: { title: 'Analógicos, gatilhos e botões', description: diff --git a/src/renderer/src/i18n/ru.ts b/src/renderer/src/i18n/ru.ts index c16621a..7f1bd19 100644 --- a/src/renderer/src/i18n/ru.ts +++ b/src/renderer/src/i18n/ru.ts @@ -328,6 +328,15 @@ export const ru: Messages = { wired: 'Проводной', use: 'Для игры', inUse: 'Выбран', + keys: { + title: 'Геймпад как клавиатура', + description: + 'Для игр без поддержки геймпада: кнопки, курки и левый стик нажимают клавиши внутри изолированной игры. Общая клавиатура остаётся заблокированной, до игры доходят только эти клавиши. Работает в играх, которые читают клавиши из сообщений окна; игры, читающие клавиатуру через Raw Input или DirectInput, их не увидят.', + preset: 'Раскладка WASD', + clear: 'Очистить', + press: 'Нажмите клавишу…', + stick: 'Стик', + }, tuning: { title: 'Стики, курки и кнопки', description: diff --git a/src/renderer/src/i18n/tr.ts b/src/renderer/src/i18n/tr.ts index 1006d2c..fe8199a 100644 --- a/src/renderer/src/i18n/tr.ts +++ b/src/renderer/src/i18n/tr.ts @@ -329,6 +329,15 @@ export const tr: Messages = { wired: 'Kablolu', use: 'Oyun için kullan', inUse: 'Seçildi', + keys: { + title: 'Kumanda klavye olarak', + description: + 'Kumanda desteği olmayan oyunlar için: düğmeler, tetikler ve sol çubuk izole oyunun içinde tuşlara basar. Paylaşılan klavye engelli kalır; oyuna yalnızca bu tuşlar ulaşır. Tuşları pencere mesajlarından okuyan oyunlarda çalışır; klavyeyi Raw Input veya DirectInput ile okuyan oyunlar bunları görmez.', + preset: 'WASD düzeni', + clear: 'Temizle', + press: 'Bir tuşa basın…', + stick: 'Çubuk', + }, tuning: { title: 'Çubuklar, tetikler ve tuşlar', description: diff --git a/src/renderer/src/i18n/uk.ts b/src/renderer/src/i18n/uk.ts index 7d4f032..a900fc2 100644 --- a/src/renderer/src/i18n/uk.ts +++ b/src/renderer/src/i18n/uk.ts @@ -328,6 +328,15 @@ export const uk: Messages = { wired: 'Дротовий', use: 'Для гри', inUse: 'Вибрано', + keys: { + title: 'Геймпад як клавіатура', + description: + 'Для ігор без підтримки геймпада: кнопки, курки й лівий стік натискають клавіші всередині ізольованої гри. Спільна клавіатура лишається заблокованою, до гри доходять лише ці клавіші. Працює в іграх, які читають клавіші з повідомлень вікна; ігри, що читають клавіатуру через Raw Input або DirectInput, їх не побачать.', + preset: 'Розкладка WASD', + clear: 'Очистити', + press: 'Натисніть клавішу…', + stick: 'Стік', + }, tuning: { title: 'Стіки, курки та кнопки', description: diff --git a/src/renderer/src/i18n/zh-CN.ts b/src/renderer/src/i18n/zh-CN.ts index 234374c..dbccc2a 100644 --- a/src/renderer/src/i18n/zh-CN.ts +++ b/src/renderer/src/i18n/zh-CN.ts @@ -314,6 +314,15 @@ export const zhCN: Messages = { wired: '有线', use: '用于游戏', inUse: '已选择', + keys: { + title: '手柄当键盘', + description: + '适用于不支持手柄的游戏:按键、扳机和左摇杆会在隔离的游戏内按下键盘按键。共享键盘仍被屏蔽,只有这些按键会到达游戏。适用于从窗口消息读取按键的游戏;通过 Raw Input 或 DirectInput 读取键盘的游戏收不到它们。', + preset: 'WASD 预设', + clear: '清除', + press: '请按一个键…', + stick: '摇杆', + }, tuning: { title: '摇杆、扳机和按键', description: '在隔离的游戏中,对游戏读取的 Xbox 手柄输入生效。手柄本身和其他程序不受影响。', diff --git a/src/renderer/src/views/ControllersView.vue b/src/renderer/src/views/ControllersView.vue index 2e96a52..5ecee14 100644 --- a/src/renderer/src/views/ControllersView.vue +++ b/src/renderer/src/views/ControllersView.vue @@ -7,6 +7,7 @@ import { GAMEPAD_MODELS } from '@shared/gamepad-models' import { INPUT_TOOLS } from '@shared/input-tools' import ControllerSlotCard from '../components/ControllerSlotCard.vue' import ControllerTuningCard from '../components/ControllerTuningCard.vue' +import GamepadKeysCard from '../components/GamepadKeysCard.vue' import GamepadVisualizer from '../components/GamepadVisualizer.vue' import PageHeader from '../components/PageHeader.vue' import UiButton from '../components/ui/UiButton.vue' @@ -145,6 +146,7 @@ onBeforeUnmount(() => void devices.stopTest().catch(() => {})) + @@ -469,6 +471,7 @@ export const SettingsSchema = z.object({ triggerDeadzone: 0, remap: {}, playerOrder: [0, 1, 2, 3], + keys: {}, }), blockGameBarButton: ADDED_SETTINGS_FIELDS.blockGameBarButton.default(true), controllerAlerts: ADDED_SETTINGS_FIELDS.controllerAlerts.default(true), diff --git a/src/shared/key-names.ts b/src/shared/key-names.ts new file mode 100644 index 0000000..61ff29a --- /dev/null +++ b/src/shared/key-names.ts @@ -0,0 +1,46 @@ +/** Short names of Windows virtual-key codes, for the "Controller as keyboard" table. */ +const NAMES: Record = { + 0x08: 'Backspace', + 0x09: 'Tab', + 0x0d: 'Enter', + 0x10: 'Shift', + 0x11: 'Ctrl', + 0x12: 'Alt', + 0x13: 'Pause', + 0x14: 'Caps Lock', + 0x1b: 'Esc', + 0x20: 'Space', + 0x21: 'Page Up', + 0x22: 'Page Down', + 0x23: 'End', + 0x24: 'Home', + 0x25: '←', + 0x26: '↑', + 0x27: '→', + 0x28: '↓', + 0x2d: 'Insert', + 0x2e: 'Delete', + 0x6a: 'Num *', + 0x6b: 'Num +', + 0x6d: 'Num -', + 0x6e: 'Num .', + 0x6f: 'Num /', + 0xba: ';', + 0xbb: '=', + 0xbc: ',', + 0xbd: '-', + 0xbe: '.', + 0xbf: '/', + 0xc0: '`', + 0xdb: '[', + 0xdc: '\\', + 0xdd: ']', + 0xde: "'", +} + +export function keyName(vk: number): string { + if ((vk >= 0x30 && vk <= 0x39) || (vk >= 0x41 && vk <= 0x5a)) return String.fromCharCode(vk) + if (vk >= 0x60 && vk <= 0x69) return `Num ${vk - 0x60}` + if (vk >= 0x70 && vk <= 0x87) return `F${vk - 0x6f}` + return NAMES[vk] ?? `0x${vk.toString(16).toUpperCase()}` +} diff --git a/src/shared/tuning.test.ts b/src/shared/tuning.test.ts index 47cee7b..486ab08 100644 --- a/src/shared/tuning.test.ts +++ b/src/shared/tuning.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { isDefaultTuning, stickPercent, toHelperTuning, withPlayerSlot } from './tuning' +import { keyName } from './key-names' describe('toHelperTuning', () => { it('turns percents into XInput units and buttons into bit indexes', () => { @@ -9,7 +10,13 @@ describe('toHelperTuning', () => { triggerDeadzone: 20, remap: { a: 'b', b: 'a', back: 'off' }, playerOrder: [1, 0, 2, 3], + keys: { stickUp: 0x57, a: 0x20, rightTrigger: 0x11 }, }) + expect(tuning.keyMap).toHaveLength(22) + expect(tuning.keyMap[18]).toBe(0x57) // stick up -> W + expect(tuning.keyMap[12]).toBe(0x20) // A -> Space + expect(tuning.keyMap[17]).toBe(0x11) // RT -> Ctrl + expect(tuning.keyMap[0]).toBe(0) expect(tuning.playerSlots).toEqual([1, 0, 2, 3]) expect(tuning.leftDeadzone).toBe(3277) expect(tuning.triggerDeadzone).toBe(51) @@ -29,8 +36,10 @@ describe('isDefaultTuning', () => { triggerDeadzone: 0, remap: {}, playerOrder: [0, 1, 2, 3], + keys: {}, } expect(isDefaultTuning(base)).toBe(true) + expect(isDefaultTuning({ ...base, keys: { a: 0x20 } })).toBe(false) expect(isDefaultTuning({ ...base, remap: { a: 'a' } })).toBe(true) expect(isDefaultTuning({ ...base, remap: { a: 'b' } })).toBe(false) expect(isDefaultTuning({ ...base, rightDeadzone: 5 })).toBe(false) @@ -52,3 +61,13 @@ describe('withPlayerSlot', () => { expect(withPlayerSlot([2, 1, 0, 3], 0, 2)).toEqual([2, 1, 0, 3]) }) }) + +describe('keyName', () => { + it('names common keys', () => { + expect(keyName(0x57)).toBe('W') + expect(keyName(0x20)).toBe('Space') + expect(keyName(0x70)).toBe('F1') + expect(keyName(0x31)).toBe('1') + expect(keyName(0xe2)).toBe('0xE2') + }) +}) diff --git a/src/shared/tuning.ts b/src/shared/tuning.ts index 74f4cdc..8b9390d 100644 --- a/src/shared/tuning.ts +++ b/src/shared/tuning.ts @@ -1,7 +1,7 @@ /** * Dead zones and button remapping (Controllers page) in the form the hook DLL takes. */ -import { XInputButton, type GamepadButton } from './defaults' +import { XInputButton, type GamepadButton, type KeyBinding } from './defaults' import type { GamepadTuning } from './domain' /** What the helper's setTuning request carries (see TuningMessage in hook_protocol.h). */ @@ -13,6 +13,24 @@ export interface HelperTuning { buttonMap: number[] /** Physical slot behind the game's player 1..4 (games that read every controller). */ playerSlots: number[] + /** Virtual-key code per input (see KeyBinding in hook_protocol.h), 0 = none. */ + keyMap: number[] +} + +/** Index of each non-button input in keyMap; buttons use their XInput bit. */ +const KEY_SLOTS: Record, number> = { + leftTrigger: 16, + rightTrigger: 17, + stickUp: 18, + stickDown: 19, + stickLeft: 20, + stickRight: 21, +} + +function keySlot(binding: KeyBinding): number { + return binding in KEY_SLOTS + ? KEY_SLOTS[binding as keyof typeof KEY_SLOTS] + : bitOf(binding as GamepadButton) } const BUTTON_OFF = 255 @@ -33,7 +51,16 @@ export function toHelperTuning(tuning: GamepadTuning): HelperTuning { triggerDeadzone: Math.round((tuning.triggerDeadzone / 100) * 255), buttonMap, playerSlots: [...tuning.playerOrder], + keyMap: toKeyMap(tuning.keys), + } +} + +export function toKeyMap(keys: GamepadTuning['keys']): number[] { + const keyMap = Array.from({ length: 22 }, () => 0) + for (const [binding, vk] of Object.entries(keys) as [KeyBinding, number][]) { + keyMap[keySlot(binding)] = vk } + return keyMap } export function isDefaultTuning(tuning: GamepadTuning): boolean { @@ -42,7 +69,8 @@ export function isDefaultTuning(tuning: GamepadTuning): boolean { tuning.rightDeadzone === 0 && tuning.triggerDeadzone === 0 && Object.entries(tuning.remap).every(([from, to]) => from === to) && - tuning.playerOrder.every((slot, player) => slot === player) + tuning.playerOrder.every((slot, player) => slot === player) && + Object.keys(tuning.keys).length === 0 ) }