diff --git a/.github/changes/stambha-arm64-graceful-stop.json b/.github/changes/stambha-arm64-graceful-stop.json index 1bb88dc..d5343d0 100644 --- a/.github/changes/stambha-arm64-graceful-stop.json +++ b/.github/changes/stambha-arm64-graceful-stop.json @@ -2,6 +2,6 @@ "group": "fixes", "order": 0, "authors": ["yxc0915"], - "zh": "修复 ARM macOS 虚拟机从客户端停止时无法触发正常关机的问题。", - "en": "Fix Stop for ARM macOS VMs so the guest can shut down normally." + "zh": "修复 ARM macOS 虚拟机在桌面或登录窗口从客户端请求正常关机时可能超时的问题。", + "en": "Fix graceful shutdown of ARM macOS VMs from the desktop or login window." } diff --git a/docs/arm64-preview.md b/docs/arm64-preview.md index 8e07c53..2e5fcd3 100644 --- a/docs/arm64-preview.md +++ b/docs/arm64-preview.md @@ -27,4 +27,4 @@ macOS 27.2.1 的实验配置使用 8 个 vCPU 和 16 GiB 内存。首次登录 如果配置使用原始安装介质,可以用 `--usb-image` 指定文件。原始介质须预先包含与托管 Reims vGPU 相容的 Stambha EFI。首次从 IPSW 制作 ARM 安装介质仍是独立流程。 -日常关机请在 macOS 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。 +客户端的「关机」会请求 macOS 正常退出。在桌面上,macOS 可以提示保存工作。在登录窗口,客户端通过 Windows OCR 识别电源菜单中的「关机」,目前支持英语、简体中文和繁体中文菜单。若提示无法识别,请在虚拟机中手动选择「关机」。只在来宾无响应时使用强制停止。 diff --git a/internal/macos/stambhadriver/shutdown_menu.go b/internal/macos/stambhadriver/shutdown_menu.go new file mode 100644 index 0000000..cb52e17 --- /dev/null +++ b/internal/macos/stambhadriver/shutdown_menu.go @@ -0,0 +1,311 @@ +package stambhadriver + +import ( + "context" + "errors" + "image" + "image/color" + "math" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" + "github.com/Nwflower/reims-go/internal/macos/autoinstall/vision" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/thumb" +) + +// 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 + } + engine, err := ocr.NewWinOCREngine("") + if err != nil { + return false, nil + } + defer engine.Close() + bounds := frame.Bounds() + // A power-shaped status item alone can also belong to an ordinary desktop app. + clockRegion := image.Rect(bounds.Dx()/4, bounds.Dy()/18, bounds.Dx()*3/4, bounds.Dy()/3).Add(bounds.Min) + clock := thumb.Scale(vision.Crop(frame, clockRegion), 512) + probe, cancel := context.WithTimeout(ctx, 2*time.Second) + reading, err := engine.Recognize(probe, clock) + cancel() + if ctx.Err() != nil { + return false, ctx.Err() + } + if err != nil || !hasLoginClock(reading.Lines, clock.Bounds()) { + 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") + } + iconArea := image.Rect(icon.X-7*scale, icon.Y-7*scale, icon.X+8*scale, icon.Y+8*scale) + crop := image.Rect(bounds.Max.X-165*scale, bounds.Min.Y, bounds.Max.X, bounds.Min.Y+125*scale).Intersect(bounds) + before := scalePowerMenu(frame, crop) + menuCtx, cancel := context.WithTimeout(ctx, 7*time.Second) + defer cancel() + opened := false + for menuCtx.Err() == nil { + menu := scalePowerMenu(frame, crop) + // The user may already have opened the power menu. In that case + // select the verified entry without toggling the menu closed first. + if !opened || menuAppeared(before, menu) { + result, ocrErr := engine.Recognize(menuCtx, menu) + if ocrErr != nil { + break + } + if entry, ok := shutdownMenuEntry(result.Lines); ok { + point := crop.Min.Add(entry.Div(3)) + 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 + } + // The guest can unlock, resize or dismiss its menu while OCR runs. + current, err := readFrame() + if err != nil { + return true, err + } + menuArea := image.Rect(crop.Min.X, icon.Y+10*scale, crop.Max.X, crop.Max.Y) + target := image.Rect(point.X-20*scale, point.Y-6*scale, point.X+20*scale, point.Y+6*scale) + if !samePowerMenuArea(frame, current, menuArea) || !samePowerMenuArea(frame, current, target) || + !samePowerMenuArea(frame, current, clockRegion) { + break + } + return true, clickGuestPowerMenu(menuCtx, conn, point, bounds) + } + } + if !opened { + current, err := readFrame() + if err != nil { + return false, err + } + if !samePowerMenuArea(frame, current, iconArea) || !samePowerMenuArea(frame, current, clockRegion) || + !samePowerMenuArea(frame, current, crop) { + break + } + if err := clickGuestPowerMenu(menuCtx, conn, icon, bounds); err != nil { + return true, err + } + opened = true + } + if waitShutdownInput(menuCtx, 400*time.Millisecond) != nil { + break + } + frame, err = readFrame() + if err != nil { + return true, err + } + if frame.Bounds() != bounds { + break + } + } + if err := ctx.Err(); err != nil { + return true, err + } + 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)) +} + +var loginClock = regexp.MustCompile("^(?:[01]?[0-9]|2[0-3])[::][0-5][0-9](?:AM|PM)?$") + +func hasLoginClock(lines []ocr.Line, bounds image.Rectangle) bool { + for _, line := range lines { + r := line.Rect + centerX := (r.Min.X + r.Max.X) / 2 + if r.Empty() || !r.In(bounds) || r.Dy() < bounds.Dy()/6 || + centerX < bounds.Min.X+bounds.Dx()*2/5 || centerX > bounds.Min.X+bounds.Dx()*3/5 { + continue + } + text := strings.ToUpper(strings.Join(strings.Fields(line.Text), "")) + if loginClock.MatchString(text) { + return true + } + } + return false +} + +// Allow minor antialiasing changes while the pointer moves, but require the +// scene or popover that authorized the click to still be present. +func samePowerMenuArea(a, b image.Image, area image.Rectangle) bool { + if a.Bounds() != b.Bounds() || area.Empty() || !area.In(a.Bounds()) { + return false + } + changed, samples := 0, 0 + for y := area.Min.Y; y < area.Max.Y; y += 2 { + for x := area.Min.X; x < area.Max.X; x += 2 { + ac := color.RGBAModel.Convert(a.At(x, y)).(color.RGBA) + bc := color.RGBAModel.Convert(b.At(x, y)).(color.RGBA) + if absColorDelta(ac.R, bc.R)+absColorDelta(ac.G, bc.G)+absColorDelta(ac.B, bc.B) > 45 { + changed++ + } + samples++ + } + } + return changed*100 <= samples +} + +func shutdownMenuEntry(lines []ocr.Line) (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 !a.Rect.Empty() && !b.Rect.Empty() && !c.Rect.Empty() && + math.Abs(float64(a.Rect.Min.X-b.Rect.Min.X)) <= 30 && math.Abs(float64(c.Rect.Min.X-b.Rect.Min.X)) <= 30 && + b.Rect.Min.Y-a.Rect.Min.Y >= 35 && b.Rect.Min.Y-a.Rect.Min.Y <= 160 && c.Rect.Min.Y-b.Rect.Min.Y >= 35 && c.Rect.Min.Y-b.Rect.Min.Y <= 160 { + return b.Rect.Min.Add(b.Rect.Max).Div(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..c36ed77 --- /dev/null +++ b/internal/macos/stambhadriver/shutdown_menu_test.go @@ -0,0 +1,85 @@ +package stambhadriver + +import ( + "image" + "image/color" + "image/draw" + "testing" + + "github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr" +) + +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 := []ocr.Line{ + {Text: "Restart", Rect: image.Rect(95, 125, 235, 155)}, + {Text: "Shut Down", Rect: image.Rect(95, 200, 305, 230)}, + {Text: "SIeep", Rect: image.Rect(95, 275, 195, 305)}, + } + 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].Rect = lines[2].Rect.Add(image.Pt(0, 200)) + if _, ok := shutdownMenuEntry(lines); ok { + t.Fatal("selected a label from an unrelated layout") + } +} + +func TestLoginClockRequiresLargeCenteredTime(t *testing.T) { + bounds := image.Rect(0, 0, 512, 168) + clock := image.Rect(166, 49, 340, 110) + for _, tc := range []struct { + text string + rect image.Rectangle + want bool + }{ + {"7:58", clock, true}, {"23:59", clock, true}, {"7:58 PM", clock, true}, + {"7:58", image.Rect(210, 70, 236, 80), false}, {"7:58", image.Rect(5, 49, 111, 110), false}, + {"Restart", clock, false}, {"24:15", clock, false}, + } { + if got := hasLoginClock([]ocr.Line{{Text: tc.text, Rect: tc.rect}}, bounds); got != tc.want { + t.Errorf("clock %q at %v = %v", tc.text, tc.rect, got) + } + } +} + +func TestPowerMenuClickRejectsChangedFrame(t *testing.T) { + a := image.NewRGBA(image.Rect(0, 0, 100, 50)) + b := image.NewRGBA(a.Bounds()) + target := image.Rect(10, 10, 60, 40) + if !samePowerMenuArea(a, b, target) { + t.Fatal("rejected unchanged menu") + } + draw.Draw(b, image.Rect(25, 15, 45, 35), image.White, image.Point{}, draw.Src) + if samePowerMenuArea(a, b, target) || samePowerMenuArea(a, image.NewRGBA(image.Rect(0, 0, 90, 50)), target) { + t.Fatal("accepted changed or resized menu") + } +} 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