Files
Reims-Go/internal/host/keymap_test.go
T
棠渚听潮 7c18815f53 feat(input,ui): add per-VM focus-exclusive host shortcut capture and hook promotion
- Add per-VM `capture_host_shortcuts` option persisted in `.reims-go-keymap.json`
  (independent from modifier preset and backward-compatible with legacy configs
  and Wails callers omitting the field). When enabled, unmapped Win and Alt keys
  route through the existing Guest Tools v8 hidutil carrier (`lcmd`/`rcmd`/`lopt`/
  `ropt`) while the VM is focused, preventing host Win/Alt shortcuts (e.g. PixPin
  Alt+A, Alt+Tab, Alt+F4, Ctrl+Alt+A, Win+...) without modifying explicit custom
  bindings or bumping Guest Tools version.
- Monitor `EVENT_SYSTEM_FOREGROUND` and `EVENT_OBJECT_NAMECHANGE` on the Windows
  keymap hook thread to immediately release held modifiers on focus loss and
  promote `WH_KEYBOARD_LL` back to the top of the hook chain on VM focus entry
  and SDL3 in-window re-capture, with per-key timestamp filtering for delayed
  focus-loss events, swap-window event deduplication, Win64 32-bit parameter
  narrowing, and fallback timer recovery.
- Serialize `SetVMKeymap` read-merge-save under `keymapMu`, expose the toggle in
  Settings with zh-CN/en-US i18n, and add Go + frontend unit tests.
2026-12-02 10:00:09 +08:00

235 lines
11 KiB
Go

