Files
Reims-Go/internal/host/input_service_windows.go

202 lines
4.8 KiB
Go

//go:build windows
package host
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
const (
whMouseLL = 14
wmMouseWheel = 0x020A
wmMouseHWheel = 0x020E
inputMouse = 0
mouseEventfWheel = 0x0800
mouseEventfHWheel = 0x01000
llmhfInjected = 0x00000001
gaRoot = 2
// reimsInjectedInputMagic tags re-emitted wheel events so the hook ignores
// its own inverted events and never loops (§5.4).
reimsInjectedInputMagic uintptr = 0x5245494D // "REIM"
)
var (
procSendInput = user32.NewProc("SendInput")
procWindowFromPoint = user32.NewProc("WindowFromPoint")
procGetAncestor = user32.NewProc("GetAncestor")
activeMouseInputService atomic.Pointer[InputService]
mouseHookCBOnce sync.Once
mouseHookCB uintptr
)
type point struct {
X int32
Y int32
}
type msLLHookStruct struct {
pt point
mouseData uint32
flags uint32
time uint32
dwExtraInfo uintptr
}
// winMouseInput mirrors Win32 INPUT for INPUT_MOUSE on amd64 (40 bytes total).
type winMouseInput struct {
inputType uint32
_ [0]uintptr // Align the INPUT union on both 32-bit and 64-bit.
dx int32
dy int32
mouseData uint32
dwFlags uint32
time uint32
dwExtraInfo uintptr
}
func getMouseHookCallback() uintptr {
mouseHookCBOnce.Do(func() {
mouseHookCB = syscall.NewCallback(mouseLowLevelProc)
})
return mouseHookCB
}
func mouseLowLevelProc(nCode int32, wParam uintptr, ms *msLLHookStruct) uintptr {
if nCode == hcAction && ms != nil && (wParam == wmMouseWheel || wParam == wmMouseHWheel) {
// Pass through our own injected events without recursion.
if !((ms.flags&llmhfInjected) != 0 && ms.dwExtraInfo == reimsInjectedInputMagic) {
if svc := activeMouseInputService.Load(); svc != nil {
if target, ok := svc.matchTargetAtPoint(ms.pt); ok {
delta := int16(ms.mouseData >> 16)
horizontal := wParam == wmMouseHWheel
rulesPtr := svc.rules.Load()
if rulesPtr != nil {
if newDelta, transformed := EvalWheelFilter(*rulesPtr, target.VMName, horizontal, delta); transformed {
if injectWheelEvent(horizontal, newDelta) {
return 1
}
}
}
}
}
}
}
r, _, _ := procCallNextHookEx.Call(0, uintptr(nCode), wParam, uintptr(unsafe.Pointer(ms)))
return r
}
func injectWheelEvent(horizontal bool, delta int16) bool {
flags := uint32(mouseEventfWheel)
if horizontal {
flags = mouseEventfHWheel
}
in := winMouseInput{
inputType: inputMouse,
mouseData: uint32(int32(delta)),
dwFlags: flags,
dwExtraInfo: reimsInjectedInputMagic,
}
r, _, _ := procSendInput.Call(1, uintptr(unsafe.Pointer(&in)), unsafe.Sizeof(in))
return r == 1
}
func (s *InputService) matchTargetAtPoint(pt point) (IMETarget, bool) {
m := s.targetByPID.Load()
if m == nil || len(*m) == 0 {
return IMETarget{}, false
}
var hwnd uintptr
if unsafe.Sizeof(uintptr(0)) == 8 {
packed := uintptr(uint32(pt.X)) | (uintptr(uint32(pt.Y)) << 32)
hwnd, _, _ = procWindowFromPoint.Call(packed)
if hwnd != 0 {
if root, _, _ := procGetAncestor.Call(hwnd, gaRoot); root != 0 {
hwnd = root
}
}
}
if hwnd == 0 {
hwnd, _, _ = procGetForegroundWindow.Call()
}
if hwnd == 0 {
return IMETarget{}, false
}
var pid uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
if pid == 0 {
return IMETarget{}, false
}
t, ok := (*m)[pid]
return t, ok
}
type mouseWheelHook struct {
svc *InputService
threadID uint32
done chan struct{}
closeOnce sync.Once
}
func startMouseWheelHook(svc *InputService) (*mouseWheelHook, error) {
h := &mouseWheelHook{
svc: svc,
done: make(chan struct{}),
}
activeMouseInputService.Store(svc)
ready := make(chan error, 1)
go h.hookThread(ready)
if err := <-ready; err != nil {
activeMouseInputService.CompareAndSwap(svc, nil)
return nil, err
}
return h, nil
}
func (h *mouseWheelHook) hookThread(ready chan<- error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(h.done)
tid, _, _ := procGetCurrentThreadId.Call()
h.threadID = uint32(tid)
var msg winMsg
_, _, _ = procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove)
hMod, _, _ := procGetModuleHandleW.Call(0)
hhook, _, err := procSetWindowsHookExW.Call(whMouseLL, getMouseHookCallback(), hMod, 0)
if hhook == 0 {
ready <- fmt.Errorf("SetWindowsHookExW(WH_MOUSE_LL): %w", err)
return
}
defer procUnhookWindowsHookEx.Call(hhook)
ready <- nil
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) <= 0 {
return
}
}
}
func (h *mouseWheelHook) Close() {
if h == nil {
return
}
h.closeOnce.Do(func() {
activeMouseInputService.CompareAndSwap(h.svc, nil)
if h.threadID != 0 {
_, _, _ = procPostThreadMessageW.Call(uintptr(h.threadID), wmQuit, 0, 0)
}
<-h.done
})
}