feat: open a macOS app in a separate Windows window
This commit is contained in:
1 parent
e9b3758c57
commit
9f6c9aa90e
35 files changed
+1904
-21
No files matched your search
@@ -24,7 +24,7 @@
|
||||
| 正在创建 | 无(展示分步进度) | 取消创建 |
|
||||
| 已停止 | 启动 | 设置、恢复点、派生副本、磁盘扩容与空间回收、打开目录、删除 |
|
||||
| 正在启动 | 启动中(忙碌禁用) | 设置、强制关机 |
|
||||
| 运行中 | 显示虚拟机窗口 | 挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 |
|
||||
| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 |
|
||||
| 正在停止 | 停止中(忙碌禁用) | 强制关机 |
|
||||
| 正在挂起 | 挂起中(忙碌禁用) | 强制关机 |
|
||||
| 已挂起 | 恢复(需运行时支持) | 放弃挂起状态(需破坏性操作确认)、打开目录 |
|
||||
|
||||
@@ -52,6 +52,7 @@ const failKey: Record<VMAction, I18nKey> = {
|
||||
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))
|
||||
|
||||
@@ -68,6 +68,7 @@ export type VMAction =
|
||||
| 'focus'
|
||||
| 'fullscreen'
|
||||
| 'screenshot'
|
||||
| 'appWindow'
|
||||
| 'eject'
|
||||
| 'finishInstall'
|
||||
| 'enterRecovery'
|
||||
@@ -592,6 +593,11 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
|
||||
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
|
||||
</Menu.Item>
|
||||
{isMacOSDriver && !installing && (
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('appWindow')}>
|
||||
{tr('openAppWindow')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -55,6 +55,7 @@ export const vmZh: Record<string, string> = {
|
||||
"failFocus": "无法定位虚拟机窗口",
|
||||
"failFullscreen": "无法切换全屏",
|
||||
"failGuestTools": "Guest Tools 操作失败",
|
||||
"failOpenAppWindow": "无法打开独立应用窗口",
|
||||
"failOpenFolder": "无法打开文件夹",
|
||||
"failRestart": "重启失败",
|
||||
"failResume": "恢复失败",
|
||||
@@ -126,6 +127,7 @@ export const vmZh: Record<string, string> = {
|
||||
"onlineRecoveryConfirm": "拉取并挂载(约 1 GB)",
|
||||
"onlineRecoveryDesc": "本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?",
|
||||
"onlineRecoveryTitle": "拉取在线恢复镜像?",
|
||||
"openAppWindow": "打开独立应用窗口",
|
||||
"openSharedFolder": "打开共享文件夹",
|
||||
"openShort": "打开",
|
||||
"pendingRestartHint": "重启虚拟机后生效",
|
||||
@@ -288,6 +290,7 @@ export const vmEn: Record<string, string> = {
|
||||
"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<string, string> = {
|
||||
"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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
Vendored
+2
@@ -214,6 +214,8 @@ export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function OpenAppWindow(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenQQGroup():Promise<void>;
|
||||
|
||||
@@ -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']();
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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:
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
+29
-4
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠",
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
"failFullscreen": "无法切换全屏",
|
||||
"showInstallGuide": "显示安装引导",
|
||||
"copyScreenshot": "截屏并复制",
|
||||
"openAppWindow": "打开独立应用窗口",
|
||||
"failOpenAppWindow": "无法打开独立应用窗口",
|
||||
"toastScreenshotCopied": "已复制虚拟机画面",
|
||||
"failFocus": "无法定位虚拟机窗口",
|
||||
"failScreenshot": "截屏失败",
|
||||
|
||||
Reference in new issue
Block a user