//go:build windows package host import ( "slices" "testing" ) func newTestKeymapHook(rule KeymapRule) (*keymapHook, *[]EmittedKey, *int) { var emitted []EmittedKey promotions := 0 h := &keymapHook{ engine: NewKeymapEngine([]KeymapRule{rule}), winEventHook: 1, nameChangeHook: 2, windowTitleFn: func(uintptr) string { return "macOS" }, emitFn: func(keys []EmittedKey) { emitted = append(emitted, keys...) }, promoteFn: func() bool { promotions++ return true }, syncTimerFn: func() {}, } return h, &emitted, &promotions } func TestKeymapHookRapidFocusRoundTripUsesEventHWND(t *testing.T) { rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt"}} const ( hwndVM uintptr = 0x1001 hwndWin uintptr = 0x2002 ) optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} t.Run("releases key pressed before focus left", func(t *testing.T) { h, emitted, promotions := newTestKeymapHook(rule) h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } h.foregroundWindowFn = func() uintptr { return hwndVM } h.lastForegroundVM = "vm" h.lastForegroundHWND = hwndVM if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 100}) { t.Fatal("expected LAlt to be suppressed in VM") } *emitted = nil // Queued focus-loss event happened at t=120 (after press at t=100), while live focus is already back on VM. h.handleForegroundEvent(hwndWin, 120) if !slices.Equal(*emitted, []EmittedKey{optionUp}) { t.Fatalf("queued focus loss did not release Option: %v", *emitted) } if *promotions != 1 || h.lastForegroundVM != "vm" { t.Fatalf("expected re-promotion on live VM return: promotions=%d last=%q", *promotions, h.lastForegroundVM) } }) t.Run("stale focus-loss notification does not release newly pressed key", func(t *testing.T) { h, emitted, promotions := newTestKeymapHook(rule) h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } h.foregroundWindowFn = func() uintptr { return hwndVM } h.lastForegroundVM = "vm" h.lastForegroundHWND = hwndVM // User returned to VM and pressed a fresh LAlt at t=135 before delayed B event (t=120) arrived. if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 135}) { t.Fatal("expected fresh LAlt to be suppressed in VM") } *emitted = nil h.handleForegroundEvent(hwndWin, 120) if len(*emitted) != 0 { t.Fatalf("stale focus-loss notification released newly pressed key: %v", *emitted) } if *promotions != 1 || h.lastForegroundVM != "vm" { t.Fatalf("expected re-promotion on live VM: promotions=%d last=%q", *promotions, h.lastForegroundVM) } }) t.Run("releases stale key while preserving newly pressed key", func(t *testing.T) { mixedRule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt", "lwin": "lcmd"}} h, emitted, _ := newTestKeymapHook(mixedRule) h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } h.foregroundWindowFn = func() uintptr { return hwndVM } h.lastForegroundVM = "vm" h.lastForegroundHWND = hwndVM h.lastForegroundTitle = "macOS" // LAlt pressed before focus left (t=100), LWin pressed after returning (t=135). if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 100}) { t.Fatal("expected LAlt to be suppressed") } if !h.handleKeyEvent(wmKeyDown, &kbdLLHookStruct{vkCode: vkLWin, scanCode: 0x5B, time: 135}) { t.Fatal("expected LWin to be suppressed") } *emitted = nil // Delayed focus-loss event at t=120 releases LAlt (Option) only, keeping LWin (Command) held. h.handleForegroundEvent(hwndWin, 120) if !slices.Equal(*emitted, []EmittedKey{optionUp}) { t.Fatalf("expected only stale Option up, got %v", *emitted) } if h.engine.heldVM != "vm" || h.engine.activeMapped[vkLWin].VK != 0x84 { t.Fatalf("newly pressed Command should remain active: heldVM=%q active=%v", h.engine.heldVM, h.engine.activeMapped) } }) t.Run("foreground event resets when same HWND title changed before name-change callback", func(t *testing.T) { h, emitted, _ := newTestKeymapHook(rule) title := "macOS" h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } h.foregroundWindowFn = func() uintptr { return hwndVM } h.windowTitleFn = func(uintptr) string { return title } h.lastForegroundVM = "vm" h.lastForegroundHWND = hwndVM h.lastForegroundTitle = "macOS" if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 100}) { t.Fatal("expected LAlt to be suppressed") } *emitted = nil // SDL already changed the title and swallowed physical LAlt up before foreground event arrived. title = "macOS — Ctrl+Alt+Win to release" h.handleForegroundEvent(hwndVM, 150) if !slices.Equal(*emitted, []EmittedKey{optionUp}) { t.Fatalf("foreground event with changed title did not release Option: %v", *emitted) } *emitted = nil optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 160}) || !slices.Equal(*emitted, []EmittedKey{optionDown}) { t.Fatalf("next LAlt press after foreground title reset did not emit Option down: %v", *emitted) } }) } func TestKeymapHookWindowNameChangeRepromotesAndReleases(t *testing.T) { rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt", "lwin": "disabled"}} h, emitted, promotions := newTestKeymapHook(rule) const ( hwndVM uintptr = 0x1001 hwndVM2 uintptr = 0x1002 hwndOther uintptr = 0x2002 ) titles := map[uintptr]string{ hwndVM: "macOS", hwndVM2: "macOS helper", } h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM || hwnd == hwndVM2 { return "vm" } return "" } h.foregroundWindowFn = func() uintptr { return hwndVM } h.windowTitleFn = func(hwnd uintptr) string { return titles[hwnd] } h.lastForegroundVM = "vm" h.lastForegroundHWND = hwndVM h.lastForegroundTitle = "macOS" optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} // Hold LAlt in foreground VM window. if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 10}) { t.Fatal("expected LAlt to be suppressed") } *emitted = nil // Non-VM window and second window of the SAME VM process must NOT release Option or promote. h.handleWindowNameChange(hwndOther) h.handleWindowNameChange(hwndVM2) if len(*emitted) != 0 || *promotions != 0 { t.Fatalf("non-foreground window title change interfered: emitted=%v promotions=%d", *emitted, *promotions) } // Duplicate notification with unchanged title on foreground HWND is ignored. h.handleWindowNameChange(hwndVM) if len(*emitted) != 0 || *promotions != 0 { t.Fatalf("unchanged title interfered: emitted=%v promotions=%d", *emitted, *promotions) } // Simulate SDL3 re-capture: SDL3 grabs keyboard, swallows the physical LAlt key-up // (so Reims never receives wmSysKeyUp), and updates the foreground window title. titles[hwndVM] = "macOS — Ctrl+Alt+Win to release" h.handleWindowNameChange(hwndVM) if !slices.Equal(*emitted, []EmittedKey{optionUp}) { t.Fatalf("SDL re-capture handoff did not release Option: %v", *emitted) } if *promotions != 1 { t.Fatalf("SDL re-capture handoff did not re-promote hook: %d", *promotions) } // Next physical LAlt press MUST immediately map to Option (not trapped by missed key-up). *emitted = nil if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 20}) { t.Fatal("next LAlt press after missed key-up should be suppressed") } if !slices.Equal(*emitted, []EmittedKey{optionDown}) { t.Fatalf("next LAlt press after missed key-up did not emit Option down: %v", *emitted) } } func TestKeymapWinEventProcTruncatesHighBits(t *testing.T) { rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt"}} h, _, promotions := newTestKeymapHook(rule) const hwndVM uintptr = 0x1001 title := "macOS" h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } h.foregroundWindowFn = func() uintptr { return hwndVM } h.windowTitleFn = func(uintptr) string { return title } h.lastForegroundVM = "vm" h.lastForegroundHWND = hwndVM h.lastForegroundTitle = "macOS" prev := activeKeymapHook.Swap(h) t.Cleanup(func() { activeKeymapHook.Store(prev) }) // Set non-zero upper 32 bits simulating Win64 ABI stack garbage on DWORD/LONG params. const dirtyHigh = uintptr(0xDEADBEEF) << 32 title = "macOS — Ctrl+Alt+Win to release" keymapWinEventProc( h.nameChangeHook, dirtyHigh|uintptr(eventObjectNameChange), hwndVM, dirtyHigh|uintptr(objidWindow), dirtyHigh|0, 0, dirtyHigh|500, ) if *promotions != 1 { t.Fatalf("keymapWinEventProc dropped EVENT_OBJECT_NAMECHANGE with dirty upper 32 bits: promotions=%d", *promotions) } } func TestKeymapHookPromotionRetryAndWinEventRecovery(t *testing.T) { rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}} h, _, promotions := newTestKeymapHook(rule) const hwndVM uintptr = 0x1001 h.foregroundWindowFn = func() uintptr { return hwndVM } h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } // Fail promotion once: lastForegroundVM stays empty and fallback timer stays armed. allowPromote := false h.promoteFn = func() bool { *promotions++ return allowPromote } h.handleForegroundEvent(hwndVM, 100) if h.lastForegroundVM != "" || !h.promotePending { t.Fatalf("failed promotion should stay pending: last=%q pending=%v", h.lastForegroundVM, h.promotePending) } if got := h.desiredTimerInterval(); got != keymapFallbackTimerMS { t.Fatalf("desiredTimerInterval with promotePending = %d, want %d", got, keymapFallbackTimerMS) } // Retry succeeds on timer tick and disarms idle timer when both WinEvent hooks are installed. allowPromote = true h.handleForegroundChange() if h.lastForegroundVM != "vm" || h.promotePending || *promotions != 2 { t.Fatalf("retry did not succeed: last=%q pending=%v promotions=%d", h.lastForegroundVM, h.promotePending, *promotions) } if got := h.desiredTimerInterval(); got != 0 { t.Fatalf("idle desiredTimerInterval with WinEvent hooks = %d, want 0", got) } // If nameChangeHook failed at startup, fallback timer stays armed, retries install, // syncs title transitions that occurred while missing, resets trapped keys, and // re-promotes both on recovery and on subsequent SDL3 re-capture (T2 -> T1). title := "macOS — Ctrl+Alt+Win to release" h.windowTitleFn = func(uintptr) string { return title } h.lastForegroundHWND = hwndVM h.lastForegroundTitle = title h.nameChangeHook = 0 if got := h.desiredTimerInterval(); got != keymapFallbackTimerMS { t.Fatalf("desiredTimerInterval without nameChangeHook = %d, want %d", got, keymapFallbackTimerMS) } if !h.handleKeyEvent(wmKeyDown, &kbdLLHookStruct{vkCode: vkLWin, scanCode: 0x5B, time: 200}) { t.Fatal("expected LWin to be suppressed before title transition") } title = "macOS" installCalls := 0 h.installWinEventFn = func(ev uint32) uintptr { installCalls++ if ev == eventObjectNameChange { return 99 } return 0 } h.handleForegroundChange() if installCalls != 1 || h.nameChangeHook != 99 || *promotions != 3 || h.lastForegroundTitle != "macOS" { t.Fatalf("nameChangeHook recovery failed: calls=%d hook=%d promotions=%d title=%q", installCalls, h.nameChangeHook, *promotions, h.lastForegroundTitle) } if len(h.engine.activeMapped) != 0 { t.Fatalf("recovery tick did not reset mapped keys after missed title change: %v", h.engine.activeMapped) } if got := h.desiredTimerInterval(); got != 0 { t.Fatalf("idle desiredTimerInterval after recovery = %d, want 0", got) } // Subsequent SDL3 re-capture switches title back to T1 and must re-promote. title = "macOS — Ctrl+Alt+Win to release" h.handleWindowNameChange(hwndVM) if *promotions != 4 { t.Fatalf("subsequent re-capture T2->T1 did not re-promote: promotions=%d", *promotions) } } func TestKeymapHookSwapDeduplicatesReentrantEvent(t *testing.T) { rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt"}} h, emitted, _ := newTestKeymapHook(rule) const hwndVM uintptr = 0x1001 h.foregroundWindowFn = func() uintptr { return hwndVM } h.vmForWindowFn = func(hwnd uintptr) string { if hwnd == hwndVM { return "vm" } return "" } h.swappingHook = true ev := &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, flags: 0, time: 1234} if !h.handleKeyEvent(wmSysKeyDown, ev) { t.Fatal("first callback during swap should suppress LAlt") } if !h.handleKeyEvent(wmSysKeyDown, ev) { t.Fatal("duplicate callback during swap should return same suppress decision") } optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} if !slices.Equal(*emitted, []EmittedKey{optionDown}) { t.Fatalf("duplicate swap callback emitted twice: %v", *emitted) } // Distinct key-up event during swap is still processed cleanly. *emitted = nil upEv := &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, flags: 0x80, time: 1235} if !h.handleKeyEvent(wmSysKeyUp, upEv) { t.Fatal("key-up during swap should suppress physical LAlt up") } optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} if !slices.Equal(*emitted, []EmittedKey{optionUp}) { t.Fatalf("key-up during swap did not emit Option up: %v", *emitted) } }