Files
Reims-Go/internal/host/keymap_windows.go
T

226 lines
5.7 KiB
Go

//go:build windows
package host
import (
"runtime"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
const (
llkhfInjected = 0x10
wmKeymapRefresh = 0x8001
wmTimer = 0x0113
desktopReadObjects = 0x0001
)
var (
procKeymapSetTimer = user32.NewProc("SetTimer")
procKeymapKillTimer = user32.NewProc("KillTimer")
procKeymapAsyncKeyState = user32.NewProc("GetAsyncKeyState")
procOpenInputDesktop = user32.NewProc("OpenInputDesktop")
procCloseDesktop = user32.NewProc("CloseDesktop")
keymapCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapKeyboardProc) })
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 keymapHook struct {
service *InputService
threadID uintptr
done chan struct{}
engine *KeymapEngine
snapshot *keymapSnapshot
timer uintptr
inputDesktopAvailable bool
closeOnce sync.Once
}
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
}
}
module, _, _ := procGetModuleHandleW.Call(0)
hook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), module, 0)
if hook == 0 {
ready <- false
return
}
defer procUnhookWindowsHookEx.Call(hook)
defer func() { sendMappedKeys(h.engine.ReleaseAll()) }()
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 {
h.syncSnapshot()
if h.inputDesktopAvailable && !keymapInputDesktopAccessible() {
sendMappedKeys(h.engine.Reset())
} else {
sendMappedKeys(h.engine.ReconcilePhysical(keymapPhysicalDown))
if h.engine.heldVM != "" {
sendMappedKeys(h.engine.ReleaseIfFocusLost(h.foregroundVM()))
}
}
h.syncTimer()
}
}
}
func (h *keymapHook) syncSnapshot() {
if next := h.service.keymapState.Load(); next != h.snapshot {
h.snapshot = next
sendMappedKeys(h.engine.SetRules(next.rules))
}
}
func (h *keymapHook) foregroundVM() string {
window, _, _ := procGetForegroundWindow.Call()
if window == 0 {
return ""
}
var pid uint32
procGetWindowThreadProcessId.Call(window, uintptr(unsafe.Pointer(&pid)))
return h.snapshot.targets[pid]
}
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.syncSnapshot()
modifier := hostModifiers[kbd.vkCode] != ""
vm := ""
if modifier || h.engine.heldVM != "" {
vm = h.foregroundVM()
sendMappedKeys(h.engine.ReleaseIfFocusLost(vm))
}
if !modifier {
break
}
suppress, emit := h.engine.ProcessEvent(KeyEvent{
VK: kbd.vkCode, ScanCode: kbd.scanCode, Up: message == wmKeyUp || message == wmSysKeyUp,
}, vm, vm != "")
sendMappedKeys(emit)
h.syncTimer()
if suppress {
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) syncTimer() {
if h.engine.HasTrackedKeys() {
if h.timer == 0 {
h.timer, _, _ = procKeymapSetTimer.Call(0, 0, 50, 0)
}
} else if h.timer != 0 {
procKeymapKillTimer.Call(0, h.timer)
h.timer = 0
}
}
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
})
}