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

288 lines
7.6 KiB
Go

//go:build windows
package host
import (
"log"
"runtime"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
var (
fullscreenHotkeyCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(fullscreenKeyboardProc) })
activeFullscreenHotkey atomic.Pointer[fullscreenHotkeyHook]
procSetTimer = user32.NewProc("SetTimer")
procKillTimer = user32.NewProc("KillTimer")
procGetAsyncKeyState = user32.NewProc("GetAsyncKeyState")
procOpenInputDesktop = user32.NewProc("OpenInputDesktop")
procCloseDesktop = user32.NewProc("CloseDesktop")
procGetWindowTextW = user32.NewProc("GetWindowTextW")
)
const (
wmTimer = 0x0113
llkhfInjected = 0x10
desktopReadObjects = 0x0001
fullscreenHotkeyTimerMS = 50
// SDL3 may install its hook a moment after the VM window takes focus.
fullscreenHotkeySettleTicks = 10
)
type fullscreenHotkeyHook struct {
service *FullscreenHotkeyService
threadID uintptr
done chan struct{}
triggers chan fullscreenHotkeyEvent
matcher FullscreenHotkeyMatcher
physical fullscreenPhysicalModifiers
pending sync.Map
foreground uintptr
title string
settleTicks int
}
type fullscreenHotkeyEvent struct {
target IMETarget
hotkey FullscreenHotkey
hwnd uintptr
}
func startFullscreenHotkeyHook(service *FullscreenHotkeyService) *fullscreenHotkeyHook {
h := &fullscreenHotkeyHook{
service: service,
done: make(chan struct{}),
triggers: make(chan fullscreenHotkeyEvent, 16),
}
ready := make(chan bool)
go h.run(ready)
if !<-ready {
<-h.done
return nil
}
go h.dispatch()
return h
}
func (h *fullscreenHotkeyHook) run(ready chan<- bool) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(h.done)
h.threadID, _, _ = procGetCurrentThreadId.Call()
var msg winMsg
procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove)
if !activeFullscreenHotkey.CompareAndSwap(nil, h) {
ready <- false
return
}
defer activeFullscreenHotkey.CompareAndSwap(h, nil)
if inputDesktopAccessible() {
for _, vk := range fullscreenModifierVKs {
h.physical.handle(vk, physicalKeyDown(vk), false)
}
}
timer, _, _ := procSetTimer.Call(0, 0, fullscreenHotkeyTimerMS, 0)
if timer == 0 {
ready <- false
return
}
defer procKillTimer.Call(0, timer)
module, _, _ := procGetModuleHandleW.Call(0)
hook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, fullscreenHotkeyCallback(), module, 0)
if hook == 0 {
ready <- false
return
}
defer func() { procUnhookWindowsHookEx.Call(hook) }()
// The newest hook runs first. This hook must run before SDL3 swallows modifiers.
promote := func() bool {
next, _, err := procSetWindowsHookExW.Call(whKeyboardLL, fullscreenHotkeyCallback(), module, 0)
if next == 0 {
log.Printf("fullscreen hotkey: SetWindowsHookExW failed while reprioritizing the keyboard hook; exiting hook loop: %v", err)
return false
}
procUnhookWindowsHookEx.Call(hook)
hook = next
return true
}
ready <- true
for {
result, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(result) <= 0 {
return
}
if msg.message == wmTimer {
if !inputDesktopAccessible() {
h.resetKeys()
continue
}
window, title := h.foregroundVMWindow()
h.reconcilePhysical(window != 0)
if h.needsPromotion(window, title) && !promote() {
return
}
}
}
}
func (h *fullscreenHotkeyHook) Close() {
procPostThreadMessageW.Call(h.threadID, wmQuit, 0, 0)
<-h.done
}
func (h *fullscreenHotkeyHook) active() bool {
select {
case <-h.done:
return false
default:
return true
}
}
func fullscreenKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) uintptr {
if code == hcAction && kbd != nil {
switch message {
case wmKeyDown, wmSysKeyDown, wmKeyUp, wmSysKeyUp:
if h := activeFullscreenHotkey.Load(); h != nil &&
h.handleKey(kbd.vkCode, message == wmKeyDown || message == wmSysKeyDown, kbd.flags&llkhfInjected != 0) {
return 1
}
}
}
result, _, _ := procCallNextHookEx.Call(0, uintptr(code), message, uintptr(unsafe.Pointer(kbd)))
return result
}
func (h *fullscreenHotkeyHook) handleKey(vk uint32, down, injected bool) bool {
h.physical.handle(vk, down, injected)
if injected {
return false
}
settings := h.service.settings.Load()
if settings == nil {
return false
}
h.matcher.setHotkey(settings.hotkey)
if vk != settings.hotkey.VK && vk != h.matcher.suppressedVK {
return false
}
if !inputDesktopAccessible() {
h.resetKeys()
return false
}
if !down || h.matcher.down || h.matcher.suppressedVK != 0 {
consume, _ := h.matcher.Handle(vk, down, false, FullscreenHotkeyMods{})
return consume
}
window, _, _ := procGetForegroundWindow.Call()
pid := windowPID(window)
target, found := settings.targets[pid]
consume, trigger := h.matcher.Handle(vk, down, found && isProcessDisplayWindow(window, pid), h.physical.mods())
if trigger {
if _, pending := h.pending.LoadOrStore(pid, struct{}{}); !pending {
select {
case h.triggers <- fullscreenHotkeyEvent{target: target, hotkey: settings.hotkey, hwnd: window}:
default:
h.pending.Delete(pid)
}
}
}
return consume
}
func (h *fullscreenHotkeyHook) resetKeys() {
h.matcher.Reset()
h.physical = fullscreenPhysicalModifiers{}
}
// foregroundVMWindow returns the focused window and its title when it belongs to a target VM.
func (h *fullscreenHotkeyHook) foregroundVMWindow() (uintptr, string) {
settings := h.service.settings.Load()
if settings == nil {
return 0, ""
}
window, _, _ := procGetForegroundWindow.Call()
if _, found := settings.targets[windowPID(window)]; !found {
return 0, ""
}
var title [256]uint16
n, _, _ := procGetWindowTextW.Call(window, uintptr(unsafe.Pointer(&title[0])), uintptr(len(title)))
return window, syscall.UTF16ToString(title[:n])
}
// needsPromotion reports when SDL3 may have put its keyboard hook above this
// one. It does so when a VM window takes focus, and again when the window
// recaptures the keyboard, which also changes the title.
func (h *fullscreenHotkeyHook) needsPromotion(window uintptr, title string) bool {
if window != h.foreground || title != h.title {
h.foreground, h.title = window, title
h.settleTicks = 0
if window != 0 {
h.settleTicks = fullscreenHotkeySettleTicks
}
return window != 0
}
if h.settleTicks == 0 {
return false
}
h.settleTicks--
return h.settleTicks == 0
}
func (h *fullscreenHotkeyHook) reconcilePhysical(vmForeground bool) {
if h.matcher.suppressedVK != 0 {
// A swallowed down does not update GetAsyncKeyState.
return
}
if h.matcher.down && !physicalKeyDown(h.matcher.Hotkey.VK) {
h.matcher.Reset()
}
if vmForeground {
// SDL3 swallows modifiers in a VM window, so GetAsyncKeyState reports
// held keys as released there.
return
}
for i, vk := range fullscreenModifierVKs {
if h.physical.down[i] && h.physical.asyncReliable[i] && !physicalKeyDown(vk) {
h.physical.down[i] = false
}
}
}
func physicalKeyDown(vk uint32) bool {
state, _, _ := procGetAsyncKeyState.Call(uintptr(vk))
return state&0x8000 != 0
}
func inputDesktopAccessible() bool {
desk, _, _ := procOpenInputDesktop.Call(0, 0, desktopReadObjects)
if desk == 0 {
return false
}
procCloseDesktop.Call(desk)
return true
}
func (h *fullscreenHotkeyHook) dispatch() {
for {
select {
case <-h.done:
return
case event := <-h.triggers:
select {
case <-h.done:
default:
settings := h.service.settings.Load()
if settings != nil && settings.hotkey == event.hotkey &&
settings.targets[event.target.PID] == event.target {
settings.onTrigger(event.target, event.hwnd)
}
}
h.pending.Delete(event.target.PID)
}
}
}