514 lines
14 KiB
Go
514 lines
14 KiB
Go
// Package appwindow presents a guest application through the VM console.
|
|
package appwindow
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
"image/draw"
|
|
"maps"
|
|
"math"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
|
"github.com/Nwflower/reims-go/internal/qmp"
|
|
"github.com/Nwflower/reims-go/internal/thumb"
|
|
)
|
|
|
|
var ErrNoWindow = errors.New("no foreground guest window reported")
|
|
var errFrameUnconfirmed = errors.New("window geometry not confirmed after capture")
|
|
|
|
const (
|
|
windowMaxAge = time.Second
|
|
frameTimeout = 800 * time.Millisecond
|
|
pasteTimeout = 4 * time.Second
|
|
maxFramePixels = 4096 * 2160
|
|
)
|
|
|
|
// Console is the host's serialized VM console, shared with its lifecycle and
|
|
// other screenshot and input callers.
|
|
type Console interface {
|
|
ScreendumpDisplay(context.Context, string, string, string, int) (string, error)
|
|
MouseMove(context.Context, string, int, int, int, int) error
|
|
MouseButtonAt(context.Context, string, int, int, int, int, string, bool) error
|
|
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 {
|
|
VMDir string
|
|
TmpDir string
|
|
Window func(time.Duration) (guesttools.ActiveWindow, time.Time, bool)
|
|
Console Console
|
|
PrepareClipboard func(context.Context) (func(), error)
|
|
OnClipboardError func(error)
|
|
}
|
|
|
|
type frameMapping struct {
|
|
window guesttools.ActiveWindow
|
|
screen image.Point
|
|
crop image.Rectangle
|
|
}
|
|
|
|
type session struct {
|
|
SessionOptions
|
|
path string
|
|
id uint32
|
|
|
|
mu sync.Mutex
|
|
mapping frameMapping
|
|
tag uint64
|
|
lastFrame time.Time
|
|
}
|
|
|
|
type inputQueue struct {
|
|
mu sync.Mutex
|
|
events []queuedInput
|
|
ready chan struct{}
|
|
focus context.Context
|
|
cancelFocus context.CancelFunc
|
|
}
|
|
|
|
type queuedInput struct {
|
|
ViewerEvent
|
|
focus context.Context
|
|
}
|
|
|
|
func (q *inputQueue) push(event ViewerEvent) bool {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
if event.Kind == ViewerFocus || event.Kind == ViewerClose {
|
|
if q.cancelFocus != nil {
|
|
q.cancelFocus()
|
|
q.focus, q.cancelFocus = nil, nil
|
|
}
|
|
if event.Kind == ViewerFocus && event.Down {
|
|
q.focus, q.cancelFocus = context.WithCancel(context.Background())
|
|
}
|
|
}
|
|
input := queuedInput{ViewerEvent: event, focus: q.focus}
|
|
last := len(q.events) - 1
|
|
if last >= 0 && q.events[last].Kind == ViewerMouseMove && event.Kind == ViewerMouseMove {
|
|
q.events[last] = input
|
|
return true
|
|
}
|
|
if len(q.events) == 64 {
|
|
return event.Kind == ViewerMouseMove
|
|
}
|
|
q.events = append(q.events, input)
|
|
if last < 0 {
|
|
q.ready <- struct{}{}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (q *inputQueue) pop() queuedInput {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
event := q.events[0]
|
|
copy(q.events, q.events[1:])
|
|
q.events[len(q.events)-1] = queuedInput{}
|
|
q.events = q.events[:len(q.events)-1]
|
|
if len(q.events) > 0 {
|
|
q.ready <- struct{}{}
|
|
}
|
|
return event
|
|
}
|
|
|
|
// Prepare waits for the initial window report and confirms capture before the
|
|
// viewer is shown. The caller must run the returned function to clean up.
|
|
func Prepare(ctx context.Context, opts SessionOptions) (func() error, error) {
|
|
initial, err := waitForWindow(ctx, opts.Window)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := os.MkdirAll(opts.TmpDir, 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
dir, err := os.MkdirTemp(opts.TmpDir, "app-window-")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s := &session{SessionOptions: opts, path: filepath.Join(dir, "frame.ppm"), id: initial.ID}
|
|
cleanup := func() {
|
|
_ = os.Remove(s.path)
|
|
_ = os.Remove(dir)
|
|
}
|
|
first, err := s.capture(ctx)
|
|
if errors.Is(err, errFrameUnconfirmed) {
|
|
retry, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
for errors.Is(err, errFrameUnconfirmed) {
|
|
select {
|
|
case <-retry.Done():
|
|
err = ErrNoWindow
|
|
case <-time.After(125 * time.Millisecond):
|
|
first, err = s.capture(retry)
|
|
}
|
|
}
|
|
cancel()
|
|
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
|
|
err = ErrNoWindow
|
|
}
|
|
}
|
|
if err != nil {
|
|
cleanup()
|
|
return nil, err
|
|
}
|
|
return func() error {
|
|
defer cleanup()
|
|
return s.run(ctx, initial.AppName, first)
|
|
}, nil
|
|
}
|
|
|
|
func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.ActiveWindow, time.Time, bool)) (guesttools.ActiveWindow, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
defer cancel()
|
|
tick := time.NewTicker(150 * time.Millisecond)
|
|
defer tick.Stop()
|
|
for {
|
|
if report, _, ok := get(windowMaxAge); ok {
|
|
return report, nil
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
|
return guesttools.ActiveWindow{}, ErrNoWindow
|
|
}
|
|
return guesttools.ActiveWindow{}, ctx.Err()
|
|
case <-tick.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
|
|
before, _, ok := s.Window(windowMaxAge)
|
|
if !ok || before.ID != s.id {
|
|
return ViewerFrame{}, ErrNoWindow
|
|
}
|
|
request, cancel := context.WithTimeout(ctx, frameTimeout)
|
|
defer os.Remove(s.path)
|
|
format, err := s.Console.ScreendumpDisplay(request, s.VMDir, s.path, "gfx", 0)
|
|
capturedAt := time.Now()
|
|
cancel()
|
|
if err != nil {
|
|
return ViewerFrame{}, err
|
|
}
|
|
size, err := thumb.Size(s.path, format)
|
|
if err != nil {
|
|
return ViewerFrame{}, err
|
|
}
|
|
if size.X < 1 || size.Y < 1 || int64(size.X)*int64(size.Y) > maxFramePixels {
|
|
return ViewerFrame{}, errors.New("guest display exceeds the app window capture size")
|
|
}
|
|
crop := guestCrop(before, size)
|
|
if crop.Empty() {
|
|
return ViewerFrame{}, ErrNoWindow
|
|
}
|
|
if err := s.confirmFrame(ctx, before, capturedAt); err != nil {
|
|
return ViewerFrame{}, err
|
|
}
|
|
frame, err := thumb.Load(s.path, format)
|
|
if err != nil {
|
|
return ViewerFrame{}, err
|
|
}
|
|
img := image.NewRGBA(crop.Sub(crop.Min))
|
|
draw.Draw(img, img.Bounds(), frame, crop.Min, draw.Src)
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
mapping := frameMapping{window: before, screen: size, crop: crop}
|
|
if s.tag == 0 || s.mapping != mapping {
|
|
s.tag++
|
|
s.mapping = mapping
|
|
}
|
|
s.lastFrame = time.Now()
|
|
return ViewerFrame{Image: img, Tag: s.tag, shape: guestViewerShape(before, size, crop)}, nil
|
|
}
|
|
|
|
func (s *session) confirmFrame(ctx context.Context, before guesttools.ActiveWindow, capturedAt time.Time) error {
|
|
// Reading the same cached report twice cannot detect a window moving between polls.
|
|
timeout := time.NewTimer(windowMaxAge)
|
|
defer timeout.Stop()
|
|
tick := time.NewTicker(15 * time.Millisecond)
|
|
defer tick.Stop()
|
|
for {
|
|
window, receivedAt, ok := s.Window(windowMaxAge)
|
|
if !ok || window != before {
|
|
return errFrameUnconfirmed
|
|
}
|
|
if receivedAt.After(capturedAt) {
|
|
return ctx.Err()
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-timeout.C:
|
|
return errFrameUnconfirmed
|
|
case <-tick.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func guestViewerShape(window guesttools.ActiveWindow, size image.Point, crop image.Rectangle) viewerShape {
|
|
scale := func(x, y int) image.Point {
|
|
return image.Pt(
|
|
int(math.Round(float64(x*size.X)/float64(window.DisplayWidth))),
|
|
int(math.Round(float64(y*size.Y)/float64(window.DisplayHeight))),
|
|
)
|
|
}
|
|
point := func(x, y int) image.Point {
|
|
return scale(window.X+x, window.Y+y).Sub(crop.Min)
|
|
}
|
|
return viewerShape{
|
|
outline: image.Rectangle{Min: point(0, 0), Max: point(window.Width, window.Height)},
|
|
// Keep the traffic lights and the outer toolbar areas available to macOS.
|
|
caption: image.Rectangle{Min: point(80, 0), Max: point(window.Width-64, 22)},
|
|
radius: scale(16, 16),
|
|
}
|
|
}
|
|
|
|
func guestCrop(window guesttools.ActiveWindow, size image.Point) image.Rectangle {
|
|
w, h := window.DisplayWidth, window.DisplayHeight
|
|
if w <= 0 || h <= 0 || window.Width <= 0 || window.Height <= 0 {
|
|
return image.Rectangle{}
|
|
}
|
|
visible := image.Rect(window.X, window.Y, window.X+window.Width, window.Y+window.Height).
|
|
Intersect(image.Rect(0, 0, w, h))
|
|
if visible.Empty() {
|
|
return image.Rectangle{}
|
|
}
|
|
return image.Rect(
|
|
visible.Min.X*size.X/w, visible.Min.Y*size.Y/h,
|
|
(visible.Max.X*size.X+w-1)/w, (visible.Max.Y*size.Y+h-1)/h,
|
|
)
|
|
}
|
|
|
|
func (s *session) eventMapping(event ViewerEvent) (frameMapping, bool) {
|
|
window, _, ok := s.Window(windowMaxAge)
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.mapping, ok && event.FrameTag == s.tag && window == s.mapping.window &&
|
|
time.Since(s.lastFrame) <= windowMaxAge
|
|
}
|
|
|
|
func (s *session) run(ctx context.Context, title string, first ViewerFrame) error {
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
queue := &inputQueue{ready: make(chan struct{}, 1)}
|
|
failure := make(chan error, 1)
|
|
fail := func(err error) {
|
|
select {
|
|
case failure <- err:
|
|
default:
|
|
}
|
|
cancel()
|
|
}
|
|
done := make(chan struct{})
|
|
var firstCaptureError time.Time
|
|
go func() {
|
|
defer close(done)
|
|
if err := s.forwardInput(ctx, queue); err != nil && !errors.Is(err, context.Canceled) {
|
|
fail(err)
|
|
}
|
|
}()
|
|
err := RunViewer(ctx, ViewerOptions{
|
|
Title: title,
|
|
Initial: first,
|
|
Frame: func(ctx context.Context) (ViewerFrame, error) {
|
|
frame, err := s.capture(ctx)
|
|
if err == nil || errors.Is(err, errFrameUnconfirmed) {
|
|
firstCaptureError = time.Time{}
|
|
} else if firstCaptureError.IsZero() {
|
|
firstCaptureError = time.Now()
|
|
} else if time.Since(firstCaptureError) > 4*time.Second && ctx.Err() == nil {
|
|
fail(err)
|
|
}
|
|
return frame, err
|
|
},
|
|
Input: func(event ViewerEvent) {
|
|
if !queue.push(event) {
|
|
fail(errors.New("app window input queue is full"))
|
|
}
|
|
},
|
|
})
|
|
cancel()
|
|
<-done
|
|
select {
|
|
case err := <-failure:
|
|
return err
|
|
default:
|
|
return err
|
|
}
|
|
}
|
|
|
|
func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result error) {
|
|
keys := make(map[string]bool)
|
|
buttons := make(map[string]bool)
|
|
release := func(timeout time.Duration) error {
|
|
if len(keys)+len(buttons) == 0 {
|
|
return nil
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
defer cancel()
|
|
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 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
|
|
var wheel int
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-checkWindow.C:
|
|
if window, _, ok := s.Window(windowMaxAge); ok && window.ID == s.id {
|
|
missingSince = time.Time{}
|
|
} else if missingSince.IsZero() {
|
|
missingSince = time.Now()
|
|
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
|
|
}
|
|
case <-queue.ready:
|
|
input := queue.pop()
|
|
event := input.ViewerEvent
|
|
if event.Kind == ViewerClose || (event.Kind == ViewerFocus && !event.Down) {
|
|
if err := release(frameTimeout); err != nil {
|
|
return fmt.Errorf("release app window input: %w", err)
|
|
}
|
|
wheel = 0
|
|
continue
|
|
}
|
|
mapping, active := s.eventMapping(event)
|
|
base := ctx
|
|
finish := func() {}
|
|
paste := active && s.PrepareClipboard != nil && isPaste(event, keys)
|
|
if paste {
|
|
if input.focus == nil || input.focus.Err() != nil {
|
|
continue
|
|
}
|
|
focused, cancelFocus := context.WithCancel(ctx)
|
|
stopFocus := context.AfterFunc(input.focus, cancelFocus)
|
|
wait, cancelWait := context.WithTimeout(focused, pasteTimeout)
|
|
releasePaste, err := s.PrepareClipboard(wait)
|
|
cancelWait()
|
|
finish = func() {
|
|
if releasePaste != nil {
|
|
releasePaste()
|
|
}
|
|
stopFocus()
|
|
cancelFocus()
|
|
}
|
|
if err != nil || input.focus.Err() != nil || focused.Err() != nil {
|
|
finish()
|
|
if err != nil && input.focus.Err() == nil && ctx.Err() == nil && s.OnClipboardError != nil {
|
|
s.OnClipboardError(err)
|
|
}
|
|
continue
|
|
}
|
|
mapping, active = s.eventMapping(event)
|
|
base = focused
|
|
}
|
|
request, cancel := context.WithTimeout(base, frameTimeout)
|
|
err := s.forwardEvent(request, event, mapping, active, keys, buttons, &wheel)
|
|
cancel()
|
|
finish()
|
|
if err != nil && paste && input.focus.Err() != nil {
|
|
continue
|
|
}
|
|
// A newer movement supersedes a timed-out hover. Button and key
|
|
// transitions still fail the session so held input gets released.
|
|
if err != nil && event.Kind != ViewerMouseMove {
|
|
return fmt.Errorf("app window input: %w", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func isPaste(event ViewerEvent, keys map[string]bool) bool {
|
|
return event.Kind == ViewerKey && event.Down && qmp.QKeyCode(event.VirtualKey) == "v" &&
|
|
!keys["v"] && (keys["meta_l"] || keys["meta_r"])
|
|
}
|
|
|
|
func (s *session) forwardEvent(ctx context.Context, event ViewerEvent, m frameMapping, active bool, keys, buttons map[string]bool, wheel *int) error {
|
|
if event.Kind == ViewerKey {
|
|
key := qmp.QKeyCode(event.VirtualKey)
|
|
if key == "" || event.Down == keys[key] || (!active && event.Down) {
|
|
return nil
|
|
}
|
|
if event.Down {
|
|
keys[key] = true
|
|
}
|
|
err := s.Console.SendKey(ctx, s.VMDir, key, event.Down)
|
|
if err == nil && !event.Down {
|
|
delete(keys, key)
|
|
}
|
|
return err
|
|
}
|
|
x, y := m.crop.Min.X+event.X, m.crop.Min.Y+event.Y
|
|
positioned := active && event.Width == m.crop.Dx() && event.Height == m.crop.Dy() &&
|
|
image.Pt(x, y).In(m.crop)
|
|
switch event.Kind {
|
|
case ViewerMouseMove:
|
|
if positioned {
|
|
return s.Console.MouseMove(ctx, s.VMDir, x, y, m.screen.X, m.screen.Y)
|
|
}
|
|
case ViewerMouseButton:
|
|
names := [...]string{"left", "right", "middle"}
|
|
if event.Button < 0 || event.Button >= len(names) {
|
|
return nil
|
|
}
|
|
button := names[event.Button]
|
|
if event.Down == buttons[button] || (!positioned && event.Down) {
|
|
return nil
|
|
}
|
|
if event.Down {
|
|
buttons[button] = true
|
|
}
|
|
var err error
|
|
if positioned {
|
|
err = s.Console.MouseButtonAt(ctx, s.VMDir, x, y, m.screen.X, m.screen.Y, button, event.Down)
|
|
} else {
|
|
err = s.Console.MouseButton(ctx, s.VMDir, button, false)
|
|
}
|
|
if err == nil && !event.Down {
|
|
delete(buttons, button)
|
|
}
|
|
return err
|
|
case ViewerMouseWheel:
|
|
if positioned {
|
|
*wheel += event.Delta
|
|
steps := *wheel / 120
|
|
*wheel %= 120
|
|
if steps == 0 {
|
|
return nil
|
|
}
|
|
if err := s.Console.MouseMove(ctx, s.VMDir, x, y, m.screen.X, m.screen.Y); err != nil {
|
|
return err
|
|
}
|
|
return s.Console.MouseScroll(ctx, s.VMDir, -steps, false)
|
|
}
|
|
}
|
|
return nil
|
|
}
|