From 34e6678eb6b7b19c1328fdd4c8b9c93f6c3af58d Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Sun, 6 Dec 2026 17:45:25 +0800 Subject: [PATCH] Shut down ARM guests from the macOS login window --- internal/macos/stambhadriver/shutdown_menu.go | 272 ++++++++++++++++++ .../macos/stambhadriver/shutdown_menu_test.go | 52 ++++ internal/macos/stambhadriver/shutdown_ocr.ps1 | 40 +++ internal/macos/stambhadriver/stambha.go | 5 +- 4 files changed, 368 insertions(+), 1 deletion(-) create mode 100644 internal/macos/stambhadriver/shutdown_menu.go create mode 100644 internal/macos/stambhadriver/shutdown_menu_test.go create mode 100644 internal/macos/stambhadriver/shutdown_ocr.ps1 diff --git a/internal/macos/stambhadriver/shutdown_menu.go b/internal/macos/stambhadriver/shutdown_menu.go new file mode 100644 index 0000000..2374a4c --- /dev/null +++ b/internal/macos/stambhadriver/shutdown_menu.go @@ -0,0 +1,272 @@ +package stambhadriver + +import ( + "context" + _ "embed" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "image" + "image/color" + "image/png" + "math" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + "unicode/utf16" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/thumb" +) + +//go:embed shutdown_ocr.ps1 +var powerMenuOCR string + +// The login window handles its power menu even when it ignores the SMC +// power-button shortcut. Read the native menu before selecting an action. +func requestLoginWindowShutdown(ctx context.Context, conn *qmp.Conn) (bool, error) { + tmp, err := os.MkdirTemp("", "reims-arm-shutdown-") + if err != nil { + return false, err + } + defer os.RemoveAll(tmp) + pp, err := filepath.Abs(filepath.Join(tmp, "screen.ppm")) + if err != nil { + return false, err + } + readFrame := func() (image.Image, error) { + format, err := qmp.ScreendumpDisplay(conn, pp, "gfx", 0) + if err != nil { + return nil, err + } + return thumb.Load(pp, format) + } + + frame, err := readFrame() + if err != nil { + // Older runtimes and guests still in their boot console use the + // existing power-button path. + return false, nil + } + icon, scale, found := findLoginPowerIcon(frame) + if !found { + return false, nil + } + mice, err := qmp.QueryMice(conn) + if err != nil { + return true, err + } + if !qmp.HasCurrentAbsoluteMouse(mice) { + return true, errors.New("the macOS login window needs an absolute pointer to use its power menu") + } + bounds := frame.Bounds() + crop := image.Rect(bounds.Max.X-165*scale, 0, bounds.Max.X, 125*scale).Intersect(bounds) + + before := scalePowerMenu(frame, crop) + if err := clickGuestPowerMenu(ctx, conn, icon, bounds); err != nil { + return true, err + } + deadline := time.Now().Add(7 * time.Second) + for time.Now().Before(deadline) { + if err := waitShutdownInput(ctx, 400*time.Millisecond); err != nil { + return true, err + } + frame, err = readFrame() + if err != nil { + return true, err + } + after := scalePowerMenu(frame, crop) + if !menuAppeared(before, after) { + continue + } + menuPath := filepath.Join(tmp, "menu.png") + if err := saveShutdownMenu(menuPath, after); err != nil { + return true, err + } + entry, ok := readShutdownMenu(ctx, menuPath) + if !ok { + continue + } + point := crop.Min.Add(entry.Div(3)) + // The commands live in a small popover under the detected icon. + // Do not direct the click elsewhere even if OCR reports a match. + if point.Y <= icon.Y+20*scale || point.Y >= icon.Y+100*scale || + point.X < icon.X-95*scale || point.X > icon.X+28*scale { + break + } + return true, clickGuestPowerMenu(ctx, conn, point, bounds) + } + return true, errors.New("could not identify the macOS Shut Down option. Open the power menu in the virtual machine to shut down") +} + +func clickGuestPowerMenu(ctx context.Context, conn *qmp.Conn, p image.Point, bounds image.Rectangle) error { + if err := ctx.Err(); err != nil { + return err + } + p = p.Sub(bounds.Min) + if err := qmp.MouseButtonAt(conn, p.X, p.Y, bounds.Dx(), bounds.Dy(), "left", true); err != nil { + _ = qmp.MouseButton(conn, "left", false) + return err + } + err := waitShutdownInput(ctx, 120*time.Millisecond) + return errors.Join(err, qmp.MouseButton(conn, "left", false)) +} + +func waitShutdownInput(ctx context.Context, delay time.Duration) error { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} + +// Intensity mask for the power symbol: a vertical stroke above a broken ring. +// Compare contrast, so the same mask works on light and dark backgrounds. +var powerIconMask = [...]string{ + "......#......", + "......#......", + ".+#...#...#+.", + ".#....#....#.", + "++....#....++", + "#.....#.....#", + "#...........#", + "#...........#", + "++.........++", + ".#.........#.", + ".+#.......#+.", + "..+#+...+#+..", + "....+###+....", +} + +func findLoginPowerIcon(frame image.Image) (image.Point, int, bool) { + b := frame.Bounds() + best, point, scale := 0.89, image.Point{}, 0 + if b.Dx() < 640 || b.Dy() < 400 { + return point, scale, false + } + for step := 1; step <= 2; step++ { + for y := 4 * step; y <= 18*step; y++ { + for x := b.Max.X - 96*step; x < b.Max.X-19*step; x++ { + candidate := image.Pt(x, y) + score := powerIconScore(frame, candidate, step) + if score > best { + best, point, scale = score, candidate.Add(image.Pt(6*step, 6*step)), step + } + } + } + } + return point, scale, scale != 0 +} + +func powerIconScore(frame image.Image, top image.Point, step int) float64 { + var n, sum, sum2, ink, ink2, dot float64 + for y, row := range powerIconMask { + for x, token := range row { + var weight float64 + if token == '#' { + weight = 1 + } else if token == '+' { + weight = .5 + } + c := color.GrayModel.Convert(frame.At(top.X+x*step, top.Y+y*step)).(color.Gray) + val := float64(c.Y) + n++ + sum, sum2 = sum+val, sum2+val*val + ink, ink2 = ink+weight, ink2+weight*weight + dot += weight * val + } + } + variance := sum2 - sum*sum/n + if variance < 10000 { + return 0 + } + return math.Abs(dot-sum*ink/n) / math.Sqrt(variance*(ink2-ink*ink/n)) +} + +func scalePowerMenu(frame image.Image, crop image.Rectangle) *image.RGBA { + result := image.NewRGBA(image.Rect(0, 0, crop.Dx()*3, crop.Dy()*3)) + for y := range result.Bounds().Dy() { + for x := range result.Bounds().Dx() { + result.Set(x, y, frame.At(crop.Min.X+x/3, crop.Min.Y+y/3)) + } + } + return result +} + +func menuAppeared(before, after *image.RGBA) bool { + // Ignore the status bar highlight around the power button. An open menu + // changes a substantial region below it, including its background. + changed := 0 + for y := 90; y < after.Bounds().Dy(); y += 6 { + for x := 0; x < after.Bounds().Dx(); x += 6 { + a, b := before.RGBAAt(x, y), after.RGBAAt(x, y) + if absColorDelta(a.R, b.R)+absColorDelta(a.G, b.G)+absColorDelta(a.B, b.B) > 65 { + changed++ + } + } + } + return changed > 250 +} + +func absColorDelta(a, b uint8) int { + return max(int(a), int(b)) - min(int(a), int(b)) +} + +func saveShutdownMenu(path string, img image.Image) error { + file, err := os.Create(path) + if err != nil { + return err + } + return errors.Join(png.Encode(file, img), file.Close()) +} + +type shutdownMenuLine struct { + Text string + X, Y float64 + Width, Height float64 +} + +func readShutdownMenu(ctx context.Context, path string) (image.Point, bool) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + units := utf16.Encode([]rune(powerMenuOCR)) + script := make([]byte, len(units)*2) + for i, unit := range units { + binary.LittleEndian.PutUint16(script[i*2:], unit) + } + cmd := exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", base64.StdEncoding.EncodeToString(script)) + cmd.Env = append(os.Environ(), "REIMS_ARM_POWER_MENU_CAPTURE="+path) + host.HideConsole(cmd) + data, err := cmd.Output() + if err != nil { + return image.Point{}, false + } + var lines []shutdownMenuLine + if json.Unmarshal(data, &lines) != nil { + return image.Point{}, false + } + return shutdownMenuEntry(lines) +} + +func shutdownMenuEntry(lines []shutdownMenuLine) (image.Point, bool) { + normal := func(s string) string { return strings.ToLower(strings.Join(strings.Fields(s), "")) } + for i := 1; i+1 < len(lines); i++ { + a, b, c := lines[i-1], lines[i], lines[i+1] + switch [3]string{normal(a.Text), normal(b.Text), normal(c.Text)} { + case [3]string{"restart", "shutdown", "sleep"}, [3]string{"restart", "shutdown", "sieep"}, + [3]string{"重新启动", "关机", "睡眠"}, [3]string{"重新啟動", "關機", "睡眠"}: + if math.Abs(a.X-b.X) <= 30 && math.Abs(c.X-b.X) <= 30 && + b.Y-a.Y >= 35 && b.Y-a.Y <= 160 && c.Y-b.Y >= 35 && c.Y-b.Y <= 160 { + return image.Pt(int(b.X+b.Width/2), int(b.Y+b.Height/2)), true + } + } + } + return image.Point{}, false +} diff --git a/internal/macos/stambhadriver/shutdown_menu_test.go b/internal/macos/stambhadriver/shutdown_menu_test.go new file mode 100644 index 0000000..4c51829 --- /dev/null +++ b/internal/macos/stambhadriver/shutdown_menu_test.go @@ -0,0 +1,52 @@ +package stambhadriver + +import ( + "image" + "image/color" + "image/draw" + "testing" +) + +func TestFindLoginPowerIcon(t *testing.T) { + frame := image.NewRGBA(image.Rect(0, 0, 1920, 1080)) + draw.Draw(frame, frame.Bounds(), image.NewUniform(color.Gray{Y: 61}), image.Point{}, draw.Src) + if _, _, ok := findLoginPowerIcon(frame); ok { + t.Fatal("recognized a blank status bar as the power icon") + } + top := image.Pt(1874, 9) + for y, row := range powerIconMask { + for x, pixel := range row { + tone := uint8(61) + switch pixel { + case '#': + tone = 235 + case '+': + tone = 148 + } + frame.Set(top.X+x, top.Y+y, color.Gray{Y: tone}) + } + } + got, scale, ok := findLoginPowerIcon(frame) + if got != (image.Pt(1880, 15)) || scale != 1 || !ok { + t.Fatalf("power icon = %v at %dx, detected %v", got, scale, ok) + } +} + +func TestShutdownMenuEntryRequiresNativeMenuRows(t *testing.T) { + lines := []shutdownMenuLine{ + {Text: "Restart", X: 95, Y: 125, Width: 140, Height: 30}, + {Text: "Shut Down", X: 95, Y: 200, Width: 210, Height: 30}, + {Text: "SIeep", X: 95, Y: 275, Width: 100, Height: 30}, + } + p, ok := shutdownMenuEntry(lines) + if !ok || p != (image.Pt(200, 215)) { + t.Fatalf("entry = %v, detected %v", p, ok) + } + if _, ok := shutdownMenuEntry(lines[1:]); ok { + t.Fatal("selected an unconfirmed Shut Down label") + } + lines[2].Y += 200 + if _, ok := shutdownMenuEntry(lines); ok { + t.Fatal("selected a label from an unrelated layout") + } +} diff --git a/internal/macos/stambhadriver/shutdown_ocr.ps1 b/internal/macos/stambhadriver/shutdown_ocr.ps1 new file mode 100644 index 0000000..2a6ec1e --- /dev/null +++ b/internal/macos/stambhadriver/shutdown_ocr.ps1 @@ -0,0 +1,40 @@ +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) +Add-Type -AssemblyName System.Runtime.WindowsRuntime +$null = [Windows.Storage.StorageFile,Windows.Storage,ContentType=WindowsRuntime] +$null = [Windows.Storage.Streams.IRandomAccessStream,Windows.Storage.Streams,ContentType=WindowsRuntime] +$null = [Windows.Graphics.Imaging.BitmapDecoder,Windows.Graphics.Imaging,ContentType=WindowsRuntime] +$null = [Windows.Graphics.Imaging.SoftwareBitmap,Windows.Graphics.Imaging,ContentType=WindowsRuntime] +$null = [Windows.Media.Ocr.OcrEngine,Windows.Foundation,ContentType=WindowsRuntime] +$null = [Windows.Media.Ocr.OcrResult,Windows.Foundation,ContentType=WindowsRuntime] +$asTask = [System.WindowsRuntimeSystemExtensions].GetMethods().Where({ + $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and + $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' +})[0] +function Await($operation, [type]$type) { + $task = $asTask.MakeGenericMethod($type).Invoke($null, @($operation)) + $task.Wait(-1) | Out-Null + $task.Result +} +$path = $env:REIMS_ARM_POWER_MENU_CAPTURE +$file = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($path)) ([Windows.Storage.StorageFile]) +$stream = Await ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream]) +$decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder]) +$bitmap = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap]) +$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages() +if (!$engine) { throw 'No Windows OCR language available' } +$result = Await ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult]) +$lines = @(foreach ($line in $result.Lines) { + $rects = @(foreach ($word in $line.Words) { $word.BoundingRect }) + if (!$rects.Count) { continue } + $first = $rects[0] + $last = $rects[$rects.Count - 1] + [pscustomobject]@{ + Text = $line.Text + X = [double]$first.X + Y = [double]$first.Y + Width = [double]($last.X + $last.Width - $first.X) + Height = [double]$first.Height + } +}) +ConvertTo-Json -InputObject $lines -Compress diff --git a/internal/macos/stambhadriver/stambha.go b/internal/macos/stambhadriver/stambha.go index b41c166..c7a812d 100644 --- a/internal/macos/stambhadriver/stambha.go +++ b/internal/macos/stambhadriver/stambha.go @@ -822,7 +822,10 @@ func (d *StambhaDriver) Stop(ctx context.Context, name string, force bool, _, _ if err != nil { return err } - err = requestStambhaShutdown(ctx, conn) + menuHandled, err := requestLoginWindowShutdown(ctx, conn) + if err == nil && !menuHandled { + err = requestStambhaShutdown(ctx, conn) + } _ = conn.Close() // Stela interprets two power-button pulses within three seconds as a // held hardware button. Keep the VM lock across that interval even