//go:build windows package host import ( "runtime" "sync" "sync/atomic" "syscall" "unsafe" ) const ( llkhfInjected = 0x10 wmKeymapRefresh = 0x8001 wmTimer = 0x0113 desktopReadObjects = 0x0001 eventSystemForeground = 0x0003 eventObjectNameChange = 0x800C wineventOutOfContext = 0x0000 objidWindow = 0 keymapActiveTimerMS = 50 keymapFallbackTimerMS = 250 ) var ( procKeymapSetTimer = user32.NewProc("SetTimer") procKeymapKillTimer = user32.NewProc("KillTimer") procKeymapAsyncKeyState = user32.NewProc("GetAsyncKeyState") procOpenInputDesktop = user32.NewProc("OpenInputDesktop") procCloseDesktop = user32.NewProc("CloseDesktop") procSetWinEventHook = user32.NewProc("SetWinEventHook") procUnhookWinEvent = user32.NewProc("UnhookWinEvent") procTranslateMessage = user32.NewProc("TranslateMessage") procDispatchMessageW = user32.NewProc("DispatchMessageW") procKeymapGetWindowTextW = user32.NewProc("GetWindowTextW") keymapCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapKeyboardProc) }) keymapWinEventCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapWinEventProc) }) activeKeymapHook atomic.Pointer[keymapHook] ) type winKeyboardInput struct { inputType uint32 keyboard struct { vk uint16 scan uint16 flags uint32 time uint32 extra uintptr padding [2]uint32 } } var _ [unsafe.Sizeof(winMouseInput{}) - unsafe.Sizeof(winKeyboardInput{})]byte var _ [unsafe.Sizeof(winKeyboardInput{}) - unsafe.Sizeof(winMouseInput{})]byte type kbdEventSig struct { message uintptr vk uint32 scan uint32 flags uint32 time uint32 } type swapDedup struct { valid bool sig kbdEventSig suppressed bool } type keymapHook struct { service *InputService threadID uintptr done chan struct{} engine *KeymapEngine snapshot *keymapSnapshot hook uintptr winEventHook uintptr nameChangeHook uintptr module uintptr lastForegroundVM string lastForegroundHWND uintptr lastForegroundTitle string activePressTime map[uint32]uint32 promotePending bool swappingHook bool swapSeen swapDedup timer uintptr timerInterval uint32 inputDesktopAvailable bool closeOnce sync.Once vmForWindowFn func(hwnd uintptr) string foregroundWindowFn func() uintptr windowTitleFn func(hwnd uintptr) string installWinEventFn func(event uint32) uintptr promoteFn func() bool emitFn func([]EmittedKey) syncTimerFn func() } func startKeymapHook(service *InputService) *keymapHook { h := &keymapHook{service: service, done: make(chan struct{})} if !activeKeymapHook.CompareAndSwap(nil, h) { return nil } ready := make(chan bool) go h.run(ready) if !<-ready { <-h.done return nil } return h } func (h *keymapHook) run(ready chan<- bool) { runtime.LockOSThread() defer runtime.UnlockOSThread() defer close(h.done) defer activeKeymapHook.CompareAndSwap(h, nil) h.threadID, _, _ = procGetCurrentThreadId.Call() var msg winMsg procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove) h.snapshot = h.service.keymapState.Load() h.engine = NewKeymapEngine(h.snapshot.rules) h.inputDesktopAvailable = keymapInputDesktopAccessible() for vk := range hostModifiers { if keymapPhysicalDown(vk) { h.engine.physical[vk] = true } } h.module, _, _ = procGetModuleHandleW.Call(0) h.hook, _, _ = procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), h.module, 0) if h.hook == 0 { ready <- false return } defer func() { if h.hook != 0 { procUnhookWindowsHookEx.Call(h.hook) } }() defer func() { sendMappedKeys(h.engine.ReleaseAll()) }() fg := h.lookupForegroundWindow() h.lastForegroundHWND = fg h.lastForegroundVM = h.lookupWindowVM(fg) if h.lastForegroundVM != "" { h.lastForegroundTitle = h.lookupWindowTitle(fg) } h.winEventHook = h.doInstallWinEvent(eventSystemForeground) defer func() { if h.winEventHook != 0 { procUnhookWinEvent.Call(h.winEventHook) } }() h.nameChangeHook = h.doInstallWinEvent(eventObjectNameChange) defer func() { if h.nameChangeHook != 0 { procUnhookWinEvent.Call(h.nameChangeHook) } }() h.syncTimer() defer func() { if h.timer != 0 { procKeymapKillTimer.Call(0, h.timer) } }() ready <- true for { result, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) if int32(result) <= 0 { return } if msg.message == wmKeymapRefresh || msg.message == wmTimer { if h.inputDesktopAvailable && !keymapInputDesktopAccessible() { h.resetTrackedKeys() } else { sendMappedKeys(h.engine.ReconcilePhysical(keymapPhysicalDown)) } h.handleForegroundChange() continue } procTranslateMessage.Call(uintptr(unsafe.Pointer(&msg))) procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg))) } } func keymapWinEventProc(hook, event, hwnd, idObject, idChild, _, eventTime uintptr) uintptr { h := activeKeymapHook.Load() if h == nil { return 0 } ev := uint32(event) obj := int32(idObject) child := int32(idChild) ts := uint32(eventTime) if hook == h.winEventHook && ev == eventSystemForeground { h.handleForegroundEvent(hwnd, ts) } else if hook == h.nameChangeHook && ev == eventObjectNameChange && obj == objidWindow && child == 0 && hwnd != 0 { h.handleWindowNameChange(hwnd) } return 0 } func (h *keymapHook) resetTrackedKeys() { h.emitKeys(h.engine.Reset()) clear(h.activePressTime) } func (h *keymapHook) prunePressTimes() { for vk := range h.activePressTime { if key, ok := h.engine.activeMapped[vk]; !ok || key.VK == 0 { delete(h.activePressTime, vk) } } } func (h *keymapHook) syncForegroundTitle(fg uintptr) bool { title := h.lookupWindowTitle(fg) if fg == h.lastForegroundHWND { if title != "" && h.lastForegroundTitle != "" && title != h.lastForegroundTitle { h.lastForegroundTitle = title return true } if h.lastForegroundTitle == "" && title != "" { h.lastForegroundTitle = title } return false } h.lastForegroundHWND = fg h.lastForegroundTitle = title return false } func (h *keymapHook) handleForegroundEvent(hwnd uintptr, eventTime uint32) { h.syncSnapshot() eventVM := h.lookupWindowVM(hwnd) if h.engine.heldVM != "" && eventVM != h.engine.heldVM { h.emitKeys(h.engine.ReleaseMatching(func(vk uint32) bool { pressTime, ok := h.activePressTime[vk] if eventTime == 0 || !ok { return true } // Wrap-safe 32-bit GetTickCount comparison: release only keys pressed // at or before the queued focus-loss notification occurred. return int32(eventTime-pressTime) >= 0 })) h.prunePressTimes() } if eventVM != h.lastForegroundVM { h.lastForegroundVM = "" } fg := h.lookupForegroundWindow() liveVM := h.lookupWindowVM(fg) h.applyForegroundFocus(fg, liveVM, true) h.doSyncTimer() } func (h *keymapHook) applyForegroundFocus(fg uintptr, vm string, alwaysPromote bool) { h.emitKeys(h.engine.ReleaseIfFocusLost(vm)) h.prunePressTimes() if vm == "" { h.lastForegroundHWND = fg h.lastForegroundVM = "" h.lastForegroundTitle = "" h.promotePending = false return } if h.syncForegroundTitle(fg) { h.resetTrackedKeys() h.promotePending = true } if alwaysPromote || vm != h.lastForegroundVM || h.promotePending { if h.doPromoteHook() { h.lastForegroundVM = vm h.promotePending = false } else { h.lastForegroundVM = "" h.promotePending = true } } } func (h *keymapHook) handleWindowNameChange(hwnd uintptr) { h.syncSnapshot() fg := h.lookupForegroundWindow() if hwnd == 0 || hwnd != fg { return } liveVM := h.lookupWindowVM(fg) if liveVM == "" { return } title := h.lookupWindowTitle(fg) if fg == h.lastForegroundHWND && title != "" && title == h.lastForegroundTitle { return } // When SDL3 re-grabs the keyboard in an already-focused VM window, it // updates the window title right after SDL_SetWindowKeyboardGrab. Reset // tracked modifier state on real title transitions (clearing any physical // key-up SDL3 may have swallowed before we re-promoted) and jump back above // SDL3 in the WH_KEYBOARD_LL chain. if h.syncForegroundTitle(fg) { h.resetTrackedKeys() } if h.doPromoteHook() { h.lastForegroundVM = liveVM h.promotePending = false } else { h.lastForegroundVM = "" h.promotePending = true } h.doSyncTimer() } func (h *keymapHook) ensureWinEventHooks(liveVM string) { if h.winEventHook == 0 { if hk := h.doInstallWinEvent(eventSystemForeground); hk != 0 { h.winEventHook = hk if liveVM != "" { h.promotePending = true } } } if h.nameChangeHook == 0 { if hk := h.doInstallWinEvent(eventObjectNameChange); hk != 0 { h.nameChangeHook = hk if liveVM != "" { h.promotePending = true } } } } func (h *keymapHook) handleForegroundChange() { h.syncSnapshot() fg := h.lookupForegroundWindow() vm := h.lookupWindowVM(fg) h.ensureWinEventHooks(vm) h.applyForegroundFocus(fg, vm, false) h.doSyncTimer() } func (h *keymapHook) promoteHook() bool { if h.hook == 0 || h.swappingHook { return false } h.swappingHook = true h.swapSeen = swapDedup{} defer func() { h.swappingHook = false h.swapSeen = swapDedup{} }() newHook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), h.module, 0) if newHook == 0 { return false } old := h.hook h.hook = newHook procUnhookWindowsHookEx.Call(old) prioritizeFullscreenHotkeyHook() return true } func (h *keymapHook) syncSnapshot() { if h.service == nil { return } if next := h.service.keymapState.Load(); next != h.snapshot { h.snapshot = next h.emitKeys(h.engine.SetRules(next.rules)) h.prunePressTimes() } } func (h *keymapHook) vmForWindow(hwnd uintptr) string { if hwnd == 0 || h.snapshot == nil { return "" } var pid uint32 procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) return h.snapshot.targets[pid] } func (h *keymapHook) lookupForegroundWindow() uintptr { if h.foregroundWindowFn != nil { return h.foregroundWindowFn() } window, _, _ := procGetForegroundWindow.Call() return window } func (h *keymapHook) lookupWindowVM(hwnd uintptr) string { if h.vmForWindowFn != nil { return h.vmForWindowFn(hwnd) } return h.vmForWindow(hwnd) } func (h *keymapHook) lookupWindowTitle(hwnd uintptr) string { if h.windowTitleFn != nil { return h.windowTitleFn(hwnd) } if hwnd == 0 { return "" } var buf [256]uint16 n, _, _ := procKeymapGetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) if n == 0 { return "" } return syscall.UTF16ToString(buf[:n]) } func (h *keymapHook) doInstallWinEvent(event uint32) uintptr { if h.installWinEventFn != nil { return h.installWinEventFn(event) } hk, _, _ := procSetWinEventHook.Call( uintptr(event), uintptr(event), 0, keymapWinEventCallback(), 0, 0, wineventOutOfContext, ) return hk } func (h *keymapHook) doPromoteHook() bool { if h.promoteFn != nil { return h.promoteFn() } return h.promoteHook() } func (h *keymapHook) emitKeys(keys []EmittedKey) { if len(keys) == 0 { return } if h.emitFn != nil { h.emitFn(keys) return } sendMappedKeys(keys) } func (h *keymapHook) doSyncTimer() { if h.syncTimerFn != nil { h.syncTimerFn() return } h.syncTimer() } func (h *keymapHook) handleKeyEvent(message uintptr, kbd *kbdLLHookStruct) bool { sig := kbdEventSig{ message: message, vk: kbd.vkCode, scan: kbd.scanCode, flags: kbd.flags, time: kbd.time, } if h.swappingHook && h.swapSeen.valid && h.swapSeen.sig == sig { return h.swapSeen.suppressed } h.syncSnapshot() modifier := hostModifiers[kbd.vkCode] != "" vm := "" if modifier || h.engine.heldVM != "" { vm = h.lookupWindowVM(h.lookupForegroundWindow()) h.emitKeys(h.engine.ReleaseIfFocusLost(vm)) h.prunePressTimes() } suppress := false if modifier { up := message == wmKeyUp || message == wmSysKeyUp _, hadMapped := h.engine.activeMapped[kbd.vkCode] var emit []EmittedKey suppress, emit = h.engine.ProcessEvent(KeyEvent{ VK: kbd.vkCode, ScanCode: kbd.scanCode, Up: up, }, vm, vm != "") if !up && !hadMapped { if mapped, ok := h.engine.activeMapped[kbd.vkCode]; ok && mapped.VK != 0 { if h.activePressTime == nil { h.activePressTime = make(map[uint32]uint32) } h.activePressTime[kbd.vkCode] = kbd.time } } h.prunePressTimes() h.emitKeys(emit) h.doSyncTimer() } if h.swappingHook { h.swapSeen = swapDedup{valid: true, sig: sig, suppressed: suppress} } return suppress } func keymapKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) uintptr { if code == hcAction && kbd != nil && !(kbd.flags&llkhfInjected != 0 && kbd.dwExtraInfo == reimsInjectedInputMagic) { switch message { case wmKeyDown, wmSysKeyDown, wmKeyUp, wmSysKeyUp: if h := activeKeymapHook.Load(); h != nil && h.handleKeyEvent(message, kbd) { return 1 } } } result, _, _ := procCallNextHookEx.Call(0, uintptr(code), message, uintptr(unsafe.Pointer(kbd))) return result } func keymapPhysicalDown(vk uint32) bool { state, _, _ := procKeymapAsyncKeyState.Call(uintptr(vk)) return state&0x8000 != 0 } func keymapInputDesktopAccessible() bool { desk, _, _ := procOpenInputDesktop.Call(0, 0, desktopReadObjects) if desk == 0 { return false } procCloseDesktop.Call(desk) return true } func (h *keymapHook) desiredTimerInterval() uint32 { if h.engine.HasTrackedKeys() { return keymapActiveTimerMS } if h.winEventHook == 0 || h.nameChangeHook == 0 || h.promotePending { return keymapFallbackTimerMS } return 0 } func (h *keymapHook) syncTimer() { desired := h.desiredTimerInterval() if desired == h.timerInterval && (desired == 0) == (h.timer == 0) { return } if h.timer != 0 { procKeymapKillTimer.Call(0, h.timer) h.timer = 0 h.timerInterval = 0 } if desired != 0 { h.timer, _, _ = procKeymapSetTimer.Call(0, 0, uintptr(desired), 0) if h.timer != 0 { h.timerInterval = desired } } } func sendMappedKeys(keys []EmittedKey) { if len(keys) == 0 { return } inputs := make([]winKeyboardInput, len(keys)) for i, key := range keys { input := &inputs[i] input.inputType = 1 // INPUT_KEYBOARD input.keyboard.vk = key.VK input.keyboard.scan = key.Scan input.keyboard.extra = reimsInjectedInputMagic if key.Extended { input.keyboard.flags |= 1 // KEYEVENTF_EXTENDEDKEY } if key.Up { input.keyboard.flags |= 2 // KEYEVENTF_KEYUP } } procSendInput.Call(uintptr(len(inputs)), uintptr(unsafe.Pointer(&inputs[0])), unsafe.Sizeof(inputs[0])) } func (h *keymapHook) refresh() { procPostThreadMessageW.Call(h.threadID, wmKeymapRefresh, 0, 0) } func (h *keymapHook) Close() { h.closeOnce.Do(func() { procPostThreadMessageW.Call(h.threadID, wmQuit, 0, 0) <-h.done }) }