Compare commits

...
Author SHA1 Message Date
YXC0915 34e6678eb6 Shut down ARM guests from the macOS login window 2026-12-06 17:46:34 +08:00
YXC0915 c181cc3c50 Keep the full macOS shutdown chord active during the SMC pulse
Windows CI / verify (push) Successful in 5m56s
2026-12-06 11:55:53 +08:00
YXC0915 ee45f40888 Request orderly shutdown from ARM macOS guests 2026-12-06 11:46:12 +08:00
yxc0915 7d02b77d7a Merge pull request '同步 GitHub 上游目录重整 #203' (#2) from sync/github-main-aac39793 into main
Windows CI / verify (push) Successful in 5m53s
2026-12-05 16:47:06 +00:00
YXC0915 74242c323a Keep ARM image downloads behind the installer boundary 2026-12-06 00:39:23 +08:00
YXC0915 7f07999a3b Merge GitHub upstream main into Gitea 2026-12-06 00:36:02 +08:00
yxc0915 2caf459647 Merge pull request '支持下载 ARM 恢复镜像并创建 ARM64 虚拟机' (#1) from release/arm64-preview.2 into main
Windows CI / verify (push) Failing after 5m1s
2026-12-05 16:32:25 +00:00
千川白浪 aac3979373 refactor: 收敛根目录布局并统一资源与脚本归属 (#203)
* refactor: 收敛根目录布局并统一资源与脚本归属

* fix: 停止监视器时等待显示定位协程退出
2026-12-05 06:34:01 -07:00
43 changed files with 527 additions and 53 deletions

No files matched your search

+1 -1
View File
@@ -21,4 +21,4 @@
- [ ] 改动归属清晰,跨仓实现已按职责拆分并附上游源码或提交依据
- [ ] 涉及默认值、配置迁移或插件行为时,已附上[已有用户升级兼容性](https://github.com/Nwflower/Reims-Go/blob/main/docs/pr-review-guidelines.md#已有用户升级兼容性)验证记录
- [ ] `node scripts/debug/check.mjs`、`node scripts/changelog.mjs check` 与 `node scripts/test.mjs ci` 通过
- [ ] 面向用户或集成方的变化已写入 `changes/<slug>.json`(纯内部重构无需添加)
- [ ] 面向用户或集成方的变化已写入 `.github/changes/<slug>.json`(纯内部重构无需添加)
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "修复 ARM macOS 虚拟机从客户端停止时无法触发正常关机的问题。",
"en": "Fix Stop for ARM macOS VMs so the guest can shut down normally."
}
+1 -1
View File
@@ -48,7 +48,7 @@ Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgp
## 版本变更与开源合规
面向用户或集成方的变化随改动写入 `changes/<slug>.json`,准备正式版时编入 [`CHANGELOG.md`](CHANGELOG.md),格式与命令见 [`docs/changelog.md`](docs/changelog.md)。
面向用户或集成方的变化随改动写入 `.github/changes/<slug>.json`,准备正式版时编入 [`CHANGELOG.md`](CHANGELOG.md),格式与命令见 [`docs/changelog.md`](docs/changelog.md)。
Reims-Go 自身代码采用 [Apache-2.0](LICENSE) 协议。便携运行时以独立子进程和独立压缩包形式集成,公开运行时发布必须同处附带对应源码包、本地补丁与完整许可证文本(见 [`NOTICE.md`](NOTICE.md))。应用不打包也不托管任何 Apple 系统文件。
File renamed without changes.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

-6
View File
@@ -1,6 +0,0 @@
//go:build !windows
package main
// attachConsole is only needed for Windows GUI-subsystem builds.
func attachConsole() {}
+2 -2
View File
@@ -1,10 +1,10 @@
# 更新日志编写与发布
[`CHANGELOG.md`](../CHANGELOG.md) 保存已编入版本的客户端变更,也是 GitHub Release 说明的正文来源。待发布的条目随改动提交到仓库根目录的 `changes/`。便携运行时 `runtime-*` 在对应的运行时 Release 中记录。客户端条目只在需要时写明它依赖的运行时版本。
[`CHANGELOG.md`](../CHANGELOG.md) 保存已编入版本的客户端变更,也是 GitHub Release 说明的正文来源。待发布的条目随改动提交到 `.github/changes/`。便携运行时 `runtime-*` 在对应的运行时 Release 中记录。客户端条目只在需要时写明它依赖的运行时版本。
## 写入待发布条目
每项值得告知用户或集成方的变化写一个 `changes/<slug>.json`,文件名用小写英文和连字符。将同一行为涉及的多个提交合为一条。内部重构、纯格式调整和日常依赖更新留在提交记录中。
每项值得告知用户或集成方的变化写一个 `.github/changes/<slug>.json`,文件名用小写英文和连字符。将同一行为涉及的多个提交合为一条。内部重构、纯格式调整和日常依赖更新留在提交记录中。
```json
{
+1 -1
View File
@@ -9,7 +9,7 @@
| 改动持久化或升级 | `node scripts/test.mjs quick storage` | 配置和数据目录、迁移及插件状态存储,使用真实临时文件 |
| 改动调试工具 | `node scripts/test.mjs quick tooling` | 临时目录和工单工具自测 |
| 改动 GitHub 自动化脚本 | `node scripts/test.mjs quick automation` | `scripts/ci/` 下 PR 审核、Issue 分诊、代码诊断和申报校验脚本的自测 |
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`cmd/`、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测、GitHub 自动化脚本自测 |
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测、GitHub 自动化脚本自测 |
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
+3 -3
View File
@@ -1,5 +1,5 @@
// scripts/brand/wordmark.py is the single source of the icon and the wordmark
// geometry: it copies assets/logo.svg into public/ and generates
// geometry: it copies build/assets/logo.svg into public/ and generates
// wordmark.gen.ts. Neither copy may be edited by hand.
import test from 'node:test'
import assert from 'node:assert/strict'
@@ -8,8 +8,8 @@ import path from 'node:path'
const repoRoot = path.resolve(import.meta.dirname, '..', '..')
test('frontend/public/logo.svg is the copy of assets/logo.svg', () => {
const source = fs.readFileSync(path.join(repoRoot, 'assets', 'logo.svg'))
test('frontend/public/logo.svg is the copy of build/assets/logo.svg', () => {
const source = fs.readFileSync(path.join(repoRoot, 'build', 'assets', 'logo.svg'))
const served = fs.readFileSync(path.join(repoRoot, 'frontend', 'public', 'logo.svg'))
assert.ok(source.equals(served), 'run python scripts/brand/wordmark.py to refresh frontend/public/logo.svg')
})
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
export const coreZh: Record<string, string> = {
"affinityMenu": "处理器相关性…",
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
import { registerBuiltinDomain } from '../runtime'
export const pluginsZh: Record<string, string> = {
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
import { registerBuiltinDomain } from '../runtime'
export const settingsZh: Record<string, string> = {
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
export const vmZh: Record<string, string> = {
"attachGuestTools": "挂载 Guest Tools",
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
import { registerBuiltinDomain } from '../runtime'
export const wizardZh: Record<string, string> = {
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
export type I18nKey =
| "aboutCommunity"
+3 -7
View File
@@ -10,7 +10,6 @@ import (
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/netproxy"
)
@@ -37,7 +36,7 @@ func (a *App) DownloadARMImage() (string, error) {
var cancel context.CancelFunc
run, id, owned := installerDownloads.reserveOrFind("arm-ipsw", armImageBuild, "installer-download", func(initialPhase string) string {
ctx, cancel = context.WithCancel(a.baseCtx())
return tasks.startWithInstaller("installer-download", "macOS 27.2.1 · ARM64", "", "arm-ipsw", armImageBuild, initialPhase, cancel)
return tasks.startWithInstaller("installer-download", "macOS 27.2.1 路 ARM64", "", "arm-ipsw", armImageBuild, initialPhase, cancel)
})
if !owned {
return id, nil
@@ -67,13 +66,10 @@ func (a *App) DownloadARMImage() (string, error) {
if err != nil && ctx.Err() != nil {
err = ctx.Err()
}
var result *installer.Result
if err == nil {
result = &installer.Result{Image: path}
} else {
if err != nil {
path = ""
}
installerDownloads.complete(run, result, err)
installerDownloads.completeImage(run, path, err)
tasks.finish(id, path, err)
}()
return id, nil
+8
View File
@@ -148,6 +148,14 @@ func (c *installerCoordinator) complete(run *installerDownloadRun, res *installe
close(run.done)
}
func (c *installerCoordinator) completeImage(run *installerDownloadRun, path string, err error) {
if err != nil {
c.complete(run, nil, err)
return
}
c.complete(run, &installer.Result{Image: path}, nil)
}
func (c *installerCoordinator) hasActive(kind, version string) bool {
c.mu.Lock()
defer c.mu.Unlock()
+8 -1
View File
@@ -101,6 +101,11 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
ctx, cancel := context.WithCancel(a.baseCtx())
done := make(chan struct{})
var prevDone chan struct{}
var displayWG sync.WaitGroup
needsDisplayPosition := vmstart.ReadVMDisplay(detail.Directory).TargetDisplay != ""
if needsDisplayPosition {
displayWG.Add(1)
}
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
@@ -114,8 +119,9 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
waitVMMonitorDone(prevDone)
}
if vmstart.ReadVMDisplay(detail.Directory).TargetDisplay != "" {
if needsDisplayPosition {
go func() {
defer displayWG.Done()
positionCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
ticker := time.NewTicker(250 * time.Millisecond)
@@ -129,6 +135,7 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
go func() {
defer func() {
cancel()
displayWG.Wait()
vmMonitors.mu.Lock()
close(done)
if cur, ok := vmMonitors.entries[name]; ok && cur.id == myID {
+1 -1
View File
@@ -28,7 +28,7 @@ func TestProductCodeHasNoUncalledFunctions(t *testing.T) {
self := ""
if fn != nil {
self = s.dir() + "." + fn.Name.Name
checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "cmd/")
checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "scripts/i18ngen/")
entry := fn.Name.Name == "main" || fn.Name.Name == "init" || fn.Name.Name == "_"
if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) {
decls[self] = decl{s, fn}
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
package cli
// AttachConsole is only needed for Windows GUI-subsystem builds.
func AttachConsole() {}
@@ -1,6 +1,6 @@
//go:build windows
package main
package cli
import (
"os"
@@ -14,12 +14,12 @@ var (
const attachParentProcess = ^uintptr(0) // ATTACH_PARENT_PROCESS, (DWORD)-1
// attachConsole gives command-line mode somewhere to write. reims-go.exe is
// AttachConsole gives command-line mode somewhere to write. reims-go.exe is
// a GUI-subsystem program, so Windows starts it without a console. Handles
// the caller passed in (a pipe, a file: how agents and scripts run it) are
// kept; only missing ones are pointed at the console of the terminal that
// launched it.
func attachConsole() {
func AttachConsole() {
out, errOut, in := usable(os.Stdout), usable(os.Stderr), usable(os.Stdin)
if out && errOut && in {
return
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by cmd/i18ngen; DO NOT EDIT.
// Code generated by scripts/i18ngen; DO NOT EDIT.
package i18n
@@ -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
}
@@ -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")
}
}
@@ -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
+46 -4
View File
@@ -822,20 +822,62 @@ func (d *StambhaDriver) Stop(ctx context.Context, name string, force bool, _, _
if err != nil {
return err
}
defer conn.Close()
if err := conn.Execute("system_powerdown", nil); err != nil {
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
// if the caller cancels or QMP cannot confirm delivery.
retryAfter := time.Now().Add(4 * time.Second)
defer func() { time.Sleep(time.Until(retryAfter)) }()
if err != nil {
if live, checkErr := stambhaLiveProcess(dir); checkErr == nil && live.PID == 0 {
return nil
}
return err
}
wait, cancel := context.WithTimeout(ctx, 30*time.Second)
wait, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
err = host.WaitProcessExit(wait, uint32(proc.PID), "qemu-system-x86_64.exe")
if errors.Is(err, context.DeadlineExceeded) {
return fmt.Errorf("macOS is still running. Shut down from the Apple menu or explicitly force stop the VM (%w)", err)
return fmt.Errorf("macOS did not finish shutting down. Check the VM for apps that need attention or shut down from the Apple menu (%w)", err)
}
return err
})
}
func requestStambhaShutdown(ctx context.Context, conn qmp.Executor) (err error) {
if err := ctx.Err(); err != nil {
return err
}
// Stela translates system_powerdown into an SMC power-button pulse.
// Send the three modifiers in the same input report before the pulse.
// macOS can then perform an orderly shutdown and prompt to save work.
keys := []string{"ctrl", "alt", "meta_l"}
defer func() { err = errors.Join(err, qmp.ReleaseInputs(conn, keys, nil)) }()
if err := qmp.PressKeys(conn, keys...); err != nil {
return err
}
timer := time.NewTimer(650 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
}
if err := ctx.Err(); err != nil {
return err
}
if err := conn.Execute("system_powerdown", nil); err != nil {
return err
}
// Keep the modifiers down while Stela and the guest handle the pulse.
time.Sleep(1500 * time.Millisecond)
return nil
}
func (d *StambhaDriver) Delete(_ context.Context, name string, keepFiles bool, _, _ io.Writer) error {
return d.withVM(name, func(dir string, proc stambhaProcess) error {
if proc.PID != 0 {
@@ -495,3 +495,45 @@ func assertEnvVal(t *testing.T, env []string, key, want string) {
t.Fatalf("env %s = %q, want %q (env=%v)", key, got, want, env)
}
}
type shutdownRecorder struct {
commands []string
onHold func()
}
func (r *shutdownRecorder) Execute(command string, args any) error {
data, err := json.Marshal(args)
if err != nil {
return err
}
r.commands = append(r.commands, command+" "+string(data))
if command == "input-send-event" && len(r.commands) == 1 && r.onHold != nil {
r.onHold()
}
return nil
}
func TestRequestStambhaShutdown(t *testing.T) {
const hold = "input-send-event " + `{"events":[{"data":{"down":true,"key":{"data":"ctrl","type":"qcode"}},"type":"key"},{"data":{"down":true,"key":{"data":"alt","type":"qcode"}},"type":"key"},{"data":{"down":true,"key":{"data":"meta_l","type":"qcode"}},"type":"key"}]}`
release := strings.ReplaceAll(hold, `"down":true`, `"down":false`)
t.Run("holds all modifiers before one power pulse", func(t *testing.T) {
qmp := &shutdownRecorder{}
if err := requestStambhaShutdown(context.Background(), qmp); err != nil {
t.Fatal(err)
}
if want := []string{hold, "system_powerdown null", release}; !slices.Equal(qmp.commands, want) {
t.Fatalf("QMP commands = %v, want %v", qmp.commands, want)
}
})
t.Run("cancellation prevents the power pulse", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
qmp := &shutdownRecorder{onHold: cancel}
if err := requestStambhaShutdown(ctx, qmp); !errors.Is(err, context.Canceled) {
t.Fatalf("shutdown error = %v, want context cancellation", err)
}
if !slices.Equal(qmp.commands, []string{hold, release}) {
t.Fatalf("unexpected QMP commands after cancellation: %v", qmp.commands)
}
})
}
+8
View File
@@ -120,6 +120,14 @@ func SendKey(q Executor, key string, down bool) error {
return sendKeys(q, down, key)
}
// PressKeys sends one input report containing all the key-down events.
func PressKeys(q Executor, keys ...string) error {
if q == nil {
return errors.New("QMP session is unavailable")
}
return sendKeys(q, true, keys...)
}
// ReleaseInputs clears held keys and pointer buttons in one QMP input report.
func ReleaseInputs(q Executor, keys, buttons []string) error {
if q == nil {
+1 -1
View File
@@ -337,7 +337,7 @@ func maxf(a, b float64) float64 {
return b
}
// resizePNGIcon scales an embedded PNG (e.g. assets/logo.png) to size×size PNG
// resizePNGIcon scales an embedded PNG (e.g. build/assets/logo.png) to size×size PNG
// bytes suitable for Windows CreateIconFromResourceEx.
func resizePNGIcon(srcPNG []byte, size int) ([]byte, error) {
if len(srcPNG) == 0 || size <= 0 {
+2 -2
View File
@@ -23,7 +23,7 @@ import (
//go:embed all:frontend/dist
var assets embed.FS
//go:embed assets/logo.png
//go:embed build/assets/logo.png
var trayIconPNG []byte
//go:embed LICENSE
@@ -45,7 +45,7 @@ func main() {
return
}
if cli.IsCommand(args) {
attachConsole()
cli.AttachConsole()
os.Exit(cli.Main(args))
}
launch, _ := cli.ParseWindowArgs(args)
+5 -5
View File
@@ -10,11 +10,11 @@ It writes .github/readme/banner-{light,dark}.svg,
frontend/src/components/wordmark.gen.ts and frontend/public/logo.svg, and
needs only the standard library.
assets/logo.svg is the source of the icon: this script copies it to
build/assets/logo.svg is the source of the icon: this script copies it to
frontend/public/logo.svg and embeds it in the banners. The raster icons
assets/logo.png (embedded by main.go for the tray), build/appicon.png and
build/assets/logo.png (embedded by main.go for the tray), build/appicon.png and
build/windows/icon.ico are exported from the same artwork by hand, so
re-export them whenever assets/logo.svg changes.
re-export them whenever build/assets/logo.svg changes.
"""
import math
@@ -163,7 +163,7 @@ def wordmark(theme, style=STYLE, gid="wm"):
def banner(theme, style=STYLE):
logo = (ROOT / "assets/logo.svg").read_text(encoding="utf-8")
logo = (ROOT / "build/assets/logo.svg").read_text(encoding="utf-8")
icon_body = re.sub(r"^.*?<svg[^>]*>", "", logo, flags=re.S).rsplit("</svg>", 1)[0]
wm = wordmark(theme, style)
icon, gap = 180, 26
@@ -235,7 +235,7 @@ def main():
(ROOT / f".github/readme/banner-{theme}.svg").write_text(banner(theme), encoding="utf-8")
(ROOT / "frontend/src/components/wordmark.gen.ts").write_text(ts_module(), encoding="utf-8")
# The frontend serves the icon from public/, so keep that copy byte-identical.
(ROOT / "frontend/public/logo.svg").write_bytes((ROOT / "assets/logo.svg").read_bytes())
(ROOT / "frontend/public/logo.svg").write_bytes((ROOT / "build/assets/logo.svg").read_bytes())
if __name__ == "__main__":
+3 -3
View File
@@ -6,7 +6,7 @@ import { cachePath, REPO_ROOT, resolveStorageRoot } from './debug/paths.mjs'
import { createTemporaryFiles } from './debug/temporary-files.mjs'
const changelog = path.join(REPO_ROOT, 'CHANGELOG.md')
const changes = path.join(REPO_ROOT, 'changes')
const changes = path.join(REPO_ROOT, '.github', 'changes')
const versionPart = '(?:0|[1-9]\\d*)'
const tagPattern = `v${versionPart}\\.${versionPart}\\.${versionPart}`
const versionHeading = new RegExp(`^## (${tagPattern}) — (\\d{4}-\\d{2}-\\d{2})$`, 'm')
@@ -60,7 +60,7 @@ function readChanges() {
throw error
}
const fragments = files.map((file) => {
const label = `changes/${file.name}`
const label = `.github/changes/${file.name}`
if (!file.isFile() || !/^[a-z0-9]+(?:-[a-z0-9]+)*\.json$/.test(file.name)) {
throw new Error(`${label} must be a regular <slug>.json file`)
}
@@ -194,7 +194,7 @@ function prepare(tag, date, storage) {
}
for (const { name, raw } of fragments) {
const file = path.join(changes, name)
if (fs.readFileSync(file, 'utf8') !== raw) throw new Error(`changes/${name} was edited during preparation`)
if (fs.readFileSync(file, 'utf8') !== raw) throw new Error(`.github/changes/${name} was edited during preparation`)
fs.unlinkSync(file)
}
console.log(`changelog: ${tag} prepared, cleared ${fragments.length} fragment(s)`)
+1 -1
View File
@@ -113,7 +113,7 @@ test("effective diff statistics exclude generated files and locks before determi
"999\t999\tgo.sum",
"999\t999\tfrontend/package-lock.json",
"999\t999\tfrontend/pnpm-lock.yaml",
"-\t-\tassets/logo.png",
"-\t-\tbuild/assets/logo.png",
].join("\0") + "\0");
assert.deepEqual(stats, { files: 2, lines: 15 });
assert.deepEqual(reviewProfile({ files: 5, lines: 300 }), { tier: "small", effort: "low", concurrency: 4, maxTokensBudget: 400_000 });
@@ -213,7 +213,7 @@ func writeGoCatalog(root string, zhByDom, enByDom map[string]map[string]parsedEn
keys := sortedKeys(zhMerged)
var b bytes.Buffer
b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\npackage i18n\n\n")
b.WriteString("// Code generated by scripts/i18ngen; DO NOT EDIT.\n\npackage i18n\n\n")
b.WriteString("var catalog = map[Locale]map[string]string{\n")
b.WriteString("\tZhCN: {\n")
for _, k := range keys {
@@ -281,7 +281,7 @@ func writeFrontendCatalogs(root string, zhByDom, enByDom map[string]map[string]p
}
var b bytes.Buffer
b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n")
b.WriteString("// Code generated by scripts/i18ngen; DO NOT EDIT.\n")
if isLazy {
b.WriteString("import { registerBuiltinDomain } from '../runtime'\n\n")
} else {
@@ -308,7 +308,7 @@ func writeFrontendCatalogs(root string, zhByDom, enByDom map[string]map[string]p
sort.Strings(allFEKeys)
var kb bytes.Buffer
kb.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\n")
kb.WriteString("// Code generated by scripts/i18ngen; DO NOT EDIT.\n\n")
kb.WriteString("export type I18nKey =\n")
for i, k := range allFEKeys {
sep := ""
+1 -1
View File
@@ -7,7 +7,7 @@ import { cachePath, REPO_ROOT, resolveStorageRoot } from './debug/paths.mjs'
import { createTemporaryFiles } from './debug/temporary-files.mjs'
const frontend = path.join(REPO_ROOT, 'frontend')
const goTrees = ['./cmd/...', './internal/...', './pkg/...', './scripts/...']
const goTrees = ['./internal/...', './pkg/...', './scripts/...']
const ciTests = fs.readdirSync(path.join(REPO_ROOT, 'scripts', 'ci'))
.filter((name) => name.endsWith('.test.mjs'))
.sort()