package host
import (
"slices"
"testing"
)
func TestKeymapEngine(t *testing.T) {
rule := KeymapRule{VMName: "mac", Bindings: map[string]string{"lwin": "lcmd", "rwin": "rctrl", "lalt": "disabled"}}
e := NewKeymapEngine([]KeymapRule{rule})
event := func(vk uint32, up bool, vm string, suppress bool, expected ...EmittedKey) {
t.Helper()
got, emit := e.ProcessEvent(KeyEvent{VK: vk, Up: up}, vm, vm != "")
if got != suppress || !slices.Equal(emit, expected) {
t.Fatalf("event %#x up=%v vm=%q = %v %v, want %v %v", vk, up, vm, got, emit, suppress, expected)
}
}
event(vkLWin, false, "mac", false)
event(vkLWin, true, "mac", false)
rightCtrl := EmittedKey{VK: vkRCtrl, Scan: 0x1D, Extended: true}
event(vkRWin, false, "mac", true, rightCtrl)
event(vkRWin, false, "mac", true)
rightCtrl.Up = true
event(vkRWin, true, "", true, rightCtrl)
event(vkLAlt, false, "mac", true)
event(vkLCtrl, false, "mac", false)
event(vkLWin, false, "mac", false, EmittedKey{VK: vkLAlt, Scan: 0x38})
event(vkLAlt, true, "mac", true, EmittedKey{VK: vkLAlt, Scan: 0x38, Up: true})
event(vkLWin, false, "mac", false)
event(vkLWin, true, "mac", false)
event(vkLCtrl, true, "mac", false)
rule.CarrierReady = true
e.SetRules([]KeymapRule{rule})
event(vkLWin, false, "other", false)
event(vkLWin, false, "mac", false)
event(vkLWin, true, "mac", false)
cmd := EmittedKey{VK: 0x84, Scan: 0x6C}
event(vkLWin, false, "mac", true, cmd)
cmd.Up = true
if got := e.ReleaseIfFocusLost("other"); !slices.Equal(got, []EmittedKey{cmd}) {
t.Fatalf("focus loss = %v", got)
}
event(vkLWin, true, "", true)
event(vkRWin, false, "mac", true, EmittedKey{VK: vkRCtrl, Scan: 0x1D, Extended: true})
if got := e.SetRules(nil); !slices.Equal(got, []EmittedKey{rightCtrl}) {
t.Fatalf("rule replacement = %v", got)
}
event(vkRWin, true, "mac", true)
}
func TestKeymapHookStaysOffWithoutReadyTarget(t *testing.T) {
svc := NewInputService(nil)
defer svc.Close()
svc.SetKeymapRules([]KeymapRule{{VMName: "mac", Bindings: map[string]string{"lwin": "lcmd"}}})
svc.SetTargets([]IMETarget{{VMName: "mac", PID: 42}})
if svc.IsKeymapHookInstalled() || svc.IsKeymapActiveForVM("mac") {
t.Fatal("hook should stay inactive while the carrier is unavailable")
}
svc.SetKeymapRules([]KeymapRule{{VMName: "other", Bindings: map[string]string{"lwin": "esc"}}})
if svc.IsKeymapHookInstalled() {
t.Fatal("hook should stay inactive for a nonmatching VM")
}
}
func TestKeymapReconcilesLostKeyUps(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}}})
for _, vk := range []uint32{vkLCtrl, vkLAlt} {
e.ProcessEvent(KeyEvent{VK: vk}, "vm", true)
}
isDown := func(uint32) bool { return false }
// First tick arms the two-tick grace so a freshly pressed key is never cleared early.
if keys := e.ReconcilePhysical(isDown); len(keys) != 0 || !e.physical[vkLCtrl] || !e.physical[vkLAlt] {
t.Fatalf("first reconcile tick should retain grace state: keys=%v physical=%v", keys, e.physical)
}
// Second tick clears lost unsuppressed modifiers.
if keys := e.ReconcilePhysical(isDown); len(keys) != 0 || e.physical[vkLCtrl] || e.physical[vkLAlt] {
t.Fatalf("second reconcile tick should clear lost unmapped keys: keys=%v physical=%v", keys, e.physical)
}
// A suppressed mapped key never sets GetAsyncKeyState on Windows, so repeated
// ReconcilePhysical ticks with isDown==false must NEVER release it early.
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets["lcmd"] {
t.Fatalf("Win down after reconciliation: %v %v", suppress, keys)
}
for i := 0; i < 5; i++ {
if keys := e.ReconcilePhysical(isDown); len(keys) != 0 {
t.Fatalf("reconcile tick %d prematurely released suppressed key: %v", i, keys)
}
}
if !e.physical[vkLWin] || e.activeMapped[vkLWin] != keymapTargets["lcmd"] {
t.Fatalf("suppressed Win key state lost during reconcile: physical=%v mapped=%v", e.physical, e.activeMapped)
}
// Secure Desktop transition clears both physical and suppressed state via Reset().
if keys := e.Reset(); len(keys) != 1 || keys[0].VK != keymapTargets["lcmd"].VK || !keys[0].Up {
t.Fatalf("Reset after secure desktop: %v", keys)
}
if e.HasTrackedKeys() {
t.Fatalf("Reset left tracked keys: physical=%v mapped=%v", e.physical, e.activeMapped)
}
// After returning from Secure Desktop, Win works normally again.
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets["lcmd"] {
t.Fatalf("Win down after Reset: %v %v", suppress, keys)
}
}
func TestKeymapAltGrCrossFocusAutoRepeat(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"ralt": "rcmd"}}})
fake := KeyEvent{VK: vkLCtrl, ScanCode: 0x21D}
// Pressed outside the VM -> must not suppress.
if suppress, keys := e.ProcessEvent(fake, "", false); suppress || len(keys) != 0 || !e.HasTrackedKeys() {
t.Fatalf("AltGr down outside VM: suppress=%v keys=%v tracked=%v", suppress, keys, e.HasTrackedKeys())
}
// Auto-repeat after focus enters the VM -> must keep initial non-suppressed decision.
if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress || len(keys) != 0 {
t.Fatalf("AltGr repeat inside VM: suppress=%v keys=%v", suppress, keys)
}
// Release inside VM -> must pass through so Windows receives fake LCtrl UP.
fake.Up = true
if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress || len(keys) != 0 || e.HasTrackedKeys() {
t.Fatalf("AltGr up inside VM: suppress=%v keys=%v tracked=%v", suppress, keys, e.HasTrackedKeys())
}
}
func TestKeymapAltGr(t *testing.T) {
for _, mapped := range []bool{false, true} {
bindings := map[string]string{"lctrl": "esc", "lwin": "lcmd"}
if mapped {
bindings["ralt"] = "rcmd"
bindings["lwin"] = "lopt"
}
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", Bindings: bindings, CarrierReady: true}})
fake := KeyEvent{VK: vkLCtrl, ScanCode: 0x21D}
if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress != mapped || len(keys) != 0 || e.physical[vkLCtrl] {
t.Fatalf("AltGr fake Ctrl down: %v %v", suppress, keys)
}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkRAlt}, "vm", true); suppress != mapped || (mapped && (len(keys) != 1 || keys[0] != keymapTargets["rcmd"])) {
t.Fatalf("AltGr right Alt: %v %v", suppress, keys)
}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets[bindings["lwin"]] {
t.Fatalf("Win with AltGr: %v %v", suppress, keys)
}
e.ReleaseIfFocusLost("")
fake.Up = true
if suppress, keys := e.ProcessEvent(fake, "", false); suppress != mapped || len(keys) != 0 || e.altGrCtrlSuppressed {
t.Fatalf("AltGr fake Ctrl up after focus loss: %v %v", suppress, keys)
}
}
}
func TestKeymapUnrelatedRuleChangeKeepsHeldKey(t *testing.T) {
rule := KeymapRule{VMName: "a", Bindings: map[string]string{"lwin": "lcmd"}, CarrierReady: true}
e := NewKeymapEngine([]KeymapRule{rule})
e.ProcessEvent(KeyEvent{VK: vkLWin}, "a", true)
if keys := e.SetRules([]KeymapRule{rule, {VMName: "b", Bindings: map[string]string{"lwin": "esc"}}}); len(keys) != 0 {
t.Fatalf("unrelated update released key: %v", keys)
}
if keys := e.SetRules(nil); len(keys) != 1 || !keys[0].Up {
t.Fatalf("removing held rule should release key: %v", keys)
}
}
func TestKeymapCapturePreservesPhysicalCtrl(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", Bindings: map[string]string{"lalt": "lctrl"}}})
e.ProcessEvent(KeyEvent{VK: vkLCtrl}, "vm", true)
e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true)
suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true)
if suppress || len(keys) != 1 || keys[0] != (EmittedKey{VK: vkLAlt, Scan: 0x38}) {
t.Fatalf("capture release with physical Ctrl: %v %v", suppress, keys)
}
}
func TestKeymapHostShortcutCapture(t *testing.T) {
rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{
"lwin": "lcmd", "rwin": "rcmd", "lalt": "lopt", "ralt": "ropt",
}}
optionDown := EmittedKey{VK: 0x83, Scan: 0x6B}
optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true}
t.Run("focus loss", func(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{rule})
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true); !suppress || !slices.Equal(keys, []EmittedKey{optionDown}) {
t.Fatalf("Alt down in VM: suppress=%v keys=%v", suppress, keys)
}
if keys := e.ReleaseIfFocusLost(""); !slices.Equal(keys, []EmittedKey{optionUp}) {
t.Fatalf("Alt carrier on focus loss: %v", keys)
}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt, Up: true}, "", false); !suppress || len(keys) != 0 {
t.Fatalf("release of captured Alt: suppress=%v keys=%v", suppress, keys)
}
for _, up := range []bool{false, true} {
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt, Up: up}, "", false); suppress || len(keys) != 0 {
t.Fatalf("Alt outside VM (up=%v): suppress=%v keys=%v", up, suppress, keys)
}
}
})
t.Run("release capture chord", func(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{rule})
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLCtrl}, "vm", true); suppress || len(keys) != 0 {
t.Fatalf("Ctrl down: suppress=%v keys=%v", suppress, keys)
}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true); !suppress || !slices.Equal(keys, []EmittedKey{optionDown}) {
t.Fatalf("Alt down: suppress=%v keys=%v", suppress, keys)
}
physicalAlt := EmittedKey{VK: vkLAlt, Scan: 0x38}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); suppress || !slices.Equal(keys, []EmittedKey{optionUp, physicalAlt}) {
t.Fatalf("Ctrl+Alt+Win: suppress=%v keys=%v", suppress, keys)
}
physicalAlt.Up = true
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt, Up: true}, "vm", true); !suppress || !slices.Equal(keys, []EmittedKey{physicalAlt}) {
t.Fatalf("restored Alt up: suppress=%v keys=%v", suppress, keys)
}
})
}
func TestKeymapWinLPassesOrdinaryKey(t *testing.T) {
for _, modifier := range []uint32{0, 0xA0, vkLAlt, vkLCtrl} {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}}})
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 {
t.Fatalf("Win in VM: %v %v", suppress, keys)
}
if modifier != 0 {
e.ProcessEvent(KeyEvent{VK: modifier}, "vm", true)
}
for _, up := range []bool{false, true} {
if suppress, keys := e.ProcessEvent(KeyEvent{VK: 'L', Up: up}, "vm", true); suppress || len(keys) != 0 {
t.Fatalf("L with modifier %#x: %v %v", modifier, suppress, keys)
}
}
}
e := NewKeymapEngine(nil)
for _, vk := range []uint32{vkLWin, 'L'} {
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vk}, "", false); suppress || len(keys) != 0 {
t.Fatalf("Win+L outside VM: %v %v", suppress, keys)
}
}
}