From e9b3758c57ac6073d938f115f8e8b83fb22b48bc Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 07:26:56 +0800 Subject: [PATCH 01/10] chore: record the macOS app window feature --- changes/macos-app-window.json | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 changes/macos-app-window.json diff --git a/changes/macos-app-window.json b/changes/macos-app-window.json new file mode 100644 index 0000000..16d18e6 --- /dev/null +++ b/changes/macos-app-window.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 0, + "authors": ["yxc0915"], + "zh": "可在 Windows 独立窗口中查看和操作正在运行的 macOS 虚拟机的前台应用。", + "en": "View and interact with the foreground app of a running macOS VM in a separate Windows window." +} From 9f6c9aa90ea604f7342ed0befc7773935e6db078 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 07:32:27 +0800 Subject: [PATCH 02/10] feat: open a macOS app in a separate Windows window --- docs/design-guidelines.md | 2 +- frontend/src/App.tsx | 2 + frontend/src/components/VMPage.tsx | 6 + frontend/src/i18n/domains/vm.gen.ts | 4 + frontend/src/i18n/keys.gen.ts | 2 + frontend/wailsjs/go/app/App.d.ts | 2 + frontend/wailsjs/go/app/App.js | 4 + internal/app/app.go | 3 + internal/app/app_window_flow.go | 137 +++++ internal/appwindow/session.go | 382 +++++++++++++ internal/appwindow/session_test.go | 90 +++ internal/appwindow/viewer.go | 40 ++ internal/appwindow/viewer_other.go | 12 + internal/appwindow/viewer_windows.go | 517 ++++++++++++++++++ internal/console/manager.go | 50 +- internal/guesttools/active_window.go | 137 +++++ internal/guesttools/active_window_reporter.js | 87 +++ internal/guesttools/active_window_test.go | 116 ++++ internal/guesttools/folder_agent_test.go | 3 - internal/guesttools/folder_share.go | 3 +- internal/guesttools/guesttools_test.go | 7 +- internal/guesttools/image.go | 40 ++ internal/guesttools/server.go | 12 + internal/i18n/catalog_gen.go | 20 + internal/plugin/builtin/computer_use.go | 3 + internal/qmp/app_window_test.go | 80 +++ internal/qmp/client.go | 6 + internal/qmp/keys.go | 9 + internal/qmp/pointer.go | 33 +- internal/qmp/screendump.go | 24 +- internal/qmp/windows_keys.go | 74 +++ locales/en-US/native.json | 7 + locales/en-US/vm.json | 2 + locales/zh-CN/native.json | 7 + locales/zh-CN/vm.json | 2 + 35 files changed, 1904 insertions(+), 21 deletions(-) create mode 100644 internal/app/app_window_flow.go create mode 100644 internal/appwindow/session.go create mode 100644 internal/appwindow/session_test.go create mode 100644 internal/appwindow/viewer.go create mode 100644 internal/appwindow/viewer_other.go create mode 100644 internal/appwindow/viewer_windows.go create mode 100644 internal/guesttools/active_window.go create mode 100644 internal/guesttools/active_window_reporter.js create mode 100644 internal/guesttools/active_window_test.go create mode 100644 internal/qmp/app_window_test.go create mode 100644 internal/qmp/windows_keys.go diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index d2bd1e1..6711fa4 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -24,7 +24,7 @@ | 正在创建 | 无(展示分步进度) | 取消创建 | | 已停止 | 启动 | 设置、恢复点、派生副本、磁盘扩容与空间回收、打开目录、删除 | | 正在启动 | 启动中(忙碌禁用) | 设置、强制关机 | -| 运行中 | 显示虚拟机窗口 | 挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 | +| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 | | 正在停止 | 停止中(忙碌禁用) | 强制关机 | | 正在挂起 | 挂起中(忙碌禁用) | 强制关机 | | 已挂起 | 恢复(需运行时支持) | 放弃挂起状态(需破坏性操作确认)、打开目录 | diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3e0b82f..b7ef44f 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -52,6 +52,7 @@ const failKey: Record = { focus: 'failFocus', fullscreen: 'failFullscreen', screenshot: 'failScreenshot', + appWindow: 'failOpenAppWindow', stop: 'failStop', forceStop: 'failStop', restart: 'failRestart', @@ -751,6 +752,7 @@ export const App: React.FC = () => { refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen }) }) case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied')) + case 'appWindow': return runVMAction(name, action, () => api.OpenAppWindow(actionDriverID, name)) case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name })) case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name })) case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name)) diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 2891eb8..6a113f4 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -68,6 +68,7 @@ export type VMAction = | 'focus' | 'fullscreen' | 'screenshot' + | 'appWindow' | 'eject' | 'finishInstall' | 'enterRecovery' @@ -592,6 +593,11 @@ export const VMPage: React.FC = ({ onAction('screenshot')}> {tr('copyScreenshot')} + {isMacOSDriver && !installing && ( + onAction('appWindow')}> + {tr('openAppWindow')} + + )} )} diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 9b7114c..d9c74a7 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -55,6 +55,7 @@ export const vmZh: Record = { "failFocus": "无法定位虚拟机窗口", "failFullscreen": "无法切换全屏", "failGuestTools": "Guest Tools 操作失败", + "failOpenAppWindow": "无法打开独立应用窗口", "failOpenFolder": "无法打开文件夹", "failRestart": "重启失败", "failResume": "恢复失败", @@ -126,6 +127,7 @@ export const vmZh: Record = { "onlineRecoveryConfirm": "拉取并挂载(约 1 GB)", "onlineRecoveryDesc": "本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?", "onlineRecoveryTitle": "拉取在线恢复镜像?", + "openAppWindow": "打开独立应用窗口", "openSharedFolder": "打开共享文件夹", "openShort": "打开", "pendingRestartHint": "重启虚拟机后生效", @@ -288,6 +290,7 @@ export const vmEn: Record = { "failFocus": "Could not focus VM window", "failFullscreen": "Couldn’t toggle full screen", "failGuestTools": "Guest Tools operation failed", + "failOpenAppWindow": "Could not open the app window", "failOpenFolder": "Couldn’t open the folder", "failRestart": "Couldn’t restart", "failResume": "Couldn’t resume", @@ -359,6 +362,7 @@ export const vmEn: Record = { "onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)", "onlineRecoveryDesc": "No recovery image is on this PC. Download Apple’s recovery image (about 1 GB) and attach it to “{name}”?", "onlineRecoveryTitle": "Download online recovery image?", + "openAppWindow": "Open app in separate window", "openSharedFolder": "Open shared folder", "openShort": "Open", "pendingRestartHint": "Takes effect after a restart", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 4558da5..aef0520 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -264,6 +264,7 @@ export type I18nKey = | "failFullscreen" | "failGeneric" | "failGuestTools" + | "failOpenAppWindow" | "failOpenFolder" | "failRestart" | "failResume" @@ -648,6 +649,7 @@ export type I18nKey = | "onlineRecoveryConfirm" | "onlineRecoveryDesc" | "onlineRecoveryTitle" + | "openAppWindow" | "openFolder" | "openSharedFolder" | "openShort" diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index f09bcf4..94a9033 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -214,6 +214,8 @@ export function ListSnapshots(arg1:string):Promise>; export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise>; +export function OpenAppWindow(arg1:string,arg2:string):Promise; + export function OpenProcessorScheduling():Promise; export function OpenQQGroup():Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 660c568..350de45 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -406,6 +406,10 @@ export function ListSnapshotsWithDriver(arg1, arg2) { return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2); } +export function OpenAppWindow(arg1, arg2) { + return window['go']['app']['App']['OpenAppWindow'](arg1, arg2); +} + export function OpenProcessorScheduling() { return window['go']['app']['App']['OpenProcessorScheduling'](); } diff --git a/internal/app/app.go b/internal/app/app.go index 3e95a43..05999e6 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -111,6 +111,8 @@ type App struct { stopPoll context.CancelFunc guestTools *guesttools.Server guestToolsConfigLocks sync.Map + appWindow *appWindowRun + appWindowClosing bool vmDeleteEpochs map[string]uint64 resolveFolderVolume func(string) (host.DirectoryVolume, error) imeBridge *host.IMEBridge @@ -269,6 +271,7 @@ func (a *App) beforeClose(ctx context.Context) bool { } func (a *App) shutdown(ctx context.Context) { + a.stopAppWindow() a.closePacketBridges() if a.stopPoll != nil { a.stopPoll() diff --git a/internal/app/app_window_flow.go b/internal/app/app_window_flow.go new file mode 100644 index 0000000..c28598a --- /dev/null +++ b/internal/app/app_window_flow.go @@ -0,0 +1,137 @@ +package app + +import ( + "context" + "errors" + "runtime" + "time" + + "github.com/Nwflower/reims-go/internal/appwindow" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/guesttools" + "github.com/Nwflower/reims-go/internal/i18n" +) + +type appWindowRun struct { + cancel context.CancelFunc + done chan struct{} +} + +// OpenAppWindow shows the frontmost application window of a running macOS VM. +func (a *App) OpenAppWindow(driverID, name string) error { + a.mu.Lock() + locale := i18n.EffectiveLocale(a.cfg.Locale) + a.mu.Unlock() + coded := func(code, key string, cause error) error { + return i18n.NewCodedError(locale, code, key, i18n.Vars{"name": name}, cause) + } + if runtime.GOOS != "windows" { + return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil) + } + info, err := a.resolveVMInfo(driverID, name) + if err != nil { + return err + } + if info.DriverID != driver.BuiltinReimsMacOSDriverID { + return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil) + } + vm, ok := a.polledVMForDriver(info.DriverID, name) + if !ok || vm.State != "running" || vm.Dir == "" { + return coded("E_VM_NOT_RUNNING", "err.vm_not_running", nil) + } + if !a.guestToolsEnabled() { + return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + } + + a.mu.Lock() + bridge := a.guestTools + if bridge == nil || a.appWindowClosing { + a.mu.Unlock() + return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + } + if a.appWindow != nil { + a.mu.Unlock() + return coded("E_APP_WINDOW_OPEN", "err.app_window_open", nil) + } + ctx, cancel := context.WithCancel(context.Background()) + run := &appWindowRun{cancel: cancel, done: make(chan struct{})} + a.appWindow = run + tmp := a.cfg.TempDir() + a.mu.Unlock() + + reporting := false + finish := func() { + cancel() + if reporting { + bridge.SetWindowReporting(name, false) + } + a.mu.Lock() + a.appWindow = nil + close(run.done) + a.mu.Unlock() + } + started := false + defer func() { + if !started { + finish() + } + }() + + status := bridge.Status(name, 15*time.Second) + if !status.Connected { + return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + } + if status.AgentVersion < guesttools.WindowReportAgentVersion { + return coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil) + } + service := a.computerUseInternalService() + probe, stopProbe := context.WithTimeout(ctx, 2*time.Second) + pointer, err := service.PointerAvailable(probe, vm.Dir) + stopProbe() + if err != nil || !pointer { + return coded("E_APP_WINDOW_POINTER", "err.app_window_pointer", err) + } + reporting = bridge.SetWindowReporting(name, true) + if !reporting { + return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + } + show, err := appwindow.Prepare(ctx, appwindow.SessionOptions{ + VMDir: vm.Dir, + TmpDir: tmp, + Console: service, + Window: func(maxAge time.Duration) (guesttools.ActiveWindow, bool) { + return bridge.ActiveWindow(name, maxAge) + }, + }) + if errors.Is(err, appwindow.ErrNoWindow) { + return coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil) + } + if err != nil { + return coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err) + } + started = true + go func() { + defer finish() + if err := show(); err != nil && ctx.Err() == nil { + a.emitVMLogForDriver(info.DriverID, name, "App window closed: "+err.Error()) + } + }() + return nil +} + +func (a *App) stopAppWindow() { + a.mu.Lock() + a.appWindowClosing = true + run := a.appWindow + a.mu.Unlock() + if run == nil { + return + } + run.cancel() + timer := time.NewTimer(2 * time.Second) + defer timer.Stop() + select { + case <-run.done: + case <-timer.C: + } +} diff --git a/internal/appwindow/session.go b/internal/appwindow/session.go new file mode 100644 index 0000000..e37e4c2 --- /dev/null +++ b/internal/appwindow/session.go @@ -0,0 +1,382 @@ +// Package appwindow presents a guest application through the VM console. +package appwindow + +import ( + "context" + "errors" + "fmt" + "image" + "image/draw" + "os" + "path/filepath" + "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") + +const ( + windowMaxAge = time.Second + frameTimeout = 800 * time.Millisecond + 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 +} + +type SessionOptions struct { + VMDir string + TmpDir string + Window func(time.Duration) (guesttools.ActiveWindow, bool) + Console Console +} + +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 []ViewerEvent + ready chan struct{} +} + +func (q *inputQueue) push(event ViewerEvent) bool { + q.mu.Lock() + defer q.mu.Unlock() + last := len(q.events) - 1 + if last >= 0 && q.events[last].Kind == ViewerMouseMove && event.Kind == ViewerMouseMove { + q.events[last] = event + return true + } + if len(q.events) == 64 { + return event.Kind == ViewerMouseMove + } + q.events = append(q.events, event) + if last < 0 { + q.ready <- struct{}{} + } + return true +} + +func (q *inputQueue) pop() ViewerEvent { + q.mu.Lock() + defer q.mu.Unlock() + event := q.events[0] + copy(q.events, q.events[1:]) + 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 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, 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 + } + ctx, cancel := context.WithTimeout(ctx, frameTimeout) + defer cancel() + defer os.Remove(s.path) + format, err := s.Console.ScreendumpDisplay(ctx, s.VMDir, s.path, "gfx", 0) + 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 + } + frame, err := thumb.Load(s.path, format) + if err != nil { + return ViewerFrame{}, err + } + after, ok := s.Window(windowMaxAge) + if !ok || before != after { + return ViewerFrame{}, ErrNoWindow + } + 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}, nil +} + +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 && ctx.Err() == nil { + 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 { + 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) 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) + 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) + } + } + defer release() + 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() + release() + wheel = 0 + } else if time.Since(missingSince) > 4*time.Second { + return ErrNoWindow + } + case <-queue.ready: + event := queue.pop() + if event.Kind == ViewerClose || (event.Kind == ViewerFocus && !event.Down) { + release() + wheel = 0 + continue + } + mapping, active := s.eventMapping(event) + request, cancel := context.WithTimeout(ctx, frameTimeout) + err := s.forwardEvent(request, event, mapping, active, keys, buttons, &wheel) + cancel() + // 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 (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 +} diff --git a/internal/appwindow/session_test.go b/internal/appwindow/session_test.go new file mode 100644 index 0000000..62811df --- /dev/null +++ b/internal/appwindow/session_test.go @@ -0,0 +1,90 @@ +package appwindow + +import ( + "context" + "image" + "os" + "path/filepath" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/guesttools" +) + +type captureConsole struct{ Console } + +func TestInputQueueKeepsClickBetweenMoves(t *testing.T) { + q := &inputQueue{ready: make(chan struct{}, 1)} + for _, event := range []ViewerEvent{ + {Kind: ViewerMouseMove, X: 1}, + {Kind: ViewerMouseMove, X: 2}, + {Kind: ViewerMouseButton, X: 2, Down: true}, + {Kind: ViewerMouseMove, X: 3}, + {Kind: ViewerMouseMove, X: 4}, + } { + if !q.push(event) { + t.Fatal("queue unexpectedly full") + } + } + for _, want := range []ViewerEvent{ + {Kind: ViewerMouseMove, X: 2}, + {Kind: ViewerMouseButton, X: 2, Down: true}, + {Kind: ViewerMouseMove, X: 4}, + } { + select { + case <-q.ready: + default: + t.Fatal("queue did not notify its reader") + } + if got := q.pop(); got != want { + t.Fatalf("event = %+v, want %+v", got, want) + } + } +} + +func (captureConsole) ScreendumpDisplay(_ context.Context, _ string, path, device string, head int) (string, error) { + if device != "gfx" || head != 0 { + return "", ErrNoWindow + } + ppm := append([]byte("P6\n8 6\n255\n"), make([]byte, 8*6*3)...) + return "ppm", os.WriteFile(path, ppm, 0o600) +} + +func TestCaptureTracksDisplayedGeometry(t *testing.T) { + current := guesttools.ActiveWindow{ + ID: 1, AppName: "TextEdit", X: -1, Y: 1, Width: 4, Height: 2, DisplayWidth: 4, DisplayHeight: 3, + } + s := &session{ + SessionOptions: SessionOptions{ + Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return current, true }, + Console: captureConsole{}, + }, + path: filepath.Join(t.TempDir(), "test.ppm"), id: 1, + } + frame, err := s.capture(context.Background()) + if err != nil { + t.Fatal(err) + } + if frame.Image.Bounds() != image.Rect(0, 0, 6, 4) { + t.Fatalf("crop bounds = %v", frame.Image.Bounds()) + } + event := ViewerEvent{Kind: ViewerMouseButton, FrameTag: frame.Tag} + if mapping, ok := s.eventMapping(event); !ok || mapping.crop.Min != image.Pt(0, 2) { + t.Fatalf("event mapping = %#v, %v", mapping, ok) + } + current.X = 1 + if _, ok := s.eventMapping(event); ok { + t.Fatal("accepted input against a stale window position") + } + next, err := s.capture(context.Background()) + if err != nil { + t.Fatal(err) + } + if next.Tag == frame.Tag { + t.Fatal("changed window position retained the previous frame tag") + } + current.ID++ + if _, err := s.capture(context.Background()); err != ErrNoWindow { + t.Fatalf("capture after guest changed windows = %v", err) + } +} diff --git a/internal/appwindow/viewer.go b/internal/appwindow/viewer.go new file mode 100644 index 0000000..e84bf5c --- /dev/null +++ b/internal/appwindow/viewer.go @@ -0,0 +1,40 @@ +package appwindow + +import ( + "context" + "image" +) + +type ViewerFrame struct { + Image image.Image + Tag uint64 +} + +type ViewerEventKind uint8 + +const ( + ViewerFocus ViewerEventKind = iota + 1 + ViewerClose + ViewerMouseMove + ViewerMouseButton + ViewerMouseWheel + ViewerKey +) + +type ViewerEvent struct { + Kind ViewerEventKind + FrameTag uint64 + X, Y int + Width, Height int + Button int // 0 = left, 1 = right, 2 = middle + Delta int // 120 units per wheel detent + VirtualKey uint32 + Down bool +} + +type ViewerOptions struct { + Title string + Initial ViewerFrame + Frame func(context.Context) (ViewerFrame, error) + Input func(ViewerEvent) // Runs on the window thread and must return promptly. +} diff --git a/internal/appwindow/viewer_other.go b/internal/appwindow/viewer_other.go new file mode 100644 index 0000000..249f381 --- /dev/null +++ b/internal/appwindow/viewer_other.go @@ -0,0 +1,12 @@ +//go:build !windows + +package appwindow + +import ( + "context" + "errors" +) + +func RunViewer(context.Context, ViewerOptions) error { + return errors.New("the app-window viewer requires Windows") +} diff --git a/internal/appwindow/viewer_windows.go b/internal/appwindow/viewer_windows.go new file mode 100644 index 0000000..056c658 --- /dev/null +++ b/internal/appwindow/viewer_windows.go @@ -0,0 +1,517 @@ +//go:build windows + +package appwindow + +import ( + "context" + "fmt" + "image" + "image/draw" + "runtime" + "sync" + "sync/atomic" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + viewerUser32 = windows.NewLazySystemDLL("user32.dll") + viewerGDI32 = windows.NewLazySystemDLL("gdi32.dll") + + viewerRegisterClass = viewerUser32.NewProc("RegisterClassW") + viewerCreateWindow = viewerUser32.NewProc("CreateWindowExW") + viewerDefWindowProc = viewerUser32.NewProc("DefWindowProcW") + viewerDestroyWindow = viewerUser32.NewProc("DestroyWindow") + viewerShowWindow = viewerUser32.NewProc("ShowWindow") + viewerUpdateWindow = viewerUser32.NewProc("UpdateWindow") + viewerGetMessage = viewerUser32.NewProc("GetMessageW") + viewerDispatchMessage = viewerUser32.NewProc("DispatchMessageW") + viewerPostMessage = viewerUser32.NewProc("PostMessageW") + viewerPostQuitMessage = viewerUser32.NewProc("PostQuitMessage") + viewerLoadCursor = viewerUser32.NewProc("LoadCursorW") + viewerInvalidateRect = viewerUser32.NewProc("InvalidateRect") + viewerGetClientRect = viewerUser32.NewProc("GetClientRect") + viewerBeginPaint = viewerUser32.NewProc("BeginPaint") + viewerEndPaint = viewerUser32.NewProc("EndPaint") + viewerFillRect = viewerUser32.NewProc("FillRect") + viewerIsIconic = viewerUser32.NewProc("IsIconic") + viewerSetCapture = viewerUser32.NewProc("SetCapture") + viewerGetCapture = viewerUser32.NewProc("GetCapture") + viewerReleaseCapture = viewerUser32.NewProc("ReleaseCapture") + viewerScreenToClient = viewerUser32.NewProc("ScreenToClient") + viewerGetStockObject = viewerGDI32.NewProc("GetStockObject") + viewerSetStretchMode = viewerGDI32.NewProc("SetStretchBltMode") + viewerStretchDIBits = viewerGDI32.NewProc("StretchDIBits") + + viewerClassOnce sync.Once + viewerClassAtom uintptr + viewerClassErr error + viewerModule windows.Handle + viewerWindows sync.Map // HWND -> *nativeViewer +) + +const ( + viewerWmDestroy = 0x0002 + viewerWmSize = 0x0005 + viewerWmSetFocus = 0x0007 + viewerWmKillFocus = 0x0008 + viewerWmPaint = 0x000f + viewerWmClose = 0x0010 + viewerWmErase = 0x0014 + viewerWmKeyDown = 0x0100 + viewerWmKeyUp = 0x0101 + viewerWmSysKeyDown = 0x0104 + viewerWmSysKeyUp = 0x0105 + viewerWmMouseMove = 0x0200 + viewerWmLeftDown = 0x0201 + viewerWmLeftUp = 0x0202 + viewerWmRightDown = 0x0204 + viewerWmRightUp = 0x0205 + viewerWmMiddleDown = 0x0207 + viewerWmMiddleUp = 0x0208 + viewerWmMouseWheel = 0x020a + viewerWmCaptureChanged = 0x0215 + viewerWmFrame = 0x8001 + viewerWmStop = 0x8002 +) + +type viewerClass struct { + style uint32 + windowProc uintptr + classExtra int32 + windowExtra int32 + instance windows.Handle + icon uintptr + cursor uintptr + background uintptr + menuName *uint16 + className *uint16 +} + +type viewerPoint struct{ x, y int32 } +type viewerRect struct{ left, top, right, bottom int32 } + +type viewerMessage struct { + hwnd uintptr + message uint32 + wParam, lParam uintptr + time uint32 + point viewerPoint + private uint32 +} + +type viewerPaint struct { + dc uintptr + erase int32 + rect viewerRect + restore int32 + update int32 + padding [32]byte +} + +type viewerBitmapHeader struct { + size uint32 + width, height int32 + planes, bits uint16 + compression uint32 + imageSize uint32 + xPPM, yPPM int32 + colorsUsed uint32 + colorsNeeded uint32 +} + +type viewerBitmap struct { + width, height int + tag uint64 + pixels []byte +} + +type nativeViewer struct { + hwnd uintptr + options ViewerOptions + + latest atomic.Pointer[viewerBitmap] + pending atomic.Bool + postMu sync.Mutex + closed bool + + // The message loop owns these fields. Inputs use the bitmap that was painted. + displayed *viewerBitmap + imageRect image.Rectangle + keys map[uint32]bool + buttons [3]bool + lastMouse ViewerEvent +} + +func registerViewerClass() (uintptr, error) { + viewerClassOnce.Do(func() { + viewerClassErr = windows.GetModuleHandleEx(windows.GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, nil, &viewerModule) + if viewerClassErr != nil { + return + } + cursor, _, _ := viewerLoadCursor.Call(0, 32512) // IDC_ARROW + className, _ := windows.UTF16PtrFromString("ReimsGoAppWindowClass") + class := viewerClass{ + windowProc: windows.NewCallback(viewerWindowProc), + instance: viewerModule, + cursor: cursor, + className: className, + } + atom, _, err := viewerRegisterClass.Call(uintptr(unsafe.Pointer(&class))) + if atom == 0 { + viewerClassErr = fmt.Errorf("register app-window viewer: %w", err) + return + } + viewerClassAtom = atom + }) + return viewerClassAtom, viewerClassErr +} + +// RunViewer owns a native window until the user closes it or the context is canceled. +func RunViewer(ctx context.Context, opts ViewerOptions) error { + if err := ctx.Err(); err != nil { + return err + } + if opts.Title == "" { + opts.Title = "Reims-Go" + } + title, err := windows.UTF16PtrFromString(opts.Title) + if err != nil { + return fmt.Errorf("invalid app-window title: %w", err) + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + class, err := registerViewerClass() + if err != nil { + return err + } + first := makeViewerBitmap(opts.Initial) + opts.Initial = ViewerFrame{} + v := &nativeViewer{options: opts, keys: make(map[uint32]bool)} + width, height := 900, 640 + if first != nil { + v.latest.Store(first) + size := fitViewerFrame(min(first.width, 920), min(first.height, 680), first.width, first.height) + width, height = max(size.Dx()+24, 360), max(size.Dy()+48, 240) + } + hwnd, _, callErr := viewerCreateWindow.Call( + 0x00040000, class, uintptr(unsafe.Pointer(title)), 0x00cf0000, // WS_EX_APPWINDOW, WS_OVERLAPPEDWINDOW + 0x80000000, 0x80000000, uintptr(width), uintptr(height), // CW_USEDEFAULT for x and y + 0, 0, uintptr(viewerModule), 0, + ) + if hwnd == 0 { + return fmt.Errorf("create app-window viewer: %w", callErr) + } + v.hwnd = hwnd + viewerWindows.Store(hwnd, v) + defer viewerWindows.Delete(hwnd) + + work, cancel := context.WithCancel(ctx) + var workers sync.WaitGroup + defer func() { + v.stopPosting() + cancel() + workers.Wait() + }() + workers.Go(func() { + <-work.Done() + v.post(viewerWmStop) + }) + if opts.Frame != nil { + workers.Go(func() { v.pollFrames(work) }) + } + viewerShowWindow.Call(hwnd, 5) // SW_SHOW + viewerInvalidateRect.Call(hwnd, 0, 0) + viewerUpdateWindow.Call(hwnd) + + var msg viewerMessage + for { + status, _, err := viewerGetMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + switch int32(status) { + case -1: + v.releaseInputs() + viewerWindows.Delete(hwnd) + v.destroy() + return fmt.Errorf("read app-window messages: %w", err) + case 0: + return nil + } + viewerDispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + } +} + +func makeViewerBitmap(frame ViewerFrame) *viewerBitmap { + if frame.Image == nil || frame.Image.Bounds().Empty() { + return nil + } + bounds := frame.Image.Bounds() + rgba := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy())) + draw.Draw(rgba, rgba.Bounds(), frame.Image, bounds.Min, draw.Src) + for i := 0; i < len(rgba.Pix); i += 4 { + rgba.Pix[i], rgba.Pix[i+2] = rgba.Pix[i+2], rgba.Pix[i] + } + return &viewerBitmap{width: bounds.Dx(), height: bounds.Dy(), tag: frame.Tag, pixels: rgba.Pix} +} + +func (v *nativeViewer) post(message uintptr) bool { + v.postMu.Lock() + defer v.postMu.Unlock() + if v.closed { + return false + } + ok, _, _ := viewerPostMessage.Call(v.hwnd, message, 0, 0) + return ok != 0 +} + +func (v *nativeViewer) stopPosting() { + v.postMu.Lock() + v.closed = true + v.postMu.Unlock() +} + +func (v *nativeViewer) destroy() { + v.stopPosting() + viewerDestroyWindow.Call(v.hwnd) +} + +func (v *nativeViewer) pollFrames(ctx context.Context) { + timer := time.NewTimer(125 * time.Millisecond) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + if iconic, _, _ := viewerIsIconic.Call(v.hwnd); iconic == 0 { + frame, err := v.options.Frame(ctx) + if ctx.Err() != nil { + return + } + // A failed capture keeps the last painted frame until the next poll. + if err == nil { + if bitmap := makeViewerBitmap(frame); bitmap != nil { + v.latest.Store(bitmap) + if !v.pending.Swap(true) && !v.post(viewerWmFrame) { + v.pending.Store(false) + } + } + } + } + timer.Reset(125 * time.Millisecond) + } +} + +func fitViewerFrame(width, height, frameWidth, frameHeight int) image.Rectangle { + if width <= 0 || height <= 0 || frameWidth <= 0 || frameHeight <= 0 { + return image.Rectangle{} + } + w, h := width, height + if width*frameHeight <= height*frameWidth { + h = max(1, width*frameHeight/frameWidth) + } else { + w = max(1, height*frameWidth/frameHeight) + } + x, y := (width-w)/2, (height-h)/2 + return image.Rect(x, y, x+w, y+h) +} + +func (v *nativeViewer) paint() { + var ps viewerPaint + dc, _, _ := viewerBeginPaint.Call(v.hwnd, uintptr(unsafe.Pointer(&ps))) + defer viewerEndPaint.Call(v.hwnd, uintptr(unsafe.Pointer(&ps))) + if dc == 0 { + return + } + var client viewerRect + viewerGetClientRect.Call(v.hwnd, uintptr(unsafe.Pointer(&client))) + brush, _, _ := viewerGetStockObject.Call(4) // BLACK_BRUSH + bitmap := v.latest.Load() + if bitmap == nil { + viewerFillRect.Call(dc, uintptr(unsafe.Pointer(&client)), brush) + return + } + area := fitViewerFrame(int(client.right), int(client.bottom), bitmap.width, bitmap.height) + if area.Empty() { + return + } + for _, bar := range [...]viewerRect{ + {0, 0, client.right, int32(area.Min.Y)}, + {0, int32(area.Max.Y), client.right, client.bottom}, + {0, int32(area.Min.Y), int32(area.Min.X), int32(area.Max.Y)}, + {int32(area.Max.X), int32(area.Min.Y), client.right, int32(area.Max.Y)}, + } { + if bar.right > bar.left && bar.bottom > bar.top { + viewerFillRect.Call(dc, uintptr(unsafe.Pointer(&bar)), brush) + } + } + header := viewerBitmapHeader{ + size: uint32(unsafe.Sizeof(viewerBitmapHeader{})), width: int32(bitmap.width), height: -int32(bitmap.height), + planes: 1, bits: 32, + } + viewerSetStretchMode.Call(dc, 3) // COLORONCOLOR + rows, _, _ := viewerStretchDIBits.Call( + dc, uintptr(area.Min.X), uintptr(area.Min.Y), uintptr(area.Dx()), uintptr(area.Dy()), + 0, 0, uintptr(bitmap.width), uintptr(bitmap.height), + uintptr(unsafe.Pointer(&bitmap.pixels[0])), uintptr(unsafe.Pointer(&header)), 0, 0x00cc0020, // SRCCOPY + ) + if int32(rows) != -1 && rows != 0 { + v.displayed, v.imageRect = bitmap, area + } +} + +func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintptr { + entry, ok := viewerWindows.Load(hwnd) + if !ok { + result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam) + return result + } + v := entry.(*nativeViewer) + switch message { + case viewerWmFrame: + v.pending.Store(false) + viewerInvalidateRect.Call(hwnd, 0, 0) + case viewerWmSize: + viewerInvalidateRect.Call(hwnd, 0, 0) + case viewerWmPaint: + v.paint() + case viewerWmErase: + return 1 + case viewerWmClose: + v.releaseInputs() + v.emit(ViewerEvent{Kind: ViewerClose}) + v.destroy() + case viewerWmStop: + v.destroy() + case viewerWmDestroy: + v.stopPosting() + v.releaseInputs() + viewerPostQuitMessage.Call(0) + case viewerWmSetFocus: + v.emit(ViewerEvent{Kind: ViewerFocus, FrameTag: v.frameTag(), Down: true}) + case viewerWmKillFocus: + v.releaseInputs() + v.emit(ViewerEvent{Kind: ViewerFocus, FrameTag: v.frameTag()}) + case viewerWmCaptureChanged: + v.releaseButtons() + case viewerWmMouseMove: + v.pointer(ViewerMouseMove, viewerMessagePoint(lParam), 0, 0, false) + case viewerWmLeftDown, viewerWmLeftUp: + v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 0, 0, message == viewerWmLeftDown) + case viewerWmRightDown, viewerWmRightUp: + v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 1, 0, message == viewerWmRightDown) + case viewerWmMiddleDown, viewerWmMiddleUp: + v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 2, 0, message == viewerWmMiddleDown) + case viewerWmMouseWheel: + point := viewerMessagePoint(lParam) + if ok, _, _ := viewerScreenToClient.Call(hwnd, uintptr(unsafe.Pointer(&point))); ok != 0 { + v.pointer(ViewerMouseWheel, point, 0, int(int16(wParam>>16)), false) + } + case viewerWmSysKeyDown, viewerWmSysKeyUp, viewerWmKeyDown, viewerWmKeyUp: + if message == viewerWmSysKeyDown && wParam == 0x73 && lParam&(1<<29) != 0 { // Alt+F4 + result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam) + return result + } + v.key(uint32(wParam), message == viewerWmKeyDown || message == viewerWmSysKeyDown) + default: + result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam) + return result + } + return 0 +} + +func viewerMessagePoint(lParam uintptr) viewerPoint { + return viewerPoint{int32(int16(lParam)), int32(int16(lParam >> 16))} +} + +func (v *nativeViewer) emit(ev ViewerEvent) { + if v.options.Input != nil { + v.options.Input(ev) + } +} + +func (v *nativeViewer) frameTag() uint64 { + if v.displayed != nil { + return v.displayed.tag + } + if first := v.latest.Load(); first != nil { + return first.tag + } + return 0 +} + +func (v *nativeViewer) pointer(kind ViewerEventKind, pt viewerPoint, button, delta int, down bool) { + frame, area := v.displayed, v.imageRect + if frame == nil || area.Empty() { + return + } + x, y := int(pt.x), int(pt.y) + inside := image.Pt(x, y).In(area) + anyButton := v.buttons[0] || v.buttons[1] || v.buttons[2] + if !inside && !(kind == ViewerMouseMove && anyButton) && + !(kind == ViewerMouseButton && !down && v.buttons[button]) { + return + } + ev := ViewerEvent{ + Kind: kind, FrameTag: frame.tag, Width: frame.width, Height: frame.height, + X: max(0, min(x-area.Min.X, area.Dx()-1)) * frame.width / area.Dx(), + Y: max(0, min(y-area.Min.Y, area.Dy()-1)) * frame.height / area.Dy(), + Button: button, Delta: delta, Down: down, + } + if kind == ViewerMouseButton { + if !down && !v.buttons[button] { + return + } + v.buttons[button] = down + if down && !anyButton { + viewerSetCapture.Call(v.hwnd) + } + } + v.lastMouse = ev + v.emit(ev) + if kind == ViewerMouseButton && !down { + v.releaseCaptureIfIdle() + } +} + +func (v *nativeViewer) key(key uint32, down bool) { + if down { + v.keys[key] = true + } else { + if !v.keys[key] { + return + } + delete(v.keys, key) + } + v.emit(ViewerEvent{Kind: ViewerKey, FrameTag: v.frameTag(), VirtualKey: key, Down: down}) +} + +func (v *nativeViewer) releaseButtons() { + for button, down := range v.buttons { + if down { + v.buttons[button] = false + ev := v.lastMouse + ev.Kind, ev.Button, ev.Down, ev.Delta = ViewerMouseButton, button, false, 0 + v.emit(ev) + } + } +} + +func (v *nativeViewer) releaseCaptureIfIdle() { + if !v.buttons[0] && !v.buttons[1] && !v.buttons[2] { + if hwnd, _, _ := viewerGetCapture.Call(); hwnd == v.hwnd { + viewerReleaseCapture.Call() + } + } +} + +func (v *nativeViewer) releaseInputs() { + v.releaseButtons() + v.releaseCaptureIfIdle() + for key := range v.keys { + v.key(key, false) + } +} diff --git a/internal/console/manager.go b/internal/console/manager.go index 7bffe5e..c7f8417 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -83,6 +83,17 @@ func (m *Manager) Screendump(ctx context.Context, vmDir, path string) (string, e return format, err } +// ScreendumpDisplay selects a specific guest display under the same console lock. +func (m *Manager) ScreendumpDisplay(ctx context.Context, vmDir, path, device string, head int) (string, error) { + var format string + err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { + var err error + format, err = qmp.ScreendumpDisplay(conn, path, device, head) + return err + }) + return format, err +} + // TypeText sends US-layout key strokes as one serialized console job. func (m *Manager) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) { strokes, err := qmp.Strokes(text) @@ -124,7 +135,7 @@ func (m *Manager) SendPasteShortcut(ctx context.Context, vmDir string) error { func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, error) { var available bool - err := m.withConn(ctx, vmDir, func(conn qmpSession) error { + err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { mice, err := qmp.QueryMice(conn) if err == nil { available = qmp.HasCurrentAbsoluteMouse(mice) @@ -135,17 +146,29 @@ func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, err } func (m *Manager) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error { - return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { return qmp.MouseMove(conn, x, y, width, height) }) } func (m *Manager) MouseButton(ctx context.Context, vmDir, button string, down bool) error { - return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { return qmp.MouseButton(conn, button, down) }) } +func (m *Manager) MouseButtonAt(ctx context.Context, vmDir string, x, y, width, height int, button string, down bool) error { + return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.MouseButtonAt(conn, x, y, width, height, button, down) + }) +} + +func (m *Manager) SendKey(ctx context.Context, vmDir, key string, down bool) error { + return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.SendKey(conn, key, down) + }) +} + 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 { @@ -173,7 +196,7 @@ func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error { } func (m *Manager) MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error { - return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error { return qmp.MouseScroll(conn, delta, horizontal) }) } @@ -242,6 +265,16 @@ func normalizeModifier(modifier string) (string, error) { } func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error { + return m.withConnMode(ctx, vmDir, false, operation) +} + +// Single-command operations can close their connection on cancellation. +// Multi-command jobs need it to release any held guest keys or buttons. +func (m *Manager) withCancelableConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error { + return m.withConnMode(ctx, vmDir, true, operation) +} + +func (m *Manager) withConnMode(ctx context.Context, vmDir string, cancelIO bool, operation func(qmpSession) error) error { if operation == nil { return errors.New("console operation is unavailable") } @@ -274,9 +307,12 @@ func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmp if err != nil { return err } - defer func() { - _ = conn.Close() - }() + closeConn := sync.OnceFunc(func() { _ = conn.Close() }) + defer closeConn() + if cancelIO { + stopCancel := context.AfterFunc(ctx, closeConn) + defer stopCancel() + } return operation(conn) } diff --git a/internal/guesttools/active_window.go b/internal/guesttools/active_window.go new file mode 100644 index 0000000..a1bfcd6 --- /dev/null +++ b/internal/guesttools/active_window.go @@ -0,0 +1,137 @@ +package guesttools + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "time" + "unicode" +) + +const ( + activeWindowPath = "/v1/active-window" + maxWindowReportSize = 2048 + maxDisplayDimension = 16384 +) + +// ActiveWindow describes the frontmost eligible window in the guest's main +// display coordinate system. Bounds are in screen points with a top-left origin. +type ActiveWindow struct { + ID uint32 `json:"id"` + AppName string `json:"app_name"` + X int `json:"x"` + Y int `json:"y"` + Width int `json:"width"` + Height int `json:"height"` + DisplayWidth int `json:"display_width"` + DisplayHeight int `json:"display_height"` +} + +type windowReport struct { + window *ActiveWindow + receivedAt time.Time +} + +// SetWindowReporting changes the transient reporting request for a registered VM. +func (s *Server) SetWindowReporting(vmKey string, enabled bool) bool { + s.mu.Lock() + defer s.mu.Unlock() + vm := s.vms[normalizeVMRegistryKey(vmKey)] + if vm == nil { + return false + } + if (vm.windowReportGen != 0) == enabled { + return true + } + vm.windowReportGen = 0 + vm.windowReport = windowReport{} + if enabled { + s.nextWindowGen++ + vm.windowReportGen = s.nextWindowGen + } + return true +} + +// ActiveWindow returns the latest eligible window if it arrived within maxAge. +func (s *Server) ActiveWindow(vmKey string, maxAge time.Duration) (ActiveWindow, bool) { + if maxAge <= 0 { + return ActiveWindow{}, false + } + s.mu.RLock() + defer s.mu.RUnlock() + vm := s.vms[normalizeVMRegistryKey(vmKey)] + if vm == nil || vm.windowReportGen == 0 || vm.windowReport.window == nil || + time.Since(vm.windowReport.receivedAt) > maxAge { + return ActiveWindow{}, false + } + return *vm.windowReport.window, true +} + +func (w ActiveWindow) valid() bool { + return w.ID != 0 && strings.TrimSpace(w.AppName) != "" && len(w.AppName) <= 256 && + strings.IndexFunc(w.AppName, unicode.IsControl) < 0 && + w.DisplayWidth > 0 && w.DisplayWidth <= maxDisplayDimension && + w.DisplayHeight > 0 && w.DisplayHeight <= maxDisplayDimension && + w.Width > 0 && w.Width <= maxDisplayDimension && w.Height > 0 && w.Height <= maxDisplayDimension && + w.X > -w.Width && w.X < w.DisplayWidth && w.Y > -w.Height && w.Y < w.DisplayHeight +} + +func (s *Server) handleActiveWindow(w http.ResponseWriter, r *http.Request) { + vm := s.authenticateToken(bearerToken(r)) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + if vm.windowReportGen == 0 { + http.Error(w, "window reporting is disabled", http.StatusForbidden) + return + } + controller := http.NewResponseController(w) + if controller.SetReadDeadline(time.Now().Add(3*time.Second)) == nil { + defer controller.SetReadDeadline(time.Time{}) + } + var req struct { + Generation uint64 `json:"generation"` + Window *ActiveWindow `json:"window"` + } + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxWindowReportSize)) + dec.DisallowUnknownFields() + err := dec.Decode(&req) + if err == nil { + err = dec.Decode(&struct{}{}) + if err == io.EOF { + err = nil + } else if err == nil { + err = errors.New("multiple JSON values") + } + } + if err != nil || (req.Window != nil && !req.Window.valid()) { + var sizeErr *http.MaxBytesError + if errors.As(err, &sizeErr) { + http.Error(w, "window report too large", http.StatusRequestEntityTooLarge) + return + } + http.Error(w, "invalid window report", http.StatusBadRequest) + return + } + s.mu.Lock() + cur := s.vms[vm.key] + current := cur != nil && cur.token == vm.token && vm.windowReportGen == req.Generation && + cur.windowReportGen == req.Generation + if current { + cur.windowReport = windowReport{window: req.Window, receivedAt: time.Now()} + } + s.mu.Unlock() + if !current { + http.Error(w, "window report expired", http.StatusConflict) + return + } + w.WriteHeader(http.StatusNoContent) +} diff --git a/internal/guesttools/active_window_reporter.js b/internal/guesttools/active_window_reporter.js new file mode 100644 index 0000000..00e28fb --- /dev/null +++ b/internal/guesttools/active_window_reporter.js @@ -0,0 +1,87 @@ +ObjC.import('AppKit') +ObjC.import('CoreFoundation') +ObjC.import('CoreGraphics') +ObjC.import('Foundation') + +function overlaps(a, b) { + return a.X < b.X + b.Width && b.X < a.X + a.Width && a.Y < b.Y + b.Height && b.Y < a.Y + a.Height +} + +function activeWindow() { + // QMP captures the main display. The experimental mode requires a single display. + if ($.NSScreen.screens.count !== 1) return null + const display = $.CGDisplayBounds($.CGMainDisplayID()) + const displayWidth = Math.round(display.size.width) + const displayHeight = Math.round(display.size.height) + if (!(displayWidth > 0 && displayHeight > 0)) return null + + const app = $.NSWorkspace.sharedWorkspace.frontmostApplication + if (!app || app.isNil() || app.activationPolicy !== $.NSApplicationActivationPolicyRegular) return null + const options = $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements + const raw = $.CGWindowListCopyWindowInfo(options, 0) + if (!raw) return null + let windows + try { + windows = ObjC.deepUnwrap(ObjC.castRefToObject(raw)) + } finally { + $.CFRelease(raw) + } + if (!Array.isArray(windows)) return null + const appPID = app.processIdentifier + const foreignAbove = [] + for (const window of windows) { + const bounds = window && window.kCGWindowBounds + if (!bounds || !(window.kCGWindowAlpha > 0.01)) continue + if (window.kCGWindowOwnerPID !== appPID) { + foreignAbove.push(bounds) + continue + } + if (window.kCGWindowLayer !== 0 || !(bounds.Width >= 32 && bounds.Height >= 32)) continue + const x = Math.floor(bounds.X - display.origin.x) + const y = Math.floor(bounds.Y - display.origin.y) + const width = Math.ceil(bounds.X + bounds.Width - display.origin.x) - x + const height = Math.ceil(bounds.Y + bounds.Height - display.origin.y) - y + if (x >= displayWidth || y >= displayHeight || x + width <= 0 || y + height <= 0) continue + const id = window.kCGWindowNumber + if (!Number.isInteger(id) || id <= 0 || id > 0xFFFFFFFF) continue + if (foreignAbove.some(above => overlaps(above, bounds))) return null + const label = app.localizedName + const appName = ((label && !label.isNil() ? label.js : window.kCGWindowOwnerName) || '') + .replace(/[\x00-\x1f\x7f-\x9f]/g, '').trim().slice(0, 64) + return {id, app_name: appName || 'Mac App', x, y, width, height, display_width: displayWidth, + display_height: displayHeight} + } + return null +} + +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 +} + +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 + while (true) { + let window + try { window = activeWindow() } catch (_) { window = null } + let status + try { status = postReport(url, token.js, generation, window) } catch (_) { status = 0 } + if (status === 401 || status === 403 || status === 409) return + delay(status === 204 ? 0.25 : 1) + } +} diff --git a/internal/guesttools/active_window_test.go b/internal/guesttools/active_window_test.go new file mode 100644 index 0000000..873096f --- /dev/null +++ b/internal/guesttools/active_window_test.go @@ -0,0 +1,116 @@ +package guesttools + +import ( + "context" + "encoding/json" + "net" + "net/http" + "strconv" + "strings" + "testing" + "time" +) + +func TestActiveWindowReporting(t *testing.T) { + srv := NewTransportServer(&memClipboard{}) + srv.RegisterVM(VMConfig{VMName: "mac-one", Token: "token-one"}) + srv.RegisterVM(VMConfig{VMName: "mac-two", Token: "token-two"}) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + base := "http://" + net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + httpClient := &http.Client{Timeout: 5 * time.Second} + request := func(method, path, token, body string, wantStatus int) *http.Response { + t.Helper() + req, err := http.NewRequest(method, base+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := httpClient.Do(req) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = resp.Body.Close() }) + if resp.StatusCode != wantStatus { + t.Fatalf("%s %s returned %d, want %d", method, path, resp.StatusCode, wantStatus) + } + return resp + } + generation := func(token string) uint64 { + t.Helper() + var cfg struct { + Generation uint64 `json:"window_report_generation"` + } + resp := request(http.MethodGet, "/v1/config", token, "", http.StatusOK) + defer resp.Body.Close() + if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil { + t.Fatal(err) + } + return cfg.Generation + } + report := func(gen uint64, window *ActiveWindow) string { + t.Helper() + b, err := json.Marshal(struct { + Generation uint64 `json:"generation"` + Window *ActiveWindow `json:"window"` + }{gen, window}) + if err != nil { + t.Fatal(err) + } + return string(b) + } + + request(http.MethodPost, activeWindowPath, "", "", http.StatusUnauthorized) + request(http.MethodPost, activeWindowPath, "token-one", report(0, nil), http.StatusForbidden) + if got := generation("token-one"); got != 0 { + t.Fatalf("generation = %d before opt-in", got) + } + if !srv.SetWindowReporting("mac-one", true) { + t.Fatal("could not opt in") + } + gen := generation("token-one") + if gen == 0 || generation("token-two") != 0 { + t.Fatal("reporting opt-in did not stay within the specified VM") + } + request(http.MethodGet, activeWindowPath, "token-one", "", http.StatusMethodNotAllowed) + request(http.MethodPost, activeWindowPath, "token-two", report(gen, nil), http.StatusForbidden) + request(http.MethodPost, activeWindowPath, "token-one", strings.Repeat(" ", maxWindowReportSize+1), http.StatusRequestEntityTooLarge) + request(http.MethodPost, activeWindowPath, "token-one", report(gen, nil)+"{}", http.StatusBadRequest) + bad := ActiveWindow{ID: 9, AppName: "Safari", X: 16384, Width: 700, Height: 600, DisplayWidth: 1920, DisplayHeight: 1080} + request(http.MethodPost, activeWindowPath, "token-one", report(gen, &bad), http.StatusBadRequest) + + window := ActiveWindow{ID: 25, AppName: "Safari", X: -20, Y: 31, Width: 700, Height: 600, DisplayWidth: 1920, DisplayHeight: 1080} + request(http.MethodPost, activeWindowPath, "token-one", report(gen, &window), http.StatusNoContent) + if got, ok := srv.ActiveWindow("mac-one", time.Second); !ok || got != window { + t.Fatalf("active window = %+v, %t", got, ok) + } + if _, ok := srv.ActiveWindow("mac-one", 0); ok { + t.Fatal("report older than maxAge was accepted") + } + if _, ok := srv.ActiveWindow("mac-two", time.Second); ok { + t.Fatal("another VM received the report") + } + request(http.MethodPost, activeWindowPath, "token-one", report(gen, nil), http.StatusNoContent) + if _, ok := srv.ActiveWindow("mac-one", time.Second); ok { + t.Fatal("null report failed to clear the window") + } + + srv.SetWindowReporting("mac-one", false) + srv.SetWindowReporting("mac-one", true) + nextGen := generation("token-one") + if nextGen == 0 || nextGen == gen { + t.Fatal("reporting reused the previous generation") + } + request(http.MethodPost, activeWindowPath, "token-one", report(gen, &window), http.StatusConflict) + request(http.MethodPost, activeWindowPath, "token-one", report(nextGen, &window), http.StatusNoContent) + srv.RegisterVM(VMConfig{VMName: "mac-one", Token: "rotated-token"}) + if _, ok := srv.ActiveWindow("mac-one", time.Second); ok || generation("rotated-token") != 0 { + t.Fatal("token rotation retained the previous window reporting session") + } + request(http.MethodPost, activeWindowPath, "token-one", report(nextGen, &window), http.StatusUnauthorized) +} diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 55a2958..835a1f2 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -43,9 +43,6 @@ func TestGuestAgentFolderMounts(t *testing.T) { "/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command", ) uninstall = dnsPaths.Replace(uninstall) - if CurrentAgentVersion != BidirectionalClipboardFilesAgentVersion { - t.Fatalf("CurrentAgentVersion = %d, want bidirectional clipboard files version %d", CurrentAgentVersion, BidirectionalClipboardFilesAgentVersion) - } versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,` if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") { t.Fatal("Guest Tools scripts do not advertise the current agent version") diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index ba5a197..86c432c 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -21,8 +21,9 @@ const WindowDropAgentVersion = 13 const ClipboardReliabilityAgentVersion = 14 const ClipboardFilesAgentVersion = 15 const BidirectionalClipboardFilesAgentVersion = 16 +const WindowReportAgentVersion = 17 -const CurrentAgentVersion = BidirectionalClipboardFilesAgentVersion +const CurrentAgentVersion = WindowReportAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 7746c90..9e4d938 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -649,9 +649,10 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { } } for name, script := range map[string][]byte{ - "dns-proxy.pl": guestDNSProxy, - "Apply-Host-DNS.command": guestApplyHostDNS, - "Disable-Host-DNS.command": guestDisableHostDNS, + "dns-proxy.pl": guestDNSProxy, + "Apply-Host-DNS.command": guestApplyHostDNS, + "Disable-Host-DNS.command": guestDisableHostDNS, + "active-window-reporter.js": guestWindowReporter, } { offset, size, err := installer.FindFileInHFSPlusImage(f, name) if err != nil { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index fb2ebdb..1801ebd 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -31,6 +31,9 @@ var guestDropResolveJS string //go:embed drop_agent.sh var guestDropAgent string +//go:embed active_window_reporter.js +var guestWindowReporter []byte + //go:embed dns-proxy.pl var guestDNSProxy []byte @@ -112,6 +115,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { {"dns-proxy.pl", guestDNSProxy}, {"Apply-Host-DNS.command", guestApplyHostDNS}, {"Disable-Host-DNS.command", guestDisableHostDNS}, + {"active-window-reporter.js", guestWindowReporter}, } { // The Windows checkout may have CRLF line endings. data := bytes.ReplaceAll(script.data, []byte("\r\n"), []byte("\n")) @@ -164,6 +168,8 @@ CAFFEINATE_PID="" TEXT_INPUT_PID="" DROP_EVENTS_PID="" CLIPBOARD_PID="" +WINDOW_REPORTER_PID="" +window_report_generation="" keymap_active="false" keymap_applied="false" ` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + ` @@ -185,6 +191,7 @@ cleanup() { if [ -n "$CLIPBOARD_PID" ]; then kill "$CLIPBOARD_PID" 2>/dev/null || true fi + stop_window_reporter rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true } trap cleanup EXIT @@ -489,9 +496,39 @@ EOF fi } +stop_window_reporter() { + if [ -n "${WINDOW_REPORTER_PID:-}" ]; then + kill "$WINDOW_REPORTER_PID" 2>/dev/null || true + wait "$WINDOW_REPORTER_PID" 2>/dev/null || true + fi + WINDOW_REPORTER_PID="" + window_report_generation="" +} + +sync_window_reporter() { + requested_generation=$(printf '%s\n' "$1" | sed -n 's/.*"window_report_generation"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') + case "$requested_generation" in + ''|0) + stop_window_reporter + return + ;; + esac + if [ "$requested_generation" = "${window_report_generation:-}" ] && + [ -n "${WINDOW_REPORTER_PID:-}" ] && kill -0 "$WINDOW_REPORTER_PID" 2>/dev/null; then + return + fi + stop_window_reporter + [ -f "$APP_DIR/active-window-reporter.js" ] || return 0 + REIMS_HOST_URL="$REIMS_HOST_URL" REIMS_TOKEN="$REIMS_TOKEN" /usr/bin/osascript -l JavaScript \ + "$APP_DIR/active-window-reporter.js" "$requested_generation" >/dev/null 2>&1 & + WINDOW_REPORTER_PID=$! + window_report_generation="$requested_generation" +} + apply_host_config() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true) + sync_window_reporter "$cfg_json" [ -n "$cfg_json" ] || return 0 if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then clip_enabled="0" @@ -1386,6 +1423,9 @@ if [ -f "$SRC/drop-resolve.js" ]; then cp "$SRC/drop-resolve.js" "$APP_DIR/drop-resolve.js" chmod 755 "$APP_DIR/drop-resolve.js" fi +if [ -f "$SRC/active-window-reporter.js" ]; then + cp "$SRC/active-window-reporter.js" "$APP_DIR/active-window-reporter.js" +fi chmod 600 "$APP_DIR/config" chmod 755 "$APP_DIR/guest-tools.sh" [ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE_SYNC" "$HOME/Desktop/ReimsShare" 2>/dev/null || true diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 87e3da4..8d69058 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -274,6 +274,8 @@ type registeredVM struct { sleepActive bool agentVersion int lastSeen time.Time + windowReportGen uint64 + windowReport windowReport dropShares *dropShareStore dropDAVHandler *webdav.Handler @@ -308,6 +310,7 @@ type Server struct { folderAccessMu sync.RWMutex folderGeneration uint64 registrationGen uint64 + nextWindowGen uint64 dynamicRoutes map[string]http.HandlerFunc clipboardActive bool globalClipPolicy ClipboardPolicy @@ -392,6 +395,7 @@ func (s *Server) Start(preferredPort int) (int, error) { mux := http.NewServeMux() mux.HandleFunc("/v1/ping", s.handlePing) mux.HandleFunc("/v1/config", s.handleConfig) + mux.HandleFunc(activeWindowPath, s.handleActiveWindow) mux.HandleFunc("/v1/folders", s.handleFolders) mux.HandleFunc("/v1/status", s.handleStatus) mux.HandleFunc("/v1/dns-query", s.handleDNSQuery) @@ -502,6 +506,10 @@ func (s *Server) Close(ctx context.Context) error { relays := s.management s.management = nil s.clearAllClipFilesLocked() + for _, vm := range s.vms { + vm.windowReportGen = 0 + vm.windowReport = windowReport{} + } s.mu.Unlock() s.cleanupClipFiles() for _, relay := range relays { @@ -575,6 +583,8 @@ func (s *Server) RegisterVM(cfg VMConfig) { } else if cur.token != cfg.Token { cur.dropShares.revokeClipboard() s.clearVMClipFilesLocked(key) + cur.windowReportGen = 0 + cur.windowReport = windowReport{} } folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders)) for _, folder := range cfg.ResolvedFolders { @@ -957,6 +967,7 @@ func (s *Server) authenticateToken(tok string) *registeredVM { sleepActive: vm.sleepActive, agentVersion: vm.agentVersion, lastSeen: vm.lastSeen, + windowReportGen: vm.windowReportGen, } return &cp } @@ -1023,6 +1034,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(map[string]any{ "vm": vm.name, "keymap_carrier_enabled": vm.keymapCarrierEnabled, + "window_report_generation": vm.windowReportGen, "prevent_sleep": vm.preventSleep, "webdav_drop_path": "/dav-drop/" + vm.name + "/", "host_dns_enabled": vm.hostDNSEnabled, diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 202d422..ea9994d 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -123,6 +123,13 @@ var catalog = map[Locale]map[string]string{ "eject": "弹出安装盘", "emptyVMs": "还没有虚拟机", "err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器", + "err.app_window_capture": "无法获取 {name} 的应用画面", + "err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口", + "err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口", + "err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试", + "err.app_window_open": "先关闭已打开的独立应用窗口", + "err.app_window_pointer": "在 {name} 中启用 USB 数位板后再打开独立窗口", + "err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机", "err.clone.backing_in_use": "「{clone}」仍依赖此磁盘,删除该副本后才能继续", "err.clone.disk_busy": "等待此磁盘上的操作完成后再试", "err.clone.disk_missing": "找不到原虚拟机磁盘文件:{path}", @@ -793,6 +800,13 @@ var catalog = map[Locale]map[string]string{ "eject": "Eject installer", "emptyVMs": "No virtual machines", "err.affinity.empty_mask": "Select at least 1 logical processor", + "err.app_window_capture": "Could not capture the app window in {name}", + "err.app_window_guest_tools": "Connect Guest Tools in {name} and try again", + "err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again", + "err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again", + "err.app_window_open": "Close the current separate app window first", + "err.app_window_pointer": "Enable the USB tablet for {name} and try again", + "err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows", "err.clone.backing_in_use": "Delete “{clone}” before continuing because it still depends on this disk", "err.clone.disk_busy": "Wait for the operation on this disk to finish and try again", "err.clone.disk_missing": "Source disk file not found: {path}", @@ -1382,6 +1396,11 @@ var paramOrder = map[string][]string{ "doctor.pcores.detail": {"count", "mask", "cpus"}, "doctor.ram.detail": {"total", "avail"}, "doctor.runtime.active": {"commit", "dir"}, + "err.app_window_capture": {"name"}, + "err.app_window_guest_tools": {"name"}, + "err.app_window_guest_tools_update": {"name"}, + "err.app_window_no_window": {"name"}, + "err.app_window_pointer": {"name"}, "err.clone.backing_in_use": {"clone"}, "err.clone.disk_missing": {"path"}, "err.clone.disk_running": {"name"}, @@ -1394,6 +1413,7 @@ var paramOrder = map[string][]string{ "err.computer_use.not_owned": {"name"}, "err.computer_use.phase_confirmation": {"name", "phase"}, "err.computer_use.restore_confirmation": {"name"}, + "err.computer_use.vm_not_running": {"name"}, "err.dataroot.damaged": {"dir"}, "err.dataroot.locked": {"dir"}, "err.dataroot.migration_failed": {"dir"}, diff --git a/internal/plugin/builtin/computer_use.go b/internal/plugin/builtin/computer_use.go index 55786db..378b38f 100644 --- a/internal/plugin/builtin/computer_use.go +++ b/internal/plugin/builtin/computer_use.go @@ -13,6 +13,7 @@ import ( type ComputerUseService interface { WithVM(ctx context.Context, vmDir string, operation func(context.Context) error) error Screendump(ctx context.Context, vmDir, path string) (string, error) + ScreendumpDisplay(ctx context.Context, vmDir, path, device string, head int) (string, error) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) Forget(ctx context.Context, vmDir string) error Close() @@ -21,9 +22,11 @@ type ComputerUseService interface { PointerAvailable(ctx context.Context, vmDir string) (bool, error) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error MouseButton(ctx context.Context, vmDir, button string, down bool) error + MouseButtonAt(ctx context.Context, vmDir string, x, y, width, height int, button string, down bool) error MouseClick(ctx context.Context, vmDir, button string) error 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 } func defComputerUse(ver string, desiredFn func(string, bool) bool) plugin.PluginDef { diff --git a/internal/qmp/app_window_test.go b/internal/qmp/app_window_test.go new file mode 100644 index 0000000..7d42f59 --- /dev/null +++ b/internal/qmp/app_window_test.go @@ -0,0 +1,80 @@ +package qmp + +import ( + "encoding/json" + "testing" +) + +type commandRecorder struct { + command string + args any + calls int +} + +func (r *commandRecorder) Execute(command string, args any) error { + r.command = command + r.args = args + r.calls++ + return nil +} + +func TestScreendumpDisplay(t *testing.T) { + q := &commandRecorder{} + format, err := ScreendumpDisplay(q, "frame.ppm", "gfx", 1) + if err != nil || format != "ppm" || q.command != "screendump" { + t.Fatalf("display dump returned %q, %v, command %q", format, err, q.command) + } + args := q.args.(map[string]any) + if args["filename"] != "frame.ppm" || args["format"] != "ppm" || args["device"] != "gfx" || args["head"] != 1 { + t.Fatalf("unexpected display dump arguments: %v", args) + } + if _, err := ScreendumpDisplay(q, "primary.ppm", "", 0); err != nil { + t.Fatal(err) + } + args = q.args.(map[string]any) + if len(args) != 2 { + t.Fatalf("primary display dump should omit device and head: %v", args) + } + if _, err := ScreendumpDisplay(q, "invalid.ppm", "", 1); err == nil || q.calls != 2 { + t.Fatalf("invalid display head reached QEMU: calls=%d err=%v", q.calls, err) + } +} + +func TestMouseButtonAtReportsPositionAndPressTogether(t *testing.T) { + q := &commandRecorder{} + if err := MouseButtonAt(q, 99, 0, 100, 50, "left", true); err != nil { + t.Fatal(err) + } + args, err := json.Marshal(q.args) + if err != nil { + t.Fatal(err) + } + want := `{"events":[{"data":{"axis":"x","value":32767},"type":"abs"},{"data":{"axis":"y","value":0},"type":"abs"},{"data":{"button":"left","down":true},"type":"btn"}]}` + if q.calls != 1 || q.command != "input-send-event" || string(args) != want { + t.Fatalf("unexpected mouse press: calls=%d command=%q args=%s", q.calls, q.command, args) + } + if err := MouseButtonAt(q, 100, 0, 100, 50, "left", true); err == nil || q.calls != 1 { + t.Fatalf("invalid position reached QEMU: calls=%d err=%v", q.calls, err) + } +} + +func TestQKeyCode(t *testing.T) { + for vk, want := range map[uint32]string{ + 'A': "a", '9': "9", 0x11: "meta_l", 0xA3: "meta_r", 0x5B: "ctrl", 0xA5: "alt_r", + 0x21: "pgup", 0x22: "pgdn", 0x60: "kp_0", 0x87: "f24", 0xDB: "bracket_left", 0xE7: "", + } { + if got := QKeyCode(vk); got != want { + t.Errorf("QKeyCode(%#02x) = %q, want %q", vk, got, want) + } + } +} + +func TestSendKey(t *testing.T) { + q := &recorder{} + if err := SendKey(q, "meta_l", false); err != nil { + t.Fatal(err) + } + if len(q.events) != 1 || q.events[0] != "meta_l up" { + t.Fatalf("unexpected key release: %v", q.events) + } +} diff --git a/internal/qmp/client.go b/internal/qmp/client.go index 360e448..3fb81fb 100644 --- a/internal/qmp/client.go +++ b/internal/qmp/client.go @@ -26,6 +26,8 @@ func Dial(ctx context.Context, network, addr string) (*Conn, error) { c := &Conn{nc: nc, scanner: bufio.NewScanner(nc)} c.scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) + stopCancel := context.AfterFunc(ctx, func() { _ = nc.Close() }) + defer stopCancel() _ = nc.SetDeadline(time.Now().Add(5 * time.Second)) if !c.scanner.Scan() { // greeting nc.Close() @@ -38,6 +40,10 @@ func Dial(ctx context.Context, network, addr string) (*Conn, error) { nc.Close() return nil, err } + if err := ctx.Err(); err != nil { + nc.Close() + return nil, err + } return c, nil } diff --git a/internal/qmp/keys.go b/internal/qmp/keys.go index 74da21a..7b5fd47 100644 --- a/internal/qmp/keys.go +++ b/internal/qmp/keys.go @@ -2,6 +2,7 @@ package qmp import ( "context" + "errors" "fmt" "math" "path/filepath" @@ -108,6 +109,14 @@ func sendKeys(q Executor, down bool, keys ...string) error { return q.Execute("input-send-event", map[string]any{"events": events}) } +// SendKey sends one QKeyCode transition. Callers pair a press with a release. +func SendKey(q Executor, key string, down bool) error { + if q == nil { + return errors.New("QMP session is unavailable") + } + return sendKeys(q, down, key) +} + // 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. diff --git a/internal/qmp/pointer.go b/internal/qmp/pointer.go index 671144a..23ec172 100644 --- a/internal/qmp/pointer.go +++ b/internal/qmp/pointer.go @@ -52,18 +52,43 @@ func MouseMove(q Executor, x, y, width, height int) error { if q == nil { return errors.New("QMP session is unavailable") } + events, err := mouseMoveEvents(x, y, width, height) + if err != nil { + return err + } + return q.Execute("input-send-event", map[string]any{"events": events}) +} + +// MouseButtonAt sends the position and one button transition in the same +// input report, so a press cannot land at the pointer's previous position. +func MouseButtonAt(q Executor, x, y, width, height int, button string, down bool) error { + if q == nil { + return errors.New("QMP session is unavailable") + } + button = normalizeMouseButton(button) + if !validMouseButton(button) { + return fmt.Errorf("unsupported mouse button %q", button) + } + events, err := mouseMoveEvents(x, y, width, height) + if err != nil { + return err + } + return q.Execute("input-send-event", map[string]any{"events": append(events, mouseButtonEvent(button, down))}) +} + +func mouseMoveEvents(x, y, width, height int) ([]any, error) { ax, err := absoluteAxis(x, width) if err != nil { - return fmt.Errorf("mouse x coordinate: %w", err) + return nil, fmt.Errorf("mouse x coordinate: %w", err) } ay, err := absoluteAxis(y, height) if err != nil { - return fmt.Errorf("mouse y coordinate: %w", err) + return nil, fmt.Errorf("mouse y coordinate: %w", err) } - return q.Execute("input-send-event", map[string]any{"events": []any{ + return []any{ map[string]any{"type": "abs", "data": map[string]any{"axis": "x", "value": ax}}, map[string]any{"type": "abs", "data": map[string]any{"axis": "y", "value": ay}}, - }}) + }, nil } // MouseButton sends one supported QEMU mouse button transition. diff --git a/internal/qmp/screendump.go b/internal/qmp/screendump.go index d64a12a..eef5f07 100644 --- a/internal/qmp/screendump.go +++ b/internal/qmp/screendump.go @@ -1,6 +1,9 @@ package qmp -import "context" +import ( + "context" + "errors" +) // Screendump asks QEMU to write the current frame of console 0 to path as a // binary PPM and returns "ppm". PPM rather than PNG on purpose: QEMU encodes @@ -8,7 +11,24 @@ import "context" // ~820 ms there against ~35 ms for PPM (measured 2026-11-28, QEMU 11.1), so // PNG would stall the guest each time the page refreshes its thumbnail. func (c *Conn) Screendump(path string) (string, error) { - if err := c.Execute("screendump", map[string]any{"filename": path, "format": "ppm"}); err != nil { + return ScreendumpDisplay(c, path, "", 0) +} + +// ScreendumpDisplay writes a binary PPM from the requested display device and +// head. An empty device selects QEMU's primary console. +func ScreendumpDisplay(q Executor, path, device string, head int) (string, error) { + if q == nil { + return "", errors.New("QMP session is unavailable") + } + if head < 0 || (device == "" && head != 0) { + return "", errors.New("invalid QMP display head") + } + args := map[string]any{"filename": path, "format": "ppm"} + if device != "" { + args["device"] = device + args["head"] = head + } + if err := q.Execute("screendump", args); err != nil { return "", err } return "ppm", nil diff --git a/internal/qmp/windows_keys.go b/internal/qmp/windows_keys.go new file mode 100644 index 0000000..f7e1800 --- /dev/null +++ b/internal/qmp/windows_keys.go @@ -0,0 +1,74 @@ +package qmp + +import "strconv" + +// QKeyCode maps a Windows virtual-key code from an app window to a macOS guest +// key. Windows Ctrl acts as Command for familiar shortcuts, and the Windows +// key acts as Control. OEM punctuation follows the US keyboard layout. +// An empty result means the virtual key has no mapping. +func QKeyCode(vk uint32) string { + switch { + case vk >= 'A' && vk <= 'Z': + return string(rune(vk - 'A' + 'a')) + case vk >= '0' && vk <= '9': + return string(rune(vk)) + case vk >= 0x60 && vk <= 0x69: // VK_NUMPAD0 through VK_NUMPAD9 + return "kp_" + strconv.FormatUint(uint64(vk-0x60), 10) + case vk >= 0x70 && vk <= 0x87: // VK_F1 through VK_F24 + return "f" + strconv.FormatUint(uint64(vk-0x70+1), 10) + default: + return windowsVirtualKeys[vk] + } +} + +var windowsVirtualKeys = map[uint32]string{ + 0x08: "backspace", // VK_BACK + 0x09: "tab", // VK_TAB + 0x0D: "ret", // VK_RETURN + 0x10: "shift", // VK_SHIFT + 0x11: "meta_l", // VK_CONTROL + 0x12: "alt", // VK_MENU + 0x13: "pause", // VK_PAUSE + 0x14: "caps_lock", // VK_CAPITAL + 0x1B: "esc", // VK_ESCAPE + 0x20: "spc", // VK_SPACE + 0x21: "pgup", // VK_PRIOR + 0x22: "pgdn", // VK_NEXT + 0x23: "end", // VK_END + 0x24: "home", // VK_HOME + 0x25: "left", // VK_LEFT + 0x26: "up", // VK_UP + 0x27: "right", // VK_RIGHT + 0x28: "down", // VK_DOWN + 0x2C: "print", // VK_SNAPSHOT + 0x2D: "insert", // VK_INSERT + 0x2E: "delete", // VK_DELETE + 0x5B: "ctrl", // VK_LWIN + 0x5C: "ctrl_r", // VK_RWIN + 0x5D: "menu", // VK_APPS + 0x6A: "kp_multiply", // VK_MULTIPLY + 0x6B: "kp_add", // VK_ADD + 0x6D: "kp_subtract", // VK_SUBTRACT + 0x6E: "kp_decimal", // VK_DECIMAL + 0x6F: "kp_divide", // VK_DIVIDE + 0x90: "num_lock", // VK_NUMLOCK + 0x91: "scroll_lock", // VK_SCROLL + 0xA0: "shift", // VK_LSHIFT + 0xA1: "shift_r", // VK_RSHIFT + 0xA2: "meta_l", // VK_LCONTROL + 0xA3: "meta_r", // VK_RCONTROL + 0xA4: "alt", // VK_LMENU + 0xA5: "alt_r", // VK_RMENU + 0xBA: "semicolon", // VK_OEM_1 + 0xBB: "equal", // VK_OEM_PLUS + 0xBC: "comma", // VK_OEM_COMMA + 0xBD: "minus", // VK_OEM_MINUS + 0xBE: "dot", // VK_OEM_PERIOD + 0xBF: "slash", // VK_OEM_2 + 0xC0: "grave_accent", // VK_OEM_3 + 0xDB: "bracket_left", // VK_OEM_4 + 0xDC: "backslash", // VK_OEM_5 + 0xDD: "bracket_right", // VK_OEM_6 + 0xDE: "apostrophe", // VK_OEM_7 + 0xE2: "less", // VK_OEM_102 +} diff --git a/locales/en-US/native.json b/locales/en-US/native.json index b159f68..25aaa05 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -311,6 +311,13 @@ "err.computer_use.not_owned": "VM {name} is not an MCP-created temporary clone", "err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}", "err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen", + "err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows", + "err.app_window_guest_tools": "Connect Guest Tools in {name} and try again", + "err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again", + "err.app_window_open": "Close the current separate app window first", + "err.app_window_pointer": "Enable the USB tablet for {name} and try again", + "err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again", + "err.app_window_capture": "Could not capture the app window in {name}", "err.vm_window_not_found": "Couldn’t find the display window for {name}", "err.fullscreen_failed": "Couldn’t toggle full screen for {name}", "err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index a05d36c..2ee2794 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -10,6 +10,8 @@ "failFullscreen": "Couldn’t toggle full screen", "showInstallGuide": "Show install guide", "copyScreenshot": "Copy screenshot", + "openAppWindow": "Open app in separate window", + "failOpenAppWindow": "Could not open the app window", "toastScreenshotCopied": "VM screenshot copied", "failFocus": "Could not focus VM window", "failScreenshot": "Screenshot failed", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 5e8eba5..e912625 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -311,6 +311,13 @@ "err.computer_use.not_owned": "虚拟机 {name} 不是 MCP 创建的临时克隆", "err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照", "err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏", + "err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机", + "err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口", + "err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口", + "err.app_window_open": "先关闭已打开的独立应用窗口", + "err.app_window_pointer": "在 {name} 中启用 USB 数位板后再打开独立窗口", + "err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试", + "err.app_window_capture": "无法获取 {name} 的应用画面", "err.vm_window_not_found": "找不到 {name} 的显示窗口", "err.fullscreen_failed": "无法切换 {name} 的全屏状态", "err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 30b5948..30e2937 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -10,6 +10,8 @@ "failFullscreen": "无法切换全屏", "showInstallGuide": "显示安装引导", "copyScreenshot": "截屏并复制", + "openAppWindow": "打开独立应用窗口", + "failOpenAppWindow": "无法打开独立应用窗口", "toastScreenshotCopied": "已复制虚拟机画面", "failFocus": "无法定位虚拟机窗口", "failScreenshot": "截屏失败", From e281e43d078755908eaeb64349206c81a6836cef Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 07:33:21 +0800 Subject: [PATCH 03/10] fix: release app window input on close --- internal/app/app_window_flow.go | 2 +- internal/appwindow/session.go | 42 +++++++++++------- internal/console/manager.go | 6 +++ internal/guesttools/active_window_reporter.js | 43 ++++++++++++------- internal/plugin/builtin/computer_use.go | 1 + internal/qmp/keys.go | 18 ++++++++ 6 files changed, 80 insertions(+), 32 deletions(-) diff --git a/internal/app/app_window_flow.go b/internal/app/app_window_flow.go index c28598a..21abf05 100644 --- a/internal/app/app_window_flow.go +++ b/internal/app/app_window_flow.go @@ -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: diff --git a/internal/appwindow/session.go b/internal/appwindow/session.go index e37e4c2..063e17c 100644 --- a/internal/appwindow/session.go +++ b/internal/appwindow/session.go @@ -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 } diff --git a/internal/console/manager.go b/internal/console/manager.go index c7f8417..5e53479 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -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 { diff --git a/internal/guesttools/active_window_reporter.js b/internal/guesttools/active_window_reporter.js index 00e28fb..9425710 100644 --- a/internal/guesttools/active_window_reporter.js +++ b/internal/guesttools/active_window_reporter.js @@ -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) } diff --git a/internal/plugin/builtin/computer_use.go b/internal/plugin/builtin/computer_use.go index 378b38f..b577f12 100644 --- a/internal/plugin/builtin/computer_use.go +++ b/internal/plugin/builtin/computer_use.go @@ -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 { diff --git a/internal/qmp/keys.go b/internal/qmp/keys.go index 7b5fd47..73dd3f5 100644 --- a/internal/qmp/keys.go +++ b/internal/qmp/keys.go @@ -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. From d36d3ed0d64248130525a9191f31f3919a1ebd52 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 07:34:27 +0800 Subject: [PATCH 04/10] test: make app window freshness check deterministic --- internal/guesttools/active_window_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/internal/guesttools/active_window_test.go b/internal/guesttools/active_window_test.go index 873096f..28886fe 100644 --- a/internal/guesttools/active_window_test.go +++ b/internal/guesttools/active_window_test.go @@ -89,7 +89,10 @@ func TestActiveWindowReporting(t *testing.T) { if got, ok := srv.ActiveWindow("mac-one", time.Second); !ok || got != window { t.Fatalf("active window = %+v, %t", got, ok) } - if _, ok := srv.ActiveWindow("mac-one", 0); ok { + srv.mu.Lock() + srv.vms["mac-one"].windowReport.receivedAt = time.Now().Add(-2 * time.Second) + srv.mu.Unlock() + if _, ok := srv.ActiveWindow("mac-one", time.Second); ok { t.Fatal("report older than maxAge was accepted") } if _, ok := srv.ActiveWindow("mac-two", time.Second); ok { From 3bfbc3604d1188edcfc0d15a3a2b1564f78d9ed0 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 07:35:09 +0800 Subject: [PATCH 05/10] test: resolve registered VM key in freshness check --- internal/guesttools/active_window_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/internal/guesttools/active_window_test.go b/internal/guesttools/active_window_test.go index 28886fe..5e720d5 100644 --- a/internal/guesttools/active_window_test.go +++ b/internal/guesttools/active_window_test.go @@ -89,9 +89,15 @@ func TestActiveWindowReporting(t *testing.T) { if got, ok := srv.ActiveWindow("mac-one", time.Second); !ok || got != window { t.Fatalf("active window = %+v, %t", got, ok) } - srv.mu.Lock() - srv.vms["mac-one"].windowReport.receivedAt = time.Now().Add(-2 * time.Second) - srv.mu.Unlock() + func() { + srv.mu.Lock() + defer srv.mu.Unlock() + vm := srv.vms[normalizeVMRegistryKey("mac-one")] + if vm == nil { + t.Fatal("registered VM was not found") + } + vm.windowReport.receivedAt = time.Now().Add(-2 * time.Second) + }() if _, ok := srv.ActiveWindow("mac-one", time.Second); ok { t.Fatal("report older than maxAge was accepted") } From a9b2553727e583a42f3fa177693604dcaa8c49ae Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 08:01:01 +0800 Subject: [PATCH 06/10] fix: synchronize clipboard for macOS app windows --- changes/macos-app-window.json | 4 +- internal/app/app_window_flow.go | 14 +- internal/appwindow/session.go | 84 +++++- internal/appwindow/session_test.go | 86 +++++- internal/guesttools/clipboard_agent_test.go | 98 ++++++- internal/guesttools/clipboard_applied.go | 262 ++++++++++++++++++ internal/guesttools/clipboard_applied_test.go | 233 ++++++++++++++++ internal/guesttools/folder_share.go | 3 +- internal/guesttools/image.go | 58 +++- internal/guesttools/server.go | 32 ++- internal/i18n/catalog_gen.go | 2 + locales/en-US/native.json | 1 + locales/zh-CN/native.json | 1 + 13 files changed, 840 insertions(+), 38 deletions(-) create mode 100644 internal/guesttools/clipboard_applied.go create mode 100644 internal/guesttools/clipboard_applied_test.go diff --git a/changes/macos-app-window.json b/changes/macos-app-window.json index 16d18e6..3b3d70d 100644 --- a/changes/macos-app-window.json +++ b/changes/macos-app-window.json @@ -2,6 +2,6 @@ "group": "new", "order": 0, "authors": ["yxc0915"], - "zh": "可在 Windows 独立窗口中查看和操作正在运行的 macOS 虚拟机的前台应用。", - "en": "View and interact with the foreground app of a running macOS VM in a separate Windows window." + "zh": "可在 Windows 独立窗口中操作正在运行的 macOS 虚拟机的前台应用,并在宿主与客体之间复制粘贴。", + "en": "Interact with the foreground app of a running macOS VM in a separate Windows window with bidirectional copy and paste." } diff --git a/internal/app/app_window_flow.go b/internal/app/app_window_flow.go index 21abf05..d64ec4c 100644 --- a/internal/app/app_window_flow.go +++ b/internal/app/app_window_flow.go @@ -81,7 +81,7 @@ func (a *App) OpenAppWindow(driverID, name string) error { if !status.Connected { return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) } - if status.AgentVersion < guesttools.WindowReportAgentVersion { + if status.AgentVersion < guesttools.PasteReadyAgentVersion { return coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil) } service := a.computerUseInternalService() @@ -102,6 +102,18 @@ func (a *App) OpenAppWindow(driverID, name string) error { Window: func(maxAge time.Duration) (guesttools.ActiveWindow, bool) { return bridge.ActiveWindow(name, maxAge) }, + PrepareClipboard: func(wait context.Context) (func(), error) { + return bridge.PrepareGuestClipboardPaste(wait, name) + }, + OnClipboardError: func(err error) { + a.emitVMLogForDriver(info.DriverID, name, "App window paste: "+err.Error()) + a.mu.Lock() + manager := a.trayMgr + a.mu.Unlock() + if manager != nil { + manager.Notify(i18n.T(locale, "tray.notify.app_window_paste_retry"), name, true) + } + }, }) if errors.Is(err, appwindow.ErrNoWindow) { return coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil) diff --git a/internal/appwindow/session.go b/internal/appwindow/session.go index 063e17c..168f818 100644 --- a/internal/appwindow/session.go +++ b/internal/appwindow/session.go @@ -24,6 +24,7 @@ var ErrNoWindow = errors.New("no foreground guest window reported") const ( windowMaxAge = time.Second frameTimeout = 800 * time.Millisecond + pasteTimeout = 4 * time.Second maxFramePixels = 4096 * 2160 ) @@ -40,10 +41,12 @@ type Console interface { } type SessionOptions struct { - VMDir string - TmpDir string - Window func(time.Duration) (guesttools.ActiveWindow, bool) - Console Console + VMDir string + TmpDir string + Window func(time.Duration) (guesttools.ActiveWindow, bool) + Console Console + PrepareClipboard func(context.Context) (func(), error) + OnClipboardError func(error) } type frameMapping struct { @@ -64,34 +67,52 @@ type session struct { } type inputQueue struct { - mu sync.Mutex - events []ViewerEvent - ready chan 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] = event + q.events[last] = input return true } if len(q.events) == 64 { return event.Kind == ViewerMouseMove } - q.events = append(q.events, event) + q.events = append(q.events, input) if last < 0 { q.ready <- struct{}{} } return true } -func (q *inputQueue) pop() ViewerEvent { +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{}{} @@ -310,7 +331,8 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e return ErrNoWindow } case <-queue.ready: - event := queue.pop() + 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) @@ -319,9 +341,42 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e continue } mapping, active := s.eventMapping(event) - request, cancel := context.WithTimeout(ctx, frameTimeout) + 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 { @@ -331,6 +386,11 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e } } +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) diff --git a/internal/appwindow/session_test.go b/internal/appwindow/session_test.go index 62811df..e449b06 100644 --- a/internal/appwindow/session_test.go +++ b/internal/appwindow/session_test.go @@ -13,6 +13,90 @@ import ( type captureConsole struct{ Console } +type pasteConsole struct { + Console + sent chan string +} + +func (c pasteConsole) SendKey(_ context.Context, _, key string, down bool) error { + if down { + c.sent <- key + } + return nil +} + +func (c pasteConsole) ReleaseInputs(context.Context, string, []string, []string) error { + c.sent <- "released" + return nil +} + +func TestPasteWaitsForClipboardAndCancelsOnBlur(t *testing.T) { + for _, name := range []string{"applied", "blur"} { + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + window := guesttools.ActiveWindow{ID: 1} + ready, entered := make(chan struct{}), make(chan struct{}) + console := pasteConsole{sent: make(chan string, 8)} + s := &session{ + SessionOptions: SessionOptions{ + Console: console, + Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return window, true }, + PrepareClipboard: func(ctx context.Context) (func(), error) { + close(entered) + select { + case <-ready: + return func() {}, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + }, + }, + id: 1, tag: 1, mapping: frameMapping{window: window}, lastFrame: time.Now(), + } + queue := &inputQueue{ready: make(chan struct{}, 1)} + done := make(chan error, 1) + go func() { done <- s.forwardInput(ctx, queue) }() + defer func() { + cancel() + <-done + }() + + queue.push(ViewerEvent{Kind: ViewerFocus, Down: true}) + queue.push(ViewerEvent{Kind: ViewerKey, FrameTag: 1, VirtualKey: 0x11, Down: true}) + queue.push(ViewerEvent{Kind: ViewerKey, FrameTag: 1, VirtualKey: 'V', Down: true}) + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("clipboard wait did not start") + } + if key := <-console.sent; key != "meta_l" { + t.Fatalf("first key = %q", key) + } + select { + case key := <-console.sent: + t.Fatalf("forwarded %q before clipboard changed", key) + default: + } + want := "v" + if name == "blur" { + queue.push(ViewerEvent{Kind: ViewerFocus}) + want = "released" + } else { + close(ready) + } + select { + case key := <-console.sent: + if key != want { + t.Fatalf("event = %q, want %q", key, want) + } + case <-ctx.Done(): + t.Fatalf("did not receive %q", want) + } + }) + } +} + func TestInputQueueKeepsClickBetweenMoves(t *testing.T) { q := &inputQueue{ready: make(chan struct{}, 1)} for _, event := range []ViewerEvent{ @@ -36,7 +120,7 @@ func TestInputQueueKeepsClickBetweenMoves(t *testing.T) { default: t.Fatal("queue did not notify its reader") } - if got := q.pop(); got != want { + if got := q.pop().ViewerEvent; got != want { t.Fatalf("event = %+v, want %+v", got, want) } } diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 250d75b..3132a42 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -76,6 +76,11 @@ func TestGuestAgentClipboardScript(t *testing.T) { cases []string }{ {"download", []string{"failed_png", "failed_text", "missing_hash", "reencoded_png"}}, + {"paste_ready", []string{ + "paste_ack_text", "paste_ack_preapplied", "paste_ack_local_change", "paste_ack_unmarked", + "paste_ack_png", "paste_ack_unstable_png", "paste_ack_without_request", + "paste_recheck_guest_owned", "paste_recheck_local_change", "paste_recheck_inject", "paste_recheck_drop", + }}, {"download_during_copy", []string{ "guest_changes_during_get", "cold_guest_changes_during_get", "cold_lock_during_get", "repeat_host_copy", }}, @@ -231,6 +236,10 @@ post_code=200 post_hash=C post_seq=9 check_post_base=0 +offer_ack=0 +offer_recheck=0 +ack_hash=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +ack_nonce=ABCDEFGHIJKLMNOPQRSTUVWXYZ # MSYS cannot apply RLIMIT_FSIZE. The fixture still verifies the archive and HTTP flow. case "$(uname -s)" in @@ -410,6 +419,11 @@ curl() { accept="" output="" base="" + request_ack="" + acknowledged_seq="" + acknowledged_hash="" + acknowledged_generation="" + acknowledged_request="" body="" archive_upload="" url="" @@ -423,6 +437,11 @@ curl() { -H) case "$2" in 'X-Clip-Base-Seq: '*) base="$2" ;; + 'X-Reims-Clipboard-Ack: '*) request_ack="${2#*: }" ;; + 'X-Clip-Seq: '*) acknowledged_seq="${2#*: }" ;; + 'X-Clip-Hash: '*) acknowledged_hash="${2#*: }" ;; + 'X-Reims-Clipboard-Generation: '*) acknowledged_generation="${2#*: }" ;; + 'X-Reims-Clipboard-Request: '*) acknowledged_request="${2#*: }" ;; 'Accept: '*) accept="$2" ;; esac shift @@ -466,6 +485,13 @@ curl() { fi return ;; + */v1/clipboard/applied) + [ ! -d "$CLIP_LOCK" ] || exit 1 + expect "$method/$acknowledged_seq/$acknowledged_hash/$acknowledged_generation/$acknowledged_request" \ + "POST/$get_seq/$get_hash/14/$ack_nonce" + printf 'ACK %s\n' "$url" >> calls + return + ;; esac [ ! -d "$CLIP_LOCK" ] || exit 1 if [ -n "$archive_upload" ]; then @@ -509,6 +535,13 @@ curl() { : > "$headers" else printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers" + if [ "$offer_ack/$get_code" = 1/200 ]; then + expect "$request_ack" 1 + printf 'X-Reims-Clipboard-Ack: 1\r\nX-Reims-Clipboard-Generation: 14\r\nX-Reims-Clipboard-Request: %s\r\n' "$ack_nonce" >> "$headers" + if [ "$offer_recheck" = 1 ]; then + printf 'X-Reims-Clipboard-Recheck: 1\r\n' >> "$headers" + fi + fi fi printf '%s' "$get_value" > "$output" if [ "$fail_during_get" = 1 ]; then @@ -579,7 +612,10 @@ case "$1" in host_files_failed_write) : > test-fail-file-write ;; host_files_partial_write) : > test-partial-file-write ;; esac - if [ "$1" != host_files_sync_no_echo ]; then + if [ "$1" = host_files_sync_no_echo ]; then + offer_ack=1 + get_hash="$ack_hash" + else printf '%s\n' '{"changeCount":17,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json fi sync_clipboard @@ -589,7 +625,7 @@ case "$1" in [ ! -d "$CLIP_LOCK" ] exit 0 fi - expect "$last_server_hash" B + expect "$last_server_hash" "$get_hash" expect "$synced_local_cc/$synced_local_kind" 2/files expect "$(read_local_clipboard readback)" files expect "$(awk 'END {print NR}' readback)" 2 @@ -598,12 +634,14 @@ a%23note.txt' expect "$last_local_hash" "files:$(cat readback)" get_code=304 sync_clipboard - expect "$(methods)" GET,GET - expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&since_seq=8' + expect "$(methods)" GET,ACK,GET + expect_call -Fx "GET http://stub/v1/clipboard?since=$get_hash&wait=2&accept=image,files&since_seq=8" ;; host_files_tar_fallback|host_files_tar_fallback_changed) flags=typed_files get_kind=files + offer_ack=1 + get_hash="$ack_hash" get_value='{"drop_id":"clip-0123456789abcdef","items":["fallback.txt"]}' printf foreign > mount_owner printf '0 1048576\n' > clip_file_config @@ -612,13 +650,14 @@ a%23note.txt' tar -cf guest-fallback.tar fallback.txt if [ "$1" = host_files_tar_fallback_changed ]; then : > change_during_archive; fi sync_clipboard - expect "$(methods)" GET,DOWNLOAD [ ! -d "$CLIP_LOCK" ] if [ "$1" = host_files_tar_fallback_changed ]; then + expect "$(methods)" GET,DOWNLOAD expect "$last_server_hash/$file_retry_polls" /3 expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" 'new guest copy' else - expect "$last_server_hash" B + expect "$(methods)" GET,DOWNLOAD,ACK + expect "$last_server_hash" "$get_hash" expect "$(cat "$CLIP_CACHE/clip-0123456789abcdef/fallback.txt")" fallback expect "$(read_local_clipboard readback)" files grep -q '/clip_cache/clip-0123456789abcdef/fallback.txt$' readback @@ -1033,6 +1072,53 @@ a%23note.txt' expect "$(methods)" GET,GET expect_call -F 'since=png:B&' ;; + paste_ack_*) + offer_ack=1 + get_hash="$ack_hash" + get_value="$get_hash" + printf '10\n' > change_count + case "$1" in + paste_ack_preapplied) printf '%s' "$get_value" > local_value ;; + paste_ack_local_change) flags=guest_change ;; + paste_ack_unmarked) offer_ack=0 ;; + paste_ack_png) get_kind=png ;; + paste_ack_unstable_png) get_kind=png; flags=change_after_write ;; + paste_ack_without_request) ack_nonce="" ;; + esac + sync_clipboard + case "$1" in + paste_ack_text|paste_ack_preapplied) + expect "$(methods)/$(read_file local_value)" "GET,ACK/$get_value" + if [ "$1" = paste_ack_preapplied ]; then [ ! -s copies ]; fi + ;; + paste_ack_png) expect "$(methods)/$synced_local_kind" GET,ACK/png ;; + paste_ack_local_change) expect "$(methods)/$(read_file local_value)" GET/C ;; + *) expect "$(methods)" GET ;; + esac + ;; + paste_recheck_*) + offer_ack=1 + offer_recheck=1 + get_hash="$ack_hash" + get_value="$get_hash" + last_server_hash="$get_hash" + last_server_seq="$get_seq" + last_local_hash=guest-own + printf '%s' "$last_local_hash" > local_value + printf '10\n' > change_count + case "$1" in + paste_recheck_local_change) flags=guest_change ;; + paste_recheck_inject) flags=inject_during_get ;; + paste_recheck_drop) flags=drop_during_get ;; + esac + sync_clipboard + [ ! -s copies ] + case "$1" in + paste_recheck_guest_owned) expect "$(methods)/$(read_file local_value)" GET,ACK/guest-own ;; + paste_recheck_local_change) expect "$(methods)/$(read_file local_value)" GET/C ;; + *) expect "$(methods)" GET ;; + esac + ;; guest_changes_during_get|cold_guest_changes_during_get) if [ "$1" = guest_changes_during_get ]; then last_local_hash=A diff --git a/internal/guesttools/clipboard_applied.go b/internal/guesttools/clipboard_applied.go new file mode 100644 index 0000000..30963f9 --- /dev/null +++ b/internal/guesttools/clipboard_applied.go @@ -0,0 +1,262 @@ +package guesttools + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "net/http" + "strconv" + "sync" + "time" +) + +const ( + clipboardAppliedPath = "/v1/clipboard/applied" + clipboardAckHeader = "X-Reims-Clipboard-Ack" + clipboardWindowHeader = "X-Reims-Clipboard-Generation" + clipboardRequestHeader = "X-Reims-Clipboard-Request" + clipboardRecheckHeader = "X-Reims-Clipboard-Recheck" +) + +type guestClipboardStamp struct { + window uint64 + seq uint32 + hash string +} + +type guestClipboardDelivery struct { + ticket string + window uint64 + wanted guestClipboardStamp + offered guestClipboardStamp + applied guestClipboardStamp +} + +type guestClipboardOffer struct { + ticket string + window uint64 +} + +// clipboardWindowVMLocked resolves an authenticated view of the active app +// window. The caller holds s.mu for reading or writing. +func (s *Server) clipboardWindowVMLocked(vm *registeredVM) *registeredVM { + cur := s.vms[vm.key] + if cur == nil || cur.token != vm.token || cur.windowReportGen == 0 { + return nil + } + return cur +} + +func (s *Server) windowClipboardActive(vm *registeredVM) bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.clipboardWindowVMLocked(vm) != nil +} + +// offerGuestClipboard marks only snapshots currently requested by a paste. +// For unchanged content, the caller asks the agent to recheck its own +// pasteboard without overwriting a newer local selection. +func (s *Server) offerGuestClipboard(vm *registeredVM, seq uint32, hash string, recheck, expired bool) guestClipboardOffer { + s.mu.Lock() + defer s.mu.Unlock() + cur := s.clipboardWindowVMLocked(vm) + if cur == nil || !s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuest() { + return guestClipboardOffer{} + } + stamp := guestClipboardStamp{window: cur.windowReportGen, seq: seq, hash: hash} + delivery := &cur.clipboardDelivery + if delivery.ticket == "" || delivery.wanted != stamp || delivery.applied == stamp || + (recheck && delivery.offered == stamp && !expired) { + return guestClipboardOffer{} + } + delivery.offered = stamp + return guestClipboardOffer{ticket: delivery.ticket, window: delivery.window} +} + +func (s *Server) handleClipboardApplied(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + seq, seqErr := strconv.ParseUint(r.Header.Get("X-Clip-Seq"), 10, 32) + window, windowErr := strconv.ParseUint(r.Header.Get(clipboardWindowHeader), 10, 64) + hash := r.Header.Get("X-Clip-Hash") + ticket := r.Header.Get(clipboardRequestHeader) + if seqErr != nil || windowErr != nil || window == 0 || len(hash) != 64 || ticket == "" || len(ticket) > 128 { + http.Error(w, "invalid clipboard acknowledgment", http.StatusBadRequest) + return + } + if _, err := hex.DecodeString(hash); err != nil { + http.Error(w, "invalid clipboard acknowledgment", http.StatusBadRequest) + return + } + stamp := guestClipboardStamp{window: window, seq: uint32(seq), hash: hash} + hostSeq := s.clip.SequenceNumber() + s.mu.Lock() + cur := s.clipboardWindowVMLocked(vm) + accepted := cur != nil && cur.windowReportGen == stamp.window && hostSeq == stamp.seq && cur.clipboardDelivery.ticket == ticket && + cur.clipboardDelivery.wanted == stamp && cur.clipboardDelivery.offered == stamp && + s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuest() + changed := accepted && cur.clipboardDelivery.applied != stamp + if changed { + cur.clipboardDelivery.applied = stamp + } + s.mu.Unlock() + if !accepted { + http.Error(w, "clipboard acknowledgment expired", http.StatusConflict) + return + } + if changed { + s.broadcastClipChange() + } + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) beginGuestClipboardWait(vmKey string) (guestClipboardOffer, error) { + s.mu.Lock() + defer s.mu.Unlock() + vm := s.vms[vmKey] + if vm == nil || vm.windowReportGen == 0 || !s.effectiveClipboardPolicyLocked(vmKey).allowsHostToGuest() { + return guestClipboardOffer{}, nil + } + if vm.clipboardDelivery.ticket != "" && vm.clipboardDelivery.window == vm.windowReportGen { + return guestClipboardOffer{}, errors.New("guest clipboard paste is already pending") + } + request := guestClipboardOffer{ticket: rand.Text(), window: vm.windowReportGen} + vm.clipboardDelivery = guestClipboardDelivery{ticket: request.ticket, window: request.window} + return request, nil +} + +func (s *Server) endGuestClipboardWait(vmKey string, request guestClipboardOffer) { + s.mu.Lock() + defer s.mu.Unlock() + if vm := s.vms[vmKey]; vm != nil && vm.clipboardDelivery.ticket == request.ticket { + vm.clipboardDelivery = guestClipboardDelivery{} + } +} + +// WaitForGuestClipboard waits until the active app window's guest agent has +// applied the newest eligible host clipboard snapshot. Disabled or ineligible +// clipboard data leaves the guest's ordinary Paste behavior available. +func (s *Server) WaitForGuestClipboard(ctx context.Context, vmKey string) error { + vmKey = normalizeVMRegistryKey(vmKey) + request, err := s.beginGuestClipboardWait(vmKey) + if err != nil || request.ticket == "" { + return err + } + defer s.endGuestClipboardWait(vmKey, request) + // The watcher also wakes the wait, but an independent sample covers a + // concurrent change during server startup or registration teardown. + tick := time.NewTicker(150 * time.Millisecond) + defer tick.Stop() + for { + if err := ctx.Err(); err != nil { + return err + } + changed := s.clipNotifyChan() + policy := s.EffectiveClipboardPolicy(vmKey) + if !policy.allowsHostToGuest() { + return nil + } + payload, seq, hash, err := s.readClipboardForSync(policy.SyncImages, policy.SyncFiles) + if err != nil { + return err + } + _, hash = s.clipboardForGuest(vmKey, payload, seq, hash, policy.SyncFiles, policy.SyncImages, policy.MaxImageBytes) + stamp := guestClipboardStamp{window: request.window, seq: seq, hash: hash} + if seq != s.clip.SequenceNumber() { + continue + } + s.mu.Lock() + vm := s.vms[vmKey] + active := vm != nil && vm.windowReportGen == request.window && vm.clipboardDelivery.ticket == request.ticket + currentPolicy := s.effectiveClipboardPolicyLocked(vmKey) + var pendingChanged, applied bool + if active && currentPolicy == policy { + delivery := &vm.clipboardDelivery + if pendingChanged = delivery.wanted != stamp; pendingChanged { + delivery.wanted = stamp + delivery.offered = guestClipboardStamp{} + delivery.applied = guestClipboardStamp{} + } + applied = delivery.applied == stamp + } + s.mu.Unlock() + if !active { + return errors.New("guest clipboard window is no longer active") + } + if currentPolicy != policy || seq != s.clip.SequenceNumber() { + continue + } + if applied || hash == "" { + return ctx.Err() + } + if pendingChanged { + s.broadcastClipChange() + continue + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-changed: + case <-tick.C: + } + } +} + +// PrepareGuestClipboardPaste holds the per-VM text injection lock from +// readiness check through actual Paste dispatch. Always call the returned +// release function on success. +func (s *Server) PrepareGuestClipboardPaste(ctx context.Context, vmKey string) (release func(), err error) { + vmKey = normalizeVMRegistryKey(vmKey) + s.mu.RLock() + vm := s.vms[vmKey] + var token string + if vm != nil { + token = vm.token + } + s.mu.RUnlock() + if vm == nil { + return nil, ErrGuestToolsNotConnected + } + tick := time.NewTicker(25 * time.Millisecond) + defer tick.Stop() + for !vm.injectMu.TryLock() { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-tick.C: + } + } + release = sync.OnceFunc(vm.injectMu.Unlock) + s.mu.RLock() + current := s.vms[vmKey] == vm && vm.token == token + s.mu.RUnlock() + if !current { + release() + return nil, ErrGuestToolsNotConnected + } + if err := ctx.Err(); err != nil { + release() + return nil, err + } + if err := s.WaitForGuestClipboard(ctx, vmKey); err != nil { + release() + return nil, err + } + s.mu.RLock() + current = s.vms[vmKey] == vm && vm.token == token + s.mu.RUnlock() + if !current { + release() + return nil, ErrGuestToolsNotConnected + } + return release, nil +} diff --git a/internal/guesttools/clipboard_applied_test.go b/internal/guesttools/clipboard_applied_test.go new file mode 100644 index 0000000..7649837 --- /dev/null +++ b/internal/guesttools/clipboard_applied_test.go @@ -0,0 +1,233 @@ +package guesttools + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +const clipboardReadyTestVM = "clipboard-test" + +func clipboardOffer(t *testing.T, srv *Server, query string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/v1/clipboard"+query, nil) + req.Header.Set("Authorization", "Bearer clipboard-test-token") + req.Header.Set(clipboardAckHeader, "1") + w := httptest.NewRecorder() + srv.handleClipboard(w, req) + return w +} + +func sendClipboardApplied(srv *Server, offer http.Header) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, clipboardAppliedPath, nil) + req.Header.Set("Authorization", "Bearer clipboard-test-token") + for _, key := range []string{"X-Clip-Seq", "X-Clip-Hash", clipboardWindowHeader, clipboardRequestHeader} { + req.Header.Set(key, offer.Get(key)) + } + w := httptest.NewRecorder() + srv.handleClipboardApplied(w, req) + return w +} + +func startGuestClipboardWait(t *testing.T, srv *Server) <-chan error { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) + t.Cleanup(cancel) + request := srv.clipNotifyChan() + done := make(chan error, 1) + go func() { done <- srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM) }() + select { + case <-request: + case err := <-done: + t.Fatalf("paste did not request a clipboard snapshot: %v", err) + case <-ctx.Done(): + t.Fatal("paste did not request a clipboard snapshot") + } + return done +} + +func TestAppWindowClipboardWaitRequiresLatestAppliedOffer(t *testing.T) { + clip := &memClipboard{kind: ClipText, data: []byte("first"), seq: 7} + srv := newClipboardTestServer(clip) + srv.SetWindowReporting(clipboardReadyTestVM, true) + done := startGuestClipboardWait(t, srv) + old := clipboardOffer(t, srv, "") + if old.Code != http.StatusOK || old.Header().Get(clipboardAckHeader) != "1" { + t.Fatalf("guest clipboard offer: %d %v", old.Code, old.Header()) + } + + request := srv.clipNotifyChan() + if err := clip.WriteText("newest"); err != nil { + t.Fatal(err) + } + if resp := sendClipboardApplied(srv, old.Header()); resp.Code != http.StatusConflict { + t.Fatalf("stale acknowledgment got %d, want 409", resp.Code) + } + select { + case <-request: + case err := <-done: + t.Fatalf("paste did not request the newest clipboard: %v", err) + } + latest := clipboardOffer(t, srv, "") + if latest.Body.String() != "newest" || latest.Header().Get("X-Clip-Seq") != "8" || latest.Header().Get(clipboardAckHeader) != "1" { + t.Fatalf("latest clipboard offer: %q %v", latest.Body.String(), latest.Header()) + } + forged := latest.Header().Clone() + forged.Set("X-Clip-Hash", strings.Repeat("0", 64)) + if resp := sendClipboardApplied(srv, forged); resp.Code != http.StatusConflict { + t.Fatalf("unoffered acknowledgment got %d, want 409", resp.Code) + } + select { + case err := <-done: + t.Fatalf("clipboard wait returned with no applied offer: %v", err) + default: + } + if resp := sendClipboardApplied(srv, latest.Header()); resp.Code != http.StatusNoContent { + t.Fatalf("current acknowledgment got %d, want 204", resp.Code) + } + if err := <-done; err != nil { + t.Fatal(err) + } +} + +func TestAppWindowClipboardRechecksSynchronizedValueForEveryPaste(t *testing.T) { + srv := newClipboardTestServer(&memClipboard{kind: ClipText, data: []byte("unchanged"), seq: 7}) + srv.SetWindowReporting(clipboardReadyTestVM, true) + first := clipboardOffer(t, srv, "") + if first.Header().Get(clipboardAckHeader) != "" { + t.Fatalf("ordinary synchronization should not ask for an acknowledgment: %v", first.Header()) + } + query := "?since=" + url.QueryEscape(first.Header().Get("X-Clip-Hash")) + "&since_seq=7" + if same := clipboardOffer(t, srv, query); same.Code != http.StatusNotModified || same.Header().Get(clipboardAckHeader) != "" { + t.Fatalf("no pending paste should return 304: %d %v", same.Code, same.Header()) + } + var previous http.Header + for _, reopen := range []bool{false, false, true} { + if reopen { + srv.SetWindowReporting(clipboardReadyTestVM, false) + srv.SetWindowReporting(clipboardReadyTestVM, true) + if untouched := clipboardOffer(t, srv, query); untouched.Code != http.StatusNotModified { + t.Fatalf("reopening a window should not reoffer an unchanged clipboard: %d", untouched.Code) + } + } + done := startGuestClipboardWait(t, srv) + current := clipboardOffer(t, srv, query) + if current.Code != http.StatusOK || current.Header().Get(clipboardAckHeader) != "1" || + current.Header().Get(clipboardRecheckHeader) != "1" || current.Header().Get(clipboardRequestHeader) == "" { + t.Fatalf("pending paste should request a non-writing recheck: %d %v", current.Code, current.Header()) + } + if previous != nil { + if current.Header().Get(clipboardRequestHeader) == previous.Get(clipboardRequestHeader) { + t.Fatal("per-paste request ID was reused") + } + if resp := sendClipboardApplied(srv, previous); resp.Code != http.StatusConflict { + t.Fatalf("previous paste acknowledgment got %d, want 409", resp.Code) + } + } + if resp := sendClipboardApplied(srv, current.Header()); resp.Code != http.StatusNoContent { + t.Fatalf("current paste acknowledgment got %d, want 204", resp.Code) + } + if err := <-done; err != nil { + t.Fatal(err) + } + previous = current.Header() + } +} + +func TestAppWindowClipboardWaitSkipsUnavailableHostPayload(t *testing.T) { + clip := &memClipboard{seq: 7} + srv := newClipboardTestServer(clip) + srv.SetWindowReporting(clipboardReadyTestVM, true) + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + if err := srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM); err != nil { + t.Fatalf("no host content should not delay Paste: %v", err) + } + if err := clip.WriteText("kept on host"); err != nil { + t.Fatal(err) + } + policy := DefaultClipboardPolicy() + policy.Direction = ClipboardGuestToHost + srv.SetGlobalClipboardPolicy(policy) + if err := srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM); err != nil { + t.Fatalf("guest-to-host policy should not delay Paste: %v", err) + } + if denied := clipboardOffer(t, srv, ""); denied.Code != http.StatusNoContent || denied.Header().Get(clipboardAckHeader) != "" { + t.Fatalf("guest-to-host policy offered host data: %d %v", denied.Code, denied.Header()) + } +} + +func TestAppWindowClipboardAcknowledgesOrdinaryFormats(t *testing.T) { + path := filepath.Join(t.TempDir(), "clip.txt") + if err := os.WriteFile(path, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + for _, tt := range []struct { + name string + clip Clipboard + }{ + {"png", &memClipboard{kind: ClipPNG, data: makeSamplePNG(t, 1, 2, 3), seq: 23}}, + {"files", &fileClipboardSnapshot{ + memClipboard: &memClipboard{seq: 23}, + payload: ClipPayload{Kind: ClipFiles, Files: []string{path}}, + }}, + } { + t.Run(tt.name, func(t *testing.T) { + srv := newClipboardTestServer(tt.clip) + srv.SetWindowReporting(clipboardReadyTestVM, true) + vm := srv.vms[normalizeVMRegistryKey(clipboardReadyTestVM)] + vm.clipOverride = &pendingClipOverride{text: "temporary", hash: strings.Repeat("a", 64), servedCh: make(chan struct{})} + done := startGuestClipboardWait(t, srv) + if temporary := clipboardOffer(t, srv, "?accept=image,files"); temporary.Body.String() != "temporary" || + temporary.Header().Get(clipboardAckHeader) != "" { + t.Fatalf("temporary text should not register an acknowledgment: %d %v", temporary.Code, temporary.Header()) + } + ordinary := clipboardOffer(t, srv, "?accept=image,files") + if ordinary.Code != http.StatusOK || ordinary.Header().Get("X-Clip-Kind") != tt.name || + ordinary.Header().Get(clipboardAckHeader) != "1" { + t.Fatalf("ordinary %s was not offered for acknowledgment: %d %v", tt.name, ordinary.Code, ordinary.Header()) + } + if resp := sendClipboardApplied(srv, ordinary.Header()); resp.Code != http.StatusNoContent { + t.Fatalf("%s acknowledgment got %d, want 204", tt.name, resp.Code) + } + if err := <-done; err != nil { + t.Fatalf("paste readiness after applying %s: %v", tt.name, err) + } + }) + } +} + +func TestAppWindowClipboardPrepareHoldsInjectionLockUntilRelease(t *testing.T) { + srv := newClipboardTestServer(&memClipboard{seq: 7}) + srv.SetWindowReporting(clipboardReadyTestVM, true) + vm := srv.vms[normalizeVMRegistryKey(clipboardReadyTestVM)] + vm.injectMu.Lock() + blocked, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) + _, err := srv.PrepareGuestClipboardPaste(blocked, clipboardReadyTestVM) + cancel() + vm.injectMu.Unlock() + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("paste should be cancellable while text injection owns the clipboard: %v", err) + } + release, err := srv.PrepareGuestClipboardPaste(t.Context(), clipboardReadyTestVM) + if err != nil { + t.Fatal(err) + } + defer release() + if vm.injectMu.TryLock() { + vm.injectMu.Unlock() + t.Fatal("paste released the text injection lock before dispatch") + } + release() + if !vm.injectMu.TryLock() { + t.Fatal("paste release did not unlock the clipboard") + } + vm.injectMu.Unlock() +} diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index 86c432c..107c8b5 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -22,8 +22,9 @@ const ClipboardReliabilityAgentVersion = 14 const ClipboardFilesAgentVersion = 15 const BidirectionalClipboardFilesAgentVersion = 16 const WindowReportAgentVersion = 17 +const PasteReadyAgentVersion = 18 -const CurrentAgentVersion = WindowReportAgentVersion +const CurrentAgentVersion = PasteReadyAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 1801ebd..d6e30ee 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -174,6 +174,15 @@ keymap_active="false" keymap_applied="false" ` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + ` +stop_window_reporter() { + if [ -n "${WINDOW_REPORTER_PID:-}" ]; then + kill "$WINDOW_REPORTER_PID" 2>/dev/null || true + wait "$WINDOW_REPORTER_PID" 2>/dev/null || true + fi + WINDOW_REPORTER_PID="" + window_report_generation="" +} + cleanup() { if [ "$keymap_applied" = "true" ]; then apply_hidutil_carrier disable @@ -496,15 +505,6 @@ EOF fi } -stop_window_reporter() { - if [ -n "${WINDOW_REPORTER_PID:-}" ]; then - kill "$WINDOW_REPORTER_PID" 2>/dev/null || true - wait "$WINDOW_REPORTER_PID" 2>/dev/null || true - fi - WINDOW_REPORTER_PID="" - window_report_generation="" -} - sync_window_reporter() { requested_generation=$(printf '%s\n' "$1" | sed -n 's/.*"window_report_generation"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') case "$requested_generation" in @@ -869,7 +869,11 @@ clip_header() { case "$1:$hdr_key" in x-clip-hash:[Xx]-[Cc][Ll][Ii][Pp]-[Hh][Aa][Ss][Hh]|\ x-clip-kind:[Xx]-[Cc][Ll][Ii][Pp]-[Kk][Ii][Nn][Dd]|\ - x-clip-seq:[Xx]-[Cc][Ll][Ii][Pp]-[Ss][Ee][Qq]) + x-clip-seq:[Xx]-[Cc][Ll][Ii][Pp]-[Ss][Ee][Qq]|\ + x-reims-clipboard-ack:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Aa][Cc][Kk]|\ + x-reims-clipboard-generation:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Gg][Ee][Nn][Ee][Rr][Aa][Tt][Ii][Oo][Nn]|\ + x-reims-clipboard-request:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Qq][Uu][Ee][Ss][Tt]|\ + x-reims-clipboard-recheck:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Cc][Hh][Ee][Cc][Kk]) hdr_val=${hdr_val#"${hdr_val%%[![:space:]]*}"} hdr_val=${hdr_val%"${hdr_val##*[![:space:]]}"} printf '%s\n' "$hdr_val" @@ -879,6 +883,30 @@ clip_header() { done < "$hdr_out" } +acknowledge_clipboard() { + [ "$(clip_header x-reims-clipboard-ack)" = 1 ] && + [ "$read_ok" = 1 ] && [ -n "$read_cc" ] && ! clipboard_poll_interrupted || return 0 + if [ "$1" != 1 ]; then + # macOS can re-encode PNGs, and a file offer's hash identifies the + # Windows manifest, so only text has the same wire and read-back hash. + [ "$read_kind" = "$new_kind" ] || return 0 + [ "$new_kind" != text ] || [ "$read_hash" = "$new_hash" ] || return 0 + fi + case "$new_seq" in ''|*[!0-9]*) return 0 ;; esac + case "$new_hash" in ''|*[!0-9a-f]*) return 0 ;; esac + ack_generation=$(clip_header x-reims-clipboard-generation) + case "$ack_generation" in ''|0*|*[!0-9]*) return 0 ;; esac + ack_request=$(clip_header x-reims-clipboard-request) + case "$ack_request" in ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]*) return 0 ;; esac + [ "${#new_seq}" -le 10 ] && [ "${#new_hash}" -eq 64 ] && + [ "${#ack_generation}" -le 20 ] && [ "${#ack_request}" -eq 26 ] || return 0 + curl -fsS -m 1 -X POST -H "Authorization: Bearer $REIMS_TOKEN" \ + -H "X-Clip-Seq: $new_seq" -H "X-Clip-Hash: $new_hash" \ + -H "X-Reims-Clipboard-Generation: $ack_generation" \ + -H "X-Reims-Clipboard-Request: $ack_request" \ + "$REIMS_HOST_URL/v1/clipboard/applied" >/dev/null 2>&1 || true +} + last_local_hash="" synced_local_cc="" synced_local_kind="" @@ -1119,7 +1147,7 @@ sync_clipboard() { clip_url="$clip_url&since_seq=$last_server_seq" fi code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \ - -H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" \ + -H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" -H "X-Reims-Clipboard-Ack: 1" \ "$clip_url" 2>/dev/null) || code=000 case "$code" in 200) @@ -1166,6 +1194,13 @@ sync_clipboard() { release_clip_lock return 0 fi + if [ "$(clip_header x-reims-clipboard-recheck)" = 1 ]; then + # A paste of an unchanged host snapshot uses the current + # ordinary macOS clipboard. A newer guest copy keeps ownership. + release_clip_lock + acknowledge_clipboard 1 + return 0 + fi if [ "$new_hash" != "$post_get_hash" ]; then if [ "$new_kind" = files ]; then delivery=0 @@ -1226,6 +1261,7 @@ sync_clipboard() { fi last_server_hash="$new_hash" last_server_seq="$new_seq" + acknowledge_clipboard 0 ;; 204|304) if [ -z "$last_local_hash" ]; then diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 8d69058..1df12dd 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -276,6 +276,7 @@ type registeredVM struct { lastSeen time.Time windowReportGen uint64 windowReport windowReport + clipboardDelivery guestClipboardDelivery dropShares *dropShareStore dropDAVHandler *webdav.Handler @@ -400,6 +401,7 @@ func (s *Server) Start(preferredPort int) (int, error) { mux.HandleFunc("/v1/status", s.handleStatus) mux.HandleFunc("/v1/dns-query", s.handleDNSQuery) mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard")) + mux.HandleFunc(clipboardAppliedPath, s.handleClipboardApplied) mux.HandleFunc("/v1/text-input", s.handleTextInput) mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck) mux.HandleFunc("/v1/drop-events", s.handleDropEvents) @@ -509,6 +511,7 @@ func (s *Server) Close(ctx context.Context) error { for _, vm := range s.vms { vm.windowReportGen = 0 vm.windowReport = windowReport{} + vm.clipboardDelivery = guestClipboardDelivery{} } s.mu.Unlock() s.cleanupClipFiles() @@ -585,6 +588,7 @@ func (s *Server) RegisterVM(cfg VMConfig) { s.clearVMClipFilesLocked(key) cur.windowReportGen = 0 cur.windowReport = windowReport{} + cur.clipboardDelivery = guestClipboardDelivery{} } folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders)) for _, folder := range cfg.ResolvedFolders { @@ -1157,7 +1161,7 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { s.serveClipboardArchive(w, r, vm) return } - s.getClipboard(w, r, vm.key) + s.getClipboard(w, r, vm) case http.MethodPost, http.MethodPut: mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if mediaType == "application/x-tar" { @@ -1265,12 +1269,15 @@ func (s *Server) clipboardForGuest(vmKey string, payload ClipPayload, seq uint32 return ClipPayload{}, "" } -func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) { +func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vm *registeredVM) { + vmKey := vm.key waitSec, err := strconv.Atoi(r.URL.Query().Get("wait")) if err != nil { waitSec = 0 } - deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second) + wait := time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second + ackCapable := r.Header.Get(clipboardAckHeader) == "1" + start := time.Now() wantsImage := acceptsClipFormat(r.URL.Query().Get("accept"), "image") || strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png") wantsFiles := acceptsClipFormat(r.URL.Query().Get("accept"), "files") @@ -1280,6 +1287,10 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri for { ch := s.clipNotifyChan() + deadline := start.Add(wait) + if ackCapable && s.windowClipboardActive(vm) { + deadline = start.Add(min(wait, 250*time.Millisecond)) + } policy := s.EffectiveClipboardPolicy(vmKey) if !policy.Enabled { writeFeatureDisabled(w, "clipboard") @@ -1309,7 +1320,20 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantFiles, wantImage, policy.MaxImageBytes) if h != "" { unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq)) - if !unchanged || time.Until(deadline) <= 0 { + expired := !time.Now().Before(deadline) + if ackCapable { + recheck := unchanged && hasSinceSeq + if offer := s.offerGuestClipboard(vm, seq, h, recheck, expired); offer.ticket != "" { + w.Header().Set(clipboardAckHeader, "1") + w.Header().Set(clipboardWindowHeader, strconv.FormatUint(offer.window, 10)) + w.Header().Set(clipboardRequestHeader, offer.ticket) + if recheck { + w.Header().Set(clipboardRecheckHeader, "1") + } + unchanged = false + } + } + if !unchanged || expired { setClipboardSeq(w, seq) w.Header().Set("X-Clip-Hash", h) w.Header().Set("X-Clip-Kind", string(payload.Kind)) diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index ea9994d..1675c39 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -591,6 +591,7 @@ var catalog = map[Locale]map[string]string{ "tray.menu.stop": "关机(&D)", "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", + "tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次", "tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态", "tray.notify.focus_fail": "找不到 {name} 的窗口", "tray.notify.force_stop_fail": "无法强制关机 {name}", @@ -1268,6 +1269,7 @@ var catalog = map[Locale]map[string]string{ "tray.menu.stop": "Shut &Down", "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", + "tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again", "tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}", "tray.notify.focus_fail": "Couldn't find the window of {name}", "tray.notify.force_stop_fail": "Couldn't force shut down {name}", diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 25aaa05..4c9bf6b 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -318,6 +318,7 @@ "err.app_window_pointer": "Enable the USB tablet for {name} and try again", "err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again", "err.app_window_capture": "Could not capture the app window in {name}", + "tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again", "err.vm_window_not_found": "Couldn’t find the display window for {name}", "err.fullscreen_failed": "Couldn’t toggle full screen for {name}", "err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index e912625..cae624c 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -318,6 +318,7 @@ "err.app_window_pointer": "在 {name} 中启用 USB 数位板后再打开独立窗口", "err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试", "err.app_window_capture": "无法获取 {name} 的应用画面", + "tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次", "err.vm_window_not_found": "找不到 {name} 的显示窗口", "err.fullscreen_failed": "无法切换 {name} 的全屏状态", "err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠", From 8334170917c01bb0e90480f5ca6ffa599ac73a98 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 08:14:13 +0800 Subject: [PATCH 07/10] test: include window reporter cleanup in folder fixtures --- internal/guesttools/folder_agent_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 835a1f2..0bb5fb7 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -48,6 +48,7 @@ func TestGuestAgentFolderMounts(t *testing.T) { t.Fatal("Guest Tools scripts do not advertise the current agent version") } mounts := guestTimezoneAgent + guestTimezoneConfig + + scriptSection(t, agent, "\nstop_window_reporter() {", "\ncleanup() {") + scriptSection(t, agent, "urlencode() {", "\nhash_file() {") + scriptSection(t, agent, "\ndrive_mount_failures=", "\nreport_status() {") t.Run("clipboard_setting_before_mounts", func(t *testing.T) { From ce866ca749e6fd2ae83de73b510156bfe589cd1f Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 08:14:13 +0800 Subject: [PATCH 08/10] feat: remove the Windows frame from macOS app windows --- changes/macos-app-window.json | 4 +- internal/appwindow/viewer_windows.go | 178 ++++++++++++++++++++-- internal/appwindow/viewer_windows_test.go | 29 ++++ 3 files changed, 200 insertions(+), 11 deletions(-) create mode 100644 internal/appwindow/viewer_windows_test.go diff --git a/changes/macos-app-window.json b/changes/macos-app-window.json index 3b3d70d..a737f51 100644 --- a/changes/macos-app-window.json +++ b/changes/macos-app-window.json @@ -2,6 +2,6 @@ "group": "new", "order": 0, "authors": ["yxc0915"], - "zh": "可在 Windows 独立窗口中操作正在运行的 macOS 虚拟机的前台应用,并在宿主与客体之间复制粘贴。", - "en": "Interact with the foreground app of a running macOS VM in a separate Windows window with bidirectional copy and paste." + "zh": "可在 Windows 无边框独立窗口中操作 macOS 虚拟机的前台应用,并在宿主与客体之间复制粘贴。", + "en": "Interact with the foreground app of a running macOS VM in a separate borderless Windows window with bidirectional copy and paste." } diff --git a/internal/appwindow/viewer_windows.go b/internal/appwindow/viewer_windows.go index 056c658..627874e 100644 --- a/internal/appwindow/viewer_windows.go +++ b/internal/appwindow/viewer_windows.go @@ -17,8 +17,10 @@ import ( ) var ( - viewerUser32 = windows.NewLazySystemDLL("user32.dll") - viewerGDI32 = windows.NewLazySystemDLL("gdi32.dll") + viewerUser32 = windows.NewLazySystemDLL("user32.dll") + viewerGDI32 = windows.NewLazySystemDLL("gdi32.dll") + viewerDWM = windows.NewLazySystemDLL("dwmapi.dll") + viewerKernel32 = windows.NewLazySystemDLL("kernel32.dll") viewerRegisterClass = viewerUser32.NewProc("RegisterClassW") viewerCreateWindow = viewerUser32.NewProc("CreateWindowExW") @@ -33,17 +35,27 @@ var ( viewerLoadCursor = viewerUser32.NewProc("LoadCursorW") viewerInvalidateRect = viewerUser32.NewProc("InvalidateRect") viewerGetClientRect = viewerUser32.NewProc("GetClientRect") + viewerGetWindowRect = viewerUser32.NewProc("GetWindowRect") + viewerSetWindowPos = viewerUser32.NewProc("SetWindowPos") viewerBeginPaint = viewerUser32.NewProc("BeginPaint") viewerEndPaint = viewerUser32.NewProc("EndPaint") viewerFillRect = viewerUser32.NewProc("FillRect") viewerIsIconic = viewerUser32.NewProc("IsIconic") + viewerIsZoomed = viewerUser32.NewProc("IsZoomed") + viewerGetDpiForWindow = viewerUser32.NewProc("GetDpiForWindow") + viewerGetKeyState = viewerUser32.NewProc("GetKeyState") + viewerMonitorFromRect = viewerUser32.NewProc("MonitorFromRect") + viewerGetMonitorInfo = viewerUser32.NewProc("GetMonitorInfoW") viewerSetCapture = viewerUser32.NewProc("SetCapture") viewerGetCapture = viewerUser32.NewProc("GetCapture") viewerReleaseCapture = viewerUser32.NewProc("ReleaseCapture") viewerScreenToClient = viewerUser32.NewProc("ScreenToClient") + viewerClientToScreen = viewerUser32.NewProc("ClientToScreen") viewerGetStockObject = viewerGDI32.NewProc("GetStockObject") viewerSetStretchMode = viewerGDI32.NewProc("SetStretchBltMode") viewerStretchDIBits = viewerGDI32.NewProc("StretchDIBits") + viewerSetDwmAttribute = viewerDWM.NewProc("DwmSetWindowAttribute") + viewerMoveMemory = viewerKernel32.NewProc("RtlMoveMemory") viewerClassOnce sync.Once viewerClassAtom uintptr @@ -60,10 +72,16 @@ const ( viewerWmPaint = 0x000f viewerWmClose = 0x0010 viewerWmErase = 0x0014 + viewerWmNCCalcSize = 0x0083 + viewerWmNCHitTest = 0x0084 + viewerWmNCPaint = 0x0085 + viewerWmNCActivate = 0x0086 + viewerWmNCLeftDown = 0x00a1 viewerWmKeyDown = 0x0100 viewerWmKeyUp = 0x0101 viewerWmSysKeyDown = 0x0104 viewerWmSysKeyUp = 0x0105 + viewerWmSysCommand = 0x0112 viewerWmMouseMove = 0x0200 viewerWmLeftDown = 0x0201 viewerWmLeftUp = 0x0202 @@ -75,6 +93,17 @@ const ( viewerWmCaptureChanged = 0x0215 viewerWmFrame = 0x8001 viewerWmStop = 0x8002 + + viewerHTClient = 1 + viewerHTCaption = 2 + viewerHTLeft = 10 + viewerHTRight = 11 + viewerHTTop = 12 + viewerHTTopLeft = 13 + viewerHTTopRight = 14 + viewerHTBottom = 15 + viewerHTBottomLeft = 16 + viewerHTBottomRight = 17 ) type viewerClass struct { @@ -93,6 +122,12 @@ type viewerClass struct { type viewerPoint struct{ x, y int32 } type viewerRect struct{ left, top, right, bottom int32 } +type viewerMonitorInfo struct { + size uint32 + monitor, work viewerRect + flags uint32 +} + type viewerMessage struct { hwnd uintptr message uint32 @@ -195,7 +230,7 @@ func RunViewer(ctx context.Context, opts ViewerOptions) error { if first != nil { v.latest.Store(first) size := fitViewerFrame(min(first.width, 920), min(first.height, 680), first.width, first.height) - width, height = max(size.Dx()+24, 360), max(size.Dy()+48, 240) + width, height = size.Dx(), size.Dy() } hwnd, _, callErr := viewerCreateWindow.Call( 0x00040000, class, uintptr(unsafe.Pointer(title)), 0x00cf0000, // WS_EX_APPWINDOW, WS_OVERLAPPEDWINDOW @@ -208,6 +243,7 @@ func RunViewer(ctx context.Context, opts ViewerOptions) error { v.hwnd = hwnd viewerWindows.Store(hwnd, v) defer viewerWindows.Delete(hwnd) + configureViewerFrame(hwnd) work, cancel := context.WithCancel(ctx) var workers sync.WaitGroup @@ -243,6 +279,81 @@ func RunViewer(ctx context.Context, opts ViewerOptions) error { } } +func configureViewerFrame(hwnd uintptr) { + // Retain overlapped-window behavior and calculate the entire window as client area. + viewerSetWindowPos.Call(hwnd, 0, 0, 0, 0, 0, 0x37) // SWP_FRAMECHANGED | NOACTIVATE | NOZORDER | NOMOVE | NOSIZE + color := uint32(0xfffffffe) // DWMWA_COLOR_NONE + result, _, _ := viewerSetDwmAttribute.Call(hwnd, 34, uintptr(unsafe.Pointer(&color)), unsafe.Sizeof(color)) + if int32(result) < 0 { + policy := uint32(1) // DWMNCRP_DISABLED on builds without DWMWA_BORDER_COLOR. + viewerSetDwmAttribute.Call(hwnd, 2, uintptr(unsafe.Pointer(&policy)), unsafe.Sizeof(policy)) + } + corner := uint32(1) // DWMWCP_DONOTROUND, so the host frame does not clip guest pixels. + viewerSetDwmAttribute.Call(hwnd, 33, uintptr(unsafe.Pointer(&corner)), unsafe.Sizeof(corner)) +} + +func fitViewerMaximizedClient(hwnd, rect uintptr) { + if zoomed, _, _ := viewerIsZoomed.Call(hwnd); zoomed == 0 || rect == 0 { + return + } + // The maximized outer frame extends past the work area. Keep the app's pixels inside it. + monitor, _, _ := viewerMonitorFromRect.Call(rect, 2) // MONITOR_DEFAULTTONEAREST + info := viewerMonitorInfo{size: uint32(unsafe.Sizeof(viewerMonitorInfo{}))} + if ok, _, _ := viewerGetMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok != 0 { + viewerMoveMemory.Call(rect, uintptr(unsafe.Pointer(&info.work)), unsafe.Sizeof(info.work)) + } +} + +func viewerFrameHitTest(hwnd uintptr, point viewerPoint) uintptr { + if zoomed, _, _ := viewerIsZoomed.Call(hwnd); zoomed != 0 { + return viewerHTClient + } + var bounds viewerRect + if ok, _, _ := viewerGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds))); ok == 0 { + return viewerHTClient + } + return viewerResizeHit(bounds, point, viewerScale(hwnd, 5)) +} + +func viewerScale(hwnd uintptr, logical int32) int32 { + dpi, _, _ := viewerGetDpiForWindow.Call(hwnd) + if dpi == 0 { + return logical + } + return max(1, (logical*int32(dpi)+48)/96) +} + +func viewerResizeHit(bounds viewerRect, point viewerPoint, edge int32) uintptr { + if point.x < bounds.left || point.x >= bounds.right || point.y < bounds.top || point.y >= bounds.bottom { + return viewerHTClient + } + left, right := point.x < bounds.left+edge, point.x >= bounds.right-edge + switch { + case point.y < bounds.top+edge: + if left { + return viewerHTTopLeft + } + if right { + return viewerHTTopRight + } + return viewerHTTop + case point.y >= bounds.bottom-edge: + if left { + return viewerHTBottomLeft + } + if right { + return viewerHTBottomRight + } + return viewerHTBottom + case left: + return viewerHTLeft + case right: + return viewerHTRight + default: + return viewerHTClient + } +} + func makeViewerBitmap(frame ViewerFrame) *viewerBitmap { if frame.Image == nil || frame.Image.Bounds().Empty() { return nil @@ -364,6 +475,10 @@ func (v *nativeViewer) paint() { } func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintptr { + if message == viewerWmNCCalcSize { + fitViewerMaximizedClient(hwnd, lParam) + return 0 + } entry, ok := viewerWindows.Load(hwnd) if !ok { result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam) @@ -371,10 +486,24 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint } v := entry.(*nativeViewer) switch message { + case viewerWmNCHitTest: + return viewerFrameHitTest(hwnd, viewerMessagePoint(lParam)) + case viewerWmNCPaint: + return 0 + case viewerWmNCActivate: + // Let Windows update activation without repainting the nonclient frame. + result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, ^uintptr(0)) + return result case viewerWmFrame: v.pending.Store(false) viewerInvalidateRect.Call(hwnd, 0, 0) case viewerWmSize: + // Release a guest drag before changing its coordinate map. A system resize owns its own capture. + if v.holdingButton() { + v.releaseButtons() + v.releaseCaptureIfIdle() + } + v.imageRect = image.Rectangle{} viewerInvalidateRect.Call(hwnd, 0, 0) case viewerWmPaint: v.paint() @@ -400,7 +529,13 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint case viewerWmMouseMove: v.pointer(ViewerMouseMove, viewerMessagePoint(lParam), 0, 0, false) case viewerWmLeftDown, viewerWmLeftUp: - v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 0, 0, message == viewerWmLeftDown) + point := viewerMessagePoint(lParam) + if message == viewerWmLeftDown { + if state, _, _ := viewerGetKeyState.Call(0x12); int16(state) < 0 && v.moveWindow(point) { // VK_MENU + return 0 + } + } + v.pointer(ViewerMouseButton, point, 0, 0, message == viewerWmLeftDown) case viewerWmRightDown, viewerWmRightUp: v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 1, 0, message == viewerWmRightDown) case viewerWmMiddleDown, viewerWmMiddleUp: @@ -411,9 +546,16 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint v.pointer(ViewerMouseWheel, point, 0, int(int16(wParam>>16)), false) } case viewerWmSysKeyDown, viewerWmSysKeyUp, viewerWmKeyDown, viewerWmKeyUp: - if message == viewerWmSysKeyDown && wParam == 0x73 && lParam&(1<<29) != 0 { // Alt+F4 - result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam) - return result + if message == viewerWmSysKeyDown && lParam&(1<<29) != 0 { + switch wParam { + case 0x73: // Alt+F4 + result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam) + return result + case ' ': // Alt+Space opens the native system menu, including Move. + v.releaseInputs() + result, _, _ := viewerDefWindowProc.Call(hwnd, viewerWmSysCommand, 0xf100, ' ') // SC_KEYMENU + return result + } } v.key(uint32(wParam), message == viewerWmKeyDown || message == viewerWmSysKeyDown) default: @@ -423,6 +565,20 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint return 0 } +func (v *nativeViewer) moveWindow(point viewerPoint) bool { + if !image.Pt(int(point.x), int(point.y)).In(v.imageRect) || + int(point.y)-v.imageRect.Min.Y >= int(viewerScale(v.hwnd, 36)) { + return false + } + if ok, _, _ := viewerClientToScreen.Call(v.hwnd, uintptr(unsafe.Pointer(&point))); ok == 0 { + return false + } + v.releaseInputs() + packed := uintptr(uint16(point.x)) | uintptr(uint16(point.y))<<16 + viewerDefWindowProc.Call(v.hwnd, viewerWmNCLeftDown, viewerHTCaption, packed) + return true +} + func viewerMessagePoint(lParam uintptr) viewerPoint { return viewerPoint{int32(int16(lParam)), int32(int16(lParam >> 16))} } @@ -450,7 +606,7 @@ func (v *nativeViewer) pointer(kind ViewerEventKind, pt viewerPoint, button, del } x, y := int(pt.x), int(pt.y) inside := image.Pt(x, y).In(area) - anyButton := v.buttons[0] || v.buttons[1] || v.buttons[2] + anyButton := v.holdingButton() if !inside && !(kind == ViewerMouseMove && anyButton) && !(kind == ViewerMouseButton && !down && v.buttons[button]) { return @@ -501,13 +657,17 @@ func (v *nativeViewer) releaseButtons() { } func (v *nativeViewer) releaseCaptureIfIdle() { - if !v.buttons[0] && !v.buttons[1] && !v.buttons[2] { + if !v.holdingButton() { if hwnd, _, _ := viewerGetCapture.Call(); hwnd == v.hwnd { viewerReleaseCapture.Call() } } } +func (v *nativeViewer) holdingButton() bool { + return v.buttons[0] || v.buttons[1] || v.buttons[2] +} + func (v *nativeViewer) releaseInputs() { v.releaseButtons() v.releaseCaptureIfIdle() diff --git a/internal/appwindow/viewer_windows_test.go b/internal/appwindow/viewer_windows_test.go new file mode 100644 index 0000000..890b02f --- /dev/null +++ b/internal/appwindow/viewer_windows_test.go @@ -0,0 +1,29 @@ +//go:build windows + +package appwindow + +import "testing" + +func TestViewerResizeHit(t *testing.T) { + bounds := viewerRect{left: -900, top: -40, right: -500, bottom: 260} + for _, tc := range []struct { + name string + point viewerPoint + want uintptr + }{ + {"top left", viewerPoint{-900, -40}, viewerHTTopLeft}, + {"top", viewerPoint{-700, -38}, viewerHTTop}, + {"top right", viewerPoint{-501, -38}, viewerHTTopRight}, + {"right", viewerPoint{-501, 100}, viewerHTRight}, + {"bottom right", viewerPoint{-501, 259}, viewerHTBottomRight}, + {"bottom", viewerPoint{-700, 259}, viewerHTBottom}, + {"bottom left", viewerPoint{-899, 259}, viewerHTBottomLeft}, + {"left", viewerPoint{-899, 100}, viewerHTLeft}, + {"guest title controls", viewerPoint{-879, -20}, viewerHTClient}, + {"outside", viewerPoint{-901, 100}, viewerHTClient}, + } { + if got := viewerResizeHit(bounds, tc.point, 8); got != tc.want { + t.Errorf("%s: got hit %d, want %d", tc.name, got, tc.want) + } + } +} From 619ac88297c52ab85d0b7535d483046c1a58b4c0 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 08:19:38 +0800 Subject: [PATCH 09/10] fix: dispose plugin consumers before required providers --- internal/plugin/kernel_test.go | 69 ++++++++++++++++++++++++++++++++++ internal/plugin/registry.go | 42 ++++++++++++++------- 2 files changed, 97 insertions(+), 14 deletions(-) diff --git a/internal/plugin/kernel_test.go b/internal/plugin/kernel_test.go index 696c4da..99f6bbe 100644 --- a/internal/plugin/kernel_test.go +++ b/internal/plugin/kernel_test.go @@ -110,6 +110,9 @@ func TestRegistryDependencyReconcileAndCascade(t *testing.T) { if reg.StateOf("builtin.clipboard") != StatePending { t.Fatalf("clipboard state = %s, want pending", reg.StateOf("builtin.clipboard")) } + if want := []string{"up:transport", "up:clipboard", "down:clipboard", "down:transport"}; !reflect.DeepEqual(log, want) { + t.Fatalf("lifecycle order = %v, want %v", log, want) + } // Re-enabling provider automatically reactivates pending dependent. if err := reg.SetDesired(context.Background(), "builtin.transport", true); err != nil { @@ -120,6 +123,72 @@ func TestRegistryDependencyReconcileAndCascade(t *testing.T) { } } +func TestRegistryDisposesTransitiveRequiredConsumersBeforePublishedProvider(t *testing.T) { + reg := NewRegistry(nil) + ctx := context.Background() + const ( + shadowed = "builtin.legacy-transport" + provider = "builtin.transport" + bridge = "builtin.bridge" + viewer = "builtin.viewer" + optional = "builtin.optional" + ) + var disposed []string + register := func(id, service string, requirements ...ServiceRequirement) { + t.Helper() + def := PluginDef{ + Manifest: Manifest{ID: id, Version: "1.0.0", Requires: requirements}, + Source: SourceBuiltin, + Trust: TrustOfficial, + Desired: true, + Activate: func(_ context.Context, sc *Scope) error { + if service != "" { + sc.Provide(service, "1.0.0", id) + } + sc.OnDispose(func() { + for _, req := range requirements { + if _, ok := sc.Lookup(req.Service); !req.Optional && !ok { + t.Errorf("%s lost %s before its disposer ran", id, req.Service) + } + } + disposed = append(disposed, id) + }) + return nil + }, + } + if err := reg.Register(def); err != nil { + t.Fatal(err) + } + } + register(shadowed, "transport") + register(provider, "transport") + register(bridge, "bridge", ServiceRequirement{Service: "transport"}) + register(viewer, "", ServiceRequirement{Service: "bridge"}) + register(optional, "", ServiceRequirement{Service: "transport", Optional: true}) + reg.Reconcile(ctx) + + if svc, ok := reg.LookupService("transport"); !ok || svc != provider || !reg.IsActive(viewer) { + t.Fatalf("expected active consumer using published provider, service=%v consumer=%s", svc, reg.StateOf(viewer)) + } + if err := reg.SetDesired(ctx, shadowed, false); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(disposed, []string{shadowed}) || !reg.IsActive(viewer) { + t.Fatalf("disabling shadowed provider affected consumer, disposed=%v", disposed) + } + if err := reg.SetDesired(ctx, provider, false); err != nil { + t.Fatal(err) + } + if want := []string{shadowed, viewer, bridge, provider}; !reflect.DeepEqual(disposed, want) { + t.Fatalf("disposal order = %v, want %v", disposed, want) + } + if reg.StateOf(viewer) != StatePending || reg.StateOf(bridge) != StatePending || + reg.StateOf(provider) != StateOff || !reg.IsActive(optional) { + t.Fatalf("unexpected final states: viewer=%s bridge=%s provider=%s optional=%s", + reg.StateOf(viewer), reg.StateOf(bridge), reg.StateOf(provider), reg.StateOf(optional)) + } +} + func TestRegistryPanicRollbackAndInUseFailClosed(t *testing.T) { reg := NewRegistry(nil) rolledBack := false diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index d3e9b2c..dcdcaec 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -369,27 +369,41 @@ func (r *Registry) Reconcile(ctx context.Context) { for { var toDispose []*pluginEntry r.mu.RLock() - dependedOn := make(map[string]bool) - for _, e := range r.entries { - if e.scope == nil { - continue - } - for _, req := range e.def.Manifest.Requires { - if svc, ok := r.services[req.Service]; ok && svc.pluginID != e.def.Manifest.ID { - dependedOn[svc.pluginID] = true - } - } - } + requiredBy := make(map[string][]*pluginEntry) + scheduled := make(map[string]bool) var allDue []*pluginEntry - for _, e := range r.entries { + for id, e := range r.entries { if e.scope == nil { continue } if !e.def.Desired || !r.requirementsSatisfiedLocked(e.def.Manifest.Requires) { allDue = append(allDue, e) - if !dependedOn[e.def.Manifest.ID] { - toDispose = append(toDispose, e) + scheduled[id] = true + } + for _, req := range e.def.Manifest.Requires { + if req.Optional { + continue } + if svc, ok := r.services[req.Service]; ok && svc.pluginID != id { + requiredBy[svc.pluginID] = append(requiredBy[svc.pluginID], e) + } + } + } + // A provider scheduled to close still publishes its service. Include + // its required consumers before selecting leaves, even when their + // requirements are currently satisfied. + for i := 0; i < len(allDue); i++ { + for _, consumer := range requiredBy[allDue[i].def.Manifest.ID] { + id := consumer.def.Manifest.ID + if !scheduled[id] { + scheduled[id] = true + allDue = append(allDue, consumer) + } + } + } + for _, e := range allDue { + if len(requiredBy[e.def.Manifest.ID]) == 0 { + toDispose = append(toDispose, e) } } // Break cycles if every due plugin is mutually depended upon. From b21a353b285c0e923311d04b88a21525e9634479 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 08:20:01 +0800 Subject: [PATCH 10/10] feat: offer macOS app windows as an optional built-in plugin --- changes/macos-app-window.json | 4 +- docs/design-guidelines.md | 2 +- docs/plugin-architecture.md | 2 + frontend/src/App.tsx | 59 +++++---- frontend/src/components/Sidebar.tsx | 4 +- frontend/src/components/VMPage.tsx | 52 ++++---- frontend/src/i18n/domains/vm.gen.ts | 4 - frontend/src/i18n/keys.gen.ts | 2 - frontend/wailsjs/go/app/App.d.ts | 2 - frontend/wailsjs/go/app/App.js | 4 - internal/app/app.go | 4 +- internal/app/app_window_flow.go | 146 +++++++++------------ internal/app/plugins_flow.go | 1 + internal/appwindow/sessions.go | 91 +++++++++++++ internal/appwindow/sessions_test.go | 70 ++++++++++ internal/i18n/catalog_gen.go | 2 + internal/plugin/builtin/app_window.go | 80 +++++++++++ internal/plugin/builtin/app_window_test.go | 131 ++++++++++++++++++ internal/plugin/builtin/builtin.go | 3 + locales/en-US/native.json | 1 + locales/en-US/vm.json | 2 - locales/zh-CN/native.json | 1 + locales/zh-CN/vm.json | 2 - 23 files changed, 507 insertions(+), 162 deletions(-) create mode 100644 internal/appwindow/sessions.go create mode 100644 internal/appwindow/sessions_test.go create mode 100644 internal/plugin/builtin/app_window.go create mode 100644 internal/plugin/builtin/app_window_test.go diff --git a/changes/macos-app-window.json b/changes/macos-app-window.json index a737f51..807cc29 100644 --- a/changes/macos-app-window.json +++ b/changes/macos-app-window.json @@ -2,6 +2,6 @@ "group": "new", "order": 0, "authors": ["yxc0915"], - "zh": "可在 Windows 无边框独立窗口中操作 macOS 虚拟机的前台应用,并在宿主与客体之间复制粘贴。", - "en": "Interact with the foreground app of a running macOS VM in a separate borderless Windows window with bidirectional copy and paste." + "zh": "启用「macOS 应用窗口」内置插件后,可在 Windows 无边框窗口中操作虚拟机的前台应用,并在宿主与客体之间复制粘贴。", + "en": "Enable the built-in macOS App Windows plugin to use a VM’s foreground app in a borderless Windows window with bidirectional copy and paste." } diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index 6711fa4..bc5ac85 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -24,7 +24,7 @@ | 正在创建 | 无(展示分步进度) | 取消创建 | | 已停止 | 启动 | 设置、恢复点、派生副本、磁盘扩容与空间回收、打开目录、删除 | | 正在启动 | 启动中(忙碌禁用) | 设置、强制关机 | -| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 | +| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需启用 macOS 应用窗口插件并连接 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 | | 正在停止 | 停止中(忙碌禁用) | 强制关机 | | 正在挂起 | 挂起中(忙碌禁用) | 强制关机 | | 已挂起 | 恢复(需运行时支持) | 放弃挂起状态(需破坏性操作确认)、打开目录 | diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 01d17b8..5e72e54 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -32,6 +32,8 @@ flowchart TB 内置虚拟机交互服务默认启用,通过宿主控制台代理串行处理每台虚拟机的 QMP 操作,每次操作后关闭连接,并与虚拟机生命周期操作共用锁。桌面文本输入期间暂停后台缩略图捕获。该服务不实现 MCP 协议。 +内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。 + L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。 Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index b7ef44f..868e486 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -11,7 +11,7 @@ import { TitleMenus } from './components/TitleMenus' import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule' import { DataRootReadOnly } from './components/DataRootReadOnly' import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' -import { VMAction, VMPage } from './components/VMPage' +import { VMAction, VMBusyAction, VMPage } from './components/VMPage' import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { LogLine, appendLog } from './lib/logs' @@ -44,7 +44,7 @@ const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ def const errText = (e: unknown) => parseAppError(e).summary -const failKey: Record = { +const failKey: Record = { start: 'failStart', suspend: 'failSuspend', resume: 'failResume', @@ -52,7 +52,7 @@ const failKey: Record = { focus: 'failFocus', fullscreen: 'failFullscreen', screenshot: 'failScreenshot', - appWindow: 'failOpenAppWindow', + pluginCommand: 'failGeneric', stop: 'failStop', forceStop: 'failStop', restart: 'failRestart', @@ -98,8 +98,8 @@ export const App: React.FC = () => { const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) - const [busy, setBusy] = useState>({}) - const busyOpsRef = useRef>>(new Map()) + const [busy, setBusy] = useState>({}) + const busyOpsRef = useRef>>(new Map()) const nextBusyTokenRef = useRef(0) const [dropping, setDropping] = useState(false) const [loadError, setLoadError] = useState('') @@ -218,17 +218,7 @@ export const App: React.FC = () => { }, []) useEffect(() => { - Promise.all([ - api.GetPluginUIContributions().catch(() => null), - refresh(), - ]).then(([pui]) => { - if (pui) { - setPluginLocales(pui.locales) - setPluginUI(pui) - } else { - setPluginUI({} as PluginUIContributions) - } - }) + void refresh() events.emitUIPong() const offPing = events.onUIPing(() => { events.emitUIPong() }) const offState = events.onStateChanged(() => { @@ -245,7 +235,6 @@ export const App: React.FC = () => { } setLogLines((prev) => appendLog(prev, entry)) }) - api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e)) // Tasks: seed from the backend, then follow events. api.GetTasks().then((list) => { setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev)) @@ -557,10 +546,19 @@ export const App: React.FC = () => { } }, [taskMap]) - // Apply active theme pack (zero extra CSS for builtin default theme). + // Refresh contributions together with the active theme after registry changes. useEffect(() => { - api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e)) - api.GetPluginUIContributions().then(setPluginUI).catch((e) => console.warn('[app] GetPluginUIContributions failed:', e)) + let live = true + api.GetActiveTheme().then((theme) => { + if (live) setActiveThemePayload(theme) + }).catch((e) => console.warn('[app] GetActiveTheme failed:', e)) + api.GetPluginUIContributions().then((contributions) => { + if (live) setPluginUI(contributions) + }).catch((e) => { + console.warn('[app] GetPluginUIContributions failed:', e) + if (live) setPluginUI((previous) => previous ?? {} as PluginUIContributions) + }) + return () => { live = false } }, [themeRevision, state?.safe_mode]) useEffect(() => { @@ -621,25 +619,25 @@ export const App: React.FC = () => { if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '') } - const activeVMBusy = (name: string): VMAction | undefined => { + const activeVMBusy = (name: string): VMBusyAction | undefined => { const ops = busyOpsRef.current.get(name) if (!ops || ops.size === 0) return undefined - let latest: VMAction | undefined + let latest: VMBusyAction | undefined for (const act of ops.values()) latest = act return latest } const syncBusyState = () => { - const next: Record = Object.create(null) + const next: Record = Object.create(null) for (const [vmName, ops] of busyOpsRef.current) { - let latest: VMAction | undefined + let latest: VMBusyAction | undefined for (const act of ops.values()) latest = act if (latest) next[vmName] = latest } setBusy(next) } - const beginVMBusy = (name: string, action: VMAction): number | null => { + const beginVMBusy = (name: string, action: VMBusyAction): number | null => { const ops = busyOpsRef.current.get(name) if (ops && ops.size > 0) { if (action !== 'forceStop') return null @@ -648,7 +646,7 @@ export const App: React.FC = () => { } } const token = ++nextBusyTokenRef.current - const vmOps = ops ?? new Map() + const vmOps = ops ?? new Map() vmOps.set(token, action) busyOpsRef.current.set(name, vmOps) syncBusyState() @@ -662,7 +660,7 @@ export const App: React.FC = () => { syncBusyState() } - const runVMAction = async (name: string, action: VMAction, fn: () => Promise, okTitle?: string) => { + const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise, okTitle?: string) => { const token = beginVMBusy(name, action) if (token === null) return try { @@ -752,7 +750,6 @@ export const App: React.FC = () => { refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen }) }) case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied')) - case 'appWindow': return runVMAction(name, action, () => api.OpenAppWindow(actionDriverID, name)) case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name })) case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name })) case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name)) @@ -1238,6 +1235,12 @@ export const App: React.FC = () => { pending={pending} busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined} onAction={onVMAction} + onPluginCommand={(pluginID, command, title) => { + const name = selectedVM.name + void runVMAction(name, 'pluginCommand', async () => { + await api.InvokePluginCommand(pluginID, command, { vm: name }) + }, title) + }} onSettings={() => setShowSettings(true)} onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })} onDelete={() => setDeleteTarget(selectedVM.name)} diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index e2ebe44..a88dc5e 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -8,7 +8,7 @@ import { vmRefKey } from '../lib/vmRef' import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls' import { VersionArt } from '../macos/VersionArt' import { BrandMark, HostIcon } from '../ui/themeVisuals' -import { VMAction } from './VMPage' +import type { VMAction, VMBusyAction } from './VMPage' export const HOST_ID = '__host__' export const INSTALLERS_ID = '__installers__' @@ -24,7 +24,7 @@ interface Props { vms: VMListItem[] transitions: Record /** VM name → currently running action (disables conflicting context menu actions). */ - busyActions?: Record + busyActions?: Record selected: string hostReady: boolean /** Whether the active runtime supports VM suspend/resume. */ diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 6a113f4..cf0b573 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -68,7 +68,6 @@ export type VMAction = | 'focus' | 'fullscreen' | 'screenshot' - | 'appWindow' | 'eject' | 'finishInstall' | 'enterRecovery' @@ -84,6 +83,8 @@ export type VMAction = | 'delete' | 'openFolder' +export type VMBusyAction = VMAction | 'pluginCommand' + // Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing // macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`. const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh' @@ -114,8 +115,9 @@ interface Props { detail: VMDetail | null host: HostReport pending: PendingChange[] - busyAction?: VMAction + busyAction?: VMBusyAction onAction: (action: VMAction) => void + onPluginCommand: (pluginID: string, command: string, title: string) => void onSettings: () => void onOpenAffinity: () => void onDelete: () => void @@ -181,7 +183,7 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, + locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined @@ -193,6 +195,17 @@ export const VMPage: React.FC = ({ const installing = !!detail && (detail.has_installer || detail.recovery_mode) const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' const isMacOSDriver = !driverID || driverID === BUILTIN_MACOS_DRIVER + const toolbarMenus = (pluginUI?.menus ?? []).filter(({ slot, when }) => { + if (slot !== 'vm.toolbar') return false + switch (when) { + case undefined: + case '': return true + case 'vm.running': return running + case 'vm.stopped': return state === 'stopped' + case 'vm.macos.running': return running && isMacOSDriver && detail?.name === name && !installing && !guideActive + default: return false + } + }) const canUseHostDNS = !!detail && !installing && !detail.guest_tools_disabled && isMacOSDriver && state !== 'broken' // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(driverID, name, running) @@ -593,11 +606,6 @@ export const VMPage: React.FC = ({ onAction('screenshot')}> {tr('copyScreenshot')} - {isMacOSDriver && !installing && ( - onAction('appWindow')}> - {tr('openAppWindow')} - - )} )} @@ -635,21 +643,19 @@ export const VMPage: React.FC = ({ onAction('exportDiagnostics')}> {tr('exportDiagnostics')} - {(pluginUI?.menus ?? []) - .filter((m) => m.slot === 'vm.toolbar' && (!m.when || (m.when === 'vm.running' ? running : m.when === 'vm.stopped' ? state === 'stopped' : false))) - .map((m) => ( - { - void api.InvokePluginCommand(m.pluginId ?? '', m.command, { vm: name }) - .then(() => onToast(locText(m.title, locale, m.id))) - .catch((e) => onError(tr('failGeneric'), e)) - }} - > - {locText(m.title, locale, m.id)} - - ))} + {toolbarMenus.map((m) => { + const title = locText(m.title, locale, m.id) + return ( + onPluginCommand(m.pluginId ?? '', m.command, title)} + > + {title} + + ) + })} {suspended && ( onAction('discardSuspend')}> diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index d9c74a7..9b7114c 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -55,7 +55,6 @@ export const vmZh: Record = { "failFocus": "无法定位虚拟机窗口", "failFullscreen": "无法切换全屏", "failGuestTools": "Guest Tools 操作失败", - "failOpenAppWindow": "无法打开独立应用窗口", "failOpenFolder": "无法打开文件夹", "failRestart": "重启失败", "failResume": "恢复失败", @@ -127,7 +126,6 @@ export const vmZh: Record = { "onlineRecoveryConfirm": "拉取并挂载(约 1 GB)", "onlineRecoveryDesc": "本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?", "onlineRecoveryTitle": "拉取在线恢复镜像?", - "openAppWindow": "打开独立应用窗口", "openSharedFolder": "打开共享文件夹", "openShort": "打开", "pendingRestartHint": "重启虚拟机后生效", @@ -290,7 +288,6 @@ export const vmEn: Record = { "failFocus": "Could not focus VM window", "failFullscreen": "Couldn’t toggle full screen", "failGuestTools": "Guest Tools operation failed", - "failOpenAppWindow": "Could not open the app window", "failOpenFolder": "Couldn’t open the folder", "failRestart": "Couldn’t restart", "failResume": "Couldn’t resume", @@ -362,7 +359,6 @@ export const vmEn: Record = { "onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)", "onlineRecoveryDesc": "No recovery image is on this PC. Download Apple’s recovery image (about 1 GB) and attach it to “{name}”?", "onlineRecoveryTitle": "Download online recovery image?", - "openAppWindow": "Open app in separate window", "openSharedFolder": "Open shared folder", "openShort": "Open", "pendingRestartHint": "Takes effect after a restart", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index aef0520..4558da5 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -264,7 +264,6 @@ export type I18nKey = | "failFullscreen" | "failGeneric" | "failGuestTools" - | "failOpenAppWindow" | "failOpenFolder" | "failRestart" | "failResume" @@ -649,7 +648,6 @@ export type I18nKey = | "onlineRecoveryConfirm" | "onlineRecoveryDesc" | "onlineRecoveryTitle" - | "openAppWindow" | "openFolder" | "openSharedFolder" | "openShort" diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index 94a9033..f09bcf4 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -214,8 +214,6 @@ export function ListSnapshots(arg1:string):Promise>; export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise>; -export function OpenAppWindow(arg1:string,arg2:string):Promise; - export function OpenProcessorScheduling():Promise; export function OpenQQGroup():Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 350de45..660c568 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -406,10 +406,6 @@ export function ListSnapshotsWithDriver(arg1, arg2) { return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2); } -export function OpenAppWindow(arg1, arg2) { - return window['go']['app']['App']['OpenAppWindow'](arg1, arg2); -} - export function OpenProcessorScheduling() { return window['go']['app']['App']['OpenProcessorScheduling'](); } diff --git a/internal/app/app.go b/internal/app/app.go index 05999e6..f545fb3 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -111,8 +111,7 @@ type App struct { stopPoll context.CancelFunc guestTools *guesttools.Server guestToolsConfigLocks sync.Map - appWindow *appWindowRun - appWindowClosing bool + appWindowGate sync.Mutex vmDeleteEpochs map[string]uint64 resolveFolderVolume func(string) (host.DirectoryVolume, error) imeBridge *host.IMEBridge @@ -271,7 +270,6 @@ func (a *App) beforeClose(ctx context.Context) bool { } func (a *App) shutdown(ctx context.Context) { - a.stopAppWindow() a.closePacketBridges() if a.stopPoll != nil { a.stopPoll() diff --git a/internal/app/app_window_flow.go b/internal/app/app_window_flow.go index d64ec4c..21db7ac 100644 --- a/internal/app/app_window_flow.go +++ b/internal/app/app_window_flow.go @@ -4,23 +4,20 @@ import ( "context" "errors" "runtime" + "sync" "time" "github.com/Nwflower/reims-go/internal/appwindow" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/plugin/builtin" ) -type appWindowRun struct { - cancel context.CancelFunc - done chan struct{} -} - -// OpenAppWindow shows the frontmost application window of a running macOS VM. -func (a *App) OpenAppWindow(driverID, name string) error { +func (a *App) openAppWindow(command context.Context, sessions *appwindow.Sessions, bridge *guesttools.Server, service builtin.ComputerUseService, name string) error { a.mu.Lock() locale := i18n.EffectiveLocale(a.cfg.Locale) + tmp := a.cfg.TempDir() a.mu.Unlock() coded := func(code, key string, cause error) error { return i18n.NewCodedError(locale, code, key, i18n.Vars{"name": name}, cause) @@ -28,72 +25,62 @@ func (a *App) OpenAppWindow(driverID, name string) error { if runtime.GOOS != "windows" { return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil) } - info, err := a.resolveVMInfo(driverID, name) - if err != nil { - return err - } - if info.DriverID != driver.BuiltinReimsMacOSDriverID { - return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil) - } - vm, ok := a.polledVMForDriver(info.DriverID, name) + vm, ok := a.polledVMForDriver(driver.BuiltinReimsMacOSDriverID, name) if !ok || vm.State != "running" || vm.Dir == "" { return coded("E_VM_NOT_RUNNING", "err.vm_not_running", nil) } - if !a.guestToolsEnabled() { - return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) - } - - a.mu.Lock() - bridge := a.guestTools - if bridge == nil || a.appWindowClosing { - a.mu.Unlock() - return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) - } - if a.appWindow != nil { - a.mu.Unlock() + err := sessions.Start(command, func(ctx context.Context) (func(), error) { + // A previous activation may still be clearing its input when Windows + // takes longer than the plugin's shutdown deadline. + if !a.appWindowGate.TryLock() { + return nil, appwindow.ErrWindowOpen + } + run, err := a.prepareAppWindow(ctx, bridge, service, vm, tmp, locale, coded) + if err != nil { + a.appWindowGate.Unlock() + return nil, err + } + return func() { + defer a.appWindowGate.Unlock() + run() + }, nil + }) + switch { + case errors.Is(err, appwindow.ErrWindowOpen): return coded("E_APP_WINDOW_OPEN", "err.app_window_open", nil) + case errors.Is(err, appwindow.ErrSessionsClosed), errors.Is(err, context.Canceled): + return coded("E_APP_WINDOW_DISABLED", "err.app_window_disabled", nil) + default: + return err } - ctx, cancel := context.WithCancel(context.Background()) - run := &appWindowRun{cancel: cancel, done: make(chan struct{})} - a.appWindow = run - tmp := a.cfg.TempDir() - a.mu.Unlock() - - reporting := false - finish := func() { - cancel() - if reporting { - bridge.SetWindowReporting(name, false) - } - a.mu.Lock() - a.appWindow = nil - close(run.done) - a.mu.Unlock() - } - started := false - defer func() { - if !started { - finish() - } - }() +} +func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, service builtin.ComputerUseService, vm driver.VMListItem, tmp string, locale i18n.Locale, coded func(string, string, error) error) (func(), error) { + name := vm.Name status := bridge.Status(name, 15*time.Second) if !status.Connected { - return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + return nil, coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) } if status.AgentVersion < guesttools.PasteReadyAgentVersion { - return coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil) + return nil, coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil) } - service := a.computerUseInternalService() probe, stopProbe := context.WithTimeout(ctx, 2*time.Second) pointer, err := service.PointerAvailable(probe, vm.Dir) stopProbe() - if err != nil || !pointer { - return coded("E_APP_WINDOW_POINTER", "err.app_window_pointer", err) + if ctx.Err() != nil { + return nil, ctx.Err() } - reporting = bridge.SetWindowReporting(name, true) - if !reporting { - return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + if err != nil || !pointer { + return nil, coded("E_APP_WINDOW_POINTER", "err.app_window_pointer", err) + } + if !bridge.SetWindowReporting(name, true) { + return nil, coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil) + } + clearReporting := sync.OnceFunc(func() { bridge.SetWindowReporting(name, false) }) + stopReporting := context.AfterFunc(ctx, clearReporting) + finishReporting := func() { + stopReporting() + clearReporting() } show, err := appwindow.Prepare(ctx, appwindow.SessionOptions{ VMDir: vm.Dir, @@ -106,7 +93,7 @@ func (a *App) OpenAppWindow(driverID, name string) error { return bridge.PrepareGuestClipboardPaste(wait, name) }, OnClipboardError: func(err error) { - a.emitVMLogForDriver(info.DriverID, name, "App window paste: "+err.Error()) + a.emitVMLogForDriver(vm.DriverID, name, "App window paste: "+err.Error()) a.mu.Lock() manager := a.trayMgr a.mu.Unlock() @@ -115,35 +102,20 @@ func (a *App) OpenAppWindow(driverID, name string) error { } }, }) - if errors.Is(err, appwindow.ErrNoWindow) { - return coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil) - } if err != nil { - return coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err) - } - started = true - go func() { - defer finish() - if err := show(); err != nil && ctx.Err() == nil { - a.emitVMLogForDriver(info.DriverID, name, "App window closed: "+err.Error()) + finishReporting() + if ctx.Err() != nil { + return nil, ctx.Err() } - }() - return nil -} - -func (a *App) stopAppWindow() { - a.mu.Lock() - a.appWindowClosing = true - run := a.appWindow - a.mu.Unlock() - if run == nil { - return - } - run.cancel() - timer := time.NewTimer(5 * time.Second) - defer timer.Stop() - select { - case <-run.done: - case <-timer.C: + if errors.Is(err, appwindow.ErrNoWindow) { + return nil, coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil) + } + return nil, coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err) } + return func() { + defer finishReporting() + if err := show(); err != nil && ctx.Err() == nil { + a.emitVMLogForDriver(vm.DriverID, name, "App window closed: "+err.Error()) + } + }, nil } diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 6af9b3b..b5ee79c 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -172,6 +172,7 @@ func (a *App) initPlugins() { return a.guestToolsImagePath(vmName) }, BuildGuestToolsImage: a.buildGuestToolsImage, + OpenAppWindow: a.openAppWindow, PrepareVMNetwork: a.prepareManagedVMNetwork, RestorePacketBridges: func(ctx context.Context) func() { return a.startPacketBridgeRestore(ctx, func(ctx context.Context) { diff --git a/internal/appwindow/sessions.go b/internal/appwindow/sessions.go new file mode 100644 index 0000000..b4d486c --- /dev/null +++ b/internal/appwindow/sessions.go @@ -0,0 +1,91 @@ +package appwindow + +import ( + "context" + "errors" + "sync" + "time" +) + +var ( + ErrWindowOpen = errors.New("an app window is already open") + ErrSessionsClosed = errors.New("app window service is closed") +) + +// Sessions owns the single app window opened during one plugin activation. +type Sessions struct { + mu sync.Mutex + closed bool + active *activeSession +} + +type activeSession struct { + cancel context.CancelFunc + done chan struct{} +} + +// Start prepares the window under the command's cancellation and transfers +// its runtime to Sessions after preparation succeeds. +func (s *Sessions) Start(command context.Context, prepare func(context.Context) (func(), error)) error { + if err := command.Err(); err != nil { + return err + } + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return ErrSessionsClosed + } + if s.active != nil { + s.mu.Unlock() + return ErrWindowOpen + } + ctx, cancel := context.WithCancel(context.Background()) + active := &activeSession{cancel: cancel, done: make(chan struct{})} + s.active = active + s.mu.Unlock() + + finish := func() { + cancel() + s.mu.Lock() + s.active = nil + close(active.done) + s.mu.Unlock() + } + stopStartup := context.AfterFunc(command, cancel) + run, err := prepare(ctx) + if !stopStartup() { + cancel() + } + if err != nil { + finish() + return err + } + // Run even when startup was canceled after preparation. The prepared + // function owns the initial capture resources and releases them on exit. + startupErr := ctx.Err() + go func() { + defer finish() + run() + }() + return startupErr +} + +// Close prevents new sessions and cancels preparation or the active viewer. +func (s *Sessions) Close() { + s.mu.Lock() + s.closed = true + active := s.active + s.mu.Unlock() + if active == nil { + return + } + active.cancel() + + // Keep plugin transitions bounded if the OS clipboard owner is stalled. + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + select { + case <-active.done: + case <-timer.C: + } +} diff --git a/internal/appwindow/sessions_test.go b/internal/appwindow/sessions_test.go new file mode 100644 index 0000000..b43cb17 --- /dev/null +++ b/internal/appwindow/sessions_test.go @@ -0,0 +1,70 @@ +package appwindow + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestSessionsEnforcePluginLifetime(t *testing.T) { + var sessions Sessions + command, cancel := context.WithCancel(context.Background()) + defer cancel() + var window context.Context + finished := make(chan struct{}) + prepare := func(ctx context.Context) (func(), error) { + window = ctx + return func() { + <-ctx.Done() + close(finished) + }, nil + } + if err := sessions.Start(command, prepare); err != nil { + t.Fatal(err) + } + defer sessions.Close() + cancel() + if err := window.Err(); err != nil { + t.Fatalf("command completion canceled the open window: %v", err) + } + if err := sessions.Start(context.Background(), prepare); !errors.Is(err, ErrWindowOpen) { + t.Fatalf("opening a second window: %v", err) + } + sessions.Close() + select { + case <-finished: + default: + t.Fatal("scope closed before the viewer finished") + } + if err := sessions.Start(context.Background(), prepare); !errors.Is(err, ErrSessionsClosed) { + t.Fatalf("opening a window after deactivation: %v", err) + } +} + +func TestSessionsCloseCancelsPendingStart(t *testing.T) { + var sessions Sessions + entered := make(chan struct{}) + errs := make(chan error, 1) + go func() { + errs <- sessions.Start(context.Background(), func(ctx context.Context) (func(), error) { + close(entered) + <-ctx.Done() + return nil, ctx.Err() + }) + }() + select { + case <-entered: + case <-time.After(2 * time.Second): + t.Fatal("preparation did not start") + } + sessions.Close() + select { + case err := <-errs: + if !errors.Is(err, context.Canceled) { + t.Fatalf("startup after deactivation: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("preparation did not stop") + } +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 1675c39..320ecb0 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -124,6 +124,7 @@ var catalog = map[Locale]map[string]string{ "emptyVMs": "还没有虚拟机", "err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器", "err.app_window_capture": "无法获取 {name} 的应用画面", + "err.app_window_disabled": "在插件页启用 macOS 应用窗口后重试", "err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口", "err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口", "err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试", @@ -802,6 +803,7 @@ var catalog = map[Locale]map[string]string{ "emptyVMs": "No virtual machines", "err.affinity.empty_mask": "Select at least 1 logical processor", "err.app_window_capture": "Could not capture the app window in {name}", + "err.app_window_disabled": "Enable macOS App Windows under Plugins and try again", "err.app_window_guest_tools": "Connect Guest Tools in {name} and try again", "err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again", "err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again", diff --git a/internal/plugin/builtin/app_window.go b/internal/plugin/builtin/app_window.go new file mode 100644 index 0000000..ca1ac04 --- /dev/null +++ b/internal/plugin/builtin/app_window.go @@ -0,0 +1,80 @@ +package builtin + +import ( + "context" + "errors" + "fmt" + "runtime" + "strings" + + "github.com/Nwflower/reims-go/internal/appwindow" + "github.com/Nwflower/reims-go/internal/guesttools" + "github.com/Nwflower/reims-go/internal/plugin" +) + +// IDAppWindow is the optional built-in extension for macOS application windows. +const IDAppWindow = "builtin.macos.app-window" + +func defAppWindow(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef { + const commandID = "open" + title := plugin.LocalizedText{ZhCN: "打开独立应用窗口", EnUS: "Open app in separate window"} + return plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: IDAppWindow, + Version: ver, + Name: plugin.LocalizedText{ZhCN: "macOS 应用窗口", EnUS: "macOS App Windows"}, + Description: plugin.LocalizedText{ + ZhCN: "在 Windows 桌面上显示和操作当前 macOS 应用窗口", + EnUS: "View and control the active macOS app in a separate Windows window", + }, + Publisher: "Reims-Go", + License: "Apache-2.0", + Platforms: []string{"windows-x64"}, + Requires: []plugin.ServiceRequirement{ + {Service: ServiceGuestToolsTransport, Version: "^1.0.0"}, + {Service: ServiceComputerUse, Version: "^1.0.0"}, + }, + Permissions: []string{"vm:screen", "qmp:write", "ui:slot"}, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + Desired: desiredFn(IDAppWindow, false), + Activate: func(_ context.Context, sc *plugin.Scope) error { + // The CLI uses this definition to manage plugin state. Only the + // supported desktop host can expose the native window command. + if cb.OpenAppWindow == nil || runtime.GOOS != "windows" || runtime.GOARCH != "amd64" { + return nil + } + rawTools, _ := sc.Lookup(ServiceGuestToolsTransport) + tools, ok := rawTools.(*guesttools.Server) + if !ok || tools == nil { + return fmt.Errorf("invalid %q service instance", ServiceGuestToolsTransport) + } + rawConsole, _ := sc.Lookup(ServiceComputerUse) + console, ok := rawConsole.(ComputerUseService) + if !ok || console == nil { + return fmt.Errorf("invalid %q service instance", ServiceComputerUse) + } + + sessions := new(appwindow.Sessions) + sc.OnDispose(sessions.Close) + sc.Registry().RegisterCommand(sc, plugin.CommandContribution{ID: commandID, Title: title}, + func(ctx context.Context, args map[string]any) (any, error) { + if sc.Disposed() { + return nil, appwindow.ErrSessionsClosed + } + name, _ := args["vm"].(string) + name = strings.TrimSpace(name) + if name == "" { + return nil, errors.New("a VM name is required") + } + return nil, cb.OpenAppWindow(ctx, sessions, tools, console, name) + }) + sc.Registry().RegisterMenu(sc, plugin.MenuContribution{ + ID: commandID, Slot: "vm.toolbar", Command: commandID, Title: title, When: "vm.macos.running", + }) + return nil + }, + } +} diff --git a/internal/plugin/builtin/app_window_test.go b/internal/plugin/builtin/app_window_test.go new file mode 100644 index 0000000..350c2f3 --- /dev/null +++ b/internal/plugin/builtin/app_window_test.go @@ -0,0 +1,131 @@ +package builtin + +import ( + "context" + "errors" + "runtime" + "slices" + "testing" + + "github.com/Nwflower/reims-go/internal/appwindow" + "github.com/Nwflower/reims-go/internal/guesttools" + "github.com/Nwflower/reims-go/internal/plugin" +) + +func TestAppWindowPluginDefaultOffAndCLIState(t *testing.T) { + reg := plugin.NewRegistry(nil) + t.Cleanup(reg.DisposeAll) + if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil { + t.Fatal(err) + } + reg.Reconcile(t.Context()) + info, ok := reg.Info(IDAppWindow) + if !ok || info.Enabled || info.State != plugin.StateOff { + t.Fatalf("default app window plugin state: %+v", info) + } + assertAppWindowContributions(t, reg, false) + if err := reg.SetDesired(t.Context(), IDAppWindow, true); err != nil { + t.Fatal(err) + } + if !reg.IsActive(IDAppWindow) { + t.Fatalf("CLI cannot enable app window plugin state: %s", reg.StateOf(IDAppWindow)) + } + assertAppWindowContributions(t, reg, false) +} + +func TestAppWindowPluginOwnsWindowAcrossDependencyChanges(t *testing.T) { + if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" { + t.Skip("native app window command is available on Windows x64") + } + for _, dependency := range []string{IDGuestTools, IDComputerUse} { + t.Run(dependency, func(t *testing.T) { + reg := plugin.NewRegistry(nil) + t.Cleanup(reg.DisposeAll) + var owner *appwindow.Sessions + var closed chan struct{} + cb := HostCallbacks{ + OpenAppWindow: func(ctx context.Context, sessions *appwindow.Sessions, tools *guesttools.Server, console ComputerUseService, vm string) error { + if tools == nil || console == nil || vm != "fixture" { + t.Fatalf("invalid command arguments: tools=%v console=%v vm=%q", tools != nil, console != nil, vm) + } + owner = sessions + done := make(chan struct{}) + closed = done + return sessions.Start(ctx, func(sessionCtx context.Context) (func(), error) { + return func() { + <-sessionCtx.Done() + close(done) + }, nil + }) + }, + } + if err := RegisterAll(reg, cb, nil); err != nil { + t.Fatal(err) + } + if err := reg.SetDesired(t.Context(), IDAppWindow, true); err != nil { + t.Fatal(err) + } + assertAppWindowContributions(t, reg, true) + if _, err := reg.InvokeCommand(t.Context(), IDAppWindow, "open", map[string]any{"vm": 17}); err == nil { + t.Fatal("native window command accepted a non-string VM name") + } + open := func() { + t.Helper() + if _, err := reg.InvokeCommand(t.Context(), IDAppWindow, "open", map[string]any{"vm": "fixture"}); err != nil { + t.Fatal(err) + } + } + open() + first := owner + if err := reg.SetDesired(t.Context(), dependency, false); err != nil { + t.Fatal(err) + } + if reg.StateOf(IDAppWindow) != plugin.StatePending { + t.Fatalf("app window plugin remained active without %s", dependency) + } + select { + case <-closed: + default: + t.Fatalf("window was not closed when %s was disabled", dependency) + } + assertAppWindowContributions(t, reg, false) + if err := first.Start(t.Context(), func(context.Context) (func(), error) { + t.Fatal("disposed scope still accepted a window") + return nil, nil + }); !errors.Is(err, appwindow.ErrSessionsClosed) { + t.Fatalf("disposed session owner returned %v", err) + } + + if err := reg.SetDesired(t.Context(), dependency, true); err != nil { + t.Fatal(err) + } + assertAppWindowContributions(t, reg, true) + open() + if owner == first { + t.Fatal("reactivation reused the disposed session owner") + } + if err := reg.SetDesired(t.Context(), IDAppWindow, false); err != nil { + t.Fatal(err) + } + select { + case <-closed: + default: + t.Fatal("disabling the app window plugin left a window open") + } + assertAppWindowContributions(t, reg, false) + }) + } +} + +func assertAppWindowContributions(t *testing.T, reg *plugin.Registry, want bool) { + t.Helper() + hasCommand := slices.ContainsFunc(reg.Commands(), func(cmd plugin.CommandContribution) bool { + return cmd.PluginID == IDAppWindow && cmd.ID == "open" + }) + hasMenu := slices.ContainsFunc(reg.Menus("vm.toolbar"), func(item plugin.MenuContribution) bool { + return item.PluginID == IDAppWindow && item.Command == "open" && item.When == "vm.macos.running" + }) + if hasCommand != want || hasMenu != want { + t.Fatalf("app window command=%v menu=%v, want %v", hasCommand, hasMenu, want) + } +} diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index ff02bcb..fcbc8a2 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -10,6 +10,7 @@ import ( "fmt" "strings" + "github.com/Nwflower/reims-go/internal/appwindow" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" @@ -57,6 +58,7 @@ type HostCallbacks struct { CancelColdReboot func(vmName string) GuestToolsImg func(vmName string) string BuildGuestToolsImage func(vmName, vmDir string) error + OpenAppWindow func(context.Context, *appwindow.Sessions, *guesttools.Server, ComputerUseService, string) error PrepareVMNetwork func(context.Context, string, bool) (func(), error) // 返回取消并等待本次恢复任务结束的清理函数,由插件 scope 先于通道释放执行。 RestorePacketBridges func(context.Context) func() @@ -98,6 +100,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin defInput(ver, cb, desiredFn), defNpcapBridge(ver, cb, desiredFn), defComputerUse(ver, desiredFn), + defAppWindow(ver, cb, desiredFn), defDownloaderParallel(ver, cb, desiredFn), } for _, d := range defs { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 4c9bf6b..804377d 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -312,6 +312,7 @@ "err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}", "err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen", "err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows", + "err.app_window_disabled": "Enable macOS App Windows under Plugins and try again", "err.app_window_guest_tools": "Connect Guest Tools in {name} and try again", "err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again", "err.app_window_open": "Close the current separate app window first", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 2ee2794..a05d36c 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -10,8 +10,6 @@ "failFullscreen": "Couldn’t toggle full screen", "showInstallGuide": "Show install guide", "copyScreenshot": "Copy screenshot", - "openAppWindow": "Open app in separate window", - "failOpenAppWindow": "Could not open the app window", "toastScreenshotCopied": "VM screenshot copied", "failFocus": "Could not focus VM window", "failScreenshot": "Screenshot failed", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index cae624c..909a776 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -312,6 +312,7 @@ "err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照", "err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏", "err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机", + "err.app_window_disabled": "在插件页启用 macOS 应用窗口后重试", "err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口", "err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口", "err.app_window_open": "先关闭已打开的独立应用窗口", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 30e2937..30b5948 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -10,8 +10,6 @@ "failFullscreen": "无法切换全屏", "showInstallGuide": "显示安装引导", "copyScreenshot": "截屏并复制", - "openAppWindow": "打开独立应用窗口", - "failOpenAppWindow": "无法打开独立应用窗口", "toastScreenshotCopied": "已复制虚拟机画面", "failFocus": "无法定位虚拟机窗口", "failScreenshot": "截屏失败",