fix: release app window input on close

This commit is contained in:
YXC0915 committed 2026-12-03 07:33:21 +08:00
1 parent 9f6c9aa90e
commit e281e43d07
6 files changed
+80 -32

No files matched your search

+1 -1
View File
@@ -128,7 +128,7 @@ func (a *App) stopAppWindow() {
return
}
run.cancel()
timer := time.NewTimer(2 * time.Second)
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
select {
case <-run.done:
+27 -15
View File
@@ -7,8 +7,10 @@ import (
"fmt"
"image"
"image/draw"
"maps"
"os"
"path/filepath"
"slices"
"sync"
"time"
@@ -34,6 +36,7 @@ type Console interface {
MouseButton(context.Context, string, string, bool) error
MouseScroll(context.Context, string, int, bool) error
SendKey(context.Context, string, string, bool) error
ReleaseInputs(context.Context, string, []string, []string) error
}
type SessionOptions struct {
@@ -230,7 +233,7 @@ func (s *session) run(ctx context.Context, title string, first ViewerFrame) erro
var firstCaptureError time.Time
go func() {
defer close(done)
if err := s.forwardInput(ctx, queue); err != nil && ctx.Err() == nil {
if err := s.forwardInput(ctx, queue); err != nil && !errors.Is(err, context.Canceled) {
fail(err)
}
}()
@@ -264,23 +267,28 @@ func (s *session) run(ctx context.Context, title string, first ViewerFrame) erro
}
}
func (s *session) forwardInput(ctx context.Context, queue *inputQueue) error {
func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result error) {
keys := make(map[string]bool)
buttons := make(map[string]bool)
release := func() {
// A local window can close while the guest holds a modifier or button.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
release := func(timeout time.Duration) error {
if len(keys)+len(buttons) == 0 {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
for key := range keys {
_ = s.Console.SendKey(ctx, s.VMDir, key, false)
delete(keys, key)
}
for button := range buttons {
_ = s.Console.MouseButton(ctx, s.VMDir, button, false)
delete(buttons, button)
err := s.Console.ReleaseInputs(ctx, s.VMDir, slices.Sorted(maps.Keys(keys)), slices.Sorted(maps.Keys(buttons)))
if err == nil {
clear(keys)
clear(buttons)
}
return err
}
defer release()
defer func() {
// Allow an in-flight QEMU readback to finish before releasing input.
if err := release(4 * time.Second); err != nil {
result = fmt.Errorf("release app window input: %w", err)
}
}()
checkWindow := time.NewTicker(500 * time.Millisecond)
defer checkWindow.Stop()
var missingSince time.Time
@@ -294,7 +302,9 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) error {
missingSince = time.Time{}
} else if missingSince.IsZero() {
missingSince = time.Now()
release()
if err := release(frameTimeout); err != nil {
return fmt.Errorf("release app window input: %w", err)
}
wheel = 0
} else if time.Since(missingSince) > 4*time.Second {
return ErrNoWindow
@@ -302,7 +312,9 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) error {
case <-queue.ready:
event := queue.pop()
if event.Kind == ViewerClose || (event.Kind == ViewerFocus && !event.Down) {
release()
if err := release(frameTimeout); err != nil {
return fmt.Errorf("release app window input: %w", err)
}
wheel = 0
continue
}
+6
View File
@@ -169,6 +169,12 @@ func (m *Manager) SendKey(ctx context.Context, vmDir, key string, down bool) err
})
}
func (m *Manager) ReleaseInputs(ctx context.Context, vmDir string, keys, buttons []string) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.ReleaseInputs(conn, keys, buttons)
})
}
func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error {
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
if err := qmp.MouseButton(conn, button, true); err != nil {
+27 -16
View File
@@ -55,32 +55,43 @@ function activeWindow() {
}
function postReport(url, token, generation, window) {
const request = $.NSMutableURLRequest.requestWithURL(url)
request.HTTPMethod = $('POST')
request.timeoutInterval = 1
request.setValueForHTTPHeaderField($('Bearer ' + token), $('Authorization'))
request.setValueForHTTPHeaderField($('application/json'), $('Content-Type'))
request.HTTPBody = $(JSON.stringify({generation, window})).dataUsingEncoding($.NSUTF8StringEncoding)
const response = Ref()
$.NSURLConnection.sendSynchronousRequestReturningResponseError(request, response, null)
const http = response[0]
return http && !http.isNil() ? Number(http.statusCode) : 0
const config = [
'url = ' + JSON.stringify(url),
'header = ' + JSON.stringify('Authorization: Bearer ' + token),
'header = "Content-Type: application/json"',
'data-raw = ' + JSON.stringify(JSON.stringify({generation, window})),
]
const task = $.NSTask.alloc.init
const input = $.NSPipe.pipe
const output = $.NSPipe.pipe
task.launchPath = '/usr/bin/curl'
task.arguments = $(['-q', '--noproxy', '*', '-sm', '1', '-o', '/dev/null', '-w', '%{http_code}', '-K', '-'])
task.standardInput = input
task.standardOutput = output
task.standardError = $.NSFileHandle.fileHandleWithNullDevice
task.launch
try { input.fileHandleForWriting.writeData($(config.join('\n') + '\n').dataUsingEncoding($.NSUTF8StringEncoding)) }
finally { input.fileHandleForWriting.closeFile }
const data = output.fileHandleForReading.readDataToEndOfFile
task.waitUntilExit
return task.terminationStatus === 0 ? Number($.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js) : 0
}
function run(args) {
const generation = Number(args[0])
if (!Number.isSafeInteger(generation) || generation <= 0) return
const env = $.NSProcessInfo.processInfo.environment
const host = env.objectForKey($('REIMS_HOST_URL'))
const token = env.objectForKey($('REIMS_TOKEN'))
if (!host || host.isNil() || !token || token.isNil()) return
const url = $.NSURL.URLWithString($(host.js + '/v1/active-window'))
if (!url || url.isNil()) return
const hostValue = env.objectForKey($('REIMS_HOST_URL'))
const tokenValue = env.objectForKey($('REIMS_TOKEN'))
const host = hostValue && !hostValue.isNil() ? hostValue.js.replace(/\/+$/, '') : ''
const token = tokenValue && !tokenValue.isNil() ? tokenValue.js : ''
if (!/^http:\/\/(?:[a-z0-9.-]+|\[[0-9a-f:]+\]):\d{1,5}$/i.test(host) || !token || /[\r\n\0]/.test(token)) return
const url = host + '/v1/active-window'
while (true) {
let window
try { window = activeWindow() } catch (_) { window = null }
let status
try { status = postReport(url, token.js, generation, window) } catch (_) { status = 0 }
try { status = postReport(url, token, generation, window) } catch (_) { status = 0 }
if (status === 401 || status === 403 || status === 409) return
delay(status === 204 ? 0.25 : 1)
}
+1
View File
@@ -27,6 +27,7 @@ type ComputerUseService interface {
MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error
PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error
SendKey(ctx context.Context, vmDir, key string, down bool) error
ReleaseInputs(ctx context.Context, vmDir string, keys, buttons []string) error
}
func defComputerUse(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
+18
View File
@@ -117,6 +117,24 @@ func SendKey(q Executor, key string, down bool) error {
return sendKeys(q, down, key)
}
// ReleaseInputs clears held keys and pointer buttons in one QMP input report.
func ReleaseInputs(q Executor, keys, buttons []string) error {
if q == nil {
return errors.New("QMP session is unavailable")
}
if len(keys)+len(buttons) == 0 {
return nil
}
events := make([]map[string]any, 0, len(keys)+len(buttons))
for _, key := range keys {
events = append(events, keyEvent(key, false))
}
for _, button := range buttons {
events = append(events, mouseButtonEvent(button, false))
}
return q.Execute("input-send-event", map[string]any{"events": events})
}
// TypeStrokes presses and releases each key in turn, holding it for hold and
// waiting gap before the next, so the guest's USB keyboard queue never fills.
// On any error or cancel it releases Shift so no modifier is left held down.