package app import ( "context" "sort" "time" "github.com/Nwflower/reims-go/internal/driver" ) // heldInputIdleTimeout bounds how long a plugin may leave a key or a pointer // button held in a guest without touching that console again. A plugin that // stops calling without releasing must not leave the guest stuck with a // modifier down, so the record carries its own timer instead of waiting for the // plugin's next call. var heldInputIdleTimeout = 2 * time.Minute // heldReleaseRetryTimeout is how long the host waits before trying a fallback // release again. A release can fail while the VM is still running, for example // while its console is busy, and a plugin that already exited will never make // the next call that would otherwise retry it. var heldReleaseRetryTimeout = 30 * time.Second // heldReleaseTimeout bounds one fallback release, which runs while the plugin // that held the input may already be gone. const heldReleaseTimeout = 5 * time.Second // heldInputs is what one plugin currently holds in one guest. QEMU and a // driver's own console keep a pressed key or button down in the guest until a // release arrives, and that state does not depend on the connection, so the // host has to remember what it pressed and lift it when the plugin can no // longer do so. type heldInputs struct { keys map[string]bool buttons map[string]bool touched time.Time timer *time.Timer // generation counts every change to this record. A release that finishes // after the plugin pressed something new compares it with the generation it // snapshotted, so it never deletes a press it did not lift. generation uint64 } // noteHeldKey records or forgets one key transition. code must already be a // QKeyCode. func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() held := a.heldLocked(pluginID, vmKey) if down { held.keys[code] = true } else { delete(held.keys, code) } a.touchHeldLocked(pluginID, vmKey, held) } // noteHeldButton records or forgets one pointer button transition. func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() held := a.heldLocked(pluginID, vmKey) if down { held.buttons[button] = true } else { delete(held.buttons, button) } a.touchHeldLocked(pluginID, vmKey, held) } // heldLocked returns the record for one plugin and VM, creating it when // needed. The caller holds computerUseHeldMu. func (a *App) heldLocked(pluginID, vmKey string) *heldInputs { if a.hostAPI.computerUseHeld == nil { a.hostAPI.computerUseHeld = map[string]map[string]*heldInputs{} } byVM := a.hostAPI.computerUseHeld[pluginID] if byVM == nil { byVM = map[string]*heldInputs{} a.hostAPI.computerUseHeld[pluginID] = byVM } held := byVM[vmKey] if held == nil { held = &heldInputs{keys: map[string]bool{}, buttons: map[string]bool{}} byVM[vmKey] = held } return held } // touchHeldLocked marks the record as changed, drops it when it holds nothing // and rearms its idle timer otherwise. The caller holds computerUseHeldMu. func (a *App) touchHeldLocked(pluginID, vmKey string, held *heldInputs) { held.generation++ held.touched = time.Now() if len(held.keys)+len(held.buttons) == 0 { a.pruneHeldLocked(pluginID, vmKey) return } a.armHeldTimerLocked(pluginID, vmKey, held, heldInputIdleTimeout) } // armHeldTimerLocked replaces the record's timer with one that fires after d. // The caller holds computerUseHeldMu. func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d time.Duration) { if held.timer != nil { held.timer.Stop() } held.timer = time.AfterFunc(d, func() { a.releaseHeldForVM(pluginID, vmKey) }) } // pruneHeldLocked drops a record that holds nothing, so an idle plugin leaves // no state behind. The caller holds computerUseHeldMu. func (a *App) pruneHeldLocked(pluginID, vmKey string) { byVM := a.hostAPI.computerUseHeld[pluginID] if byVM == nil { return } if held := byVM[vmKey]; held != nil { if held.timer != nil { held.timer.Stop() held.timer = nil } delete(byVM, vmKey) } if len(byVM) == 0 { delete(a.hostAPI.computerUseHeld, pluginID) } } // heldSnapshot returns what one plugin holds in one VM, sorted, with the // generation it was read at. func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() byVM := a.hostAPI.computerUseHeld[pluginID] if byVM == nil { return nil, nil, 0 } held := byVM[vmKey] if held == nil { return nil, nil, 0 } for code := range held.keys { keys = append(keys, code) } for button := range held.buttons { buttons = append(buttons, button) } sort.Strings(keys) sort.Strings(buttons) return keys, buttons, held.generation } // heldGeneration returns the record's current generation, or 0 when there is // no record. func (a *App) heldGeneration(pluginID, vmKey string) uint64 { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() if held := a.hostAPI.computerUseHeld[pluginID][vmKey]; held != nil { return held.generation } return 0 } // heldVMs lists the VMs one plugin currently holds input in. func (a *App) heldVMs(pluginID string) map[string]bool { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() out := map[string]bool{} for vmKey := range a.hostAPI.computerUseHeld[pluginID] { out[vmKey] = true } return out } // dropHeld forgets the named keys and buttons of one plugin and VM. It is used // when the caller itself named what it lifted, so there is no snapshot to // compare with. func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() held := a.hostAPI.computerUseHeld[pluginID][vmKey] if held == nil { return } for _, code := range keys { delete(held.keys, code) } for _, button := range buttons { delete(held.buttons, button) } a.touchHeldLocked(pluginID, vmKey, held) } // dropHeldIfGeneration forgets the named keys and buttons only when the record // has not changed since generation was read. A record that changed in the // meantime may hold a press this release did not lift, so it keeps everything // and its timer releases it later. func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() held := a.hostAPI.computerUseHeld[pluginID][vmKey] if held == nil { return false } if held.generation != generation { return false } for _, code := range keys { delete(held.keys, code) } for _, button := range buttons { delete(held.buttons, button) } a.touchHeldLocked(pluginID, vmKey, held) return true } // rearmHeld schedules another fallback release for a record whose release // failed while the VM is still running. func (a *App) rearmHeld(pluginID, vmKey string) { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() held := a.hostAPI.computerUseHeld[pluginID][vmKey] if held == nil || len(held.keys)+len(held.buttons) == 0 { return } a.armHeldTimerLocked(pluginID, vmKey, held, heldReleaseRetryTimeout) } // forgetHeld drops the record of one plugin and VM without touching the // guest. It is for a VM that is not running: nothing in a powered-off guest // can still be held, and a release sent later could lift a key the user is // pressing after the VM starts again. func (a *App) forgetHeld(pluginID, vmKey string) { a.hostAPI.heldMu.Lock() defer a.hostAPI.heldMu.Unlock() a.pruneHeldLocked(pluginID, vmKey) } // heldConsoleRoute resolves the console a held release has to go through. It // reports false when the VM is gone or not running, because then nothing can // be held in it. func (a *App) heldConsoleRoute(vmKey string) (consoleRoute, bool) { ref, ok := driver.ParseVMRef(vmKey) if !ok { return consoleRoute{}, false } vm, err := a.resolveVMInfo(ref.DriverID, ref.Name) if err != nil { return consoleRoute{}, false } current, ok := a.polledVMForDriver(vm.DriverID, vm.Name) if !ok || current.State != "running" { return consoleRoute{}, false } if vm.Directory == "" { vm.Directory = current.Dir } route, err := a.resolveConsoleRoute(vm) if err != nil { return consoleRoute{}, false } route.vm = vm return route, true } // releaseHeldForVM lifts everything one plugin still holds in one VM. It is the // fallback for a plugin that can no longer release: its process exited, its // scope was disposed, or it stopped calling. A VM that is not running has // nothing held, so its record is dropped instead of retried. A release that // fails while the VM is running keeps its record and is retried. func (a *App) releaseHeldForVM(pluginID, vmKey string) { keys, buttons, generation := a.heldSnapshot(pluginID, vmKey) if len(keys)+len(buttons) == 0 { a.forgetHeld(pluginID, vmKey) return } route, ok := a.heldConsoleRoute(vmKey) if !ok { a.forgetHeld(pluginID, vmKey) return } // The plugin may have pressed something since the snapshot; lifting now // would undo that press, so wait for the record to settle instead. if a.heldGeneration(pluginID, vmKey) != generation { a.rearmHeld(pluginID, vmKey) return } ctx, cancel := context.WithTimeout(context.Background(), heldReleaseTimeout) defer cancel() if err := a.consoleRelease(ctx, route, keys, buttons); err != nil { // The VM may have stopped while the release was in flight. if _, stillRunning := a.heldConsoleRoute(vmKey); !stillRunning { a.forgetHeld(pluginID, vmKey) return } a.emitLog("plugin", "Could not release input held by "+pluginID+" in "+vmKey+": "+err.Error()) a.rearmHeld(pluginID, vmKey) return } if !a.dropHeldIfGeneration(pluginID, vmKey, keys, buttons, generation) { // Something was pressed while the release was in flight. The record // keeps it, and its timer lifts it if the plugin goes quiet again. a.rearmHeld(pluginID, vmKey) } } // releaseHeldForPlugin lifts everything one plugin holds in any VM. func (a *App) releaseHeldForPlugin(pluginID string) { for vmKey := range a.heldVMs(pluginID) { a.releaseHeldForVM(pluginID, vmKey) } }