Merge pull request #180 from yxc0915/codex/fix-macos-app-window-reporter

Fix macOS app window reporting, cropping, and drag rendering.
This commit is contained in:
Xiaochi You authored and GitHub committed 2026-12-05 03:49:23 +08:00
commit a11d08cb9b
13 files changed
+415 -48

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "清理 macOS 独立应用窗口边角残留的桌面画面。拖动标题栏中部即可移动 Windows 窗口,拖动期间保留上一帧,避免闪出来宾桌面。",
"en": "Remove stray desktop pixels from the corners of separate macOS app windows. Drag the middle of the title bar to move the Windows window. The last frame stays visible during the move to prevent the guest desktop from flashing through."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "修复 Guest Tools 窗口上报进程崩溃导致的「打开独立应用窗口」失败。已有虚拟机请重新安装 Guest Tools,更新至 `v22`。",
"en": "Fix a Guest Tools window reporter crash that prevented macOS apps from opening in separate windows. Reinstall Guest Tools in existing VMs to update to `v22`."
}
+5 -2
View File
@@ -86,8 +86,8 @@ func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, s
VMDir: vm.Dir,
TmpDir: tmp,
Console: service,
Window: func(maxAge time.Duration) (guesttools.ActiveWindow, bool) {
return bridge.ActiveWindow(name, maxAge)
Window: func(maxAge time.Duration) (guesttools.ActiveWindow, time.Time, bool) {
return bridge.ActiveWindowSample(name, maxAge)
},
PrepareClipboard: func(wait context.Context) (func(), error) {
return bridge.PrepareGuestClipboardPaste(wait, name)
@@ -108,6 +108,9 @@ func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, s
return nil, ctx.Err()
}
if errors.Is(err, appwindow.ErrNoWindow) {
if status.AgentVersion < guesttools.StableWindowReporterAgentVersion {
return nil, coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil)
}
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)
+74 -15
View File
@@ -8,6 +8,7 @@ import (
"image"
"image/draw"
"maps"
"math"
"os"
"path/filepath"
"slices"
@@ -20,6 +21,7 @@ import (
)
var ErrNoWindow = errors.New("no foreground guest window reported")
var errFrameUnconfirmed = errors.New("window geometry not confirmed after capture")
const (
windowMaxAge = time.Second
@@ -43,7 +45,7 @@ type Console interface {
type SessionOptions struct {
VMDir string
TmpDir string
Window func(time.Duration) (guesttools.ActiveWindow, bool)
Window func(time.Duration) (guesttools.ActiveWindow, time.Time, bool)
Console Console
PrepareClipboard func(context.Context) (func(), error)
OnClipboardError func(error)
@@ -140,6 +142,21 @@ func Prepare(ctx context.Context, opts SessionOptions) (func() error, error) {
_ = os.Remove(dir)
}
first, err := s.capture(ctx)
if errors.Is(err, errFrameUnconfirmed) {
retry, cancel := context.WithTimeout(ctx, 2*time.Second)
for errors.Is(err, errFrameUnconfirmed) {
select {
case <-retry.Done():
err = ErrNoWindow
case <-time.After(125 * time.Millisecond):
first, err = s.capture(retry)
}
}
cancel()
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
err = ErrNoWindow
}
}
if err != nil {
cleanup()
return nil, err
@@ -150,13 +167,13 @@ func Prepare(ctx context.Context, opts SessionOptions) (func() error, error) {
}, nil
}
func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.ActiveWindow, bool)) (guesttools.ActiveWindow, error) {
func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.ActiveWindow, time.Time, bool)) (guesttools.ActiveWindow, error) {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
tick := time.NewTicker(150 * time.Millisecond)
defer tick.Stop()
for {
if report, ok := get(windowMaxAge); ok {
if report, _, ok := get(windowMaxAge); ok {
return report, nil
}
select {
@@ -171,14 +188,15 @@ func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.Acti
}
func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
before, ok := s.Window(windowMaxAge)
before, _, ok := s.Window(windowMaxAge)
if !ok || before.ID != s.id {
return ViewerFrame{}, ErrNoWindow
}
ctx, cancel := context.WithTimeout(ctx, frameTimeout)
defer cancel()
request, cancel := context.WithTimeout(ctx, frameTimeout)
defer os.Remove(s.path)
format, err := s.Console.ScreendumpDisplay(ctx, s.VMDir, s.path, "gfx", 0)
format, err := s.Console.ScreendumpDisplay(request, s.VMDir, s.path, "gfx", 0)
capturedAt := time.Now()
cancel()
if err != nil {
return ViewerFrame{}, err
}
@@ -193,14 +211,13 @@ func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
if crop.Empty() {
return ViewerFrame{}, ErrNoWindow
}
if err := s.confirmFrame(ctx, before, capturedAt); err != nil {
return ViewerFrame{}, err
}
frame, err := thumb.Load(s.path, format)
if err != nil {
return ViewerFrame{}, err
}
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()
@@ -211,7 +228,49 @@ func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
s.mapping = mapping
}
s.lastFrame = time.Now()
return ViewerFrame{Image: img, Tag: s.tag}, nil
return ViewerFrame{Image: img, Tag: s.tag, shape: guestViewerShape(before, size, crop)}, nil
}
func (s *session) confirmFrame(ctx context.Context, before guesttools.ActiveWindow, capturedAt time.Time) error {
// Reading the same cached report twice cannot detect a window moving between polls.
timeout := time.NewTimer(windowMaxAge)
defer timeout.Stop()
tick := time.NewTicker(15 * time.Millisecond)
defer tick.Stop()
for {
window, receivedAt, ok := s.Window(windowMaxAge)
if !ok || window != before {
return errFrameUnconfirmed
}
if receivedAt.After(capturedAt) {
return ctx.Err()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-timeout.C:
return errFrameUnconfirmed
case <-tick.C:
}
}
}
func guestViewerShape(window guesttools.ActiveWindow, size image.Point, crop image.Rectangle) viewerShape {
scale := func(x, y int) image.Point {
return image.Pt(
int(math.Round(float64(x*size.X)/float64(window.DisplayWidth))),
int(math.Round(float64(y*size.Y)/float64(window.DisplayHeight))),
)
}
point := func(x, y int) image.Point {
return scale(window.X+x, window.Y+y).Sub(crop.Min)
}
return viewerShape{
outline: image.Rectangle{Min: point(0, 0), Max: point(window.Width, window.Height)},
// Keep the traffic lights and the outer toolbar areas available to macOS.
caption: image.Rectangle{Min: point(80, 0), Max: point(window.Width-64, 22)},
radius: scale(16, 16),
}
}
func guestCrop(window guesttools.ActiveWindow, size image.Point) image.Rectangle {
@@ -231,7 +290,7 @@ func guestCrop(window guesttools.ActiveWindow, size image.Point) image.Rectangle
}
func (s *session) eventMapping(event ViewerEvent) (frameMapping, bool) {
window, ok := s.Window(windowMaxAge)
window, _, ok := s.Window(windowMaxAge)
s.mu.Lock()
defer s.mu.Unlock()
return s.mapping, ok && event.FrameTag == s.tag && window == s.mapping.window &&
@@ -263,7 +322,7 @@ func (s *session) run(ctx context.Context, title string, first ViewerFrame) erro
Initial: first,
Frame: func(ctx context.Context) (ViewerFrame, error) {
frame, err := s.capture(ctx)
if err == nil {
if err == nil || errors.Is(err, errFrameUnconfirmed) {
firstCaptureError = time.Time{}
} else if firstCaptureError.IsZero() {
firstCaptureError = time.Now()
@@ -319,7 +378,7 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e
case <-ctx.Done():
return ctx.Err()
case <-checkWindow.C:
if window, ok := s.Window(windowMaxAge); ok && window.ID == s.id {
if window, _, ok := s.Window(windowMaxAge); ok && window.ID == s.id {
missingSince = time.Time{}
} else if missingSince.IsZero() {
missingSince = time.Now()
+40 -2
View File
@@ -13,6 +13,18 @@ import (
type captureConsole struct{ Console }
func TestGuestViewerShapeKeepsOffscreenCornersOutsideCapture(t *testing.T) {
window := guesttools.ActiveWindow{
X: -35, Y: -18, Width: 300, Height: 180, DisplayWidth: 800, DisplayHeight: 600,
}
size := image.Pt(1600, 1200)
shape := guestViewerShape(window, size, guestCrop(window, size))
if shape.outline != image.Rect(-70, -36, 530, 324) ||
shape.caption != image.Rect(90, -36, 402, 8) || shape.radius != image.Pt(32, 32) {
t.Fatalf("unexpected shape: %+v", shape)
}
}
type pasteConsole struct {
Console
sent chan string
@@ -41,7 +53,7 @@ func TestPasteWaitsForClipboardAndCancelsOnBlur(t *testing.T) {
s := &session{
SessionOptions: SessionOptions{
Console: console,
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return window, true },
Window: func(time.Duration) (guesttools.ActiveWindow, time.Time, bool) { return window, time.Now(), true },
PrepareClipboard: func(ctx context.Context) (func(), error) {
close(entered)
select {
@@ -140,7 +152,7 @@ func TestCaptureTracksDisplayedGeometry(t *testing.T) {
}
s := &session{
SessionOptions: SessionOptions{
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return current, true },
Window: func(time.Duration) (guesttools.ActiveWindow, time.Time, bool) { return current, time.Now(), true },
Console: captureConsole{},
},
path: filepath.Join(t.TempDir(), "test.ppm"), id: 1,
@@ -172,3 +184,29 @@ func TestCaptureTracksDisplayedGeometry(t *testing.T) {
t.Fatalf("capture after guest changed windows = %v", err)
}
}
func TestCaptureDiscardsFrameWhenDelayedReportShowsMovement(t *testing.T) {
window := guesttools.ActiveWindow{
ID: 1, AppName: "TextEdit", Width: 4, Height: 2, DisplayWidth: 4, DisplayHeight: 3,
}
oldReport := time.Now().Add(-time.Second)
moved := window
moved.X++
samples := 0
s := &session{
SessionOptions: SessionOptions{
Window: func(time.Duration) (guesttools.ActiveWindow, time.Time, bool) {
samples++
if samples <= 2 {
return window, oldReport, true
}
return moved, time.Now(), true
},
Console: captureConsole{},
},
path: filepath.Join(t.TempDir(), "test.ppm"), id: 1,
}
if frame, err := s.capture(context.Background()); err != errFrameUnconfirmed || frame.Image != nil || s.tag != 0 {
t.Fatalf("capture published a stale crop: frame=%+v, tag=%d, error=%v", frame, s.tag, err)
}
}
+7
View File
@@ -8,6 +8,13 @@ import (
type ViewerFrame struct {
Image image.Image
Tag uint64
shape viewerShape
}
type viewerShape struct {
outline image.Rectangle
caption image.Rectangle
radius image.Point
}
type ViewerEventKind uint8
+139 -14
View File
@@ -37,6 +37,7 @@ var (
viewerGetClientRect = viewerUser32.NewProc("GetClientRect")
viewerGetWindowRect = viewerUser32.NewProc("GetWindowRect")
viewerSetWindowPos = viewerUser32.NewProc("SetWindowPos")
viewerSetWindowRegion = viewerUser32.NewProc("SetWindowRgn")
viewerBeginPaint = viewerUser32.NewProc("BeginPaint")
viewerEndPaint = viewerUser32.NewProc("EndPaint")
viewerFillRect = viewerUser32.NewProc("FillRect")
@@ -54,6 +55,10 @@ var (
viewerGetStockObject = viewerGDI32.NewProc("GetStockObject")
viewerSetStretchMode = viewerGDI32.NewProc("SetStretchBltMode")
viewerStretchDIBits = viewerGDI32.NewProc("StretchDIBits")
viewerCreateRectRgn = viewerGDI32.NewProc("CreateRectRgn")
viewerCreateRoundRgn = viewerGDI32.NewProc("CreateRoundRectRgn")
viewerCombineRgn = viewerGDI32.NewProc("CombineRgn")
viewerDeleteObject = viewerGDI32.NewProc("DeleteObject")
viewerSetDwmAttribute = viewerDWM.NewProc("DwmSetWindowAttribute")
viewerMoveMemory = viewerKernel32.NewProc("RtlMoveMemory")
@@ -91,6 +96,8 @@ const (
viewerWmMiddleUp = 0x0208
viewerWmMouseWheel = 0x020a
viewerWmCaptureChanged = 0x0215
viewerWmEnterSizeMove = 0x0231
viewerWmExitSizeMove = 0x0232
viewerWmFrame = 0x8001
viewerWmStop = 0x8002
@@ -161,6 +168,13 @@ type viewerBitmap struct {
width, height int
tag uint64
pixels []byte
shape viewerShape
moveEpoch uint64
}
type viewerRegion struct {
client, frame, outline image.Rectangle
radius image.Point
}
type nativeViewer struct {
@@ -169,12 +183,15 @@ type nativeViewer struct {
latest atomic.Pointer[viewerBitmap]
pending atomic.Bool
move atomic.Uint64 // Odd during a native move or resize.
postMu sync.Mutex
closed bool
// The message loop owns these fields. Inputs use the bitmap that was painted.
bitmap *viewerBitmap
displayed *viewerBitmap
imageRect image.Rectangle
region viewerRegion
keys map[uint32]bool
buttons [3]bool
lastMouse ViewerEvent
@@ -229,6 +246,7 @@ func RunViewer(ctx context.Context, opts ViewerOptions) error {
width, height := 900, 640
if first != nil {
v.latest.Store(first)
v.bitmap = first
size := fitViewerFrame(min(first.width, 920), min(first.height, 680), first.width, first.height)
width, height = size.Dx(), size.Dy()
}
@@ -244,6 +262,7 @@ func RunViewer(ctx context.Context, opts ViewerOptions) error {
viewerWindows.Store(hwnd, v)
defer viewerWindows.Delete(hwnd)
configureViewerFrame(hwnd)
v.updateRegion()
work, cancel := context.WithCancel(ctx)
var workers sync.WaitGroup
@@ -304,15 +323,31 @@ func fitViewerMaximizedClient(hwnd, rect uintptr) {
}
}
func viewerFrameHitTest(hwnd uintptr, point viewerPoint) uintptr {
if zoomed, _, _ := viewerIsZoomed.Call(hwnd); zoomed != 0 {
return viewerHTClient
}
func (v *nativeViewer) hitTest(point viewerPoint) uintptr {
hwnd := v.hwnd
var bounds viewerRect
if ok, _, _ := viewerGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds))); ok == 0 {
return viewerHTClient
}
return viewerResizeHit(bounds, point, viewerScale(hwnd, 5))
if zoomed, _, _ := viewerIsZoomed.Call(hwnd); zoomed == 0 {
if hit := viewerResizeHit(bounds, point, viewerScale(hwnd, 5)); hit != viewerHTClient {
return hit
}
}
if v.displayed == nil || v.holdingButton() {
return viewerHTClient
}
if ok, _, _ := viewerScreenToClient.Call(hwnd, uintptr(unsafe.Pointer(&point))); ok == 0 {
return viewerHTClient
}
return viewerCaptionHit(v.displayed, v.imageRect, image.Pt(int(point.x), int(point.y)))
}
func viewerCaptionHit(bitmap *viewerBitmap, area image.Rectangle, point image.Point) uintptr {
if point.In(area) && point.In(bitmap.mapRect(bitmap.shape.caption, area)) {
return viewerHTCaption
}
return viewerHTClient
}
func viewerScale(hwnd uintptr, logical int32) int32 {
@@ -364,7 +399,81 @@ func makeViewerBitmap(frame ViewerFrame) *viewerBitmap {
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}
return &viewerBitmap{width: bounds.Dx(), height: bounds.Dy(), tag: frame.Tag, pixels: rgba.Pix, shape: frame.shape}
}
func (b *viewerBitmap) mapRect(rect, area image.Rectangle) image.Rectangle {
point := func(p image.Point) image.Point {
return area.Min.Add(image.Pt(p.X*area.Dx()/b.width, p.Y*area.Dy()/b.height))
}
return image.Rectangle{Min: point(rect.Min), Max: point(rect.Max)}
}
func (v *nativeViewer) updateRegion() {
bitmap := v.bitmap
if bitmap == nil || bitmap.shape.outline.Empty() {
return
}
var client, outer viewerRect
var origin viewerPoint
viewerGetClientRect.Call(v.hwnd, uintptr(unsafe.Pointer(&client)))
viewerGetWindowRect.Call(v.hwnd, uintptr(unsafe.Pointer(&outer)))
viewerClientToScreen.Call(v.hwnd, uintptr(unsafe.Pointer(&origin)))
width, height := int(client.right), int(client.bottom)
area := fitViewerFrame(width, height, bitmap.width, bitmap.height)
if area.Empty() {
return
}
offset := image.Pt(int(origin.x-outer.left), int(origin.y-outer.top))
area = area.Add(offset)
outline := bitmap.mapRect(bitmap.shape.outline, area)
radius := bitmap.shape.radius
region := viewerRegion{
client: image.Rect(0, 0, width, height).Add(offset), frame: area, outline: outline,
radius: image.Pt(
min(outline.Dx()/2, max(1, radius.X*area.Dx()/bitmap.width)),
min(outline.Dy()/2, max(1, radius.Y*area.Dy()/bitmap.height)),
),
}
if region == v.region || region.radius.X == 0 || region.radius.Y == 0 {
return
}
previous := v.region
v.region = region
if !region.apply(v.hwnd) {
v.region = previous
}
}
func (r viewerRegion) apply(hwnd uintptr) bool {
rectRegion := func(rect image.Rectangle) uintptr {
handle, _, _ := viewerCreateRectRgn.Call(uintptr(rect.Min.X), uintptr(rect.Min.Y), uintptr(rect.Max.X), uintptr(rect.Max.Y))
return handle
}
full, corners := rectRegion(r.client), rectRegion(r.frame)
outline := r.outline
rounded, _, _ := viewerCreateRoundRgn.Call(
uintptr(outline.Min.X), uintptr(outline.Min.Y), uintptr(outline.Max.X), uintptr(outline.Max.Y),
uintptr(2*r.radius.X), uintptr(2*r.radius.Y),
)
defer viewerDeleteObject.Call(corners)
defer viewerDeleteObject.Call(rounded)
// Remove only the pixels between the captured rectangle and the rounded guest outline.
// Keep the client area used for letterboxing and for Windows edge resizing.
if full != 0 && corners != 0 && rounded != 0 {
const difference = 4 // RGN_DIFF
cut, _, _ := viewerCombineRgn.Call(corners, corners, rounded, difference)
if cut != 0 {
shape, _, _ := viewerCombineRgn.Call(full, full, corners, difference)
if shape != 0 {
if ok, _, _ := viewerSetWindowRegion.Call(hwnd, full, 1); ok != 0 {
return true // Windows now owns full.
}
}
}
}
viewerDeleteObject.Call(full)
return false
}
func (v *nativeViewer) post(message uintptr) bool {
@@ -389,22 +498,24 @@ func (v *nativeViewer) destroy() {
}
func (v *nativeViewer) pollFrames(ctx context.Context) {
timer := time.NewTimer(125 * time.Millisecond)
defer timer.Stop()
ticker := time.NewTicker(125 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
case <-ticker.C:
}
if iconic, _, _ := viewerIsIconic.Call(v.hwnd); iconic == 0 {
epoch := v.move.Load()
if iconic, _, _ := viewerIsIconic.Call(v.hwnd); iconic == 0 && epoch%2 == 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 err == nil && v.move.Load() == epoch {
if bitmap := makeViewerBitmap(frame); bitmap != nil {
bitmap.moveEpoch = epoch
v.latest.Store(bitmap)
if !v.pending.Swap(true) && !v.post(viewerWmFrame) {
v.pending.Store(false)
@@ -412,7 +523,6 @@ func (v *nativeViewer) pollFrames(ctx context.Context) {
}
}
}
timer.Reset(125 * time.Millisecond)
}
}
@@ -440,7 +550,7 @@ func (v *nativeViewer) paint() {
var client viewerRect
viewerGetClientRect.Call(v.hwnd, uintptr(unsafe.Pointer(&client)))
brush, _, _ := viewerGetStockObject.Call(4) // BLACK_BRUSH
bitmap := v.latest.Load()
bitmap := v.bitmap
if bitmap == nil {
viewerFillRect.Call(dc, uintptr(unsafe.Pointer(&client)), brush)
return
@@ -487,7 +597,7 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint
v := entry.(*nativeViewer)
switch message {
case viewerWmNCHitTest:
return viewerFrameHitTest(hwnd, viewerMessagePoint(lParam))
return v.hitTest(viewerMessagePoint(lParam))
case viewerWmNCPaint:
return 0
case viewerWmNCActivate:
@@ -496,7 +606,21 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint
return result
case viewerWmFrame:
v.pending.Store(false)
bitmap, epoch := v.latest.Load(), v.move.Load()
if bitmap == nil || epoch%2 != 0 || bitmap.moveEpoch != epoch {
return 0
}
v.bitmap = bitmap
v.updateRegion()
viewerInvalidateRect.Call(hwnd, 0, 0)
case viewerWmEnterSizeMove:
if v.move.Load()%2 == 0 {
v.move.Add(1)
}
case viewerWmExitSizeMove:
if v.move.Load()%2 != 0 {
v.move.Add(1)
}
case viewerWmSize:
// Release a guest drag before changing its coordinate map. A system resize owns its own capture.
if v.holdingButton() {
@@ -504,6 +628,7 @@ func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uint
v.releaseCaptureIfIdle()
}
v.imageRect = image.Rectangle{}
v.updateRegion()
viewerInvalidateRect.Call(hwnd, 0, 0)
case viewerWmPaint:
v.paint()
+27 -1
View File
@@ -2,7 +2,33 @@
package appwindow
import "testing"
import (
"image"
"testing"
)
func TestViewerCaptionHit(t *testing.T) {
bitmap := &viewerBitmap{
width: 800, height: 500,
shape: viewerShape{caption: image.Rect(80, 0, 736, 22)},
}
area := image.Rect(50, 50, 450, 300)
for _, tc := range []struct {
name string
point image.Point
want uintptr
}{
{"title bar", image.Pt(220, 57), viewerHTCaption},
{"traffic lights", image.Pt(78, 57), viewerHTClient},
{"right controls", image.Pt(432, 57), viewerHTClient},
{"content", image.Pt(220, 73), viewerHTClient},
{"letterbox", image.Pt(220, 40), viewerHTClient},
} {
if got := viewerCaptionHit(bitmap, area, tc.point); got != tc.want {
t.Errorf("%s: got hit %d, want %d", tc.name, got, tc.want)
}
}
}
func TestViewerResizeHit(t *testing.T) {
bounds := viewerRect{left: -900, top: -40, right: -500, bottom: 260}
+9 -3
View File
@@ -56,17 +56,23 @@ func (s *Server) SetWindowReporting(vmKey string, enabled bool) bool {
// ActiveWindow returns the latest eligible window if it arrived within maxAge.
func (s *Server) ActiveWindow(vmKey string, maxAge time.Duration) (ActiveWindow, bool) {
window, _, ok := s.ActiveWindowSample(vmKey, maxAge)
return window, ok
}
// ActiveWindowSample also returns the time the host received the report.
func (s *Server) ActiveWindowSample(vmKey string, maxAge time.Duration) (ActiveWindow, time.Time, bool) {
if maxAge <= 0 {
return ActiveWindow{}, false
return ActiveWindow{}, time.Time{}, 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 ActiveWindow{}, time.Time{}, false
}
return *vm.windowReport.window, true
return *vm.windowReport.window, vm.windowReport.receivedAt, true
}
func (w ActiveWindow) valid() bool {
+15 -10
View File
@@ -1,5 +1,4 @@
ObjC.import('AppKit')
ObjC.import('CoreFoundation')
ObjC.import('CoreGraphics')
ObjC.import('Foundation')
@@ -7,25 +6,31 @@ 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 isDockBackdrop(window, bounds, display) {
// The Dock reports a display-sized layer even while only its bar is visible.
if (window.kCGWindowLayer !== Number($.CGWindowLevelForKey($.kCGDockWindowLevelKey)) ||
bounds.X !== display.origin.x || bounds.Y !== display.origin.y ||
bounds.Width !== display.size.width || bounds.Height !== display.size.height) return false
const owner = $.NSRunningApplication.runningApplicationWithProcessIdentifier(window.kCGWindowOwnerPID)
const bundle = owner && !owner.isNil() ? owner.bundleIdentifier : null
return !!bundle && !bundle.isNil() && bundle.js === 'com.apple.dock'
}
function activeWindow() {
// QMP captures the main display. The experimental mode requires a single display.
if ($.NSScreen.screens.count !== 1) return null
if (Number($.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
if (!app || app.isNil() || Number(app.activationPolicy) !== Number($.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)
}
// The JXA bridge manages this reference. Releasing it manually crashes osascript.
const windows = ObjC.deepUnwrap(ObjC.castRefToObject(raw))
if (!Array.isArray(windows)) return null
const appPID = app.processIdentifier
const foreignAbove = []
@@ -33,7 +38,7 @@ function activeWindow() {
const bounds = window && window.kCGWindowBounds
if (!bounds || !(window.kCGWindowAlpha > 0.01)) continue
if (window.kCGWindowOwnerPID !== appPID) {
foreignAbove.push(bounds)
if (!isDockBackdrop(window, bounds, display)) foreignAbove.push(bounds)
continue
}
if (window.kCGWindowLayer !== 0 || !(bounds.Width >= 32 && bounds.Height >= 32)) continue
@@ -0,0 +1,17 @@
package guesttools
import (
"os/exec"
"testing"
)
func TestActiveWindowReporterBridge(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("Node.js is unavailable")
}
cmd := exec.Command(node, "testdata/active_window_reporter.cjs", "active_window_reporter.js")
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("window reporter: %v\n%s", err, output)
}
}
+2 -1
View File
@@ -26,8 +26,9 @@ const PasteReadyAgentVersion = 18
const FileClipboardReadinessAgentVersion = 19
const SharedFolderWebDAVAgentVersion = 20
const DropNetworkVolumesAgentVersion = 21
const StableWindowReporterAgentVersion = 22
const CurrentAgentVersion = DropNetworkVolumesAgentVersion
const CurrentAgentVersion = StableWindowReporterAgentVersion
type SharedFolderConfig struct {
ID string `json:"id"`
+66
View File
@@ -0,0 +1,66 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const vm = require('node:vm')
const source = fs.readFileSync(process.argv[2], 'utf8')
const display = { origin: { x: 0, y: 0 }, size: { width: 2336, height: 1320 } }
const desktop = { X: 0, Y: 0, Width: 2336, Height: 1320 }
const appWindow = {
kCGWindowOwnerPID: 42,
kCGWindowNumber: 7,
kCGWindowLayer: 0,
kCGWindowAlpha: 1,
kCGWindowBounds: { X: 129, Y: 220, Width: 877, Height: 499 },
}
const dockBackdrop = {
kCGWindowOwnerPID: 43,
kCGWindowLayer: 20,
kCGWindowAlpha: 1,
kCGWindowBounds: desktop,
}
function report({ screens = '1', above = [], bundleId = 'com.apple.dock' } = {}) {
const frontmostApplication = {
isNil: () => false,
activationPolicy: '0',
processIdentifier: 42,
localizedName: { isNil: () => false, js: 'Terminal' },
}
const native = {
NSScreen: { screens: { count: screens } },
NSWorkspace: { sharedWorkspace: { frontmostApplication } },
NSApplicationActivationPolicyRegular: 0,
NSRunningApplication: {
runningApplicationWithProcessIdentifier: () => ({
isNil: () => false,
bundleIdentifier: { isNil: () => false, js: bundleId },
}),
},
kCGDockWindowLevelKey: 7,
CGWindowLevelForKey: () => 20,
CGMainDisplayID: () => 1,
CGDisplayBounds: () => display,
CGWindowListCopyWindowInfo: () => [...above, appWindow],
CFRelease: () => assert.fail('release of a JXA-managed reference'),
}
const bridge = {
import() {},
castRefToObject: value => value,
deepUnwrap: value => value,
}
return JSON.parse(vm.runInNewContext(source + '\nJSON.stringify(activeWindow())', { $: native, ObjC: bridge }))
}
const expected = {
id: 7, app_name: 'Terminal', x: 129, y: 220, width: 877, height: 499,
display_width: 2336, display_height: 1320,
}
assert.deepEqual(report({ above: [dockBackdrop] }), expected, 'Tahoe Dock backdrop leaves the window visible')
assert.deepEqual(report({ screens: 1 }), expected, 'numeric screen counts remain supported')
assert.equal(report({ screens: '2' }), null, 'multiple displays remain unsupported')
assert.equal(report({ above: [dockBackdrop], bundleId: 'com.example.overlay' }), null,
'other owners cannot cover the target at the Dock level')
assert.equal(report({ above: [{ ...dockBackdrop, kCGWindowBounds: appWindow.kCGWindowBounds }] }), null,
'overlapping Dock windows with their own bounds still block capture')
assert.equal(report({ above: [{ ...dockBackdrop, kCGWindowLayer: 0 }] }), null,
'a full-size window at another level still blocks capture')