Files
Reims-Go/internal/host/fullscreen_hotkey_windows.go
T
NwflowerandClaude Opus 5.5 b39c240677 fix(input): keep the fullscreen shortcut working in captured VM windows
Put the hook back above key mapping and SDL3 whenever either reinstalls
its own hook, and stop treating modifiers swallowed by SDL3 as released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:40:30 -07:00

283 lines
7.5 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]
)
const (
wmPrioritizeFullscreenHotkey = 0x8002
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 keymapInputDesktopAccessible() {
keymapActive := activeKeymapHook.Load() != nil
for _, vk := range fullscreenModifierVKs {
// Ctrl may already be held by key mapping when this hook starts.
if keymapActive && (vk == vkLCtrl || vk == vkRCtrl) {
continue
}
h.physical.handle(vk, keymapPhysicalDown(vk), false, keymapActive && hostModifiers[vk] != "")
}
}
timer, _, _ := procKeymapSetTimer.Call(0, 0, fullscreenHotkeyTimerMS, 0)
if timer == 0 {
ready <- false
return
}
defer procKeymapKillTimer.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. Key mapping and SDL3 both swallow modifiers,
// so this hook must sit above them to see physical keys.
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
}
switch msg.message {
case wmTimer:
if !keymapInputDesktopAccessible() {
h.resetKeys()
continue
}
window, title := h.foregroundVMWindow()
h.reconcilePhysical(window != 0)
if h.needsPromotion(window, title) && !promote() {
return
}
case wmPrioritizeFullscreenHotkey:
if !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 prioritizeFullscreenHotkeyHook() {
if h := activeFullscreenHotkey.Load(); h != nil {
procPostThreadMessageW.Call(h.threadID, wmPrioritizeFullscreenHotkey, 0, 0)
}
}
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, activeKeymapHook.Load() != nil && hostModifiers[vk] != "")
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 !keymapInputDesktopAccessible() {
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, _, _ := procKeymapGetWindowTextW.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 && !keymapPhysicalDown(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] && !keymapPhysicalDown(vk) {
h.physical.down[i] = false
}
}
}
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)
}
}
}