feat: add experimental macOS desktop support on Apple Silicon (#207)

* feat: add experimental Apple Silicon support with Nivfold

Integrate the standalone Nivfold protocol 1 runner; tested against Nivfold f436fb6. The Windows Reims vGPU runtime remains independent.

* fix: open QQ invites and VM SSH on macOS

* fix: move VM, View and Help to the macOS menu bar

* feat(macos): add resumable Apple restore image downloads

Expose the compatible restore image in the VM wizard and Images page, validate downloads before caching, and fix macOS memory reporting and plugin SVG rendering.

* fix(macos): localize the native application menu

* fix(macos): address native desktop review findings
This commit is contained in:
千川白浪 authored and GitHub committed 2026-12-06 00:47:07 +08:00
1 parent aac3979373
commit e0ff794b0e
130 files changed
+6014 -540

No files matched your search

@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 的实验性源码构建新增原生 macOS 虚拟机后端,可用本地 `.ipsw` 创建虚拟机并在独立窗口启动和关机。",
"en": "The experimental Apple silicon source build can create macOS VMs from local `.ipsw` restores, start them with a separate viewer, and shut them down."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 的恢复镜像目录查询支持重试与 Apple 官方来源回退,原生红黄绿按钮与标题栏菜单纵向对齐。",
"en": "Retry Apple silicon restore catalog queries with an official Apple fallback, and vertically align the native window controls with the title bar menus."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复 macOS 上的开发构建,并防止关闭窗口时把应用隐藏到不存在的托盘。内置虚拟机运行时仍仅支持 Windows x64。",
"en": "Fix development builds on macOS and prevent the window from hiding to an unavailable tray. The built-in VM runtime still requires Windows x64."
}
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 可在镜像页或新建向导内从 Apple 下载兼容恢复镜像,支持暂停续传,并使用系统原生的红黄绿窗口按钮。",
"en": "Download a compatible Apple restore image with pause and resume in Images or New VM on Apple silicon, and use the native macOS window controls."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "Mac 客户端使用系统采样显示宿主机内存,不再误报内存满载,并修复无法显示的插件 SVG 图标。",
"en": "Show sampled host memory on macOS instead of reporting full memory use, and fix plugin SVG icons that failed to render."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "macOS 的应用、编辑和窗口菜单跟随当前界面语言,应用菜单统一显示 Reims-Go。",
"en": "Match the macOS application, Edit, and Window menus to the selected interface language and show Reims-Go as the application name."
}
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "macOS 的「虚拟机」「视图」和「帮助」移至屏幕顶部的系统菜单栏,Windows 保留窗口内菜单。",
"en": "Move VM, View, and Help to the macOS system menu bar and keep them in the app window on Windows."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "在 macOS 上使用本机 QQ 打开交流群邀请;不能直接打开时仍可打开邀请页。虚拟机的 SSH 入口也可在 Mac 的终端中打开。",
"en": "Open QQ group invites with the installed QQ app on macOS, with the invite page as a fallback. Open VM SSH sessions in the Mac terminal."
}
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "macOS 恢复镜像校验暂时失败后可继续重试,启动虚拟机时会等待读取状态,宿主机诊断会同时显示原生虚拟化和常规诊断信息。",
"en": "Retry temporary macOS restore image verification failures without redownloading, tolerate transient VM startup status errors, and show native virtualization alongside standard host diagnostics."
}
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "Apple 芯片 Mac 的实验版改用独立的 Nivfold 运行器,支持安全取消安装,并在保存时检查宿主和客体的 CPU 与内存要求。",
"en": "The experimental Apple silicon build uses the standalone Nivfold runner, supports cooperative installation cancellation, and checks host and guest CPU and memory requirements before saving settings."
}
+2
View File
@@ -10,6 +10,8 @@ Reims-Go 是面向 Windows x86-64 的免编译 macOS 虚拟机桌面启动器与
Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时维护仓库通过 `vendor/qemu` 固定团队 QEMU 仓库的提交,并负责编译、依赖补丁、打包和预览发布。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) · [运行时构建流程](https://github.com/reims-go/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml)
Apple 芯片 Mac 的实验性后端使用独立 `nivfold` 仓库中的原生运行器。虚拟设备、安装事务和运行器测试归 Nivfold;此仓库只维护客户端及兼容协议适配。
## 存储与调试目录纪律
1. 便携运行时、系统镜像、虚拟磁盘与快照只保存在用户本地指定的数据目录,不提交到仓库,也不放入 `.debug/`。
+20
View File
@@ -123,6 +123,26 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/reims-go/reims-vgpu).
On Apple silicon, the experimental client uses the standalone Nivfold runner instead of the Windows QEMU runtime. Run `sh build.sh` in a separate `nivfold` checkout first. Building the runner requires Xcode with Swift 6, and running it requires macOS 13 or later. The example assumes sibling checkouts; omit `--runtime` to build only the client.
```sh
node scripts/build-macos.mjs --runtime ../nivfold/.debug/runs/nivfold/nivfold
.debug/runs/macos-client/reims-go doctor
.debug/runs/macos-client/reims-go
```
In New VM, download the compatible macOS restore image offered by Apple for the current host, or choose an existing local `.ipsw`. The Images page can also download and manage cached images. Transfer only starts when you click Download, and downloaded images can be reused. Creation installs macOS onto a new virtual disk. When it finishes, start the VM and complete Setup Assistant manually in the separate guest window. CLI creation takes the absolute path to a local restore image:
```sh
client=.debug/runs/macos-client/reims-go
"$client" vm create --ipsw /absolute/path/to/Restore.ipsw mac-test
"$client" vm list
"$client" vm start mac-test
"$client" vm stop mac-test
```
The native backend cannot open Windows x86-64 VMs or their snapshots. This experimental build does not support snapshots, suspend, restore points, shared folders, or Reims vGPU.
</details>
## FAQ
+20
View File
@@ -119,6 +119,26 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 单独构建。
Apple 芯片 Mac 的实验版使用独立的 Nivfold 运行器,不安装 Windows 的 QEMU 运行时。先在单独检出的 `nivfold` 仓库运行 `sh build.sh`。运行器构建需要带 Swift 6 的 Xcode,运行需要 macOS 13 或更高版本。下例假设两个仓库位于同一个父目录;只构建客户端时可省略 `--runtime`。
```sh
node scripts/build-macos.mjs --runtime ../nivfold/.debug/runs/nivfold/nivfold
.debug/runs/macos-client/reims-go doctor
.debug/runs/macos-client/reims-go
```
在「新建虚拟机」中下载 Apple 为当前宿主提供的兼容恢复镜像,或选择已有的本地 `.ipsw`。「镜像」页也可下载和管理缓存。应用只在你点击下载后传输镜像,下载好的镜像可重复使用。创建会把系统安装到新虚拟磁盘;完成后点击「启动」,在独立窗口里手动完成客体的设置助理。命令行创建使用本地镜像的绝对路径:
```sh
client=.debug/runs/macos-client/reims-go
"$client" vm create --ipsw /absolute/path/to/Restore.ipsw mac-test
"$client" vm list
"$client" vm start mac-test
"$client" vm stop mac-test
```
Windows 上创建的 x86-64 虚拟机和快照不能在原生后端打开。实验版暂不支持快照、挂起、恢复点、共享文件夹或 Reims vGPU。
</details>
## 常见问题
+13 -3
View File
@@ -1,6 +1,6 @@
# 系统架构
桌面窗口与命令行共用同一份 Go 核心,面向 64 位 Windows 10 与 Windows 11。客户端只负责环境体检、资产下载、配置校验、生命周期编排与宿客协作,底层虚拟化与图形转换以受控子进程方式调用便携运行时完成。
桌面窗口与命令行共用同一份 Go 核心。Windows x64 使用 Reims vGPU 与 QEMU 运行时。Apple 芯片 Mac 可使用实验性原生驱动,通过独立运行器调用系统的虚拟化框架。客户端负责环境体检、配置校验与虚拟机生命周期编排。
## 总体分层
@@ -33,7 +33,7 @@ flowchart TB
Ctl --> QEMU
```
非 Windows 平台通过构建标签隔离系统原生调用并提供桩实现,保证全平台均可编译和运行单元测试。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。
构建标签隔离系统原生调用,不支持的能力由对应平台拒绝。上图展示 Windows 的 Reims vGPU 路径。多语言词表在编译期同时生成前后端字典,默认跟随系统语言并支持通过声明式语言包扩展。
## 核心机制与安全边界
@@ -85,7 +85,7 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U
### 托管型与进程型客体驱动
客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行,宿主不探测其进程与窗口,也不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。
客体驱动按虚拟机进程的归属分为两类。进程型驱动让宿主拉起虚拟机进程,宿主据此判断运行状态、定位显示窗口并绑定处理器核心。托管型驱动在声明中带有 `hosted` 能力,虚拟机由驱动自己的管理层运行。宿主不探测托管型驱动的进程与窗口。声明查看窗口能力的驱动可自行唤出查看器。宿主不提供全屏和绑核入口;仅当驱动同时声明控制台能力时才开放截屏与键入。
托管型驱动通过宿主接口主动推送虚拟机的生命周期状态、就绪状态、所处阶段与客体系统信息。电源状态仍只取 `stopped`、`starting`、`running`、`stopping`、`suspended`、`broken` 与 `driver_unavailable`,就绪与阶段是独立字段,因此仍在启动中的客体显示为运行中但未就绪。推送缺失或过期时,宿主回退为向驱动查询。推送只对驱动自己名下的虚拟机生效。
@@ -111,6 +111,16 @@ macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主
测试同时拒绝没有调用者的函数、前端导出、样式类与文案,拒绝前端模块循环引用,并限制单个 Go 函数的长度。
## Apple 芯片 Mac 原生后端
原生驱动只在 Darwin ARM64 上注册。独立 Nivfold 仓库维护运行器、签名和底层测试。Reims-Go 不包含它的源码,不在客户端构建中编译或下载运行器。客户端在自身可执行文件旁查找 Nivfold,不搜索工作目录或系统路径,并检查运行器标识和协议。开发构建可显式传入兼容的签名二进制。
Nivfold 按虚拟机独立启动。它使用本地恢复镜像安装系统,并一次发布虚拟硬件身份、辅助存储、磁盘和客体资源下限。只有完整安装的磁盘才可启动。旧版磁盘没有客体资源下限记录,保留兼容读取。原生磁盘与 Windows 的虚拟机、快照和挂起状态互不兼容。
运行器持有逐虚拟机的系统文件锁。管理命令使用当前用户限定的本地 Unix 套接字,不通过 PID 发送关机信号,也不开放 TCP 控制端口。虚拟机由运行器持有,独立于客户端窗口。系统启动后由用户在虚拟机窗口中完成客体设置。
Mac 与 Windows 共用镜像页和下载任务。Mac 通过 Nivfold 查询 Apple 为当前宿主提供的最新兼容恢复镜像。框架目录重试失败时,Nivfold 使用 Apple 设备目录中同时提供给当前 Mac 型号和虚拟 Mac 的恢复镜像。客户端只在用户触发后从 Apple 的 HTTPS 源下载。客户端根据强 ETag 续传,校验可用的官方摘要,并在框架确认镜像版本和兼容性后发布缓存。旧运行器或网络不可用时仍可选择本地镜像。
## 便携运行时与跨仓边界
便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu)
+1 -1
View File
@@ -35,7 +35,7 @@
## 布局层级与视觉基线
窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。
窗口由左侧可折叠侧栏(`Ctrl+B`)、右侧主内容区、底部常驻状态栏与可收起日志抽屉(`Ctrl+L`)组成。侧栏上方列出虚拟机实例与新建入口(`Ctrl+N`),下方固定提供「镜像」「插件」「内核」「设置」(`Ctrl+,`)与「关于」入口。虚拟机操作按钮固定在详情页头而非全局标题栏,避免切换页面时顶栏跳动。macOS 在系统菜单栏提供「虚拟机」「视图」和「帮助」菜单,应用及标准菜单均跟随界面语言,使用 `Command` 组合键;`Command+,` 打开应用设置,原有 `Ctrl` 快捷键仍可在窗口中使用。Windows 在窗口标题栏提供这三项菜单。
- 同一项硬件规格或运行状态在同一视图内只展示一次,相同动作不在同屏提供两个按钮出口。
- 页面只用单层分组容器或留白表达层级,禁止卡片嵌套卡片;下拉选择统一使用自绘弹出控件,不混用系统原生表单控件。
+1
View File
@@ -14,6 +14,7 @@
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
| Apple 芯片 Mac 原生运行器 | 虚拟机设备、安装事务、实例锁、查看器和关机协议 | 独立 `nivfold` 仓库。客户端的驱动注册、命令适配与任务界面仍归 `Reims-Go`。 |
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 |
+3 -1
View File
@@ -12,6 +12,8 @@
| 跨模块改动或提 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 中完成首启数据目录设置 |
| Apple 芯片 Mac 构建 | `node scripts/build-macos.mjs` | 独立构建桌面端。`--runtime` 可接入已构建并签名的 Nivfold |
| Mac 客户端运行时契约检查 | `node scripts/test.mjs applevz .debug/runs/macos-client/nivfold` | 无系统镜像地检查 Nivfold 签名、协议、宿主能力和空实例状态。运行器内部套接字和安装取消测试在 Nivfold 仓库执行 |
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。滚动开发版检查推送到 `main` 的最新提交消息的第一行,包含 `#` 且不包含 `docs`(忽略大小写)时才复用该提交的 CI 测试自动构建。自动构建跳过有多个父提交的合并提交及纯文档推送。手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
@@ -28,4 +30,4 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限
- 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
- Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。
- 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在对应宿主实测。Mac 原生后端的完整冒烟需使用数据目录外的本地 Apple `.ipsw`,验证安装、首次启动、重新显示窗口和正常关机。执行客体图形安装向导前必须确认。
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { buildNativeMenu, resolveMenuClick, buildTitleMenus, runMenuCommand, vmFeatures } = await loadTestModule(`
import './i18n/domains/core.gen'
import './i18n/domains/vm.gen'
export * from './macos/applicationMenuModel'
export * from './lib/titleMenu'
export { vmFeatures } from './lib/endpoints'
`)
const props = { locale: 'en-US', sidebarOpen: true, logsOpen: false, themeMode: 'system', canLight: true, canDark: true, vm: null }
const state = { workspaceReady: true, dialogOpen: false, vmSettingsReady: false }
const vm = { name: 'test', state: 'stopped', busy: false, canSuspend: false, features: vmFeatures() }
const find = (model, command) => model.groups.flatMap((group) => group.rows).find((row) => row.command === command)
test('the native bar localizes three menus and reflects view state and Command shortcuts', () => {
const { groups } = buildNativeMenu({ ...props, locale: 'zh-CN' }, state)
assert.deepEqual(groups.map(({ label }) => label), ['虚拟机', '视图', '帮助'])
const menu = buildNativeMenu({ ...props, canDark: false, themeMode: 'light', logsOpen: true, vm }, state)
assert.deepEqual(menu.groups.map(({ label }) => label), ['VM', 'View', 'Help'])
assert.equal(find(menu, 'sidebar').checked, true)
assert.equal(find(menu, 'logs').checked, true)
assert.equal(find(menu, 'theme:light').checked, true)
assert.equal(find(menu, 'theme:dark'), undefined)
assert.equal(find(menu, 'theme:system'), undefined)
assert.deepEqual(['new', 'sidebar', 'logs', 'settings', 'vm:start'].map((command) => find(menu, command).key), ['n', 'b', 'l', ',', '\r'])
assert.equal(buildTitleMenus(props).vm.rows[0].shortcut, 'Ctrl+N')
})
test('standard macOS menus use the same locale as the app-defined menus', () => {
const { standard: zh } = buildNativeMenu({ ...props, locale: 'zh-CN' }, state)
const { standard: en } = buildNativeMenu(props, state)
assert.deepEqual([zh.edit, zh.window, zh['hide:'], zh.Quit], ['编辑', '窗口', '隐藏 Reims-Go', '退出 Reims-Go'])
assert.deepEqual([en.edit, en.window, en['hide:'], en.Quit], ['Edit', 'Window', 'Hide Reims-Go', 'Quit Reims-Go'])
assert.deepEqual([zh['undo:'], zh['redo:'], zh['pasteAsRichText:'], zh['startSpeaking:']], ['撤销', '重做', '粘贴并匹配样式', '开始朗读'])
for (const key of Object.keys(en)) assert.notEqual(zh[key], en[key], key)
})
test('VM menu validates the current VM state and ignores stale targets', () => {
const selected = { ...state, selectedVMKey: 'driver:test', vmSettingsReady: true }
let menu = buildNativeMenu({ ...props, vm }, selected)
const click = (command, scope = selected.selectedVMKey) => resolveMenuClick({ command, scope }, menu.scope, menu.commands)
assert.equal(click('vm:start'), 'vm:start')
assert.equal(click('vm:start', 'another-driver:test'), undefined)
assert.equal(click('vmSettings'), 'vmSettings')
assert.equal(click('vm:stop'), undefined)
menu = buildNativeMenu({ ...props, vm: { ...vm, state: 'running' } }, selected)
assert.equal(click('vm:start'), undefined)
assert.equal(click('vm:focus'), 'vm:focus')
assert.equal(click('vm:stop'), 'vm:stop')
assert.equal(click('vm:delete'), undefined)
menu = buildNativeMenu({ ...props, vm: { ...vm, state: 'suspended' } }, selected)
assert.equal(click('vm:resume'), undefined)
assert.equal(click('vmSettings'), undefined)
assert.equal(click('vm:discardSuspend'), 'vm:discardSuspend')
})
test('setup only exposes external help, and modal dialogs block native menu commands', () => {
const setup = buildNativeMenu(props, { ...state, workspaceReady: false })
assert.deepEqual([...setup.commands], ['website', 'docs', 'project', 'report'])
assert.equal(buildNativeMenu(props, { ...state, dialogOpen: true }).commands.size, 0)
})
test('native menu commands reuse the renderer actions and URL localization', () => {
const calls = []
const actions = { ...props, locale: 'zh-CN',
onVMAction: (action) => calls.push(action),
onVMDelete: () => calls.push('confirm delete'),
onNavigate: (page) => calls.push(page),
onThemeMode: (mode) => calls.push(mode),
onOpenURL: (url) => calls.push(url),
}
for (const id of ['vm:stop', 'vm:delete', 'settings', 'update', 'theme:dark', 'docs']) runMenuCommand(actions, id)
assert.deepEqual(calls, ['stop', 'confirm delete', 'settings', 'about', 'dark', 'https://reims.dev/docs/quick-start'])
})
+15 -1
View File
@@ -103,7 +103,7 @@ test('macOS VMs keep every action; other VMs follow their capabilities', () => {
assert.equal(withAffinity.screenshot, false)
})
test('hosted VMs never offer window, fullscreen, affinity, screenshot or typing', () => {
test('hosted VMs without a window or console do not offer process or display controls', () => {
const hosted = lib.vmFeatures({
driver_id: 'acme.wsl',
capabilities: ['hosted', 'affinity', 'qmp', 'snapshot'],
@@ -117,6 +117,20 @@ test('hosted VMs never offer window, fullscreen, affinity, screenshot or typing'
assert.equal(hosted.snapshot, true)
})
test('a hosted native window takes priority over ready endpoints', () => {
const windowed = lib.vmFeatures({ driver_id: 'example.native', capabilities: ['hosted', 'window', 'affinity'] })
const ssh = ep('ssh')
assert.equal(windowed.window, true)
assert.equal(windowed.fullscreen, false)
assert.equal(windowed.affinity, false)
assert.deepEqual(lib.primaryVMAccess(windowed, [ssh]), { kind: 'window' })
assert.deepEqual(lib.primaryVMAccess(windowed, []), { kind: 'window' })
const endpointOnly = lib.vmFeatures({ driver_id: 'example.wsl', capabilities: ['hosted'] })
assert.deepEqual(lib.primaryVMAccess(endpointOnly, [ssh]), { kind: 'endpoint', endpoint: ssh })
assert.equal(lib.primaryVMAccess(endpointOnly, [ep('ssh', false)]), undefined)
})
test('a hosted VM offers screenshots and typing only when its driver serves a console', () => {
const withConsole = lib.vmFeatures({ driver_id: 'acme.wsl', capabilities: ['hosted', 'console'] })
assert.equal(withConsole.screenshot, true)
+45
View File
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { defaultGuestDriver, eligibleGuestDrivers, hasRestoreImagePicker, needsRuntimeSetup, restoreImageField } = await loadTestModule(`export * from './lib/guestDrivers'`)
const mac = { os: 'darwin', arch: 'arm64' }
const win = { os: 'windows', arch: 'amd64' }
const restore = { type: 'string', 'x-filePattern': '*.ipsw' }
const create_schema = { properties: { restore_path: restore } }
const native = { id: 'example.native', runtime_kind: 'external', builtin: true, create_schema }
const thirdParty = { id: 'example.additional', runtime_kind: 'external', create_schema }
const legacy = { id: 'builtin.driver.reims-macos', runtime_kind: 'reims-vgpu', builtin: true }
test('Apple Silicon skips portable runtime setup, but Windows still offers it when missing', () => {
assert.equal(needsRuntimeSetup(mac, false), false)
assert.equal(needsRuntimeSetup(win, false), true)
assert.equal(needsRuntimeSetup(win, true), false)
assert.equal(needsRuntimeSetup({ os: 'darwin', arch: 'amd64' }, false), true)
})
test('a host-provided external driver can create without a portable runtime', () => {
const eligible = eligibleGuestDrivers([legacy, native, thirdParty], false)
assert.deepEqual(eligible, [native, thirdParty])
assert.equal(defaultGuestDriver(eligible, mac), native)
assert.equal(defaultGuestDriver([thirdParty, native], mac), thirdParty)
assert.equal(defaultGuestDriver(eligible, mac, 'offline'), undefined)
assert.equal(defaultGuestDriver([thirdParty, legacy], win), legacy)
assert.equal(defaultGuestDriver([thirdParty, legacy], win, 'online'), legacy)
assert.deepEqual(eligibleGuestDrivers([legacy, native], true), [legacy, native])
})
test('cached IPSW routes only to the trusted native restore driver', () => {
assert.equal(defaultGuestDriver([thirdParty, legacy, native], mac, 'ipsw'), native)
assert.equal(defaultGuestDriver([thirdParty, legacy], mac, 'ipsw'), undefined)
assert.equal(defaultGuestDriver([legacy, native], win, 'ipsw'), undefined)
assert.equal(restoreImageField(native, mac), 'restore_path')
})
test('only a host-trusted create schema can add the IPSW picker', () => {
assert.equal(hasRestoreImagePicker(native, restore), true)
assert.equal(hasRestoreImagePicker(thirdParty, restore), false)
assert.equal(hasRestoreImagePicker(native, { ...restore, 'x-filePattern': '*.ipsw;*' }), false)
assert.equal(hasRestoreImagePicker(native, { ...restore, type: 'integer' }), false)
})
+36
View File
@@ -0,0 +1,36 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { cachedRestoreImage, matchesRestoreImage, restoreImageChoiceKey, restoreImageChoices, restoreImagePathMissing } = await loadTestModule(`export * from './lib/restoreImages'`)
const latest = { version: '26.6.2', build: '25G83', title: 'macOS Tahoe' }
const olderBuild = { kind: 'ipsw', version: latest.version, build: '25G82', title: 'macOS Tahoe', path: '/saved/old.ipsw' }
const partial = { ...olderBuild, build: latest.build, path: '/saved/new.ipsw.part', partial: true }
const otherKind = { ...olderBuild, build: latest.build, kind: 'offline' }
test('a previous IPSW build stays selectable without masking the latest one', () => {
const cache = [olderBuild, partial, otherKind]
assert.deepEqual(restoreImageChoices(latest, cache).map((choice) => choice.key), [
restoreImageChoiceKey(latest.version, latest.build), restoreImageChoiceKey(olderBuild.version, olderBuild.build),
])
assert.equal(cachedRestoreImage(cache, latest.version, latest.build), undefined)
assert.equal(cachedRestoreImage(cache, olderBuild.version, olderBuild.build), olderBuild)
assert.equal(matchesRestoreImage(olderBuild, latest.version, latest.build), false)
assert.equal(matchesRestoreImage(partial, latest.version, latest.build), true)
})
test('a downloaded latest build is not repeated and is used by its exact matching row', () => {
const complete = { ...partial, partial: false, path: '/saved/new.ipsw' }
const cache = [otherKind, olderBuild, partial, complete]
assert.equal(restoreImageChoices(latest, cache).length, 2)
assert.equal(cachedRestoreImage(cache, latest.version, latest.build), complete)
assert.equal(restoreImageChoices(undefined, [otherKind, olderBuild, partial]).length, 1)
})
test('a completed IPSW missing a cache path is distinct from an absent or partial download', () => {
const missing = { ...partial, partial: false, path: '' }
assert.equal(restoreImagePathMissing([missing], latest.version, latest.build), true)
assert.equal(restoreImagePathMissing([olderBuild, otherKind, { ...partial, path: '' }], latest.version, latest.build), false)
assert.equal(restoreImagePathMissing([missing], latest.version, olderBuild.build), false)
})
+31 -2
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { creatingVMTasks, currentTask, findActiveOfflineTask, pruneFinishedTasks, taskDetail, upsertTask } =
const { creatingVMTasks, currentTask, findActiveCachedTask, findActiveInstallerTask, findRunningRestoreTask, groupUnmatchedInstallerTasks, pruneFinishedTasks, taskDetail, taskStopAction, taskTitle, upsertTask } =
await loadTestModule(`export * from './lib/tasks'`)
const task = (id, overrides = {}) => ({
@@ -29,11 +29,23 @@ test('one installer download represents the VM creations waiting for it', () =>
const download = task('download', { kind: 'installer-download', started_at: 15 })
const vm = task('vm', { vm: 'vm one' })
const other = task('other', { installer_version: '15.8.3' })
assert.deepEqual(findActiveOfflineTask([vm, other, download], '26.7.3'), {
assert.deepEqual(findActiveInstallerTask([vm, other, download], 'offline', '26.7.3'), {
primary: download, waitingVMs: ['vm one'], matchedIDs: ['download', 'vm'],
})
})
test('native and Windows installers of the same version keep separate download state', () => {
const win = task('win', { kind: 'installer-download' })
const mac = task('mac', { kind: 'installer-download', installer_kind: 'ipsw' })
const other = task('other', { kind: 'installer-download', installer_kind: 'ipsw', installer_version: '27.0' })
const tasks = [win, mac, other]
assert.equal(findActiveInstallerTask(tasks, 'ipsw', '26.7.3')?.primary, mac)
assert.equal(findActiveInstallerTask(tasks, 'offline', '26.7.3')?.primary, win)
assert.equal(findActiveCachedTask(tasks, { kind: 'ipsw', version: '26.7.3', partial: true })?.primary, mac)
assert.deepEqual(groupUnmatchedInstallerTasks(tasks, new Set()).map((match) => match.primary.id), ['win', 'mac', 'other'])
assert.deepEqual(taskStopAction('en-US', mac), { kind: 'pause', label: 'Pause download' })
})
test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
assert.equal(taskDetail(task('slow', { done: 5e6, total: 50e6, rate: 512e3 })), '5 MB / 50 MB · 512 KB/s')
assert.equal(taskDetail(task('tiny', { done: 1e6, total: 10e6, rate: 200 })), '1 MB / 10 MB · 1 KB/s')
@@ -41,6 +53,23 @@ test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
assert.equal(taskDetail(task('gig', { done: 2e9, total: 10e9, rate: 1.2e9 })), '2.0 GB / 10.0 GB · 1.2 GB/s')
})
test('guest restore is labeled as installing and can be canceled, not paused', () => {
const restore = task('macOS', { kind: 'vm-restore', installer_kind: '', installer_phase: '' })
assert.equal(taskTitle('en-US', restore), 'Installing macOS on macOS')
assert.deepEqual(taskStopAction('en-US', restore), { kind: 'cancel', label: 'Cancel creation' })
})
test('restore progress and cancel target the matching driver and case-preserved VM name', () => {
const running = task('native', { kind: 'vm-restore', vm: 'builtin.driver.apple-vz:Test VM' })
const otherDriver = { ...running, id: 'other', vm: 'example.driver:Test VM' }
const finished = { ...running, id: 'finished', status: 'done' }
const tasks = [otherDriver, finished, running]
assert.equal(findRunningRestoreTask(tasks, 'builtin.driver.apple-vz', ' Test VM '), running)
assert.equal(findRunningRestoreTask(tasks, 'example.driver', 'Test VM'), otherDriver)
assert.equal(findRunningRestoreTask(tasks, 'builtin.driver.apple-vz', 'test vm'), undefined)
assert.equal(findRunningRestoreTask(tasks, '', 'Test VM'), undefined)
})
test('creatingVMTasks lists only running vm-create tasks not yet present in vms, oldest first', () => {
const first = task('t1', { subject: 'macos-a', started_at: 10 })
const second = task('t2', { subject: 'macos-b', started_at: 20 })
+102 -70
View File
@@ -4,7 +4,9 @@ import type { WizardDraft } from './components/CreateWizard'
import { AppDialogs } from './components/AppDialogs'
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus'
import { SidebarToggle, TitleMenus } from './components/TitleMenus'
import { ApplicationMenu } from './macos/ApplicationMenu'
import type { TitleMenuProps } from './lib/titleMenu'
import { UpdateCapsule } from './components/UpdateCapsule'
import { DataRootReadOnly } from './components/DataRootReadOnly'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
@@ -13,7 +15,8 @@ import { VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
import { initialWizardResolution } from './lib/displayResolution'
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { isMacOSDriver, liveVMInfo, primaryVMAccess, vmFeatures } from './lib/endpoints'
import { defaultGuestDriver, eligibleGuestDrivers, isAppleSilicon, needsRuntimeSetup } from './lib/guestDrivers'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog, createLogLine } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
@@ -31,7 +34,7 @@ import { vmRefKey } from './lib/vmRef'
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
import { publishPluginHostEvent } from './lib/pluginViewEvents'
import { buildSafePluginAssetURL } from './lib/pluginAssets'
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, DriverSummary, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
import { Tip, TooltipProvider } from './ui/controls'
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
@@ -48,6 +51,10 @@ const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m)
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
// Detect desktop chrome before GetState resolves, including the loading and setup screens.
const nativeTitlebar = navigator.platform.startsWith('Mac')
const titleMenuPages = { installers: INSTALLERS_ID, plugins: PLUGINS_ID, host: HOST_ID, settings: SETTINGS_ID, about: ABOUT_ID }
const errText = (e: unknown) => parseAppError(e).summary
type HostDropAck = { status: string; error?: string }
@@ -100,12 +107,15 @@ const failKey: Record<VMBusyAction, I18nKey> = {
export const App: React.FC = () => {
const [state, setState] = useState<AppState | null>(null)
const [nativeMenuReady, setNativeMenuReady] = useState(false)
const [selected, setSelectedPage] = useState<string>(HOST_ID)
const [detail, setDetail] = useState<VMDetail | null>(null)
// GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail).
const [vmInfoLoaded, setVMInfoLoaded] = useState<VMInfo | null>(null)
const [detailRevision, setDetailRevision] = useState(0)
const [showWizard, setShowWizard] = useState(false)
const [wizardDrivers, setWizardDrivers] = useState<DriverSummary[]>([])
const loadingWizardDrivers = useRef(false)
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
const [pendingCreates, setPendingCreates] = useState<string[]>([])
const [showSettings, setShowSettings] = useState(false)
@@ -488,7 +498,8 @@ export const App: React.FC = () => {
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const nativeHost = isAppleSilicon(state?.host)
const hostReady = !!state && (nativeHost ? !!state.host.apple_virtualization?.ready : state.host.whpx === 'ready' && !!state.active_runtime)
const canSuspend = state?.can_suspend ?? false
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
@@ -595,14 +606,14 @@ export const App: React.FC = () => {
try {
const s = await api.GetState()
setState(s)
setSetupStage(s?.active_runtime ? null : 'runtime')
setSetupStage(needsRuntimeSetup(s.host, !!s.active_runtime) ? 'runtime' : null)
} catch (e) {
console.warn('[app] GetState after setup failed:', e)
fail(tr('failGeneric'), e)
setSetupStage('runtime')
setSetupStage(!nativeHost ? 'runtime' : null)
}
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
const showSetup = !!state && (state.needs_setup || (!nativeHost && setupStage === 'runtime'))
// The data folder opened read-only (internal/dataroot): nothing in it may be
// changed, so the workspace gives way to a screen that explains why.
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
@@ -787,15 +798,6 @@ export const App: React.FC = () => {
}
}
// Hosted VMs have no window: the primary action is their best ready endpoint.
const openEndpoint = (vm: VMListItem, kind: string) => {
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
}
const openPrimaryEndpoint = (vm: VMListItem) => {
const { primary } = splitEndpoints(vm.endpoints)
if (primary) openEndpoint(vm, primary.kind)
}
// Actions that only the macOS driver implements (name-based or macOS guest features).
const MACOS_ONLY_ACTIONS: readonly VMAction[] = [
'finishInstall', 'enterRecovery', 'attachInstaller', 'attachGuestTools', 'detachGuestTools',
@@ -810,13 +812,10 @@ export const App: React.FC = () => {
const features = vmFeatures(actionVM)
if (!canSuspendVM(actionVM) && (action === 'suspend' || action === 'resume')) return
if (!features.macos && MACOS_ONLY_ACTIONS.includes(action)) return
if (action === 'focus' && !features.window) return
if (action === 'fullscreen' && !features.fullscreen) return
if (action === 'screenshot' && !features.screenshot) return
if ((action === 'type' || action === 'sendText') && !features.sendText) return
if (action === 'focus' && !features.window) {
if (actionVM) openPrimaryEndpoint(actionVM)
return
}
const activeBusy = vmBusy.current(key)
if (
activeBusy
@@ -883,9 +882,7 @@ export const App: React.FC = () => {
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, Resume while suspended, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar. A running hosted VM has no window; its action is its
// best ready endpoint, and nothing when none is ready.
// Ctrl+Enter and sidebar double-click use the same primary action as the VM page.
const primaryAction = (name: string) => {
const vm = findVM(name)
if (!vm) return
@@ -894,7 +891,13 @@ export const App: React.FC = () => {
const st = state?.transitions[key] ?? vm.state
if (st === 'stopped') onVMActionFor(key, 'start', false)
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
else if (st === 'running') onVMActionFor(key, 'focus', true)
else if (st === 'running') {
const access = primaryVMAccess(vmFeatures(vm), vm.endpoints)
if (access?.kind === 'window') onVMActionFor(key, 'focus', true)
else if (access?.kind === 'endpoint') {
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, access.endpoint.kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
}
}
}
const confirmDelete = (keepFiles: boolean) => {
@@ -936,26 +939,44 @@ export const App: React.FC = () => {
}, tr('toastCloned', { name: cloneName }))
}
const openWizard = () => {
if (!state?.active_runtime) {
const loadWizardDrivers = async (kind?: 'offline' | 'online' | 'ipsw') => {
if (!state || loadingWizardDrivers.current) return false
loadingWizardDrivers.current = true
try {
const drivers = eligibleGuestDrivers(await api.ListDrivers() ?? [], !!state.active_runtime)
if (defaultGuestDriver(drivers, state.host, kind)) {
setWizardDrivers(drivers)
return true
}
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
toasts.push({ kind: 'error', title: tr(needsRuntimeSetup(state.host, !!state.active_runtime) ? 'noRuntimeAlert' : 'wizardNoDriver') })
return false
} catch (e) {
fail(tr('wizardDriverListFailed'), e)
return false
} finally {
loadingWizardDrivers.current = false
}
}
const openWizard = async () => {
if (!(await loadWizardDrivers())) return
setWizardDraft(null)
setShowWizard(true)
}
const openWizardWithInstaller = (item: CachedInstaller) => {
if (!state?.active_runtime) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
}
const openWizardWithInstaller = async (item: CachedInstaller) => {
if (!state || item.partial || item.kind === 'other' || !item.path || !(await loadWizardDrivers(item.kind))) return
const existing = new Set((state.vms ?? []).map((v) => v.name.toLowerCase()))
let defaultName = 'macos-tahoe'
const baseName = item.kind === 'ipsw' ? 'macos' : 'macos-tahoe'
let defaultName = baseName
for (let i = 2; existing.has(defaultName.toLowerCase()); i++) {
defaultName = `macos-tahoe-${i}`
defaultName = `${baseName}-${i}`
}
if (item.kind === 'ipsw') {
setWizardDraft({ step: 1, restoreImage: item, name: defaultName })
setShowWizard(true)
return
}
const isOffline = item.kind === 'offline' && !!item.version
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
@@ -1109,47 +1130,52 @@ export const App: React.FC = () => {
.catch((e) => fail(tr('failGuestTools'), e))
})
const workspaceReady = !!state && !showSetup && !showReadOnly
const titleMenuProps: TitleMenuProps = {
locale, sidebarOpen, logsOpen, themeMode, canLight, canDark, fullscreenHotkey,
vm: selectedVM ? {
name: selectedVM.name,
driver_id: selectedVM.driver_id,
state: effectiveState,
busy: vmRefKey(selectedVM) in vmBusy.busy,
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend: canSuspendVM(selectedVM),
features: selectedFeatures,
} : null,
appVersion: state?.app_version,
onToggleSidebar: toggleSidebar,
onToggleLogs: toggleLogs,
onThemeMode: setThemeMode,
onNewVM: openWizard,
onVMAction,
onVMSettings: () => { if (detail && effectiveState !== 'suspended') setShowSettings(true) },
onVMDelete: () => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) },
onNavigate: (page) => setSelected(titleMenuPages[page]),
onOpenURL: (url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) },
}
return (
<ThemeVisualsProvider payload={activeThemePayload}>
<TooltipProvider>
{nativeTitlebar && <ApplicationMenu props={titleMenuProps} onReady={setNativeMenuReady} state={{
workspaceReady,
dialogOpen: workspaceReady && (!!appDialogOpen || pluginViewState.dialogs.length > 0),
selectedVMKey: selectedVM && vmRefKey(selectedVM),
vmSettingsReady: !!detail && detail.name === selectedVM?.name,
}} />}
<div className="app-shell rg-p-shell">
<div className="rg-layer rg-layer-background" data-rg-layer="layer.background" aria-hidden="true" />
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
{showSetup || showReadOnly || !state ? (
<header className="titlebar rg-p-titlebar" data-native-titlebar={nativeTitlebar || undefined} onDoubleClick={nativeTitlebar ? undefined : WindowToggleMaximise}>
{!workspaceReady ? (
<div className="brand rg-p-brand">
<BrandMark className="brand-mark" />
Reims-Go
</div>
) : (
<TitleMenus
locale={locale}
sidebarOpen={sidebarOpen}
onToggleSidebar={toggleSidebar}
logsOpen={logsOpen}
onToggleLogs={toggleLogs}
themeMode={themeMode}
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
vm={selectedVM ? {
name: selectedVM.name,
driver_id: selectedVM.driver_id,
state: effectiveState,
busy: vmRefKey(selectedVM) in vmBusy.busy,
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend: canSuspendVM(selectedVM),
features: selectedFeatures,
} : null}
fullscreenHotkey={fullscreenHotkey}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(vmRefKey(selectedVM)) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
appVersion={state.app_version}
/>
)}
) : nativeTitlebar && nativeMenuReady ? (
<div className="titlebar-left">
<SidebarToggle {...titleMenuProps} mac />
</div>
) : <TitleMenus {...titleMenuProps} />}
<div className="rg-slot-anchor titlebar-center" data-rg-slot="titlebar.center" />
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
{canLight && canDark && (
@@ -1164,11 +1190,11 @@ export const App: React.FC = () => {
</button>
</Tip>
)}
<div className="win-controls">
{!nativeTitlebar && <div className="win-controls">
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} aria-hidden="true" /></button>
</div>
</div>}
</div>
</header>
@@ -1407,6 +1433,7 @@ export const App: React.FC = () => {
locale={locale}
onRefresh={refresh}
onNewVM={openWizard}
hostReady={hostReady}
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
runtimeTask={runtimeTask}
@@ -1462,7 +1489,12 @@ export const App: React.FC = () => {
displayNames={displayNames}
showWizard={showWizard}
wizardDraft={wizardDraft}
wizardDrivers={wizardDrivers}
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
onDriverCreated={(driverID, name) => {
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
void refresh().then(() => setSelected(vmRefKey({ driver_id: driverID, name })))
}}
onSubmitCreate={submitCreate}
showSettings={showSettings}
onCloseSettings={() => setShowSettings(false)}
+18 -19
View File
@@ -8,12 +8,13 @@ import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { Segmented } from '../ui/settings'
import { api } from '../wails'
import { REPO_URL, siteURL } from './TitleMenus'
import { REPO_URL, siteURL } from '../lib/titleMenu'
import type { UpdatePhase } from '../lib/useAppUpdate'
import { BrandMark } from '../ui/themeVisuals'
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
const QQ_GROUP_ID = '1136042744'
const QQ_GROUP_INVITE_URL = 'https://qm.qq.com/q/TBmRJlVbSo'
type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
@@ -100,7 +101,7 @@ export const AboutPage: React.FC<Props> = ({
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
.catch((e) => {
console.warn('[about] CanOpenQQGroup failed:', e)
if (!cancelled) setQQInstalled(false)
if (!cancelled) setQQLaunchErr(String(e))
})
return () => {
mountedRef.current = false
@@ -319,25 +320,23 @@ export const AboutPage: React.FC<Props> = ({
) : null}
</div>
<div className="row-right">
{onCopy && (
<IconButton
small
label={tr('aboutCopyQQGroup')}
icon={<Copy size={14} aria-hidden="true" />}
onClick={() => onCopy(QQ_GROUP_ID)}
/>
)}
{qqInstalled && !qqLaunchErr ? (
<>
{onCopy && (
<IconButton
small
label={tr('aboutCopyQQGroup')}
icon={<Copy size={14} aria-hidden="true" />}
onClick={() => onCopy(QQ_GROUP_ID)}
/>
)}
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
{tr('aboutJoinQQGroup')}
</Button>
</>
) : onCopy ? (
<Button icon={<Copy size={14} aria-hidden="true" />} onClick={() => onCopy(QQ_GROUP_ID)}>
{tr('aboutCopyQQGroup')}
<Button busy={openingQQ} icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => void openQQGroup()}>
{tr('aboutJoinQQGroup')}
</Button>
) : null}
) : (
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(QQ_GROUP_INVITE_URL)}>
{tr('aboutQQOpenInvite')}
</Button>
)}
</div>
</div>
</div>
+7 -2
View File
@@ -8,7 +8,7 @@ import { I18nKey, t } from '../i18n'
import { latestVMStats } from '../lib/vmStats'
import { vmRefKey } from '../lib/vmRef'
import type { PluginViewRoute } from '../lib/pluginViewRouter'
import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types'
import type { AppState, CreateOpts, DriverSummary, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types'
import { Button } from '../ui/controls'
import { ConfirmDialog, Modal } from '../ui/dialog'
import type { ToastInput } from '../ui/toast'
@@ -33,7 +33,9 @@ interface AppDialogsProps {
showWizard: boolean
wizardDraft: WizardDraft | null
wizardDrivers: DriverSummary[]
onCloseWizard: () => void
onDriverCreated: (driverID: string, name: string) => void
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void
showSettings: boolean
@@ -87,7 +89,7 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
const {
locale, state, detail, selectedVM, selectedIsMacOS, effectiveState,
fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames,
showWizard, wizardDraft, onCloseWizard, onSubmitCreate,
showWizard, wizardDraft, wizardDrivers, onCloseWizard, onDriverCreated, onSubmitCreate,
showSettings, onCloseSettings, onSavedSettings,
affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied,
updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate,
@@ -109,11 +111,14 @@ export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
<CreateWizard
locale={locale}
host={state.host}
drivers={wizardDrivers}
fixedModeSupported={fixedModeSupported}
captureSupported={state.runtime_capture_supported}
tasks={tasks}
draft={wizardDraft}
onCancelTask={api.CancelTask}
onClose={onCloseWizard}
onDriverCreated={onDriverCreated}
onSubmit={onSubmitCreate}
/>
</Suspense>
+86 -46
View File
@@ -1,5 +1,5 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
import React, { Suspense, lazy, useCallback, useEffect, useMemo, useState } from 'react'
import { useNetworkPlan } from '../lib/useNetworkPlan'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
@@ -45,30 +45,33 @@ import {
toggleWizardBorderless,
} from '../lib/displayResolution'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
import { findActiveInstallerTask, findRunningRestoreTask, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
import { isMacOSDriver } from '../lib/endpoints'
import { defaultGuestDriver, hasRestoreImagePicker, restoreImageField } from '../lib/guestDrivers'
import { RestoreImageSource } from './RestoreImageSource'
import { Button, IconButton } from '../ui/controls'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Modal } from '../ui/dialog'
import { api } from '../wails'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
/** Reopen the wizard where the user left it (e.g. after a failed create). */
export interface WizardDraft {
opts: CreateOpts
step: number
manualResolution?: boolean
}
export type WizardDraft =
| { opts: CreateOpts; step: number; manualResolution?: boolean; restoreImage?: never; name?: never }
| { step: number; restoreImage: CachedInstaller; name: string; opts?: never; manualResolution?: never }
interface Props {
locale: Locale
host: HostReport
drivers: DriverSummary[]
fixedModeSupported?: boolean
captureSupported?: boolean
tasks?: Task[]
draft?: WizardDraft | null
onCancelTask: (id: string) => Promise<void>
onClose: () => void
onDriverCreated: (driverID: string, name: string) => void
/** Called with the cleaned payload; the caller runs the create in the background. */
onSubmit: (payload: CreateOpts, draft: WizardDraft) => void
}
@@ -93,7 +96,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
]
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => {
export const CreateWizard: React.FC<Props> = ({ locale, host, drivers, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onCancelTask, onClose, onDriverCreated, onSubmit }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [step, setStep] = useState(draft?.step ?? 1)
// Once the user has reached the review step, keep validating so step markers stay current.
@@ -102,25 +105,23 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [err, setErr] = useState('')
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [cmdPreview, setCmdPreview] = useState('')
const [drivers, setDrivers] = useState<DriverSummary[]>([])
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
const [driverID, setDriverID] = useState(() => defaultGuestDriver(drivers, host, draft?.restoreImage ? 'ipsw' : draft?.opts ? 'offline' : undefined)?.id ?? '')
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [restorePath, setRestorePath] = useState('')
const [driverCreating, setDriverCreating] = useState(false)
const [canceling, setCanceling] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
const [dependencyRefresh, setDependencyRefresh] = useState(0)
const [validationRefresh, setValidationRefresh] = useState(0)
useEffect(() => {
let live = true
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
return () => { live = false }
}, [])
const activeDriver = drivers.find((d) => d.id === driverID)
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const legacyDriver = !!activeDriver && isMacOSDriver(activeDriver.id)
const restoreField = activeDriver && restoreImageField(activeDriver, host)
const updateRestorePath = useCallback((path: string) => setRestorePath(path), [])
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe',
name: draft?.name ?? 'macos-tahoe',
dir: '',
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
source_mode: 'offline',
@@ -150,17 +151,17 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
start: true,
})
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
initialWizardManualResolution(draft),
initialWizardManualResolution(draft?.opts ? { ...draft, opts: draft.opts } : null),
)
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
const [networkAdapters, setNetworkAdapters] = useState<VMNetworkSettings['adapters'] | null>(null)
const [networkError, setNetworkError] = useState<ParsedAppError | null>(null)
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', legacyDriver && step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`)
const networkBlocked = networkMode === 'bridge' && (networkPlanning || !!networkPlanError || !networkPlan || !opts.uplink_guid)
useEffect(() => {
if (step !== 4 || networkMode !== 'bridge') return
if (!legacyDriver || step !== 4 || networkMode !== 'bridge') return
let active = true
setNetworkError(null)
api.ListNetworkAdapters().then((list) => {
@@ -170,7 +171,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
if (connected.length === 1) setOpts((current) => current.uplink_guid ? current : { ...current, uplink_guid: connected[0].guid })
}).catch((error) => { if (active) setNetworkError(parseAppError(error)) })
return () => { active = false }
}, [step, networkMode, locale])
}, [legacyDriver, step, networkMode, locale])
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
const fullscreenPresets = fullscreenDisplayPresets(host)
const activePresets: FullscreenDisplayPreset[] = opts.borderless ? fullscreenPresets : windowPresets
@@ -218,7 +219,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [cached, setCached] = useState<CachedInstaller[]>([])
const [releasesErr, setReleasesErr] = useState('')
useEffect(() => {
if (opts.source_mode !== 'offline' || releases) return
if (!legacyDriver || opts.source_mode !== 'offline' || releases) return
let live = true
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e))
api.ListOfflineReleases()
@@ -229,9 +230,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
})
.catch((e) => { if (live) setReleasesErr(String(e).replace(/^Error:\s*/, '')) })
return () => { live = false }
}, [opts.source_mode])
}, [legacyDriver, opts.source_mode])
const isCached = (v: string) => cached.some((c) => c.kind === 'offline' && !c.partial && c.version === v)
const activeRelease = (v: string) => findActiveOfflineTask(tasks, v)
const activeRelease = (v: string) => findActiveInstallerTask(tasks, 'offline', v)
const chosenRelease = releases?.find((r) => r.version === opts.macos)
// reims-util pre-allocates the whole image as it starts (19.7 GB for an 18.4 GB release, measured).
const needGB = chosenRelease && !isCached(chosenRelease.version) && !activeRelease(chosenRelease.version)
@@ -246,7 +247,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
}, [reviewed, issues.length])
useEffect(() => {
if (!reviewed && step !== REVIEW_STEP) return
if (!legacyDriver || (!reviewed && step !== REVIEW_STEP)) return
let live = true
setChecking(true)
const timer = setTimeout(() => {
@@ -262,7 +263,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
.finally(() => { if (live) setChecking(false) })
}, 200)
return () => { live = false; clearTimeout(timer) }
}, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
}, [legacyDriver, step, reviewed, effectiveOpts, validationRefresh, captureSupported])
const pickDir = async () => {
const dir = await api.PickDirectory(tr('vmDir'))
@@ -290,11 +291,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
const memGB = Math.round(parseMemoryGB(opts.memory) ?? memRec)
const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5']
const restoreTask = driverCreating ? findRunningRestoreTask(tasks, driverID, opts.name) : undefined
return (
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} dismissable={!driverCreating} onClose={onClose}>
{legacyDriver && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{steps.map((key, idx) => {
const n = idx + 1
const bad = issueSteps.has(n) && n !== REVIEW_STEP
@@ -312,10 +313,16 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</button>
)
})}
</nav>
</nav>}
<div className="dialog-body">
{err && <div className="notice notice-error">{err}</div>}
{err && <div className="notice notice-error" role="alert">{err}</div>}
{restoreTask && (
<div role="status" className="hstack">
<span>{taskTitle(locale, restoreTask)}</span>
<progress aria-label={taskTitle(locale, restoreTask)} max={100} value={restoreTask.percent >= 0 ? restoreTask.percent : undefined} />
</div>
)}
<div key={step} className="step-anim">
{step === 1 && (
@@ -324,6 +331,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<SetGroup title={tr('wizardDriverGroup')}>
<SetRow
title={tr('wizardDriverType')}
disabled={driverCreating}
control={
<PopupSelect
label={tr('wizardDriverType')}
@@ -332,27 +340,46 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
value: d.id,
label: locText(d.name, locale, d.id),
}))}
onChange={(id) => { setDriverID(id); setErr('') }}
onChange={(id) => { setDriverID(id); setDriverOpts({}); setRestorePath(''); setErr('') }}
/>
}
/>
</SetGroup>
)}
{isCustomDriver ? (
{!activeDriver ? <div className="notice notice-error" role="alert">{tr('wizardNoDriver')}</div> : !legacyDriver ? (
<div className="stack-3">
{restoreField && <RestoreImageSource
key={activeDriver.id}
locale={locale}
host={host}
tasks={tasks}
initialImage={draft?.restoreImage}
disabled={driverCreating}
selectedPath={restorePath}
onPathChange={updateRestorePath}
onCancelTask={onCancelTask}
/>}
<SetGroup title={tr('wizardBasics')}>
<SetRow
title={tr('vmName')}
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
disabled={driverCreating}
control={<input aria-label={tr('vmName')} className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
/>
</SetGroup>
{activeDriver.create_schema && (
<Suspense fallback={null}>
<SchemaForm
key={activeDriver.id}
locale={locale}
schema={activeDriver.create_schema}
values={driverOpts}
disabled={driverCreating}
hideFields={restoreField ? [restoreField] : undefined}
onChange={setDriverOpts}
filePicker={activeDriver.builtin ? {
supports: (prop) => hasRestoreImagePicker(activeDriver, prop),
pick: (label) => api.PickFile(label, '*.ipsw'),
} : undefined}
/>
</Suspense>
)}
@@ -703,7 +730,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
{networkAdapters?.length === 0 && <span className="muted">{tr('bridgeNoAdapters')}</span>}
</div>} />}
{networkMode === 'bridge' && <>
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking || driverCreating} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
<NpcapDependency plan={networkPlan} locale={locale} disabled={checking} onBusy={setDependencyBusy} onInstalled={() => setDependencyRefresh((value) => value + 1)} />
{networkPlanning && <div className="srow-desc" role="status">{tr('bridgePlanPending')}</div>}
<NetworkErrorNotice error={networkPlanError} locale={locale} />
</>}
@@ -779,26 +806,39 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</div>
<div className="dialog-foot">
<Button variant="ghost" disabled={step === 1 || isCustomDriver} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
{isCustomDriver ? (
{legacyDriver && <Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>}
{restoreTask && (
<Button variant="ghost" busy={canceling} disabled={canceling} onClick={async () => {
setCanceling(true)
try {
await onCancelTask(restoreTask.id)
} catch (e) {
setErr(parseAppError(e).summary)
setCanceling(false)
}
}}>
{taskStopAction(locale, restoreTask).label}
</Button>
)}
{!legacyDriver ? (
<Button
variant="primary"
busy={driverCreating}
disabled={!opts.name.trim() || driverCreating}
disabled={!activeDriver || !opts.name.trim() || driverCreating || (!!restoreField && !restorePath.trim())}
onClick={async () => {
const name = opts.name.trim()
setDriverCreating(true)
setErr('')
try {
await api.CreateVMWithDriver({
driver_id: driverID,
name: opts.name.trim(),
dir: opts.dir,
options: driverOpts,
})
const options = restoreField ? { ...driverOpts, [restoreField]: restorePath.trim() } : driverOpts
await api.CreateVMWithDriver({ driver_id: driverID, name, dir: opts.dir, options })
onDriverCreated(driverID, name)
onClose()
} catch (e) {
setErr(parseAppError(e).summary)
const message = parseAppError(e).summary
setErr(/\bcontext canceled\b/i.test(message) ? tr('toastCreateCanceled', { name }) : message)
} finally {
setCanceling(false)
setDriverCreating(false)
}
}}
+28 -16
View File
@@ -5,6 +5,7 @@ import '../i18n/domains/wizard.gen'
import { I18nKey, t } from '../i18n'
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { isAppleSilicon } from '../lib/guestDrivers'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Switch } from '../ui/settings'
@@ -17,6 +18,7 @@ interface Props {
locale: Locale
onRefresh: () => Promise<void>
onNewVM?: () => void
hostReady: boolean
onError: (title: string, e: unknown) => void
onToast?: (title: string) => void
runtimeTask: Task | null
@@ -26,7 +28,7 @@ interface Props {
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, hostReady, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [savingASLR, setSavingASLR] = useState(false)
@@ -43,7 +45,13 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
return () => { live = false }
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
const whpx = describeHostWHPX(locale, host)
const nativeHost = isAppleSilicon(host)
const virtualization = nativeHost ? {
short: tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
hint: host.apple_virtualization?.detail,
tone: hostReady ? 'ok' : 'warn',
canEnable: false,
} : describeHostWHPX(locale, host)
const guard = (fn: () => Promise<unknown>) => async () => {
try {
@@ -111,7 +119,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
</div>
</header>
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
{(state.vms?.length ?? 0) === 0 && hostReady && onNewVM && (
<section className="welcome-card">
<h1>{tr('welcomeTitle')}</h1>
<p>{tr('welcomeSub')}</p>
@@ -124,14 +132,14 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<div className="tiles">
<div className="tile">
<div className="tile-head">
<span className={`tile-icon ${whpx.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
{tr('whpxTitle')}
<span className={`tile-icon ${virtualization.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
{tr(nativeHost ? 'appleVirtualizationTitle' : 'whpxTitle')}
</div>
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
{whpx.canEnable ? (
<div className={`tile-value ${virtualization.tone}`}>{virtualization.short}</div>
{virtualization.canEnable ? (
<Button variant="primary" className="tile-action" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
) : whpx.hint ? (
<div className="tile-sub" title={whpx.hint}>{whpx.hint}</div>
) : virtualization.hint ? (
<div className="tile-sub" title={virtualization.hint}>{virtualization.hint}</div>
) : null}
</div>
<div className="tile">
@@ -149,13 +157,17 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
<span className="tile-icon accent" aria-hidden="true"><MemoryStick size={13} /></span>
{tr('hostRAM')}
</div>
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
<div className="tile-sub">
<div className="tile-value">
{host.memory_usage_known
? tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })
: host.total_ram_gb > 0 ? tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) }) : '—'}
</div>
{host.memory_usage_known && <div className="tile-sub">
{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
{host.memory_spec?.speed_mhz
? ` · ${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
: ''}
</div>
</div>}
</div>
<div className="tile">
<div className="tile-head">
@@ -201,7 +213,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
)
})()}
<section className="section">
{!nativeHost && <section className="section">
<div className="section-title">
{tr('hostRuntime')}
<Button variant="ghost" busy={importing} onClick={importRuntime}>
@@ -266,9 +278,9 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
</div>
))}
</div>
</section>
</section>}
<section className="section">
{!nativeHost && <section className="section">
<div className="section-title">{tr('hostGPUs')}</div>
<div className="list">
{realGPUs.length === 0 ? (
@@ -296,7 +308,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
})
)}
</div>
</section>
</section>}
{(host.displays?.length ?? 0) > 0 && (
<section className="section">
<div className="section-title">{tr('hostDisplays')}</div>
+2 -8
View File
@@ -111,13 +111,7 @@ export const LogPanel: React.FC<Props> = ({
const content = tab === 'app' ? filteredLines : filteredText
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
const memPct = host
? Math.max(0, Math.min(100, host.memory_load_pct > 0
? host.memory_load_pct
: host.total_ram_gb > 0
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
: 0))
: 0
const memPct = Math.max(0, Math.min(100, host?.memory_load_pct ?? 0))
const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0
const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : ''
const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30
@@ -247,7 +241,7 @@ export const LogPanel: React.FC<Props> = ({
</button>
</Tip>
)}
{host.total_ram_gb > 0 && (
{host.memory_usage_known && host.total_ram_gb > 0 && (
<Tip
side="top"
label={tr('footerMemTip', {
@@ -0,0 +1,137 @@
import { CloudDownload, Disc3, Download, Pause, X } from 'lucide-react'
import { useEffect, useLayoutEffect, useState } from 'react'
import '../i18n/domains/settings.gen'
import '../i18n/domains/wizard.gen'
import { parseAppError, t } from '../i18n'
import { cachedRestoreImage, matchesRestoreImage, restoreImageChoiceKey, restoreImageChoices } from '../lib/restoreImages'
import { findActiveInstallerTask, taskDetail, taskInstallerKind, taskInstallerPhase, taskStopAction } from '../lib/tasks'
import type { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect, SetGroup, SetRow } from '../ui/settings'
import { api } from '../wails'
type Source = 'apple' | 'local'
interface Props {
locale: Locale
host: HostReport
tasks: Task[]
initialImage?: CachedInstaller
disabled: boolean
selectedPath: string
onPathChange: (path: string) => void
onCancelTask: (id: string) => Promise<void>
}
export function RestoreImageSource({ locale, host, tasks, initialImage, disabled, selectedPath, onPathChange, onCancelTask }: Props) {
const [source, setSource] = useState<Source>('apple')
const [localPath, setLocalPath] = useState('')
const [cached, setCached] = useState<CachedInstaller[]>(() => initialImage ? [initialImage] : [])
const [latest, setLatest] = useState<Release | null>()
const [selection, setSelection] = useState(() => initialImage?.version ? restoreImageChoiceKey(initialImage.version, initialImage.build ?? '') : '')
const [releaseErr, setReleaseErr] = useState('')
const [cacheErr, setCacheErr] = useState('')
const [actionErr, setActionErr] = useState('')
const [catalogRequest, setCatalogRequest] = useState(0)
const [pending, setPending] = useState<'download' | 'stop' | 'file' | ''>('')
const tr = (key: Parameters<typeof t>[1], vars?: Record<string, string | number>) => t(locale, key, vars)
const tasksSig = tasks.filter((task) => taskInstallerKind(task) === 'ipsw')
.map((task) => `${task.id}:${task.status}:${task.installer_phase}`).join('|')
useEffect(() => {
if (source !== 'apple') return
let live = true
api.ListInstallers().then((items) => {
if (!live) return
setCacheErr('')
setCached(items ?? [])
}).catch((error) => { if (live) setCacheErr(parseAppError(error).summary) })
return () => { live = false }
}, [source, tasksSig, catalogRequest])
useEffect(() => {
if (source !== 'apple') return
let live = true
setReleaseErr('')
setLatest(undefined)
api.ListOfflineReleases().then((items) => {
if (live) setLatest(items?.[0] ?? null)
}).catch((error) => {
if (!live) return
setLatest(null)
setReleaseErr(parseAppError(error).summary)
})
return () => { live = false }
}, [source, catalogRequest])
const choices = restoreImageChoices(latest ?? undefined, cached)
const selected = choices.find((choice) => choice.key === selection) ?? choices[0]
const complete = selected && cachedRestoreImage(cached, selected.version, selected.build)
const currentRelease = selected && latest?.version === selected.version && latest.build === selected.build ? latest : undefined
const active = currentRelease && findActiveInstallerTask(tasks, 'ipsw', currentRelease.version)?.primary
const partial = currentRelease && cached.find((item) => item.partial && matchesRestoreImage(item, currentRelease.version, currentRelease.build))
const needGB = currentRelease?.size ? Math.max(0, currentRelease.size - (partial?.bytes ?? 0)) / (2 ** 30) : 0
const lowSpace = needGB > 0 && !complete && !active && host.free_disk_gb > 0 && host.free_disk_gb < needGB
const local = source === 'local'
const path = local ? localPath : complete?.path ?? ''
// Update the parent submit control before the new selection is painted.
useLayoutEffect(() => { if (selectedPath !== path) onPathChange(path) }, [path, selectedPath, onPathChange])
const doAction = async (action: Exclude<typeof pending, ''>, fn: () => Promise<void>) => {
setPending(action)
setActionErr('')
try {
await fn()
} catch (error) {
setActionErr(parseAppError(error).summary)
} finally {
setPending('')
}
}
return (
<>
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
{(['apple', 'local'] as const).map((mode) => {
const apple = mode === 'apple'
const Icon = apple ? CloudDownload : Disc3
return <label key={mode} className="source-card" data-selected={source === mode || undefined}>
<input type="radio" name="restore-source" checked={source === mode} disabled={disabled} onChange={() => { setActionErr(''); setSource(mode) }} />
<span className={`source-icon source-icon-${apple ? 'apple' : 'installer'}`} aria-hidden="true"><Icon size={20} /></span>
<span className="source-title">{tr(apple ? 'srcIPSWDownloadTitle' : 'srcIPSWLocalTitle')}</span>
<span className="source-sub">{tr(apple ? 'srcIPSWDownloadSub' : 'srcIPSWLocalSub')}</span>
</label>
})}
</div>
{actionErr && <div className="notice notice-error" role="alert">{actionErr}</div>}
{local ? <SetGroup>
<SetRow title={tr('srcIPSWLocalTitle')} disabled={disabled} control={
<div className="input-group">
<input className="input rg-p-input mono" value={localPath} aria-label={tr('srcIPSWLocalTitle')} onChange={(e) => setLocalPath(e.target.value)} />
<Button busy={pending === 'file'} disabled={!!pending} onClick={() => doAction('file', async () => {
const file = await api.PickFile(tr('srcIPSWLocalTitle'), '*.ipsw')
if (file) setLocalPath(file)
})}>{tr('wizChooseFile')}</Button>
</div>
} />
</SetGroup> : <SetGroup>
{choices.length > 0 && <SetRow title={tr('macosVersion')} disabled={disabled} control={
<PopupSelect label={tr('macosVersion')} value={selected?.key ?? ''} onChange={setSelection} options={choices.map((choice) => ({ value: choice.key, label: choice.label }))} />
} />}
{active ? <SetRow title={tr(taskInstallerPhase(active) === 'queued' ? 'offlineQueued' : 'offlineDownloading')} desc={taskDetail(active)} disabled={disabled} control={
<div className="hstack" role="status">
<progress aria-label={tr('offlineDownloading')} max={100} value={active.percent >= 0 ? active.percent : undefined} />
{active.cancelable && <Button icon={taskStopAction(locale, active).kind === 'pause' ? <Pause size={14} /> : <X size={14} />} busy={pending === 'stop'} disabled={!!pending} onClick={() => doAction('stop', () => onCancelTask(active.id))}>{taskStopAction(locale, active).label}</Button>}
</div>
} /> : complete ? <SetRow title={tr('offlineCached')} desc={selected?.label} /> : currentRelease && <SetRow title={tr('srcIPSWDownloadTitle')} disabled={disabled} desc={lowSpace ? tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: Math.ceil(needGB) }) : undefined} control={
<Button icon={<Download size={14} />} busy={pending === 'download'} disabled={!!pending || lowSpace} onClick={() => doAction('download', async () => { await api.DownloadInstaller(currentRelease.version) })}>{tr(partial ? 'installersResume' : 'installersDownload')}</Button>
} />}
{(releaseErr || cacheErr) && <div className="notice notice-error hstack" role="alert">
<span>{releaseErr || cacheErr}</span>
<Button onClick={() => setCatalogRequest((id) => id + 1)}>{tr('installersRetry')}</Button>
</div>}
{!releaseErr && latest === undefined && !complete && <p className="hint" role="status">{tr('offlineLoading')}</p>}
{!releaseErr && latest === null && choices.length === 0 && <p className="hint">{tr('srcIPSWNone')}</p>}
</SetGroup>}
</>
)
}
+33 -4
View File
@@ -1,8 +1,10 @@
import React from 'react'
import React, { useState } from 'react'
import { FolderOpen } from 'lucide-react'
import '../i18n/domains/plugins.gen'
import '../i18n/domains/settings.gen'
import { locText, t } from '../i18n'
import { locText, parseAppError, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { Button } from '../ui/controls'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
interface Props {
@@ -13,6 +15,10 @@ interface Props {
groupFilter?: string
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
hideGroupHeader?: boolean
hideFields?: readonly string[]
disabled?: boolean
/** Only the trusted driver's create form supplies a native file picker. */
filePicker?: { supports: (prop: SettingProperty) => boolean; pick: (label: string) => Promise<string> }
}
const SECRET_MASK = '••••••••'
@@ -20,13 +26,16 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
export const SchemaForm: React.FC<Props> = ({
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, hideFields, disabled, filePicker,
}) => {
const [picking, setPicking] = useState('')
const [pickError, setPickError] = useState<{ key: string; text: string } | null>(null)
const propsMap = schema.properties ?? {}
const keys = (schema['x-order'] && schema['x-order'].length > 0
? schema['x-order'].filter((k) => !FORBIDDEN_KEYS.has(k) && Object.prototype.hasOwnProperty.call(propsMap, k))
: Object.keys(propsMap).filter((k) => !FORBIDDEN_KEYS.has(k))
).filter((k) => {
if (hideFields?.includes(k)) return false
const prop = propsMap[k]
const effScope = prop['x-scope'] || schema['x-scope'] || 'app'
const effGroup = prop['x-group'] || schema['x-group'] || ''
@@ -134,7 +143,7 @@ export const SchemaForm: React.FC<Props> = ({
)
}
return (
const textInput = (
<input
type="text"
className="input rg-p-input"
@@ -143,6 +152,24 @@ export const SchemaForm: React.FC<Props> = ({
onChange={(e) => setKey(k, e.target.value)}
/>
)
if (!filePicker?.supports(prop)) return textInput
return (
<div className="input-group">
{textInput}
<Button icon={<FolderOpen size={14} />} busy={picking === k} disabled={!!picking} onClick={async () => {
setPicking(k)
setPickError(null)
try {
const path = await filePicker.pick(label)
if (path) setKey(k, path)
} catch (e) {
setPickError({ key: k, text: parseAppError(e).summary })
} finally {
setPicking('')
}
}}>{t(locale, 'choose')}</Button>
</div>
)
}
const rows = keys.map((k) => {
@@ -154,6 +181,8 @@ export const SchemaForm: React.FC<Props> = ({
<SetRow
key={k}
title={title}
disabled={disabled}
error={pickError?.key === k ? pickError.text : undefined}
desc={badge || desc ? <span className="hstack">{badge}{desc ? <span>{desc}</span> : null}</span> : undefined}
control={renderControl(k, prop)}
/>
+60 -141
View File
@@ -1,49 +1,23 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, PanelLeft } from 'lucide-react'
import React, { useRef, useState } from 'react'
import { I18nKey, localeDir, t } from '../i18n'
import { localeDir, t } from '../i18n'
import { hasVisibleDialog } from '../lib/dialogState'
import { VMFeatures, vmFeatures } from '../lib/endpoints'
import { buildTitleMenus, MENU_IDS, runMenuCommand, type MenuId, type MenuRow, type TitleMenuProps } from '../lib/titleMenu'
import { useVMStats } from '../lib/vmStats'
import { Locale, VMAction } from '../types'
import { Tip } from '../ui/controls'
import type { ThemeMode } from '../lib/useAppearance'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
/** A page on reims.dev in the UI language: Chinese at the root, every other locale under /en. */
export function siteURL(locale: Locale, path = ''): string {
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
return path ? `${base}${path}` : `${base}/`
}
const MENU_IDS = ['vm', 'view', 'help'] as const
type MenuId = (typeof MENU_IDS)[number]
const HOVER_CLICK_GUARD_MS = 300
interface Props {
locale: Locale
sidebarOpen: boolean
onToggleSidebar: () => void
logsOpen: boolean
onToggleLogs: () => void
themeMode: ThemeMode
canLight?: boolean
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. `features` gates actions by driver capabilities (default: everything a macOS VM offers). */
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean; features?: VMFeatures } | null
/** Active global fullscreen toggle shortcut when enabled, else undefined. */
fullscreenHotkey?: string
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
onVMDelete: () => void
onNavigate: (id: string) => void
onOpenURL: (url: string) => void
appVersion: string
export function SidebarToggle({ locale, sidebarOpen, onToggleSidebar, mac, disabled }: Pick<TitleMenuProps, 'locale' | 'sidebarOpen' | 'onToggleSidebar'> & { mac?: boolean; disabled?: boolean }) {
const label = t(locale, sidebarOpen ? 'hideSidebar' : 'showSidebar')
return (
<Tip label={label} shortcut={mac ? '⌘B' : 'Ctrl+B'} disabled={disabled}>
<button type="button" className="titlebar-icon" aria-label={label} aria-pressed={sidebarOpen} onClick={onToggleSidebar}>
<PanelLeft size={16} aria-hidden="true" />
</button>
</Tip>
)
}
/**
@@ -52,11 +26,8 @@ interface Props {
* discoverable and still reachable with the sidebar hidden. Once one menu is
* open, hovering the next title switches to it, as in a native menu bar.
*/
export const TitleMenus: React.FC<Props> = ({
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, canLight = true, canDark = true, onThemeMode,
vm, fullscreenHotkey, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
export const TitleMenus: React.FC<TitleMenuProps> = (props) => {
const { locale, vm, themeMode } = props
const [menuState, setMenuState] = useState<{ id: MenuId | null; switched: boolean }>({ id: null, switched: false })
const openRef = useRef<MenuId | null>(null)
const navRef = useRef<HTMLElement>(null)
@@ -70,36 +41,55 @@ export const TitleMenus: React.FC<Props> = ({
}
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const vmBusy = !vm || vm.busy
const features = vm?.features ?? vmFeatures(null)
const canFullscreen = running && features.fullscreen && vm?.graphics !== 'vmware-svga'
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
const fullscreenLabel = !canFullscreen || !stats?.running
? tr('toggleFullscreen')
: stats.window_fullscreen
? tr('exitFullscreen')
: tr('enterFullscreen')
const stats = useVMStats(vm?.driver_id ?? '', running && vm.features.fullscreen && vm.graphics !== 'vmware-svga' ? vm.name : null, running)
const menus = buildTitleMenus(props, stats?.running ? stats.window_fullscreen : undefined)
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
<Menu.Item className={`menu-item rg-p-menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
<span className="menu-label">{label}</span>
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
</Menu.Item>
)
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
<Menu.CheckboxItem className="menu-item rg-p-menu-item menu-item-check" checked={checked} onSelect={onSelect}>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{label}</span>
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
</Menu.CheckboxItem>
)
const renderRow = (row: MenuRow, index: number) => {
if (row.kind === 'separator') return <Menu.Separator key={index} className="menu-sep" />
if (row.kind === 'label') return <Menu.Label key={index} className="menu-group-label">{row.label}</Menu.Label>
const onSelect = () => runMenuCommand(props, row.command)
const label = <span className="menu-label">{row.label}</span>
const shortcut = row.shortcut && <kbd className="menu-shortcut">{row.shortcut}</kbd>
const indicator = <Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
if (row.kind === 'radio') return (
<Menu.RadioItem key={row.command} className="menu-item rg-p-menu-item menu-item-check" value={row.command} disabled={row.disabled}>
{indicator}{label}
</Menu.RadioItem>
)
if (row.kind === 'check') return (
<Menu.CheckboxItem key={row.command} className="menu-item rg-p-menu-item menu-item-check" checked={row.checked} disabled={row.disabled} onSelect={onSelect}>
{indicator}{label}{shortcut}
</Menu.CheckboxItem>
)
return (
<Menu.Item key={row.command} className={`menu-item rg-p-menu-item${row.danger ? ' danger' : ''}`} disabled={row.disabled} onSelect={onSelect}>
{label}{shortcut}
</Menu.Item>
)
}
const renderRows = (rows: MenuRow[]) => {
const firstRadio = rows.findIndex((row) => row.kind === 'radio')
if (firstRadio === -1) return rows.map(renderRow)
const radioRows = rows.filter((row) => row.kind === 'radio')
return (
<>
{rows.slice(0, firstRadio).map(renderRow)}
<Menu.RadioGroup value={`theme:${themeMode}`} onValueChange={(value) => {
const row = radioRows.find((entry) => entry.kind === 'radio' && entry.command === value)
if (row?.kind === 'radio') runMenuCommand(props, row.command)
}}>
{radioRows.map(renderRow)}
</Menu.RadioGroup>
{rows.slice(firstRadio + radioRows.length).map((row, i) => renderRow(row, firstRadio + radioRows.length + i))}
</>
)
}
// `indented`: the menu has check marks, so every row shares their indent.
const menu = (id: MenuId, label: string, content: React.ReactNode, indented = false) => (
<Menu.Root
key={id}
dir={localeDir(locale)}
modal={false}
open={menuState.id === id}
@@ -214,80 +204,9 @@ export const TitleMenus: React.FC<Props> = ({
return (
<div className="titlebar-left" onDoubleClick={(e) => e.stopPropagation()}>
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B" disabled={menuState.id !== null}>
<button
type="button"
className="titlebar-icon"
aria-label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')}
aria-pressed={sidebarOpen}
onClick={onToggleSidebar}
>
<PanelLeft size={16} aria-hidden="true" />
</button>
</Tip>
<nav ref={navRef} className="titlebar-menus" aria-label={tr('menuBar')}>
{menu('vm', tr('menuVM'), (
<>
{item(tr('newVMEllipsis'), onNewVM, { shortcut: 'Ctrl+N' })}
<Menu.Separator className="menu-sep" />
{running
? (features.window && item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }))
: suspended
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
{features.fullscreen && item(fullscreenLabel, () => onVMAction('fullscreen'), { shortcut: fullscreenHotkey, disabled: vmBusy || !canFullscreen })}
{features.suspend && item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
{features.screenshot && item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
<Menu.Separator className="menu-sep" />
{features.macos && item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })}
{features.macos && item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
<Menu.Separator className="menu-sep" />
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })}
</>
))}
{menu('view', tr('menuView'), (
<>
{check(tr('sidebarLabel'), sidebarOpen, onToggleSidebar, 'Ctrl+B')}
{check(tr('logButton'), logsOpen, onToggleLogs, 'Ctrl+L')}
<Menu.Separator className="menu-sep" />
<Menu.Label className="menu-group-label">{tr('appearance')}</Menu.Label>
<Menu.RadioGroup value={themeMode} onValueChange={(v) => onThemeMode(v as ThemeMode)}>
{(['light', 'dark', 'system'] as const).map((m) => (
<Menu.RadioItem
key={m}
className="menu-item rg-p-menu-item menu-item-check"
value={m}
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{tr(m === 'light' ? 'themeLight' : m === 'dark' ? 'themeDark' : 'themeSystem')}</span>
</Menu.RadioItem>
))}
</Menu.RadioGroup>
<Menu.Separator className="menu-sep" />
{item(tr('sidebarInstallers'), () => onNavigate(INSTALLERS_ID))}
{item(tr('sidebarPlugins'), () => onNavigate(PLUGINS_ID))}
{item(tr('sidebarHost'), () => onNavigate(HOST_ID))}
{item(tr('sidebarSettings'), () => onNavigate(SETTINGS_ID))}
</>
), true)}
{menu('help', tr('menuHelp'), (
<>
{item(tr('helpWebsite'), () => onOpenURL(siteURL(locale)))}
{item(tr('helpDocs'), () => onOpenURL(siteURL(locale, '/docs/quick-start')))}
{item(tr('helpProjectPage'), () => onOpenURL(REPO_URL))}
{item(tr('helpReportIssue'), () => onOpenURL(`${REPO_URL}/issues`))}
{item(tr('helpCheckUpdate'), () => onNavigate(ABOUT_ID))}
{item(tr('helpAbout'), () => onNavigate(ABOUT_ID))}
<Menu.Separator className="menu-sep" />
<Menu.Label className="menu-group-label">Reims-Go {appVersion}</Menu.Label>
</>
))}
<SidebarToggle {...props} disabled={menuState.id !== null} />
<nav ref={navRef} className="titlebar-menus" aria-label={t(locale, 'menuBar')}>
{MENU_IDS.map((id) => menu(id, menus[id].label, renderRows(menus[id].rows), id === 'view'))}
</nav>
</div>
)
+20 -25
View File
@@ -31,7 +31,7 @@ import {
endpointKey,
guestFamilyOf,
isMacOSDriver as isMacOSDriverID,
splitEndpoints,
primaryVMAccess,
vmFeatures,
} from '../lib/endpoints'
import { useVMStats } from '../lib/vmStats'
@@ -163,9 +163,8 @@ export const VMPage: React.FC<Props> = ({
const guestArt = !isMacOSDriver && hasGuestArt(guestFamily)
const phase = vmInfo?.phase
const waitingForGuest = running && vmInfo?.ready === false
// A running hosted VM has no window: its best ready endpoint is the header action.
const { primary: bestEndpoint } = splitEndpoints(vmInfo?.endpoints)
const promotedEndpoint = features.hosted && running ? bestEndpoint : undefined
const access = running ? primaryVMAccess(features, vmInfo?.endpoints) : undefined
const promotedEndpoint = access?.kind === 'endpoint' ? access.endpoint : undefined
const endpoints = useEndpointActions({ locale, driverID, name, onCopy, onError })
const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = endpoints
// Polled here rather than in App so each tick re-renders only this page.
@@ -242,27 +241,23 @@ export const VMPage: React.FC<Props> = ({
primary = <Button variant="primary" busy>{tr('state_resuming')}</Button>
} else if (running) {
const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow')
if (features.hosted) {
// No window to show: the header action is the best ready endpoint, and with none ready there is no
// primary action at all (a disabled button never takes the primary slot).
if (promotedEndpoint) {
const action = defaultEndpointAction(promotedEndpoint.kind)
const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind)
primary = (
<Tip label={label} shortcut={PRIMARY_SHORTCUT}>
<Button
variant="primary"
icon={endpointIcon(promotedEndpoint.kind, 14)}
busy={endpointBusy === `${endpointKey(promotedEndpoint)}:`}
disabled={busy}
onClick={() => runEndpointAction(promotedEndpoint, '')}
>
{label}
</Button>
</Tip>
)
}
} else {
if (promotedEndpoint) {
const action = defaultEndpointAction(promotedEndpoint.kind)
const label = action ? endpointActionLabel(promotedEndpoint.kind, action) : endpointKindLabel(promotedEndpoint.kind)
primary = (
<Tip label={label} shortcut={PRIMARY_SHORTCUT}>
<Button
variant="primary"
icon={endpointIcon(promotedEndpoint.kind, 14)}
busy={endpointBusy === `${endpointKey(promotedEndpoint)}:`}
disabled={busy}
onClick={() => runEndpointAction(promotedEndpoint, '')}
>
{label}
</Button>
</Tip>
)
} else if (access?.kind === 'window') {
primary = (
<Tip label={showLabel} shortcut={PRIMARY_SHORTCUT}>
<Button variant="primary" icon={<AppWindow size={14} aria-hidden="true" />} busy={busyAction === 'focus'} disabled={busy} onClick={() => onAction('focus')}>
+44 -2
View File
@@ -12,7 +12,7 @@ export const coreZh: Record<string, string> = {
"clear": "清空",
"close": "关闭",
"closeDownloadsConfirm": "退出",
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
"closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。",
"closeDownloadsTitle": "退出 Reims-Go?",
"closeWindow": "关闭",
"collapseLogs": "收起日志",
@@ -121,6 +121,24 @@ export const coreZh: Record<string, string> = {
"maximize": "最大化",
"menuBar": "菜单栏",
"menuHelp": "帮助",
"menuMacCut": "剪切",
"menuMacDelete": "删除",
"menuMacEdit": "编辑",
"menuMacFullScreen": "进入全屏幕",
"menuMacHide": "隐藏 Reims-Go",
"menuMacHideOthers": "隐藏其他应用",
"menuMacPaste": "粘贴",
"menuMacPasteMatchStyle": "粘贴并匹配样式",
"menuMacQuit": "退出 Reims-Go",
"menuMacRedo": "重做",
"menuMacSelectAll": "全选",
"menuMacShowAll": "显示全部",
"menuMacSpeech": "朗读",
"menuMacStartSpeaking": "开始朗读",
"menuMacStopSpeaking": "停止朗读",
"menuMacUndo": "撤销",
"menuMacWindow": "窗口",
"menuMacZoom": "缩放",
"menuVM": "虚拟机",
"menuView": "视图",
"minimize": "最小化",
@@ -172,6 +190,7 @@ export const coreZh: Record<string, string> = {
"taskDownload": "下载 macOS {v}",
"taskPluginDownload": "下载 {name}",
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
"taskRestoreVM": "在 {name} 上安装 macOS",
"taskRuntime": "安装运行时 {v}",
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
"themeDark": "深色",
@@ -213,6 +232,8 @@ export const coreZh: Record<string, string> = {
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
"uptimeSeconds": "{s} 秒",
"viewLogs": "查看日志",
"wizardDriverListFailed": "无法加载客体驱动",
"wizardNoDriver": "没有可用的客体驱动",
}
export const coreEn: Record<string, string> = {
@@ -227,7 +248,7 @@ export const coreEn: Record<string, string> = {
"clear": "Clear",
"close": "Close",
"closeDownloadsConfirm": "Quit",
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
"closeDownloadsDesc": "Quitting stops any downloads or macOS installations in progress.",
"closeDownloadsTitle": "Quit Reims-Go?",
"closeWindow": "Close",
"collapseLogs": "Hide logs",
@@ -336,6 +357,24 @@ export const coreEn: Record<string, string> = {
"maximize": "Maximize",
"menuBar": "Menu bar",
"menuHelp": "Help",
"menuMacCut": "Cut",
"menuMacDelete": "Delete",
"menuMacEdit": "Edit",
"menuMacFullScreen": "Enter Full Screen",
"menuMacHide": "Hide Reims-Go",
"menuMacHideOthers": "Hide Others",
"menuMacPaste": "Paste",
"menuMacPasteMatchStyle": "Paste and Match Style",
"menuMacQuit": "Quit Reims-Go",
"menuMacRedo": "Redo",
"menuMacSelectAll": "Select All",
"menuMacShowAll": "Show All",
"menuMacSpeech": "Speech",
"menuMacStartSpeaking": "Start Speaking",
"menuMacStopSpeaking": "Stop Speaking",
"menuMacUndo": "Undo",
"menuMacWindow": "Window",
"menuMacZoom": "Zoom",
"menuVM": "VM",
"menuView": "View",
"minimize": "Minimize",
@@ -387,6 +426,7 @@ export const coreEn: Record<string, string> = {
"taskDownload": "Downloading macOS {v}",
"taskPluginDownload": "Downloading {name}",
"taskRecoveryDownload": "Downloading online recovery for {name}",
"taskRestoreVM": "Installing macOS on {name}",
"taskRuntime": "Installing runtime {v}",
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
"themeDark": "Dark",
@@ -428,4 +468,6 @@ export const coreEn: Record<string, string> = {
"uptimeMinutesSeconds": "{m}m {s}s",
"uptimeSeconds": "{s}s",
"viewLogs": "View logs",
"wizardDriverListFailed": "Could not load guest drivers",
"wizardNoDriver": "No eligible guest driver is available",
}
+12 -6
View File
@@ -15,9 +15,10 @@ export const settingsZh: Record<string, string> = {
"aboutLicensesTitle": "开源许可与声明",
"aboutLicensesView": "查看",
"aboutQQGroup": "QQ 交流群",
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
"aboutQQNotInstalled": "未安装 QQ",
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
"aboutQQLaunchFailed": "未能打开 QQ,可打开邀请页或复制群号",
"aboutQQNotInstalled": "无法直接打开 QQ",
"aboutQQNotInstalledSub": "未找到可处理加群链接的 QQ,可打开邀请页或复制群号",
"aboutQQOpenInvite": "打开邀请页",
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
"activate": "使用",
"affinityApplyNow": "立即应用",
@@ -66,6 +67,7 @@ export const settingsZh: Record<string, string> = {
"appUpdateChannelTitle": "更新通道",
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
"appVersionTitle": "客户端版本",
"appleVirtualizationTitle": "Apple 虚拟化",
"appliesNextStart": "下次启动生效",
"audioBackendAuto": "自动",
"audioBackendDesc": "「静音」保留 macOS 的声卡但不出声,适合排查音频问题",
@@ -345,6 +347,7 @@ export const settingsZh: Record<string, string> = {
"imagesOpenPlugins": "前往插件",
"imagesSourcesLabel": "镜像来源",
"installersAvailable": "Apple 提供的版本",
"installersCacheUnavailable": "缓存镜像不可用",
"installersCreateVM": "新建虚拟机",
"installersDelete": "删除",
"installersDeleteConfirm": "确认删除",
@@ -531,9 +534,10 @@ export const settingsEn: Record<string, string> = {
"aboutLicensesTitle": "Open-source licenses",
"aboutLicensesView": "View",
"aboutQQGroup": "QQ Group",
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
"aboutQQNotInstalled": "QQ not installed",
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
"aboutQQLaunchFailed": "Couldn’t open QQ — open the invite page or copy the group ID",
"aboutQQNotInstalled": "Can’t open QQ directly",
"aboutQQNotInstalledSub": "No QQ app can handle the invite link — open the invite page or copy the group ID",
"aboutQQOpenInvite": "Open invite page",
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
"activate": "Use",
"affinityApplyNow": "Apply Now",
@@ -582,6 +586,7 @@ export const settingsEn: Record<string, string> = {
"appUpdateChannelTitle": "Update channel",
"appUpdateLookupFailed": "Couldn’t check GitHub for updates",
"appVersionTitle": "App version",
"appleVirtualizationTitle": "Apple Virtualization",
"appliesNextStart": "Applies on next start",
"audioBackendAuto": "Auto",
"audioBackendDesc": "Silent keeps the macOS sound card but plays nothing; useful for troubleshooting",
@@ -861,6 +866,7 @@ export const settingsEn: Record<string, string> = {
"imagesOpenPlugins": "Open Plugins",
"imagesSourcesLabel": "Image sources",
"installersAvailable": "Releases from Apple",
"installersCacheUnavailable": "Cached image unavailable",
"installersCreateVM": "Create VM",
"installersDelete": "Delete",
"installersDeleteConfirm": "Confirm delete",
+10
View File
@@ -59,6 +59,11 @@ export const wizardZh: Record<string, string> = {
"srcAppleTitle": "从 Apple 下载",
"srcDiskSub": "已装好 macOS 的 .qcow2 等磁盘",
"srcDiskTitle": "已有磁盘",
"srcIPSWDownloadSub": "从 Apple 下载或使用已下载的镜像",
"srcIPSWDownloadTitle": "兼容恢复镜像",
"srcIPSWLocalSub": "选择这台 Mac 上的 .ipsw 文件",
"srcIPSWLocalTitle": "本地恢复镜像",
"srcIPSWNone": "没有兼容的恢复镜像",
"srcInstallerSub": "本机上的 .img 或 .dmg",
"srcInstallerTitle": "安装镜像",
"srcOfflineSub": "完整安装包,装机时不联网",
@@ -150,6 +155,11 @@ export const wizardEn: Record<string, string> = {
"srcAppleTitle": "Download from Apple",
"srcDiskSub": "A .qcow2 or other disk with macOS installed",
"srcDiskTitle": "Existing disk",
"srcIPSWDownloadSub": "Download from Apple or use a saved restore image",
"srcIPSWDownloadTitle": "Compatible restore image",
"srcIPSWLocalSub": "Choose an .ipsw file on this Mac",
"srcIPSWLocalTitle": "Local restore image",
"srcIPSWNone": "No compatible restore image is available",
"srcInstallerSub": "An .img or .dmg on this PC",
"srcInstallerTitle": "Installer image",
"srcOfflineSub": "The full installer; installs with no network",
+29
View File
@@ -17,6 +17,7 @@ export type I18nKey =
| "aboutQQLaunchFailed"
| "aboutQQNotInstalled"
| "aboutQQNotInstalledSub"
| "aboutQQOpenInvite"
| "aboutTagline"
| "activate"
| "affinityApplyNow"
@@ -67,6 +68,7 @@ export type I18nKey =
| "appUpdateLookupFailed"
| "appVersionTitle"
| "appearance"
| "appleVirtualizationTitle"
| "appliesNextStart"
| "attachGuestTools"
| "attachInstaller"
@@ -581,6 +583,7 @@ export type I18nKey =
| "imagesSourcesLabel"
| "importRuntime"
| "installersAvailable"
| "installersCacheUnavailable"
| "installersCreateVM"
| "installersDelete"
| "installersDeleteConfirm"
@@ -645,6 +648,24 @@ export type I18nKey =
| "memRecHint"
| "menuBar"
| "menuHelp"
| "menuMacCut"
| "menuMacDelete"
| "menuMacEdit"
| "menuMacFullScreen"
| "menuMacHide"
| "menuMacHideOthers"
| "menuMacPaste"
| "menuMacPasteMatchStyle"
| "menuMacQuit"
| "menuMacRedo"
| "menuMacSelectAll"
| "menuMacShowAll"
| "menuMacSpeech"
| "menuMacStartSpeaking"
| "menuMacStopSpeaking"
| "menuMacUndo"
| "menuMacWindow"
| "menuMacZoom"
| "menuVM"
| "menuView"
| "minimize"
@@ -990,6 +1011,11 @@ export type I18nKey =
| "srcAppleTitle"
| "srcDiskSub"
| "srcDiskTitle"
| "srcIPSWDownloadSub"
| "srcIPSWDownloadTitle"
| "srcIPSWLocalSub"
| "srcIPSWLocalTitle"
| "srcIPSWNone"
| "srcInstallerSub"
| "srcInstallerTitle"
| "srcOfflineSub"
@@ -1069,6 +1095,7 @@ export type I18nKey =
| "taskDownload"
| "taskPluginDownload"
| "taskRecoveryDownload"
| "taskRestoreVM"
| "taskRuntime"
| "tasksRunning"
| "techInfo"
@@ -1188,5 +1215,7 @@ export type I18nKey =
| "wizOptions"
| "wizardBasics"
| "wizardDriverGroup"
| "wizardDriverListFailed"
| "wizardDriverType"
| "wizardNoDriver"
| "wizardTitle";
+11 -2
View File
@@ -34,7 +34,7 @@ export function hasCap(caps: readonly string[] | null | undefined, capability: s
return !!caps && caps.includes(capability)
}
/** Hosted VMs are run by their driver: no process, window, PID or QMP socket on the host side. */
/** Hosted VMs are managed by their driver rather than a host-owned VM process. */
export function isHosted(caps: readonly string[] | null | undefined): boolean {
return hasCap(caps, 'hosted')
}
@@ -78,7 +78,7 @@ export function vmFeatures(vm?: { driver_id?: string; capabilities?: readonly st
screenshot: hasCap(caps, 'console') || (hasCap(caps, 'qmp') && !hosted),
sendText: hasCap(caps, 'console') || (hasCap(caps, 'qmp') && !hosted),
suspend: hasCap(caps, 'suspend'),
window: !hosted,
window: !hosted || hasCap(caps, 'window'),
}
}
@@ -144,6 +144,15 @@ export function splitEndpoints(endpoints: readonly VMEndpoint[] | null | undefin
return primaryIdx < 0 ? { rest } : { primary: list[primaryIdx], rest }
}
/** A display window takes precedence over remote access; shell-only drivers keep their endpoint shortcut. */
export function primaryVMAccess(features: VMFeatures, endpoints?: readonly VMEndpoint[] | null):
{ kind: 'window' } | { kind: 'endpoint'; endpoint: VMEndpoint } | undefined {
if (features.window) return { kind: 'window' }
if (!features.hosted) return
const { primary } = splitEndpoints(endpoints)
if (primary) return { kind: 'endpoint', endpoint: primary }
}
/** A stable React key for an endpoint row. */
export function endpointKey(ep: VMEndpoint): string {
return [ep.kind, ep.host ?? '', ep.port ?? '', ep.distro ?? '', ep.vm ?? '', ep.serial ?? ''].join('|')
+33
View File
@@ -0,0 +1,33 @@
import type { DriverSummary, HostReport, InstallerKind, SettingProperty } from '../types'
import { isMacOSDriver } from './endpoints'
type HostPlatform = Pick<HostReport, 'os' | 'arch'>
export function isAppleSilicon(host?: HostPlatform): boolean {
return host?.os === 'darwin' && host.arch === 'arm64'
}
export function needsRuntimeSetup(host: HostPlatform, hasRuntime: boolean): boolean {
return !isAppleSilicon(host) && !hasRuntime
}
export function eligibleGuestDrivers(drivers: DriverSummary[], hasRuntime: boolean): DriverSummary[] {
return drivers.filter((driver) => driver.runtime_kind === 'external' || hasRuntime)
}
export function defaultGuestDriver(drivers: DriverSummary[], host: HostPlatform, installerKind?: InstallerKind): DriverSummary | undefined {
const legacy = drivers.find((driver) => isMacOSDriver(driver.id))
if (installerKind === 'ipsw') return drivers.find((driver) => !!restoreImageField(driver, host))
if (installerKind) return legacy
return isAppleSilicon(host) ? drivers[0] : legacy ?? drivers[0]
}
export function restoreImageField(driver: DriverSummary, host: HostPlatform): string | undefined {
if (!isAppleSilicon(host)) return undefined
return Object.entries(driver.create_schema?.properties ?? {}).find(([, prop]) => hasRestoreImagePicker(driver, prop))?.[0]
}
/** Only create schemas supplied by the host's trusted built-ins may request a restore picker. */
export function hasRestoreImagePicker(driver: DriverSummary, prop: SettingProperty): boolean {
return driver.builtin === true && prop.type === 'string' && prop['x-filePattern'] === '*.ipsw'
}
+41
View File
@@ -0,0 +1,41 @@
import type { CachedInstaller, Release } from '../types'
interface RestoreImageChoice {
version: string
build: string
label: string
key: string
}
/** Offer the catalog release and all finished restore images for local reuse. */
export function restoreImageChoices(release: Release | undefined, cached: CachedInstaller[]): RestoreImageChoice[] {
const choices = new Map<string, RestoreImageChoice>()
const add = (title: string, version: string, build: string) => {
const key = restoreImageChoiceKey(version, build)
if (choices.has(key)) return
const label = title.includes(version) ? title : `${title} ${version}`
choices.set(key, { key, version, build, label: build ? `${label} (${build})` : label })
}
if (release) add(release.title, release.version, release.build)
for (const image of cached) {
if (image.kind !== 'ipsw' || image.partial || !image.path || !image.version) continue
add(image.title || 'macOS', image.version, image.build ?? '')
}
return [...choices.values()]
}
export function restoreImageChoiceKey(version: string, build: string): string {
return `${version}|${build}`
}
export function matchesRestoreImage(image: CachedInstaller, version: string, build: string): boolean {
return image.kind === 'ipsw' && image.version === version && (image.build ?? '') === build
}
export function cachedRestoreImage(cached: CachedInstaller[], version: string, build: string): CachedInstaller | undefined {
return cached.find((image) => !image.partial && !!image.path && matchesRestoreImage(image, version, build))
}
export function restoreImagePathMissing(cached: CachedInstaller[], version: string, build: string): boolean {
return cached.some((image) => !image.partial && !image.path && matchesRestoreImage(image, version, build))
}
+15 -4
View File
@@ -1,5 +1,6 @@
import { t } from '../i18n'
import { CachedInstaller, InstallerKind, InstallerPhase, Locale, Task } from '../types'
import { vmRefKey } from './vmRef'
// Match the finished-task retention period in internal/app/tasks.go.
export const finishedTaskTTL = 10 * 60 * 1000
@@ -40,12 +41,21 @@ export function creatingVMTasks(all: Record<string, Task>, existingNames: Readon
.sort((a, b) => a.started_at - b.started_at || a.subject.localeCompare(b.subject))
}
/** Match the driver-scoped VM key sent by the restore task emitter. */
export function findRunningRestoreTask(tasks: Task[], driverID: string, name: string): Task | undefined {
const driver_id = driverID.trim()
if (!driver_id || !name.trim()) return undefined
const key = vmRefKey({ driver_id, name: name.trim() })
return tasks.find((task) => task.kind === 'vm-restore' && task.status === 'running' && task.vm === key)
}
/** Localized title; the upstream step (English) goes in the tooltip. */
export function taskTitle(locale: Locale, task: Task): string {
switch (task.kind) {
case 'installer-download': return t(locale, 'taskDownload', { v: task.subject })
case 'recovery-download': return t(locale, 'taskRecoveryDownload', { name: task.subject })
case 'vm-create': return t(locale, 'taskCreate', { name: task.subject })
case 'vm-restore': return t(locale, 'taskRestoreVM', { name: task.subject })
case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject })
case 'app-update': return t(locale, 'taskAppUpdate', { v: task.subject })
case 'plugin-download': return t(locale, 'taskPluginDownload', { name: task.subject })
@@ -67,7 +77,7 @@ export function isInstallerTask(task: Task): boolean {
}
export function taskInstallerKind(task: Task): InstallerKind | '' {
if (task.installer_kind === 'offline' || task.installer_kind === 'online') return task.installer_kind
if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'ipsw') return task.installer_kind
if (task.kind === 'installer-download') return 'offline'
if (task.kind === 'recovery-download') return 'online'
return ''
@@ -112,6 +122,7 @@ function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
const kind = taskInstallerKind(task)
if (!kind || kind !== item.kind) return false
const v = taskInstallerVersion(task).toLowerCase()
if (kind === 'ipsw') return !!v && item.version?.toLowerCase() === v
if (kind === 'offline') {
if (item.version && item.version.toLowerCase() === v) return true
return item.partial && !!v && !/^\d/.test(v) && matchesOnlineInstallerTitle(item.title, v)
@@ -151,11 +162,11 @@ function pickPrimaryInstallerTask(matches: Task[]): ActiveInstallerMatch | null
return { primary, waitingVMs, matchedIDs: sorted.map((x) => x.id) }
}
export function findActiveOfflineTask(tasks: Task[], version: string): ActiveInstallerMatch | null {
export function findActiveInstallerTask(tasks: Task[], kind: InstallerKind, version: string): ActiveInstallerMatch | null {
const want = version.trim().toLowerCase()
if (!want) return null
const matches = tasks.filter(
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === 'offline' && taskInstallerVersion(x).toLowerCase() === want,
(x) => isActiveInstallerTask(x) && taskInstallerKind(x) === kind && taskInstallerVersion(x).toLowerCase() === want,
)
return pickPrimaryInstallerTask(matches)
}
@@ -184,7 +195,7 @@ export function groupUnmatchedInstallerTasks(activeTasks: Task[], matchedTaskIDs
}
export function taskStopAction(locale: Locale, task: Task): { kind: 'pause' | 'cancel'; label: string } {
if (task.kind === 'vm-create') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
if (task.kind === 'vm-create' || task.kind === 'vm-restore') return { kind: 'cancel', label: t(locale, 'cancelCreate') }
if (task.kind === 'app-update') return { kind: 'cancel', label: t(locale, 'updateCancel') }
if (taskInstallerPhase(task) === 'queued') return { kind: 'cancel', label: t(locale, 'cancelQueue') }
return { kind: 'pause', label: t(locale, 'pauseDownload') }
+134
View File
@@ -0,0 +1,134 @@
import { t } from '../i18n'
import type { Locale, VMAction } from '../types'
import { vmFeatures, type VMFeatures } from './endpoints'
import type { ThemeMode } from './useAppearance'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
export function siteURL(locale: Locale, path = ''): string {
const base = locale.toLowerCase().startsWith('zh') ? 'https://reims.dev' : 'https://reims.dev/en'
return path ? `${base}${path}` : base
}
export const MENU_IDS = ['vm', 'view', 'help'] as const
export type MenuId = (typeof MENU_IDS)[number]
export type MenuCommand = 'new' | 'vmSettings' | 'sidebar' | 'logs' | 'installers' | 'plugins' | 'host' | 'settings' |
'website' | 'docs' | 'project' | 'report' | 'update' | 'about' | `vm:${VMAction}` | `theme:${ThemeMode}`
export type MenuRow =
| { kind: 'separator' }
| { kind: 'label'; label: string }
| { kind: 'action' | 'check' | 'radio'; command: MenuCommand; label: string; disabled?: boolean; checked?: boolean; danger?: boolean; shortcut?: string; macKey?: string }
export interface TitleMenuState {
locale: Locale
sidebarOpen: boolean
logsOpen: boolean
themeMode: ThemeMode
canLight: boolean
canDark: boolean
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean; features: VMFeatures } | null
fullscreenHotkey?: string
appVersion?: string
}
export interface TitleMenuProps extends TitleMenuState {
onToggleSidebar: () => void
onToggleLogs: () => void
onThemeMode: (mode: ThemeMode) => void
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
onVMDelete: () => void
onNavigate: (page: 'installers' | 'plugins' | 'host' | 'settings' | 'about') => void
onOpenURL: (url: string) => void
}
export function buildTitleMenus(state: TitleMenuState, fullscreen: boolean | undefined = undefined) {
const { vm, locale, appVersion, fullscreenHotkey, sidebarOpen, logsOpen, canLight, canDark, themeMode } = state
const tr = (key: Parameters<typeof t>[1]) => t(locale, key)
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const busy = !vm || vm.busy
const features = vm?.features ?? vmFeatures(null)
const canFullscreen = running && features.fullscreen && vm?.graphics !== 'vmware-svga'
const fullscreenLabel = !canFullscreen || fullscreen === undefined ? tr('toggleFullscreen') : fullscreen ? tr('exitFullscreen') : tr('enterFullscreen')
const sep = { kind: 'separator' } as const
const vmRows: MenuRow[] = [{ kind: 'action', command: 'new', label: tr('newVMEllipsis'), shortcut: 'Ctrl+N', macKey: 'n' }, sep]
if (running) {
if (features.window) vmRows.push({ kind: 'action', command: 'vm:focus', label: tr('showWindow'), shortcut: 'Ctrl+Enter', macKey: '\r', disabled: busy })
} else if (suspended) {
vmRows.push({ kind: 'action', command: 'vm:resume', label: tr('resume'), shortcut: vm.canSuspend ? 'Ctrl+Enter' : undefined, macKey: vm.canSuspend ? '\r' : undefined, disabled: busy || !vm.canSuspend })
if (!vm.canSuspend) vmRows.push({ kind: 'label', label: tr('resumeUnavailable') })
} else {
vmRows.push({ kind: 'action', command: 'vm:start', label: tr('start'), shortcut: 'Ctrl+Enter', macKey: '\r', disabled: busy || !stopped })
}
if (features.fullscreen) vmRows.push({ kind: 'action', command: 'vm:fullscreen', label: fullscreenLabel, shortcut: fullscreenHotkey, disabled: busy || !canFullscreen })
if (features.suspend) vmRows.push({ kind: 'action', command: 'vm:suspend', label: tr('suspend'), disabled: busy || !running || !vm?.canSuspend })
vmRows.push(
{ kind: 'action', command: 'vm:stop', label: tr('stop'), disabled: busy || !running },
{ kind: 'action', command: 'vm:restart', label: tr('restart'), disabled: busy || !running },
)
if (features.screenshot) vmRows.push({ kind: 'action', command: 'vm:screenshot', label: tr('copyScreenshot'), disabled: busy || !running })
if (features.macos) vmRows.push(sep,
{ kind: 'action', command: 'vmSettings', label: tr('settingsEllipsis'), shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning },
{ kind: 'action', command: 'vm:openFolder', label: tr('openFolder'), disabled: !vm },
)
vmRows.push(sep)
if (suspended) vmRows.push({ kind: 'action', command: 'vm:discardSuspend', label: tr('discardSuspend'), danger: true, disabled: busy })
vmRows.push(
{ kind: 'action', command: 'vm:forceStop', label: tr('forceStop'), danger: true, disabled: !vm || !(running || transitioning) },
{ kind: 'action', command: 'vm:delete', label: tr('deleteEllipsis'), danger: true, disabled: busy || running || suspended || transitioning },
)
const viewRows: MenuRow[] = [
{ kind: 'check', command: 'sidebar', label: tr('sidebarLabel'), checked: sidebarOpen, shortcut: 'Ctrl+B', macKey: 'b' },
{ kind: 'check', command: 'logs', label: tr('logButton'), checked: logsOpen, shortcut: 'Ctrl+L', macKey: 'l' },
sep,
{ kind: 'label', label: tr('appearance') },
...(['light', 'dark', 'system'] as const).map((mode): MenuRow => ({
kind: 'radio', command: `theme:${mode}`, checked: themeMode === mode,
label: tr(mode === 'light' ? 'themeLight' : mode === 'dark' ? 'themeDark' : 'themeSystem'),
disabled: mode === 'light' ? !canLight : mode === 'dark' ? !canDark : !canLight || !canDark,
})),
sep,
{ kind: 'action', command: 'installers', label: tr('sidebarInstallers') },
{ kind: 'action', command: 'plugins', label: tr('sidebarPlugins') },
{ kind: 'action', command: 'host', label: tr('sidebarHost') },
{ kind: 'action', command: 'settings', label: tr('sidebarSettings'), macKey: ',' },
]
const helpRows: MenuRow[] = [
{ kind: 'action', command: 'website', label: tr('helpWebsite') },
{ kind: 'action', command: 'docs', label: tr('helpDocs') },
{ kind: 'action', command: 'project', label: tr('helpProjectPage') },
{ kind: 'action', command: 'report', label: tr('helpReportIssue') },
{ kind: 'action', command: 'update', label: tr('helpCheckUpdate') },
{ kind: 'action', command: 'about', label: tr('helpAbout') },
]
if (appVersion) helpRows.push(sep, { kind: 'label', label: `Reims-Go ${appVersion}` })
return {
vm: { label: tr('menuVM'), rows: vmRows },
view: { label: tr('menuView'), rows: viewRows },
help: { label: tr('menuHelp'), rows: helpRows },
}
}
export function runMenuCommand(props: TitleMenuProps, command: MenuCommand): void {
switch (command) {
case 'new': return props.onNewVM()
case 'vmSettings': return props.onVMSettings()
case 'vm:delete': return props.onVMDelete()
case 'sidebar': return props.onToggleSidebar()
case 'logs': return props.onToggleLogs()
case 'installers': case 'plugins': case 'host': case 'settings': case 'about': return props.onNavigate(command)
case 'update': return props.onNavigate('about')
case 'website': return props.onOpenURL(siteURL(props.locale))
case 'docs': return props.onOpenURL(siteURL(props.locale, '/docs/quick-start'))
case 'project': return props.onOpenURL(REPO_URL)
case 'report': return props.onOpenURL(`${REPO_URL}/issues`)
}
if (command.startsWith('vm:')) props.onVMAction(command.slice(3) as VMAction)
else if (command.startsWith('theme:')) props.onThemeMode(command.slice(6) as ThemeMode)
}
+70
View File
@@ -0,0 +1,70 @@
import { useEffect, useLayoutEffect, useRef } from 'react'
import { hasVisibleDialog } from '../lib/dialogState'
import { runMenuCommand, type TitleMenuProps } from '../lib/titleMenu'
import { useVMStats } from '../lib/vmStats'
import { api, events } from '../wails'
import { buildNativeMenu, resolveMenuClick, type MenuClick, type NativeMenuState } from './applicationMenuModel'
// Use distinct tokens across snapshots, also across renderer reloads while
// the old native menu is still installed. A click must never be retargeted.
let nextToken = 1 + Math.floor(Math.random() * 0x20000000)
export function ApplicationMenu({ props, state, onReady }: {
props: TitleMenuProps
state: NativeMenuState
onReady: (ready: boolean) => void
}) {
const { vm } = props
const running = vm?.state === 'running'
const stats = useVMStats(vm?.driver_id ?? '', running && vm.features.fullscreen && vm.graphics !== 'vmware-svga' ? vm.name : null, running)
const model = buildNativeMenu(props, state, stats?.running ? stats.window_fullscreen : undefined)
const key = JSON.stringify([model.scope, model.groups, model.standard])
const latest = useRef({ ...model, props })
const installed = useRef(new Map<number, MenuClick>())
useLayoutEffect(() => { latest.current = { ...model, props } })
useEffect(() => events.onApplicationMenuCommand((token) => {
const entry = installed.current.get(token)
const current = latest.current
if (!entry || hasVisibleDialog()) return
const command = resolveMenuClick(entry, current.scope, current.commands)
if (command) runMenuCommand(current.props, command)
}), [])
useEffect(() => {
let canceled = false
let retry: number | undefined
const publish = (attempt: number) => {
const { groups, scope, standard } = latest.current
const active = new Map<number, MenuClick>()
const appGroups = groups.map((group) => ({
label: group.label,
rows: group.rows.map(({ command, ...row }) => {
if (!command) return row
const token = nextToken++
active.set(token, { scope, command })
return { ...row, token }
}),
}))
installed.current = active
api.SyncApplicationMenu(JSON.stringify({ groups: appGroups, standard })).then(() => {
if (!canceled) onReady(true)
}).catch((error) => {
if (canceled) return
if (attempt < 2) {
retry = window.setTimeout(() => publish(attempt + 1), 250)
return
}
installed.current.clear()
onReady(false)
console.warn('[app] Could not update the macOS application menu:', error)
})
}
publish(0)
return () => {
canceled = true
window.clearTimeout(retry)
}
}, [key, onReady])
return null
}
+44 -26
View File
@@ -3,12 +3,14 @@ import React, { useEffect, useRef, useState } from 'react'
import '../i18n/domains/settings.gen'
import '../i18n/domains/wizard.gen'
import { WordmarkLoader } from '../components/WordmarkLoader'
import { I18nKey, t } from '../i18n'
import { I18nKey, parseAppError, t } from '../i18n'
import { macOSMajor } from './macosRelease'
import { isAppleSilicon } from '../lib/guestDrivers'
import { matchesRestoreImage, restoreImagePathMissing } from '../lib/restoreImages'
import {
ActiveInstallerMatch,
findActiveCachedTask,
findActiveOfflineTask,
findActiveInstallerTask,
groupUnmatchedInstallerTasks,
isActiveInstallerTask,
isInstallerTask,
@@ -82,6 +84,7 @@ export const InstallersPage: React.FC<Props> = ({
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
const [cacheError, setCacheError] = useState(false)
const [releases, setReleases] = useState<Release[] | null>(null)
const [releasesErr, setReleasesErr] = useState('')
const [confirmDelete, setConfirmDelete] = useState('')
@@ -89,20 +92,23 @@ export const InstallersPage: React.FC<Props> = ({
const onBusyChangeRef = useRef(onBusyChange)
onBusyChangeRef.current = onBusyChange
const installerTasks = tasks.filter(isInstallerTask)
const releaseKind = isAppleSilicon(host) ? 'ipsw' : 'offline'
const installerTasks = tasks.filter((task) => isInstallerTask(task) && (releaseKind === 'ipsw') === (taskInstallerKind(task) === 'ipsw'))
const activeInstallerTasks = installerTasks.filter(isActiveInstallerTask)
const installerTasksSig = installerTasks
.map((x) => `${x.id}:${x.status}:${x.installer_phase ?? ''}`)
.sort()
.join('|')
const loadCached = () => api.ListInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
const loadCached = () => api.ListInstallers()
.then((l) => { setCached(l ?? []); setCacheError(false) })
.catch((e) => { setCacheError(true); onError(tr('failGeneric'), e) })
const loadReleases = () => {
setReleases(null)
setReleasesErr('')
api.ListOfflineReleases()
.then((l) => setReleases(l ?? []))
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
.catch((e) => setReleasesErr(parseAppError(e).summary))
}
useEffect(() => { loadReleases() }, [])
useEffect(() => {
@@ -127,9 +133,13 @@ export const InstallersPage: React.FC<Props> = ({
api.OpenURL(APPLE_SLA_URL).catch((e) => onError(tr('failGeneric'), e))
}
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
const activeForRelease = (version: string) => findActiveOfflineTask(activeInstallerTasks, version)
const matchesRelease = (item: CachedInstaller, r: Release) => releaseKind === 'ipsw'
? matchesRestoreImage(item, r.version, r.build)
: item.kind === 'offline' && item.version === r.version
const downloaded = (r: Release) => (cached ?? []).find((c) => matchesRelease(c, r) && !!c.path && !c.partial)
const partial = (r: Release) => (cached ?? []).find((c) => matchesRelease(c, r) && c.partial)
const missingRestorePath = (r: Release) => releaseKind === 'ipsw' && restoreImagePathMissing(cached ?? [], r.version, r.build)
const activeForRelease = (version: string) => findActiveInstallerTask(activeInstallerTasks, releaseKind, version)
const download = (version: string) => {
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
@@ -173,7 +183,10 @@ export const InstallersPage: React.FC<Props> = ({
)
}
const spaceShort = (r: Release) => !downloaded(r.version) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
const remainingGB = (r: Release) => releaseKind === 'ipsw'
? Math.max(0, r.size - (partial(r)?.bytes ?? 0)) / (2 ** 30)
: needBytes(r) / 1e9
const spaceShort = (r: Release) => !downloaded(r) && !missingRestorePath(r) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb < remainingGB(r)
const releaseAction = (r: Release) => {
const active = activeForRelease(r.version)
@@ -194,7 +207,7 @@ export const InstallersPage: React.FC<Props> = ({
</span>
)
}
const item = downloaded(r.version)
const item = downloaded(r)
if (item) {
return (
<Button variant="primary" icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(item)}>
@@ -202,22 +215,26 @@ export const InstallersPage: React.FC<Props> = ({
</Button>
)
}
if (missingRestorePath(r)) return <span className="warn-text" role="status">{tr('installersCacheUnavailable')}</span>
if (releaseKind === 'ipsw' && cacheError) return <Button onClick={loadCached}>{tr('installersRetry')}</Button>
return (
<Button icon={<Download size={14} />} disabled={spaceShort(r)} onClick={() => download(r.version)}>
{partial(r.version) ? tr('installersResume') : tr('installersDownload')}
<Button icon={<Download size={14} />} disabled={spaceShort(r) || (releaseKind === 'ipsw' && cached === null)} onClick={() => download(r.version)}>
{partial(r) ? tr('installersResume') : tr('installersDownload')}
</Button>
)
}
const releaseMeta = (r: Release) => (
<div className="row-sub">
{r.posted} · {gb(r.size)}
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
const releaseMeta = (r: Release) => {
const details = [r.posted, r.size > 0 ? gb(r.size) : ''].filter(Boolean).join(' · ')
if (!details) return null
return <div className="row-sub">
{details}
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(remainingGB(r)), free: host.free_disk_gb.toFixed(0) })}</span>}
</div>
)
}
const matchedTaskIDs = new Set<string>()
const cachedRows: DownloadedRow[] = (cached ?? []).map((c) => {
const cachedRows: DownloadedRow[] = (cached ?? []).filter((item) => (releaseKind === 'ipsw') === (item.kind === 'ipsw')).map((c) => {
const active = findActiveCachedTask(activeInstallerTasks, c)
if (active) {
for (const id of active.matchedIDs) matchedTaskIDs.add(id)
@@ -236,13 +253,13 @@ export const InstallersPage: React.FC<Props> = ({
const task = active.primary
const kind = taskInstallerKind(task) || 'offline'
const version = taskInstallerVersion(task)
if (kind === 'offline') {
if (kind === 'offline' || kind === 'ipsw') {
const rel = (releases ?? []).find((r) => r.version.toLowerCase() === version.toLowerCase())
return {
key: `active-${taskInstallerKey(task) || task.id}`,
title: rel?.title ?? 'macOS',
version: rel?.version ?? version,
kind: 'offline',
kind,
active,
}
}
@@ -302,6 +319,7 @@ export const InstallersPage: React.FC<Props> = ({
<div className="row-title">
<span>{row.title}{row.version ? ` ${row.version}` : ''}</span>
{!task && c?.kind === 'offline' && !c.partial && <span className="badge rg-p-badge badge-ok">{tr('installersKindOffline')}</span>}
{!task && c?.kind === 'ipsw' && !c.partial && <span className="badge rg-p-badge badge-ok">IPSW</span>}
{(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online')
? <span className="badge rg-p-badge">{tr('installersKindOnline')}</span>
: null}
@@ -333,12 +351,12 @@ export const InstallersPage: React.FC<Props> = ({
/>
) : c ? (
<>
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
{!c.partial && !!c.path && c.kind !== 'other' && (
<Button variant={c.kind === 'online' ? 'secondary' : 'primary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
{tr('installersCreateVM')}
</Button>
)}
{c.partial && c.kind === 'offline' && c.version && (
{c.partial && c.version && (c.kind === 'offline' || (c.kind === 'ipsw' && (releases ?? []).some((r) => matchesRelease(c, r)))) && (
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
)}
{confirmDelete === c.name ? (
@@ -362,7 +380,7 @@ export const InstallersPage: React.FC<Props> = ({
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('offlineListFailedDetail', { err: releasesErr })}</span>
<span>{releaseKind === 'ipsw' ? releasesErr : tr('offlineListFailedDetail', { err: releasesErr })}</span>
</span>
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
</div>
@@ -383,7 +401,7 @@ export const InstallersPage: React.FC<Props> = ({
<span>{latest.title}</span>
<strong>{latest.version}</strong>
{groupIndex === 0 && <span className="badge rg-p-badge badge-accent">{tr('installersLatest')}</span>}
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
{downloaded(latest) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
</div>
{releaseMeta(latest)}
</div>
@@ -402,7 +420,7 @@ export const InstallersPage: React.FC<Props> = ({
<div className="row-title">
<span>{r.version}</span>
<span className="muted">{r.build}</span>
{downloaded(r.version) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
{downloaded(r) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
</div>
{releaseMeta(r)}
</div>
@@ -0,0 +1,49 @@
import { t, type I18nKey } from '../i18n'
import { buildTitleMenus, MENU_IDS, type MenuCommand, type TitleMenuState } from '../lib/titleMenu'
// Match Wails’ standard items by action, not by their original English title.
const standardMenuKeys = {
edit: 'menuMacEdit', window: 'menuMacWindow', speech: 'menuMacSpeech',
About: 'helpAbout', Quit: 'menuMacQuit',
'hide:': 'menuMacHide', 'hideOtherApplications:': 'menuMacHideOthers', 'unhideAllApplications:': 'menuMacShowAll',
'undo:': 'menuMacUndo', 'redo:': 'menuMacRedo',
'cut:': 'menuMacCut', 'copy:': 'copy', 'paste:': 'menuMacPaste', 'pasteAsRichText:': 'menuMacPasteMatchStyle',
'delete:': 'menuMacDelete', 'selectAll:': 'menuMacSelectAll',
'startSpeaking:': 'menuMacStartSpeaking', 'stopSpeaking:': 'menuMacStopSpeaking',
'performMiniaturize:': 'minimize', 'performZoom:': 'menuMacZoom', 'enterFullScreenMode:': 'menuMacFullScreen',
} satisfies Record<string, I18nKey>
type NativeRow = { label?: string; command?: MenuCommand; checked?: boolean; key?: string }
export type MenuClick = { scope: string; command: MenuCommand }
export interface NativeMenuState {
workspaceReady: boolean
dialogOpen: boolean
selectedVMKey?: string
vmSettingsReady: boolean
}
export function buildNativeMenu(props: TitleMenuState, state: NativeMenuState, fullscreen?: boolean) {
const menus = buildTitleMenus(props, fullscreen)
const commands = new Set<MenuCommand>()
const groups = MENU_IDS.map((id) => ({
label: menus[id].label,
rows: menus[id].rows.map((row): NativeRow => {
if (row.kind === 'separator') return {}
if (row.kind === 'label') return { label: row.label }
const alwaysAvailable = row.command === 'website' || row.command === 'docs' || row.command === 'project' || row.command === 'report'
const enabled = !state.dialogOpen && (state.workspaceReady || alwaysAvailable) && !row.disabled
&& (row.command !== 'vmSettings' || state.vmSettingsReady)
if (enabled) commands.add(row.command)
return { label: row.label, command: enabled ? row.command : undefined, checked: row.checked, key: row.macKey }
}),
}))
const standard = Object.fromEntries(Object.entries(standardMenuKeys).map(([item, key]) => [item, t(props.locale, key)]))
return { groups, standard, commands, scope: state.selectedVMKey ?? '' }
}
export function resolveMenuClick(entry: MenuClick, scope: string, commands: ReadonlySet<MenuCommand>): MenuCommand | undefined {
if (!commands.has(entry.command)) return undefined
if ((entry.command.startsWith('vm:') || entry.command === 'vmSettings') && entry.scope !== scope) return undefined
return entry.command
}
+7
View File
@@ -2069,6 +2069,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
cannot override them even with !important. */
@layer host-guard {
.rg-p-titlebar { --wails-draggable: drag !important; }
/* Match the native titlebar's centerline. The top padding balances the bottom border.
AppKit's controls occupy the physical left edge, even when the app is RTL. */
.rg-p-titlebar[data-native-titlebar] {
height: 32px !important;
padding-top: 1px !important;
padding-left: 96px !important;
}
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring) !important; }
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
/* Layers and decorations never take input, whatever a theme says. */
+1 -1
View File
@@ -126,7 +126,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
export type InstallerKind = 'offline' | 'online'
export type InstallerKind = 'offline' | 'online' | 'ipsw'
export type InstallerPhase = 'queued' | 'downloading'
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
+1
View File
@@ -198,6 +198,7 @@ export const events = {
onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb),
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onApplicationMenuCommand: (cb: (token: number) => void) => eventsOn('reims:application-menu-command', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
onRuntimeWarning: (cb: (message: string) => void) => eventsOn('reims:runtime-warning', cb),
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
+2
View File
@@ -294,6 +294,8 @@ export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
export function SuspendVM(arg1:string,arg2:string):Promise<void>;
export function SyncApplicationMenu(arg1:string):Promise<void>;
export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise<guesttools.HostDNSTestResult>;
export function ToggleVMFullscreen(arg1:string,arg2:string):Promise<boolean>;
+4
View File
@@ -566,6 +566,10 @@ export function SuspendVM(arg1, arg2) {
return window['go']['app']['App']['SuspendVM'](arg1, arg2);
}
export function SyncApplicationMenu(arg1) {
return window['go']['app']['App']['SyncApplicationMenu'](arg1);
}
export function TestHostDNS(arg1) {
return window['go']['app']['App']['TestHostDNS'](arg1);
}
+20
View File
@@ -1344,7 +1344,22 @@ export namespace host {
this.nested_virt_probe_error = source["nested_virt_probe_error"];
}
}
export class AppleVirtualizationStatus {
ready: boolean;
detail?: string;
static createFrom(source: any = {}) {
return new AppleVirtualizationStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.ready = source["ready"];
this.detail = source["detail"];
}
}
export class Report {
apple_virtualization?: AppleVirtualizationStatus;
defender_realtime_active?: boolean;
os: string;
arch: string;
@@ -1366,6 +1381,7 @@ export namespace host {
total_ram_gb: number;
avail_ram_gb: number;
memory_load_pct: number;
memory_usage_known?: boolean;
memory_spec?: HostMemorySpec;
commit_avail_gb: number;
commit_limit_gb: number;
@@ -1399,6 +1415,7 @@ export namespace host {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.apple_virtualization = this.convertValues(source["apple_virtualization"], AppleVirtualizationStatus);
this.defender_realtime_active = source["defender_realtime_active"];
this.os = source["os"];
this.arch = source["arch"];
@@ -1420,6 +1437,7 @@ export namespace host {
this.total_ram_gb = source["total_ram_gb"];
this.avail_ram_gb = source["avail_ram_gb"];
this.memory_load_pct = source["memory_load_pct"];
this.memory_usage_known = source["memory_usage_known"];
this.memory_spec = this.convertValues(source["memory_spec"], HostMemorySpec);
this.commit_avail_gb = source["commit_avail_gb"];
this.commit_limit_gb = source["commit_limit_gb"];
@@ -2341,6 +2359,7 @@ export namespace plugin {
}
export class SettingProperty {
type: string;
"x-filePattern"?: string;
title: LocalizedText;
description?: LocalizedText;
default?: any;
@@ -2361,6 +2380,7 @@ export namespace plugin {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.type = source["type"];
this["x-filePattern"] = source["x-filePattern"];
this.title = this.convertValues(source["title"], LocalizedText);
this.description = this.convertValues(source["description"], LocalizedText);
this.default = source["default"];
+39 -36
View File
@@ -122,31 +122,33 @@ type App struct {
trayMgr *tray.Manager
allowQuit bool
launchPrevDataRoot string
quitMode string
vmStarts sync.WaitGroup
lastVMs []driver.VMListItem
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
lastVMListErr error
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
launch cli.WindowArgs // flags this window was started with (window_launch.go)
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginMarket *market.MarketClient
controlServer *control.Server
driverRouter *driver.Router
vmStateTable *driver.StateTable
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
quitMode string
vmStarts sync.WaitGroup
lastVMs []driver.VMListItem
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
lastVMListErr error
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
launch cli.WindowArgs // flags this window was started with (window_launch.go)
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginMarket *market.MarketClient
controlServer *control.Server
driverRouter *driver.Router
vmStateTable *driver.StateTable
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
appleVZProbeOnce sync.Once
appleVZProbe host.AppleVirtualizationStatus
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
displayPlacements sync.Map
@@ -191,15 +193,15 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
needsSetup: needsSetup,
launch: launch,
launchPrevDataRoot: launchPrevDataRoot,
trayIcon: trayIcon,
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
pollWake: make(chan struct{}, 1),
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
uiHealth: uiHealthState{windowHidden: launch.Background},
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
trayIcon: trayIcon,
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
pollWake: make(chan struct{}, 1),
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
uiHealth: uiHealthState{windowHidden: launch.Background},
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
}
a.hostAPI.app = a
a.hostAPI.pluginFiles = make(map[string]pluginFileGrant)
@@ -278,8 +280,8 @@ func (a *App) beforeClose(ctx context.Context) bool {
wailsRuntime.WindowHide(ctx)
return true
}
if tasks.hasRunningDownload() {
// Closing now would abort a download: ask first. The window's
if tasks.hasRunningDownload() || tasks.hasRunningRestore() {
// Closing now would abort a download or restore: ask first. The window's
// confirmation calls QuitApp, which lets the next close through.
a.emit("reims:confirm-close-downloads", true)
return true
@@ -374,6 +376,7 @@ func (a *App) GetState() AppState {
a.mu.Unlock()
rep := host.Inspect(cfgCopy.DataRoot)
rep.AppleVirtualization = a.nativeVirtualizationStatus()
if needsSetup || rootStatus.ReadOnly {
rep.PendingHypervisorBoot = host.ReadPendingHypervisorBoot("", rep.WHPX)
}
+72
View File
@@ -0,0 +1,72 @@
package app
import (
"encoding/json"
"errors"
"strings"
)
type applicationMenuSnapshot struct {
Groups []applicationMenuGroup `json:"groups"`
Standard map[string]string `json:"standard"`
}
type applicationMenuGroup struct {
Label string `json:"label"`
Rows []applicationMenuRow `json:"rows"`
}
type applicationMenuRow struct {
Label string `json:"label,omitempty"`
Key string `json:"key,omitempty"`
Token int32 `json:"token,omitempty"`
Checked bool `json:"checked,omitempty"`
}
func parseApplicationMenu(raw string) (applicationMenuSnapshot, error) {
var snapshot applicationMenuSnapshot
if err := json.Unmarshal([]byte(raw), &snapshot); err != nil || len(snapshot.Groups) != 3 {
return snapshot, errors.New("invalid application menu groups")
}
for _, key := range []string{"edit", "window", "speech", "hide:", "Quit"} {
if strings.TrimSpace(snapshot.Standard[key]) == "" {
return snapshot, errors.New("missing standard application menu labels")
}
}
tokens := make(map[int32]bool)
for _, group := range snapshot.Groups {
if strings.TrimSpace(group.Label) == "" || len(group.Rows) == 0 || len(group.Rows) > 40 {
return snapshot, errors.New("invalid application menu group")
}
for _, row := range group.Rows {
switch row.Key {
case "", "n", "b", "l", ",", "\r":
default:
return snapshot, errors.New("invalid application menu shortcut")
}
if row.Token < 0 || (row.Token > 0 && (row.Label == "" || tokens[row.Token])) {
return snapshot, errors.New("invalid application menu action")
}
if row.Token > 0 {
tokens[row.Token] = true
}
}
}
return snapshot, nil
}
// SyncApplicationMenu publishes the renderer's localized menu and current
// action availability to the host's native menu bar.
func (a *App) SyncApplicationMenu(raw string) error {
if a.ctx == nil {
return errors.New("application menu is not ready")
}
if len(raw) > 32<<10 {
return errors.New("application menu snapshot is too large")
}
snapshot, err := parseApplicationMenu(raw)
if err != nil {
return err
}
return a.syncApplicationMenu(snapshot)
}
+42
View File
@@ -0,0 +1,42 @@
//go:build darwin && cgo
package app
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework AppKit
#include <stdlib.h>
int reimsSyncApplicationMenu(const char *snapshot);
*/
import "C"
import (
"encoding/json"
"errors"
"sync/atomic"
"unsafe"
)
var nativeMenuOwner atomic.Pointer[App]
func (a *App) syncApplicationMenu(menu applicationMenuSnapshot) error {
snapshot, err := json.Marshal(menu)
if err != nil {
return err
}
data := C.CString(string(snapshot))
defer C.free(unsafe.Pointer(data))
nativeMenuOwner.Store(a)
if C.reimsSyncApplicationMenu(data) == 0 {
return errors.New("macOS application menu is not ready")
}
return nil
}
//export reimsApplicationMenuClicked
func reimsApplicationMenuClicked(token C.int) {
if a := nativeMenuOwner.Load(); a != nil {
// Let AppKit finish handling the input before emitting back to WebKit.
go a.emit("reims:application-menu-command", int(token))
}
}
+120
View File
@@ -0,0 +1,120 @@
//go:build darwin && cgo
#import <AppKit/AppKit.h>
extern void reimsApplicationMenuClicked(int token);
@interface ReimsMenuTarget : NSObject
- (void)invoke:(NSMenuItem *)sender;
@end
@implementation ReimsMenuTarget
- (void)invoke:(NSMenuItem *)sender {
reimsApplicationMenuClicked((int)sender.tag);
}
@end
static ReimsMenuTarget *menuTarget;
static NSArray<NSMenuItem *> *managedItems;
static NSArray<NSMenuItem *> *standardItems;
static void setMenuTitle(NSMenuItem *item, NSString *title) {
if (title.length == 0) return;
item.title = title;
item.submenu.title = title;
}
static void localizeStandardItems(NSMenu *menu, NSDictionary<NSString *, NSString *> *labels) {
for (NSMenuItem *item in menu.itemArray) {
if (item.isSeparatorItem) continue;
if (item.hasSubmenu) {
// AppKit can also inject its own submenus, such as AutoFill.
// Only relabel the speech submenu created by Wails.
for (NSMenuItem *child in item.submenu.itemArray) {
if (child.action == @selector(startSpeaking:)) {
setMenuTitle(item, labels[@"speech"]);
localizeStandardItems(item.submenu, labels);
break;
}
}
} else if (item.action) {
NSString *action = NSStringFromSelector(item.action);
// Wails sends both Undo and Redo to undo:, with Shift for Redo.
if (item.action == @selector(undo:) && (item.keyEquivalentModifierMask & NSEventModifierFlagShift)) {
action = @"redo:";
}
setMenuTitle(item, labels[action]);
}
}
}
static NSMenu *buildMenu(NSDictionary *group) {
NSMenu *menu = [[[NSMenu alloc] initWithTitle:group[@"label"]] autorelease];
menu.autoenablesItems = NO;
for (NSDictionary *row in group[@"rows"]) {
if (!row[@"label"]) {
[menu addItem:[NSMenuItem separatorItem]];
continue;
}
NSInteger token = [row[@"token"] integerValue];
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:row[@"label"]
action:token ? @selector(invoke:) : NULL
keyEquivalent:row[@"key"] ?: @""] autorelease];
item.keyEquivalentModifierMask = NSEventModifierFlagCommand;
item.tag = token;
item.target = menuTarget;
item.enabled = token != 0;
item.state = [row[@"checked"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
[menu addItem:item];
}
return menu;
}
static BOOL setMenuGroups(NSDictionary *snapshot) {
NSMenu *main = NSApp.mainMenu;
NSArray<NSDictionary *> *groups = snapshot[@"groups"];
if (!main || groups.count != 3) return NO;
if (!menuTarget) menuTarget = [ReimsMenuTarget new];
if (!managedItems || managedItems.firstObject.menu != main) {
// Wails initializes App, Edit and Window in this order. Keep the
// original items so localization does not change targets or shortcuts.
if (main.numberOfItems != 3) return NO;
[standardItems release];
standardItems = [main.itemArray copy];
NSMutableArray *items = [NSMutableArray arrayWithCapacity:3];
NSInteger index = 2;
for (NSDictionary *group in groups) {
[items addObject:[[[NSMenuItem alloc] initWithTitle:group[@"label"] action:NULL keyEquivalent:@""] autorelease]];
}
[main insertItem:items[0] atIndex:index];
[main insertItem:items[1] atIndex:index + 1];
[main addItem:items[2]];
[managedItems release];
managedItems = [items copy];
}
NSDictionary<NSString *, NSString *> *labels = snapshot[@"standard"];
setMenuTitle(standardItems[0], @"Reims-Go");
setMenuTitle(standardItems[1], labels[@"edit"]);
setMenuTitle(standardItems[2], labels[@"window"]);
for (NSMenuItem *item in standardItems) localizeStandardItems(item.submenu, labels);
for (NSUInteger i = 0; i < groups.count; i++) {
NSMenuItem *item = managedItems[i];
item.title = groups[i][@"label"];
item.submenu = buildMenu(groups[i]);
}
NSApp.helpMenu = managedItems.lastObject.submenu;
return YES;
}
int reimsSyncApplicationMenu(const char *snapshot) {
@autoreleasepool {
NSData *data = [NSData dataWithBytes:snapshot length:strlen(snapshot)];
NSDictionary *menu = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if (NSThread.isMainThread) return setMenuGroups(menu);
__block BOOL updated = NO;
dispatch_sync(dispatch_get_main_queue(), ^{ updated = setMenuGroups(menu); });
return updated;
}
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !darwin || !cgo
package app
import "errors"
func (a *App) syncApplicationMenu(applicationMenuSnapshot) error {
return errors.New("native application menu is unavailable")
}
+35
View File
@@ -0,0 +1,35 @@
package app
import "testing"
const standardMenuFixture = `,"standard":{"edit":"编辑","window":"窗口","speech":"朗读","hide:":"隐藏 Reims-Go","Quit":"退出 Reims-Go"}`
func TestParseApplicationMenu(t *testing.T) {
const groups = `[{"label":"虚拟机","rows":[{"label":"Start","token":1,"key":"\r"}]},{"label":"View","rows":[{}, {"label":"Sidebar","checked":true,"token":2}]},{"label":"Help","rows":[{"label":"Reims-Go"}]}]`
parsed, err := parseApplicationMenu(`{"groups":` + groups + standardMenuFixture + `}`)
if err != nil {
t.Fatal(err)
}
if parsed.Groups[0].Rows[0].Key != "\r" || !parsed.Groups[1].Rows[1].Checked || parsed.Groups[2].Rows[0].Token != 0 {
t.Fatalf("menu snapshot did not keep shortcut, checked state and disabled row: %+v", parsed)
}
if parsed.Standard["edit"] != "编辑" || parsed.Standard["Quit"] != "退出 Reims-Go" {
t.Fatalf("menu snapshot did not keep localized standard items: %+v", parsed.Standard)
}
}
func TestParseApplicationMenuRejectsInvalidSnapshots(t *testing.T) {
for _, groups := range []string{
`null`,
`[{"label":"VM","rows":[{}]}]`,
`[{"label":"VM","rows":[{"label":"Start","token":1}]},{"label":"View","rows":[{"label":"Sidebar","token":1}]},{"label":"Help","rows":[{}]}]`,
`[{"label":"VM","rows":[{"label":"Start","token":1,"key":"q"}]},{"label":"View","rows":[{}]},{"label":"Help","rows":[{}]}]`,
} {
if _, err := parseApplicationMenu(`{"groups":` + groups + standardMenuFixture + `}`); err == nil {
t.Errorf("accepted invalid groups: %s", groups)
}
}
if _, err := parseApplicationMenu(`{"groups":[{"label":"VM","rows":[{}]},{"label":"View","rows":[{}]},{"label":"Help","rows":[{}]}]}`); err == nil {
t.Error("accepted missing standard menu labels")
}
}
+18
View File
@@ -152,6 +152,24 @@ func TestSSHTargetPrefersTheEndpoint(t *testing.T) {
}
}
func TestMacSSHTerminalLaunch(t *testing.T) {
for _, tc := range []struct {
host, user, want string
}{
{"", "", "ssh://127.0.0.1:2222"},
{"guest.local", "dev", "ssh://dev@guest.local:2222"},
{"2001:db8::1", "dev", "ssh://dev@[2001:db8::1]:2222"},
} {
spec, err := macSSHTerminalLaunch(tc.host, 2222, tc.user)
if err != nil || spec.exe != "/usr/bin/open" || !slices.Equal(spec.args, []string{tc.want}) {
t.Errorf("launch = %+v, %v; want %q", spec, err, tc.want)
}
}
if _, err := macSSHTerminalLaunch("example.com", 22, "-oProxyCommand"); err == nil {
t.Error("accepted a user resembling an SSH option")
}
}
func TestSSHHostAliasSeparatesDrivers(t *testing.T) {
mac := sshHostAlias("", "dev")
other := sshHostAlias("vendor.driver.linux", "dev")
+4
View File
@@ -8,6 +8,7 @@ import (
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installer"
)
@@ -91,6 +92,9 @@ func (a *App) GetStorageBreakdown() StorageBreakdown {
cfgCopy := *a.cfg
a.mu.Unlock()
vmsDir := filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms")
if guest.UsesAppleVirtualization() {
return computeStorageBreakdown(cfgCopy.DataRoot, guest.AppleVMRoot(cfgCopy.DataRoot), installer.RestoreDir(&cfgCopy), "")
}
return computeStorageBreakdown(cfgCopy.DataRoot, vmsDir, installer.Dir(&cfgCopy), cfgCopy.ImagesDir())
}
+82 -10
View File
@@ -8,6 +8,9 @@ import (
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/applevz"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installer"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
@@ -26,6 +29,14 @@ func (a *App) installerClient() (*installer.Client, error) {
// ListOfflineReleases lists the offline installers Apple offers, newest first.
// It reads Apple's catalog (a few seconds, needs the network).
func (a *App) ListOfflineReleases() ([]installer.Release, error) {
if guest.UsesAppleVirtualization() {
release, err := a.latestRestoreRelease(a.baseCtx())
if err != nil {
return nil, err
}
release.URL, release.Digest = "", "" // The UI selects a release, never a CDN URL or checksum.
return []installer.Release{release}, nil
}
c, err := a.installerClient()
if err != nil {
return nil, err
@@ -46,30 +57,72 @@ func (a *App) DownloadInstaller(version string) (string, error) {
if version == "" {
return "", fmt.Errorf("no version given")
}
if guest.UsesAppleVirtualization() {
return a.startRestoreImageDownload(version)
}
c, err := a.installerClient()
if err != nil {
return "", err
}
a.ensureTaskEmitter()
base := a.ctx
if base == nil {
base = context.Background()
return a.startInstallerDownload("offline", version, func(ctx context.Context, update func(installer.Update)) (*installer.Result, error) {
return c.DownloadOffline(ctx, version, update)
}), nil
}
func (a *App) startRestoreImageDownload(version string) (string, error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return "", err
}
cfg := a.runtimeConfig()
cache := installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}
return a.startInstallerDownload(installer.RestoreKind, version, func(ctx context.Context, update func(installer.Update)) (*installer.Result, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
release, err := a.latestRestoreRelease(ctx)
if err != nil {
return nil, err
}
if release.Version != version {
return nil, errors.New("the compatible macOS restore image changed; refresh the catalog before downloading")
}
return cache.Download(ctx, release, update)
}), nil
}
func (a *App) latestRestoreRelease(ctx context.Context) (installer.Release, error) {
release, err := installer.LatestRestore(ctx)
if err == nil || errors.Is(err, context.Canceled) {
return release, err
}
key := "err.restore_catalog_unavailable"
if errors.Is(err, applevz.ErrRestoreCatalogUnsupported) {
key = "err.restore_catalog_unsupported"
}
a.emitLog("installer", "Apple restore catalog: "+err.Error())
return installer.Release{}, i18n.NewCodedError(a.locale(), "E_RESTORE_CATALOG", key, nil, err)
}
func (a *App) startInstallerDownload(kind, version string, download installerDownloadFunc) string {
a.ensureTaskEmitter()
base := a.baseCtx()
var (
ctx context.Context
cancel context.CancelFunc
)
run, id, owned := installerDownloads.reserveOrFind("offline", version, "installer-download", func(initialPhase string) string {
run, id, owned := installerDownloads.reserveOrFind(kind, version, "installer-download", func(initialPhase string) string {
ctx, cancel = context.WithCancel(base)
return tasks.startWithInstaller("installer-download", version, "", "offline", version, initialPhase, cancel)
return tasks.startWithInstaller("installer-download", version, "", kind, version, initialPhase, cancel)
})
if !owned {
return id, nil
return id
}
a.emitLog("installer", "Downloading macOS "+version+" offline installer")
a.emitLog("installer", "Downloading macOS "+version+" ("+kind+")")
go func() {
defer cancel()
res, err := c.DownloadOffline(ctx, version, func(u installer.Update) {
res, err := download(ctx, func(u installer.Update) {
switch u.Kind {
case installer.KindStep, installer.KindNote:
a.emitLog("installer", u.Message)
@@ -93,11 +146,18 @@ func (a *App) DownloadInstaller(version string) (string, error) {
tasks.finish(id, "", err)
}
}()
return id, nil
return id
}
// ListInstallers lists the downloaded installers kept for new VMs.
func (a *App) ListInstallers() ([]installer.Cached, error) {
if guest.UsesAppleVirtualization() {
if !a.dataRootUsable() {
return nil, nil
}
cfg := a.runtimeConfig()
return (installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}).List()
}
c, err := a.installerClient()
if err != nil {
return nil, err
@@ -108,6 +168,18 @@ func (a *App) ListInstallers() ([]installer.Cached, error) {
// DeleteInstaller deletes a downloaded installer through reims-ctl, which
// refuses one a VM boots from or one being downloaded.
func (a *App) DeleteInstaller(name string) error {
if guest.UsesAppleVirtualization() {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return err
}
if tasks.hasRunningRestore() {
return errors.New("cannot delete a restore image while a macOS installation is running")
}
cfg := a.runtimeConfig()
return (installer.RestoreCache{Dir: installer.RestoreDir(&cfg)}).Delete(a.baseCtx(), name)
}
c, err := a.installerClient()
if err != nil {
return err
+1 -1
View File
@@ -17,7 +17,7 @@ type installerDownloadFunc func(ctx context.Context, onUpdate func(installer.Upd
// progress, deduplicate the same release, and surface queueing cleanly.
type installerDownloadRun struct {
key string
kind string // "offline" | "online"
kind string // "offline" | "online" | "ipsw"
version string
ownerID string
ownerKind string // "installer-download" | "vm-create" | "recovery-download"
+35
View File
@@ -117,6 +117,41 @@ func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action strin
return d.actionResults[action], nil
}
type nativeViewerDriver struct {
*appSecondDriver
shown string
}
func (d *nativeViewerDriver) ShowWindow(_ context.Context, name string) error {
d.shown = name
return nil
}
func TestHostedViewerIsOpenedThroughTheOwningDriver(t *testing.T) {
const id = "test.driver.viewer"
drv := &nativeViewerDriver{appSecondDriver: &appSecondDriver{id: id, vms: []driver.VMInfo{{
Name: "desktop", State: "running", Capabilities: []string{driver.CapHosted, driver.CapWindow},
}}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: id, Version: "1.0.0"},
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, id, drv)
return nil
}}); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
router := driver.NewRouter(reg, nil)
a := &App{driverRouter: router, lifecycleSvc: vmlifecycle.New(reg, router, nil)}
if err := a.FocusVMWindow(id, "desktop"); err != nil || drv.shown != "desktop" {
t.Fatalf("focus hosted viewer: shown=%q, err=%v", drv.shown, err)
}
drv.shown, drv.vms[0].State = "", "stopped"
if err := a.FocusVMWindow(id, "desktop"); err == nil || drv.shown != "" {
t.Fatalf("focus stopped VM: shown=%q, err=%v", drv.shown, err)
}
}
func TestAppSecondDriverUserEntry(t *testing.T) {
const driverID = "test.driver.linux"
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}}
+63 -9
View File
@@ -98,7 +98,7 @@ func (a *App) initPlugins() {
// longer release it, so the host lifts what it left down.
a.releaseHeldForPlugin(pluginID)
},
VMInventory: guest.VMInventory(),
VMInventories: guest.VMInventories(),
Callbacks: builtin.HostCallbacks{
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
@@ -170,7 +170,7 @@ func (a *App) initPlugins() {
a.wakePoll()
},
},
RegisterGuest: guest.Register,
RegisterGuest: guest.RegisterForHost,
})
if err != nil {
a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error())
@@ -765,9 +765,7 @@ func (a *App) GetPluginUIContributions() PluginUIContributions {
if kr != nil {
out.RuntimeKinds = kr.List()
}
if dr != nil {
out.Drivers = dr.Summaries()
}
out.Drivers = desktopDriverSummaries(dr)
return out
}
@@ -829,10 +827,39 @@ func (a *App) ListDrivers() []driver.DriverSummary {
a.mu.Lock()
dr := a.driverRouter
a.mu.Unlock()
if dr == nil {
return desktopDriverSummaries(dr)
}
func desktopDriverSummaries(router *driver.Router) []driver.DriverSummary {
list := router.Summaries()
if !guest.UsesAppleVirtualization() {
return list
}
for i := range list {
if list[i].ID == guest.AppleDriverID() {
list[i].Builtin = true
list[0], list[i] = list[i], list[0]
break
}
}
return list
}
func (a *App) nativeVirtualizationStatus() *host.AppleVirtualizationStatus {
if !guest.UsesAppleVirtualization() {
return nil
}
return dr.Summaries()
a.appleVZProbeOnce.Do(func() {
ctx, cancel := context.WithTimeout(a.baseCtx(), 5*time.Second)
defer cancel()
if err := guest.ProbeAppleVirtualization(ctx); err != nil {
a.appleVZProbe.Detail = host.RedactText(err.Error())
return
}
a.appleVZProbe.Ready = true
})
status := a.appleVZProbe
return &status
}
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
@@ -874,8 +901,12 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return errors.New(issues[0].Message)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(req.DriverID, req.Name, line) })
if err := drv.Create(ctx, req, w, w); err != nil {
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(drv.ID(), req.Name, line) })
if drv.ID() == guest.AppleDriverID() {
if err := a.restoreAppleVM(dr, drv, req, w); err != nil {
return err
}
} else if err := drv.Create(ctx, req, w, w); err != nil {
return err
}
if mgr != nil {
@@ -889,6 +920,29 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
return nil
}
func (a *App) restoreAppleVM(router *driver.Router, drv driver.Driver, req driver.CreateRequest, w vmstart.LineWriter) error {
ctx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
a.selectionMu.Lock()
a.mu.Lock()
stillCurrent := a.driverRouter == router && !a.allowQuit && a.quitMode == ""
a.mu.Unlock()
if !stillCurrent {
a.selectionMu.Unlock()
return errors.New("virtual machine restore could not start because the workspace changed")
}
a.ensureTaskEmitter()
id := tasks.start("vm-restore", req.Name, driver.NewVMRef(drv.ID(), req.Name).Key(), cancel)
a.selectionMu.Unlock()
defer func() {
a.wakePoll()
a.emitStateChanged()
}()
err := drv.Create(ctx, req, w, w)
tasks.finish(id, req.Name, err)
return err
}
// InspectPluginArchive runs the unified static security scanner on a local .zip
// package before installing it so the UI can display hard blockers, capabilities,
// and L3 native execution notices.
+10 -1
View File
@@ -19,6 +19,7 @@ import (
const (
qqGroupID = "1136042744"
qqGroupShortURL = "https://qm.qq.com/q/TBmRJlVbSo"
qqGroupProtocolURL = "tencent://groupwpa/"
qqGroupAuthCacheTTL = 10 * time.Minute
qqGroupLookupTimeout = 5 * time.Second
)
@@ -151,7 +152,15 @@ func buildQQGroupSchemeURL(groupUin, authKey string, now time.Time) string {
AuthKey: authKey,
Auth: "",
})
return "tencent://groupwpa/?subcmd=all&param=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from="
return qqGroupProtocolURL + "?subcmd=all&param=" + strings.ToUpper(hex.EncodeToString(raw)) + "&jump_from="
}
func validateQQGroupProtocolURL(uri string) (string, error) {
uri = strings.TrimSpace(uri)
if !strings.HasPrefix(uri, qqGroupProtocolURL+"?") || strings.ContainsAny(uri, "\x00\r\n") {
return "", errors.New("refusing to open non-QQ-group protocol URL")
}
return uri, nil
}
func decodeBase64Flexible(s string) ([]byte, bool) {
+53
View File
@@ -0,0 +1,53 @@
//go:build darwin && cgo
package app
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework AppKit
#include <AppKit/AppKit.h>
#include <stdlib.h>
static int reimsHasQQProtocolHandler(const char *uri) {
@autoreleasepool {
NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:uri]];
NSURL *appURL = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL:url];
return appURL && [[[NSBundle bundleWithURL:appURL] bundleIdentifier] isEqualToString:@"com.tencent.qq"];
}
}
static int reimsOpenQQProtocol(const char *uri) {
@autoreleasepool {
NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:uri]];
return url && [[NSWorkspace sharedWorkspace] openURL:url];
}
}
*/
import "C"
import (
"errors"
"unsafe"
)
func hasQQProtocolHandler() bool {
uri := C.CString(qqGroupProtocolURL)
defer C.free(unsafe.Pointer(uri))
return C.reimsHasQQProtocolHandler(uri) != 0
}
func launchQQProtocol(uri string) error {
clean, err := validateQQGroupProtocolURL(uri)
if err != nil {
return err
}
if !hasQQProtocolHandler() {
return errQQNotInstalled
}
target := C.CString(clean)
defer C.free(unsafe.Pointer(target))
if C.reimsOpenQQProtocol(target) == 0 {
return errors.New("macOS refused to open the QQ group invite")
}
return nil
}
+24
View File
@@ -0,0 +1,24 @@
//go:build darwin && cgo
package app
import (
"os"
"testing"
)
func TestMacQQProtocolHandler(t *testing.T) {
mode := os.Getenv("REIMS_TEST_MAC_QQ")
if mode != "1" && mode != "launch" {
t.Skip("requires QQ registered as the tencent URL handler in a macOS desktop session")
}
a := new(App)
if !a.CanOpenQQGroup() {
t.Fatal("Launch Services did not resolve the QQ group link to the QQ app")
}
if mode == "launch" {
if err := a.OpenQQGroup(); err != nil {
t.Fatal(err)
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !windows
//go:build !windows && (!darwin || !cgo)
package app
+12
View File
@@ -54,6 +54,18 @@ func TestBuildQQGroupSchemeURL(t *testing.T) {
}
}
func TestValidateQQGroupProtocolURL(t *testing.T) {
invite := buildQQGroupSchemeURL(qqGroupID, "test-key", time.UnixMilli(1))
if got, err := validateQQGroupProtocolURL(" " + invite + " "); err != nil || got != invite {
t.Fatalf("validate invite = %q, %v", got, err)
}
for _, raw := range []string{qqGroupShortURL, "tencent://message/?uin=123", "tencent://groupwpa/other?param=123", invite + "\x00extra"} {
if _, err := validateQQGroupProtocolURL(raw); err == nil {
t.Errorf("accepted %q", raw)
}
}
}
func TestExtractCommandExecutable(t *testing.T) {
cases := []struct {
in string
+5 -7
View File
@@ -3,10 +3,8 @@
package app
import (
"errors"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
@@ -14,8 +12,8 @@ import (
)
var (
qqShell32 = syscall.NewLazyDLL("shell32.dll")
qqProcShellExecW = qqShell32.NewProc("ShellExecuteW")
qqShell32 = syscall.NewLazyDLL("shell32.dll")
qqProcShellExecW = qqShell32.NewProc("ShellExecuteW")
)
func hasQQProtocolHandler() bool {
@@ -52,9 +50,9 @@ func hasQQProtocolHandler() bool {
}
func launchQQProtocol(uri string) error {
trimmed := strings.TrimSpace(uri)
if !strings.HasPrefix(trimmed, "tencent://groupwpa/") {
return errors.New("refusing to open non-QQ-group protocol URL")
trimmed, err := validateQQGroupProtocolURL(uri)
if err != nil {
return err
}
verb, err := syscall.UTF16PtrFromString("open")
if err != nil {
+21
View File
@@ -0,0 +1,21 @@
//go:build !windows
package app
import (
"context"
"testing"
"github.com/Nwflower/reims-go/internal/config"
)
func TestClosingDesktopWithoutSystemTray(t *testing.T) {
a := &App{cfg: config.Default()}
a.startTray()
if a.trayMgr != nil {
t.Fatal("host without a system tray must not register a tray manager")
}
if a.beforeClose(context.Background()) {
t.Fatal("closing the window must not hide it to an unavailable tray")
}
}
+32 -2
View File
@@ -2,10 +2,14 @@ package app
import (
"fmt"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
@@ -97,8 +101,7 @@ func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) {
return "", 0, "", false
}
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
// PowerShell) connected to the VM's forwarded SSH port.
// OpenSSHTerminal opens an interactive SSH session in the host's terminal.
func (a *App) OpenSSHTerminal(driverID, name, user string) error {
d, err := a.resolveVMInfo(driverID, name)
if err != nil {
@@ -119,6 +122,17 @@ func (a *App) OpenSSHTerminal(driverID, name, user string) error {
if user == "" {
user = endpointUser
}
if runtime.GOOS == "darwin" {
spec, err := macSSHTerminalLaunch(sshHost, sshPort, user)
if err != nil {
return err
}
if err := exec.Command(spec.exe, spec.args...).Run(); err != nil {
return fmt.Errorf("open SSH terminal: %w", err)
}
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Opened SSH terminal (%s:%d)", sshHost, sshPort))
return nil
}
target := sshHost
if user != "" {
target = user + "@" + sshHost
@@ -139,6 +153,22 @@ func (a *App) OpenSSHTerminal(driverID, name, user string) error {
return nil
}
// macSSHTerminalLaunch passes a validated SSH URL to Launch Services, not a shell command.
func macSSHTerminalLaunch(host string, port int, user string) (launchSpec, error) {
ep := driver.VMEndpoint{Kind: driver.EndpointSSH, Host: host, Port: port, User: user}
if err := driver.ValidateEndpoint(ep); err != nil {
return launchSpec{}, err
}
if host == "" {
host = "127.0.0.1"
}
target := url.URL{Scheme: "ssh", Host: net.JoinHostPort(host, strconv.Itoa(port))}
if user != "" {
target.User = url.User(user)
}
return launchSpec{exe: "/usr/bin/open", args: []string{target.String()}}, nil
}
// WriteSSHConfig idempotently writes or updates a Host block for the VM in
// ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe").
func (a *App) WriteSSHConfig(driverID, name, user string) (string, error) {
+12 -1
View File
@@ -34,7 +34,7 @@ type Task struct {
Kind string `json:"kind"` // installer/recovery/VM/runtime/app tasks or "plugin:<pluginID>"
Subject string `json:"subject"` // release ("26.7.3") or VM name
VM string `json:"vm,omitempty"`
InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" while an installer download is attached
InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" | "ipsw" while an installer download is attached
InstallerVersion string `json:"installer_version,omitempty"` // release ("26.7.3") or online target ("tahoe" / "latest")
InstallerPhase string `json:"installer_phase,omitempty"` // "queued" | "downloading" while active
Step string `json:"step"` // upstream wording, e.g. "downloading OpenCore 1.0.8"
@@ -280,6 +280,17 @@ func (m *taskManager) hasRunningDownload() bool {
return false
}
func (m *taskManager) hasRunningRestore() bool {
m.mu.Lock()
defer m.mu.Unlock()
for _, e := range m.tasks {
if e.task.Kind == "vm-restore" && e.task.Status == TaskRunning {
return true
}
}
return false
}
func (m *taskManager) cancelAll() {
m.mu.Lock()
cancels := make([]context.CancelFunc, 0, len(m.tasks))
+24 -3
View File
@@ -101,15 +101,16 @@ func (a *App) GetVMThumbnail(driverID, name string) (VMThumbnail, error) {
return readThumb(path, false), nil
}
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
// restoring it first if minimized.
// FocusVMWindow brings a running VM's display or primary endpoint to the foreground.
func (a *App) FocusVMWindow(driverID, name string) error {
info, err := a.resolveVMInfo(driverID, name)
if err != nil {
return err
}
if driver.IsHosted(info.Capabilities) {
// A hosted VM has no window of its own: bring up its best endpoint.
if driver.HasCapability(info.Capabilities, driver.CapWindow) {
return a.showHostedVMWindow(info)
}
ep, ok := driver.PrimaryHostedEndpoint(info.Endpoints)
if !ok {
return fmt.Errorf("%s has no ready endpoint to open", name)
@@ -137,6 +138,26 @@ func (a *App) FocusVMWindow(driverID, name string) error {
return nil
}
func (a *App) showHostedVMWindow(info driver.VMInfo) error {
if info.State != "running" {
return fmt.Errorf("VM %s is not running", info.Name)
}
a.mu.Lock()
router := a.driverRouter
a.mu.Unlock()
drv, err := router.DriverByID(info.DriverID)
if err != nil {
return err
}
window, ok := drv.(driver.WindowDriver)
if !ok {
return fmt.Errorf("driver %q does not provide a viewer", info.DriverID)
}
ctx, cancel := context.WithTimeout(a.baseCtx(), 10*time.Second)
defer cancel()
return window.ShowWindow(ctx, info.Name)
}
// ToggleVMFullscreen switches the running VM's display through its owning driver.
func (a *App) ToggleVMFullscreen(driverID, name string) (bool, error) {
a.mu.Lock()
+1
View File
@@ -13,6 +13,7 @@ var renameOwners = map[string]bool{
"internal/app/ui_health.go": true, // log rotation
"internal/atomicfile/atomicfile.go": true,
"internal/fetch/fetch.go": true, // download
"internal/fetch/validated.go": true, // validated restore image download
"internal/macos/installer/accelerated.go": true, // download
"internal/macos/installer/hfs_image.go": true, // disk image
"internal/macos/installer/oc_cache.go": true, // download
+8
View File
@@ -151,6 +151,14 @@ func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) {
}
for _, dir := range s.imports() {
if name, ok := strings.CutPrefix(dir, "internal/"); ok && !isMacOSDir(dir) {
if s.rel == "internal/macos/installer/restore_image.go" && name == "fetch" {
// Native restore transfer shares the client's validated HTTP cache path.
continue
}
if s.dir() == "internal/macos/applevz" && name == "atomicfile" {
// The native backend owns its settings and uses the common safe replacement primitive.
continue
}
found[name] = append(found[name], s.rel)
}
}
+1 -1
View File
@@ -71,7 +71,7 @@ var loadSources = sync.OnceValues(func() ([]source, error) {
if err != nil {
return err
}
f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution)
f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution|parser.ParseComments)
if err != nil {
return err
}
+6
View File
@@ -30,6 +30,12 @@ func TestProductCodeHasNoUncalledFunctions(t *testing.T) {
self = s.dir() + "." + fn.Name.Name
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 fn.Doc != nil {
for _, comment := range fn.Doc.List {
// cgo callbacks are called from native code, not the Go AST.
entry = entry || comment.Text == "//export "+fn.Name.Name
}
}
if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) {
decls[self] = decl{s, fn}
}
+55
View File
@@ -0,0 +1,55 @@
package cli
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
)
func TestAppleNativeCLIUsesItsOwnDriverWithoutWindowsRuntime(t *testing.T) {
root := t.TempDir()
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
cfg := &config.Config{DataRoot: root}
mgr, router, err := openCLIPluginManager(cfg, true)
if err != nil {
t.Fatal(err)
}
defer mgr.Close()
wantApple := runtime.GOOS == "darwin" && runtime.GOARCH == "arm64"
if isAppleCreateDriver(defaultCreateDriver()) != wantApple {
t.Fatalf("unexpected default %q on %s/%s", defaultCreateDriver(), runtime.GOOS, runtime.GOARCH)
}
if !wantApple {
return
}
apple, err := router.DriverByID(defaultCreateDriver())
if err != nil {
t.Fatal(err)
}
if apple.RuntimeKind() != "external" || !driver.HasCapability(apple.Capabilities(), driver.CapWindow) {
t.Fatalf("unexpected native driver metadata: %v", apple)
}
if _, err := router.DriverByID(driver.BuiltinReimsMacOSDriverID); err == nil {
t.Fatal("the Apple host must not load the Windows runtime driver")
}
registry := filepath.Join(cfg.XDGConfigDir(), "reims-ctl", "vms.toml")
if err := os.MkdirAll(filepath.Dir(registry), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(registry, []byte("[[vm]]\nname = \"legacy\"\ndir = \"/not-used\"\n"), 0o600); err != nil {
t.Fatal(err)
}
vms, err := router.ListAllVMs(t.Context())
if err != nil || len(vms) != 1 || !vms[0].DriverUnavailable || vms[0].DriverID != driver.BuiltinReimsMacOSDriverID {
t.Fatalf("legacy entries should be listed without loading the Windows runtime: %+v, %v", vms, err)
}
err = vmCreate(t.Context(), cfg, "en-US", []string{"--gpu", "auto", "mac"}, false)
if err == nil || !strings.Contains(err.Error(), "--gpu") {
t.Fatalf("native create silently accepted a Windows graphics option: %v", err)
}
}
+80 -39
View File
@@ -91,7 +91,7 @@ func run(args []string) (i18n.Locale, error) {
switch rest[0] {
case "doctor":
return loc, cmdDoctor(cfg, loc, rest[1:])
return loc, cmdDoctor(cfg, loc, root, rest[1:])
case "runtime":
return loc, cmdRuntime(cfg, loc, rest[1:])
case "vm":
@@ -114,6 +114,10 @@ func run(args []string) (i18n.Locale, error) {
}
func printUsage(loc i18n.Locale) {
if isAppleCreateDriver(defaultCreateDriver()) {
printAppleUsage(loc)
return
}
fmt.Println(i18n.T(loc, "cli.usage.header"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_usage"))
fmt.Println(i18n.T(loc, "cli.usage.line_gui"))
@@ -150,20 +154,27 @@ func printUsage(loc i18n.Locale) {
}
}
func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
func cmdDoctor(cfg *config.Config, loc i18n.Locale, root dataroot.Status, args []string) error {
fs := flag.NewFlagSet("doctor", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args); err != nil {
return err
}
rep := host.Inspect(cfg.DataRoot)
if native, err := nativeVirtualizationStatus(context.Background()); native {
rep.AppleVirtualization = &host.AppleVirtualizationStatus{Ready: err == nil}
if err != nil {
rep.AppleVirtualization.Detail = i18n.FormatCLIError(loc, err)
}
}
active, _ := rt.ResolveActive(cfg)
if *asJSON {
payload := map[string]any{
"host": rep,
"config": cfg,
"runtime": active,
"host": rep,
"config": cfg,
"runtime": active,
"data_root": root,
}
return printJSON(payload)
}
@@ -176,25 +187,60 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ecores"), i18n.T(loc, "doctor.ecores.detail", rep.ECoreCount, rep.ECoreLogicalCPUs))
}
if rep.TotalRAMGB > 0 {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB))
memory := i18n.M(loc, "doctor.ram.total_only", i18n.Vars{"total": rep.TotalRAMGB})
if rep.MemoryUsageKnown {
memory = i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB)
}
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), memory)
}
if rep.AppleVirtualization != nil {
printAppleVirtualizationStatus(loc, rep.AppleVirtualization)
}
if rep.FreeDiskGB > 0 {
fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot)
}
whpxKey := "doctor.whpx.unsupported"
switch rep.WHPX {
case host.WHPXReady:
whpxKey = "doctor.whpx.ok"
case host.WHPXHypervisorOff:
whpxKey = "doctor.whpx.hypervisor_off"
case host.WHPXNoHypervisor:
whpxKey = "doctor.whpx.no_hv"
case host.WHPXMissing:
whpxKey = "doctor.whpx.missing"
if err := dataroot.Error(loc, root); err != nil {
fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, err))
}
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey))
if rep.AppleVirtualization == nil {
whpxKey := "doctor.whpx.unsupported"
switch rep.WHPX {
case host.WHPXReady:
whpxKey = "doctor.whpx.ok"
case host.WHPXHypervisorOff:
whpxKey = "doctor.whpx.hypervisor_off"
case host.WHPXNoHypervisor:
whpxKey = "doctor.whpx.no_hv"
case host.WHPXMissing:
whpxKey = "doctor.whpx.missing"
}
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey))
}
printDoctorVulkan(loc, rep)
if active == nil {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none"))
} else {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir))
}
if len(rep.DeepBackingChains) > 0 {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain"))
for _, c := range rep.DeepBackingChains {
if c.Broken {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path))
} else {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth))
}
}
}
return nil
}
func printDoctorVulkan(loc i18n.Locale, rep host.Report) {
if rep.AppleVirtualization != nil && rep.VulkanProbeError == "" && len(rep.GPUs) == 0 {
return // The native host does not use or probe Vulkan.
}
if rep.VulkanProbeError != "" {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.M(loc, "doctor.gpu.probe_failed", i18n.Vars{"detail": rep.VulkanProbeError}))
}
@@ -237,23 +283,6 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
}
}
}
if active == nil {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none"))
} else {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir))
}
if len(rep.DeepBackingChains) > 0 {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain"))
for _, c := range rep.DeepBackingChains {
if c.Broken {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path))
} else {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth))
}
}
}
return nil
}
func sameGPU(a, b *host.GPUInfo) bool {
@@ -409,11 +438,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
}
return startVM(ctx, cfg, driverID, name, viaWindow)
case "stop":
driverID, name, err := parseVMTarget(args)
if err != nil {
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
force := fs.Bool("force", false, "Force power off if the guest cannot shut down normally")
if err := fs.Parse(args[1:]); err != nil {
return err
}
return stopVM(ctx, cfg, driverID, name)
if fs.NArg() != 1 {
return fmt.Errorf("usage: reims-go vm stop [--driver <id>] [--force] <name>")
}
return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force)
case "suspend":
driverID, name, err := parseVMTarget(args)
if err != nil {
@@ -497,7 +531,8 @@ func parseVMTarget(args []string) (driverID, name string, err error) {
func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
fs := flag.NewFlagSet("vm create", flag.ContinueOnError)
driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)")
driverID := fs.String("driver", defaultCreateDriver(), "Guest VM driver ID")
ipsw := fs.String("ipsw", "", "Local Apple macOS restore image (Apple Virtualization only)")
dir := fs.String("dir", "", "Custom VM directory")
macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)")
cpus := fs.Int("cpus", 8, "vCPU count")
@@ -518,6 +553,12 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
if *ipsw != "" && !isAppleCreateDriver(*driverID) {
return fmt.Errorf("--ipsw is only supported by the Apple Virtualization driver")
}
if isAppleCreateDriver(*driverID) {
return createAppleVM(ctx, cfg, *driverID, name, *dir, *ipsw, *cpus, *mem, *diskSize, *start, fs)
}
// Route non-reims guest drivers through the plugin Driver Router (§5.3, §10).
if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID {
mgr, router, err := openCLIPluginManager(cfg, false)
+88
View File
@@ -3,16 +3,21 @@ package cli
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore"
@@ -24,6 +29,48 @@ import (
func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) }
func defaultCreateDriver() string {
if guest.UsesAppleVirtualization() {
return guest.AppleDriverID()
}
return driver.BuiltinReimsMacOSDriverID
}
func isAppleCreateDriver(id string) bool { return id == guest.AppleDriverID() }
func nativeVirtualizationStatus(ctx context.Context) (bool, error) {
if !guest.UsesAppleVirtualization() {
return false, nil
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return true, guest.ProbeAppleVirtualization(ctx)
}
func printAppleUsage(loc i18n.Locale) {
fmt.Println(i18n.T(loc, "cli.usage.apple.header"))
fmt.Println(i18n.T(loc, "cli.usage.line_cmd"))
fmt.Println()
for _, k := range []string{
"cli.usage.apple.doctor", "cli.usage.apple.create", "cli.usage.cmd_vm_list",
"cli.usage.apple.start", "cli.usage.apple.stop", "cli.usage.apple.delete",
"cli.usage.cmd_vm_set", "cli.usage.cmd_plugin", "cli.usage.cmd_version",
} {
fmt.Println(i18n.T(loc, k))
}
}
func printAppleVirtualizationStatus(loc i18n.Locale, status *host.AppleVirtualizationStatus) {
key := "doctor.apple_virtualization.ready"
if !status.Ready {
key = "doctor.apple_virtualization.unavailable"
}
fmt.Printf("%-36s: %s\n", "Apple Virtualization", i18n.T(loc, key))
if status.Detail != "" {
fmt.Fprintln(os.Stderr, status.Detail)
}
}
func requireDirectNetwork(vm driver.VMInfo) error {
if vm.Ref().DriverID != driver.BuiltinReimsMacOSDriverID {
return nil
@@ -63,6 +110,47 @@ func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error {
return nil
}
func createAppleVM(ctx context.Context, cfg *config.Config, id, name, dir, ipsw string, cpus int, mem, disk string, start bool, flags *flag.FlagSet) error {
options := map[string]any{"restore_path": ipsw}
var unsupported error
flags.Visit(func(f *flag.Flag) {
switch f.Name {
case "driver", "ipsw", "start":
case "cpus":
options["cpus"] = cpus
case "memory":
options["memory"] = mem
case "disk-size":
options["disk_size"] = disk
default:
unsupported = fmt.Errorf("--%s is not supported by the Apple Virtualization driver", f.Name)
}
})
if unsupported != nil {
return unsupported
}
if dir != "" {
return errors.New("the Apple Virtualization driver manages its VM directories under the data folder")
}
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
drv, err := router.DriverByID(id)
if err != nil {
return err
}
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
req := driver.CreateRequest{DriverID: drv.ID(), Name: name, Options: options}
if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil || !start {
return err
}
_, err = lifecycle.New(mgr.Registry(), router, nil).Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr)
return err
}
// macOSCreateOptions is the CLI-neutral input to the native macOS create flow.
type macOSCreateOptions struct {
Name, Dir, MacOS, Memory, DiskSize, Disk, DiskMode, DiskCache, GPU, GuestLang string
+3 -3
View File
@@ -31,8 +31,8 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
LocaleFn: func() i18n.Locale {
return i18n.EffectiveLocale(cfg.Locale)
},
Logger: logf,
VMInventory: guest.VMInventory(),
Logger: logf,
VMInventories: guest.VMInventories(),
Callbacks: builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
@@ -40,7 +40,7 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
},
Log: logf,
},
RegisterGuest: guest.Register,
RegisterGuest: guest.RegisterForHost,
StrictRegister: true,
})
if err != nil {
+4 -1
View File
@@ -21,11 +21,14 @@ func TestMacOSPluginDisableAndVMInventory(t *testing.T) {
_, err := run(append(args, command...))
return err
}
if isAppleCreateDriver(defaultCreateDriver()) {
t.Skip("this test exercises registration and toggling of the Reims vGPU driver")
}
t.Setenv("REIMS_CTL_CONFIG_DIR", filepath.Join(root, "config", "reims-ctl"))
if err := runCLI("plugin", "disable", "builtin.guest.macos"); err != nil {
t.Fatalf("disable without a runtime or VMs: %v", err)
}
for _, cmd := range [][]string{{"vm", "create", "--start", "mac"}, {"vm", "type", "mac", "test"}} {
for _, cmd := range [][]string{{"vm", "create", "--driver", driver.BuiltinReimsMacOSDriverID, "--start", "mac"}, {"vm", "type", "mac", "test"}} {
if err := runCLI(cmd...); err == nil || err.Error() != i18n.T(i18n.EnUS, "err.macos.disabled") {
t.Fatalf("%v while disabled: %v", cmd, err)
}
+2 -2
View File
@@ -103,13 +103,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (
return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr)
}
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error {
svc, closeService, err := openCLILifecycle(cfg)
if err != nil {
return err
}
defer closeService()
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr)
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr)
}
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
+6
View File
@@ -41,6 +41,7 @@ const (
// CapHosted marks VMs the driver runs itself: the host does not spawn,
// watch, pin or window-manage a process for them.
CapHosted = "hosted"
CapWindow = "window" // a hosted driver can bring its own viewer forward
CapConsole = "console"
CapTPM = "tpm"
CapRDP = "rdp"
@@ -237,6 +238,11 @@ type ActionDriver interface {
InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error)
}
// WindowDriver lets a hosted driver bring its own guest viewer forward.
type WindowDriver interface {
ShowWindow(context.Context, string) error
}
// LogDriver exposes driver-owned serial and QEMU logs.
type LogDriver interface {
ReadLogs(context.Context, string, bool) (string, error)
+264
View File
@@ -0,0 +1,264 @@
package fetch
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
)
// InvalidDownloadError marks a validation failure that proves the bytes are bad.
// Other validation failures leave the staged bytes and ETag available for retry.
type InvalidDownloadError struct{ Err error }
func (e *InvalidDownloadError) Error() string { return e.Err.Error() }
func (e *InvalidDownloadError) Unwrap() error { return e.Err }
// ResumeValidated downloads directly from the supplied client. A strong ETag
// binds a partial to the same representation; only a complete, consumer-validated
// file is published. The validator checks any consumer-specific integrity data.
func ResumeValidated(ctx context.Context, client *http.Client, url, final, part string, maxBytes int64,
onProgress Progress, validate func(context.Context, string) error) error {
if onProgress == nil {
onProgress = func(int64, int64) {}
}
for _, path := range []string{part, part + ".etag"} {
if _, err := plainDownloadFile(path); err != nil {
return err
}
}
info, err := plainDownloadFile(final)
if err != nil {
return err
}
if info != nil {
if info.Size() <= 0 || info.Size() > maxBytes {
return errors.New("cached download has an invalid size; delete it before retrying")
}
onProgress(info.Size(), info.Size())
return validate(ctx, final)
}
if err := streamValidated(ctx, client, url, part, maxBytes, onProgress); err != nil {
return err
}
if err := validate(ctx, part); err != nil {
if ctx.Err() != nil {
return ctx.Err() // Keep the partial so validation can be retried.
}
var invalid *InvalidDownloadError
if errors.As(err, &invalid) {
return errors.Join(err, removeDownloadPart(part+".etag"), removeDownloadPart(part))
}
return err
}
if err := ctx.Err(); err != nil {
return err
}
if err := removeDownloadPart(part + ".etag"); err != nil {
return err
}
return os.Rename(part, final)
}
func plainDownloadFile(path string) (os.FileInfo, error) {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("download path is not a regular file: %s", path)
}
return info, nil
}
func removeDownloadPart(path string) error {
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
func streamValidated(ctx context.Context, client *http.Client, url, part string, maxBytes int64, progress Progress) error {
info, err := plainDownloadFile(part)
if err != nil {
return err
}
var have int64
var validator string
if info != nil && info.Size() > 0 && info.Size() <= maxBytes {
if tag, err := plainDownloadFile(part + ".etag"); err != nil {
return err
} else if tag != nil && tag.Size() <= 1024 {
data, err := os.ReadFile(part + ".etag")
if err != nil {
return err
}
if strongETag(string(data)) {
validator, have = string(data), info.Size()
}
}
}
retry, err := transferValidated(ctx, client, url, part, validator, have, maxBytes, progress)
if retry && err == nil {
_, err = transferValidated(ctx, client, url, part, "", 0, maxBytes, progress)
}
return err
}
func transferValidated(ctx context.Context, client *http.Client, url, part, validator string, have, maxBytes int64, progress Progress) (bool, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := NewRequest(ctx, url)
if err != nil {
return false, err
}
req.Header.Set("Accept-Encoding", "identity")
if have > 0 {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have))
req.Header.Set("If-Range", validator)
}
resp, err := client.Do(req)
if err != nil {
return false, err
}
if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && have > 0 {
// A 416 body is not image data; close it before any follow-up request.
resp.Body.Close()
if !confirmedCompleteRange(client, req, resp, validator, have) {
return true, nil
}
if err := checkValidatedSize(part, have); err != nil {
return false, err
}
progress(have, have)
return false, nil
}
defer resp.Body.Close()
tag := singleHeader(resp.Header, "ETag")
contentRange := singleHeader(resp.Header, "Content-Range")
flags, total := os.O_CREATE|os.O_WRONLY, resp.ContentLength
switch resp.StatusCode {
case http.StatusPartialContent:
if have == 0 || tag != validator || !validTailRange(contentRange, have, resp.ContentLength) {
if have > 0 {
return true, nil
}
return false, errors.New("download returned an unsolicited partial response")
}
flags, total = flags|os.O_APPEND, have+resp.ContentLength
case http.StatusOK:
have, flags = 0, flags|os.O_TRUNC
default:
return false, fmt.Errorf("download: HTTP %d", resp.StatusCode)
}
if !identityEncoding(resp) {
return false, errors.New("download returned an unexpected content encoding")
}
if total <= 0 || total > maxBytes {
return false, fmt.Errorf("download has an invalid content length: %d", total)
}
if have == 0 {
if err := resetDownloadValidator(part, tag); err != nil {
return false, err
}
}
if err := copyBody(resp.Body, cancel, part, flags, have, total, total, 45*time.Second, "restore image", progress); err != nil {
return false, err
}
return false, checkValidatedSize(part, total)
}
func confirmedCompleteRange(client *http.Client, req *http.Request, resp *http.Response, validator string, have int64) bool {
if !completeRange(singleHeader(resp.Header, "Content-Range"), have) {
return false
}
if tags := resp.Header.Values("ETag"); len(tags) != 0 {
return len(tags) == 1 && tags[0] == validator
}
// Some servers do not send ETag on 416. Confirm the same unencoded
// representation via a bounded conditional HEAD, never from length alone.
ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
defer cancel()
head := req.Clone(ctx)
head.Method = http.MethodHead
head.Header.Del("Range")
head.Header.Del("If-Range")
head.Header.Set("If-Match", validator)
meta, err := client.Do(head)
if err != nil {
return false
}
defer meta.Body.Close()
return meta.StatusCode == http.StatusOK && meta.Request != nil && resp.Request != nil &&
meta.Request.URL.String() == resp.Request.URL.String() &&
singleHeader(meta.Header, "ETag") == validator && meta.ContentLength == have && identityEncoding(meta)
}
func identityEncoding(resp *http.Response) bool {
encodings := resp.Header.Values("Content-Encoding")
return !resp.Uncompressed && (len(encodings) == 0 || len(encodings) == 1 && strings.EqualFold(encodings[0], "identity"))
}
func checkValidatedSize(part string, total int64) error {
if info, err := plainDownloadFile(part); err != nil || info == nil || info.Size() != total {
return errors.Join(errors.New("restore image download is incomplete"), err)
}
return nil
}
func resetDownloadValidator(part, tag string) error {
if err := removeDownloadPart(part + ".etag"); err != nil {
return err
}
if err := removeDownloadPart(part); err != nil {
return err
}
if !strongETag(tag) {
return nil
}
return atomicfile.Write(part+".etag", []byte(tag), 0o600)
}
func singleHeader(header http.Header, name string) string {
if values := header.Values(name); len(values) == 1 {
return values[0]
}
return ""
}
func strongETag(tag string) bool {
if len(tag) < 2 || len(tag) > 1024 || tag[0] != '"' || tag[len(tag)-1] != '"' {
return false
}
for i := 1; i < len(tag)-1; i++ {
if b := tag[i]; b <= ' ' || b == '"' || b == '\x7f' {
return false
}
}
return true
}
func completeRange(header string, have int64) bool {
length, ok := strings.CutPrefix(header, "bytes */")
return ok && strings.TrimLeft(length, "0") == strconv.FormatInt(have, 10)
}
func validTailRange(header string, have, length int64) bool {
span, totalRaw, ok := strings.Cut(strings.TrimPrefix(header, "bytes "), "/")
firstRaw, lastRaw, found := strings.Cut(span, "-")
first, e1 := strconv.ParseInt(firstRaw, 10, 64)
last, e2 := strconv.ParseInt(lastRaw, 10, 64)
total, e3 := strconv.ParseInt(totalRaw, 10, 64)
return strings.HasPrefix(header, "bytes ") && ok && found && e1 == nil && e2 == nil && e3 == nil &&
length > 0 && first == have && last >= first && last < total && total-last == 1 && last-first+1 == length
}
+288
View File
@@ -0,0 +1,288 @@
package fetch
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"testing"
)
func TestValidatedTransferUsesBoundPartialAndPublishesAfterValidation(t *testing.T) {
const payload = "fake IPSW body used only in a local test"
for _, tc := range []struct{ name, reply string }{{"resume", "matched"}, {"restart when file changes", "changed"}, {"restart on incorrect content range", "wrong-range"}} {
t.Run(tc.name, func(t *testing.T) {
var requests []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rangeHeader := r.Header.Get("Range")
requests = append(requests, rangeHeader)
w.Header().Set("ETag", `"stable"`)
if rangeHeader != "" {
if rangeHeader != "bytes=5-" || r.Header.Get("If-Range") != `"stable"` {
t.Errorf("unsafe resume request: %s, %s", rangeHeader, r.Header.Get("If-Range"))
}
switch tc.reply {
case "changed":
w.Header().Set("ETag", `"changed"`)
case "wrong-range", "matched":
first := 5
if tc.reply == "wrong-range" {
first = 4
}
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", first, len(payload)-1, len(payload)))
w.WriteHeader(http.StatusPartialContent)
fmt.Fprint(w, payload[first:])
return
}
}
fmt.Fprint(w, payload)
}))
defer server.Close()
dir := t.TempDir()
final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw")
for p, body := range map[string]string{part: payload[:5], part + ".etag": `"stable"`} {
if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
validate := func(_ context.Context, name string) error {
if name != part {
t.Errorf("validation path = %s", name)
}
if _, err := os.Stat(final); !os.IsNotExist(err) {
t.Error("download published before validation")
}
body, err := os.ReadFile(name)
if string(body) != payload {
t.Errorf("unexpected body: %q", body)
}
return err
}
if err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, validate); err != nil {
t.Fatal(err)
}
if len(requests) != 1 && tc.reply != "wrong-range" || len(requests) != 2 && tc.reply == "wrong-range" {
t.Fatalf("requests: %v", requests)
}
if body, err := os.ReadFile(final); err != nil || string(body) != payload {
t.Fatalf("final = %q, %v", body, err)
}
if _, err := os.Stat(part + ".etag"); !os.IsNotExist(err) {
t.Fatalf("validator remains: %v", err)
}
})
}
}
func TestValidatedTransferReusesOnlyBoundComplete416(t *testing.T) {
const payload = "bound fixture"
const replacement = "changed bytes" // Same size, distinct bytes.
exact := fmt.Sprintf("bytes */%d", len(payload))
for _, tc := range []struct {
name, savedTag string
tags, ranges []string
wantRange, wantFresh bool
}{
{"complete", `"stable"`, []string{`"stable"`}, []string{exact}, true, false},
{"changed", `"stable"`, []string{`"changed"`}, []string{exact}, true, true},
{"weak response ETag", `"stable"`, []string{`W/"stable"`}, []string{exact}, true, true},
{"ambiguous response ETag", `"stable"`, []string{`"stable"`, `"changed"`}, []string{exact}, true, true},
{"wrong size", `"stable"`, []string{`"stable"`}, []string{fmt.Sprintf("bytes */%d", len(payload)-1)}, true, true},
{"missing size", `"stable"`, []string{`"stable"`}, nil, true, true},
{"malformed size", `"stable"`, []string{`"stable"`}, []string{fmt.Sprintf("bytes */+%d", len(payload))}, true, true},
{"ambiguous size", `"stable"`, []string{`"stable"`}, []string{exact, "bytes */1"}, true, true},
{"missing saved ETag", "", []string{`"stable"`}, []string{exact}, false, true},
{"weak saved ETag", `W/"stable"`, []string{`"stable"`}, []string{exact}, false, true},
{"malformed saved ETag", `"not valid"`, []string{`"stable"`}, []string{exact}, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
var requests []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rangeHeader := r.Header.Get("Range")
requests = append(requests, rangeHeader)
if rangeHeader == "" {
w.Header().Set("ETag", `"changed"`)
fmt.Fprint(w, replacement)
return
}
if r.Header.Get("If-Range") != tc.savedTag || r.Header.Get("Accept-Encoding") != "identity" {
t.Errorf("unexpected resume headers: %v", r.Header)
}
for _, tag := range tc.tags {
w.Header().Add("ETag", tag)
}
for _, value := range tc.ranges {
w.Header().Add("Content-Range", value)
}
w.Header().Set("Content-Encoding", "gzip") // The 416 error body is ignored.
w.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
fmt.Fprint(w, "not image data")
}))
defer server.Close()
dir := t.TempDir()
final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw")
if err := os.WriteFile(part, []byte(payload), 0o600); err != nil {
t.Fatal(err)
}
if tc.savedTag != "" {
if err := os.WriteFile(part+".etag", []byte(tc.savedTag), 0o600); err != nil {
t.Fatal(err)
}
}
var wantRequests []string
wantBody := payload
if tc.wantRange {
wantRequests = append(wantRequests, fmt.Sprintf("bytes=%d-", len(payload)))
}
if tc.wantFresh {
wantRequests = append(wantRequests, "")
wantBody = replacement
}
var done, total int64
err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, func(d, n int64) {
done, total = d, n
}, func(_ context.Context, file string) error {
if file != part {
t.Errorf("validation path = %s", file)
}
if _, err := os.Stat(final); !os.IsNotExist(err) {
t.Errorf("download published before validation: %v", err)
}
if body, err := os.ReadFile(file); err != nil || string(body) != wantBody {
t.Errorf("staged body = %q, %v; want %q", body, err, wantBody)
}
return nil
})
if err != nil {
t.Fatal(err)
}
if !slices.Equal(requests, wantRequests) {
t.Fatalf("requests = %q, want %q", requests, wantRequests)
}
if want := int64(len(wantBody)); done != want || total != want {
t.Fatalf("progress = %d/%d, want %d/%d", done, total, want, want)
}
if body, err := os.ReadFile(final); err != nil || string(body) != wantBody {
t.Fatalf("final = %q, %v; want %q", body, err, wantBody)
}
})
}
}
func TestValidatedTransferConfirmsUntaggedComplete416WithHead(t *testing.T) {
const staged = "staged bytes"
const fresh = "fresh bytes"
const tag = `"stable"`
for _, tc := range []struct {
name, headTag, encoding string
headSize, headStatus int
redirect, wantFresh bool
}{
{"match", tag, "", len(staged), http.StatusOK, false, false},
{"changed", `"changed"`, "", len(staged), http.StatusOK, false, true},
{"weak", `W/"stable"`, "", len(staged), http.StatusOK, false, true},
{"missing", "", "", len(staged), http.StatusOK, false, true},
{"wrong size", tag, "", len(staged) + 1, http.StatusOK, false, true},
{"encoded", tag, "gzip", len(staged), http.StatusOK, false, true},
{"precondition failed", tag, "", len(staged), http.StatusPreconditionFailed, false, true},
{"different target", tag, "", len(staged), http.StatusOK, true, true},
} {
t.Run(tc.name, func(t *testing.T) {
var requests []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Method+" "+r.URL.Path+" "+r.Header.Get("Range"))
if r.Method == http.MethodHead {
if r.Header.Get("If-Match") != tag || r.Header.Get("Range") != "" || r.Header.Get("If-Range") != "" || r.Header.Get("Accept-Encoding") != "identity" {
t.Errorf("unexpected confirmation headers: %v", r.Header)
}
if tc.redirect && r.URL.Path == "/" {
http.Redirect(w, r, "/other", http.StatusTemporaryRedirect)
return
}
if tc.headTag != "" {
w.Header().Set("ETag", tc.headTag)
}
if tc.encoding != "" {
w.Header().Set("Content-Encoding", tc.encoding)
}
w.Header().Set("Content-Length", fmt.Sprint(tc.headSize))
w.WriteHeader(tc.headStatus)
return
}
if r.Header.Get("Range") != "" {
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(staged)))
w.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
return
}
fmt.Fprint(w, fresh)
}))
defer server.Close()
dir := t.TempDir()
final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw")
for path, bytes := range map[string]string{part: staged, part + ".etag": tag} {
if err := os.WriteFile(path, []byte(bytes), 0o600); err != nil {
t.Fatal(err)
}
}
wantRequests := []string{fmt.Sprintf("GET / bytes=%d-", len(staged)), "HEAD / "}
if tc.redirect {
wantRequests = append(wantRequests, "HEAD /other ")
}
wantBody := staged
if tc.wantFresh {
wantRequests = append(wantRequests, "GET / ")
wantBody = fresh
}
if err := ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, func(_ context.Context, file string) error {
body, err := os.ReadFile(file)
if err == nil && string(body) != wantBody {
return fmt.Errorf("staged body = %q, want %q", body, wantBody)
}
return err
}); err != nil {
t.Fatal(err)
}
if !slices.Equal(requests, wantRequests) {
t.Fatalf("requests = %q, want %q", requests, wantRequests)
}
})
}
}
func TestValidatedTransferKeepsPartialOnPauseButRejectsInvalidImage(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("ETag", `"first"`)
fmt.Fprint(w, "fake body")
}))
defer server.Close()
dir := t.TempDir()
final, part := filepath.Join(dir, "restore.ipsw"), filepath.Join(dir, "restore.part.ipsw")
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
err := ResumeValidated(ctx, server.Client(), server.URL, final, part, 1024, nil, func(ctx context.Context, _ string) error {
cancel()
return ctx.Err()
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("pause: %v", err)
}
if _, err := os.Stat(part); err != nil {
t.Fatalf("pause did not keep partial: %v", err)
}
badImage := errors.New("not a restore image")
err = ResumeValidated(t.Context(), server.Client(), server.URL, final, part, 1024, nil, func(context.Context, string) error {
return &InvalidDownloadError{Err: badImage}
})
if !errors.Is(err, badImage) {
t.Fatalf("validate: %v", err)
}
for _, file := range []string{part, part + ".etag", final} {
if _, err := os.Stat(file); !os.IsNotExist(err) {
t.Fatalf("invalid image left %s: %v", file, err)
}
}
}
+29 -22
View File
@@ -61,29 +61,36 @@ type LogicalCPUInfo struct {
SMT bool `json:"smt"`
}
type AppleVirtualizationStatus struct {
Ready bool `json:"ready"`
Detail string `json:"detail,omitempty"`
}
type Report struct {
DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"`
OS string `json:"os"`
Arch string `json:"arch"`
Timezone string `json:"timezone,omitempty"`
LogicalCPUs int `json:"logical_cpus"`
PhysicalCores int `json:"physical_cores"`
HasHybridCores bool `json:"has_hybrid_cores"`
PCoreCount int `json:"p_core_count"`
ECoreCount int `json:"e_core_count"`
LPECoreCount int `json:"lpe_core_count,omitempty"`
PCoreMask uint64 `json:"p_core_mask"`
PCoreMaskHex string `json:"p_core_mask_hex"`
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"`
TotalRAMGB float64 `json:"total_ram_gb"`
AvailRAMGB float64 `json:"avail_ram_gb"`
MemoryLoadPct int `json:"memory_load_pct"`
MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"`
AppleVirtualization *AppleVirtualizationStatus `json:"apple_virtualization,omitempty"`
DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"`
OS string `json:"os"`
Arch string `json:"arch"`
Timezone string `json:"timezone,omitempty"`
LogicalCPUs int `json:"logical_cpus"`
PhysicalCores int `json:"physical_cores"`
HasHybridCores bool `json:"has_hybrid_cores"`
PCoreCount int `json:"p_core_count"`
ECoreCount int `json:"e_core_count"`
LPECoreCount int `json:"lpe_core_count,omitempty"`
PCoreMask uint64 `json:"p_core_mask"`
PCoreMaskHex string `json:"p_core_mask_hex"`
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"`
TotalRAMGB float64 `json:"total_ram_gb"`
AvailRAMGB float64 `json:"avail_ram_gb"`
MemoryLoadPct int `json:"memory_load_pct"`
MemoryUsageKnown bool `json:"memory_usage_known,omitempty"`
MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"`
// QEMU commits all guest RAM at start (CreateFileMapping), so a VM requires
// available Windows commit charge rather than physical free RAM alone. Both
// values include expandable paging-file headroom (CommitHeadroom).
+1
View File
@@ -172,6 +172,7 @@ func Inspect(dataRoot string) Report {
if totalGB, availGB, ok := probeMemoryGB(); ok {
rep.TotalRAMGB = totalGB
rep.AvailRAMGB = availGB
rep.MemoryUsageKnown = true
}
if ms, ok := memoryStatus(); ok {
rep.MemoryLoadPct = int(ms.MemoryLoad)
+22
View File
@@ -0,0 +1,22 @@
package host
import "math/bits"
// Non-cache usage is anonymous memory less purgeable pages, plus wired
// memory and the physical pages occupied by the compressor. File-backed
// cache is not counted as used here; this is an estimate, not memory pressure.
func darwinMemoryBytes(total, pageSize, anonymous, purgeable, wired, compressed uint64) (uint64, bool) {
if total == 0 || pageSize == 0 {
return 0, false
}
anonymous -= min(anonymous, purgeable)
pages, carry := bits.Add64(anonymous, wired, 0)
if carry != 0 {
return 0, false
}
pages, carry = bits.Add64(pages, compressed, 0)
if carry != 0 || pages > total/pageSize {
return 0, false
}
return pages * pageSize, true
}
+27
View File
@@ -0,0 +1,27 @@
//go:build darwin && cgo
package host
/*
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <unistd.h>
static int reims_memory_stats(vm_statistics64_data_t *stats) {
mach_port_t host = mach_host_self();
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
kern_return_t result = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)stats, &count);
mach_port_deallocate(mach_task_self(), host);
return result == KERN_SUCCESS && count >= HOST_VM_INFO64_REV1_COUNT;
}
*/
import "C"
func darwinUsedMemory(total uint64) (uint64, bool) {
var stats C.vm_statistics64_data_t
if C.reims_memory_stats(&stats) == 0 {
return 0, false
}
return darwinMemoryBytes(total, uint64(C.getpagesize()), uint64(stats.internal_page_count),
uint64(stats.purgeable_count), uint64(stats.wire_count), uint64(stats.compressor_page_count))
}
+5
View File
@@ -0,0 +1,5 @@
//go:build darwin && !cgo
package host
func darwinUsedMemory(_ uint64) (uint64, bool) { return 0, false }
+28
View File
@@ -0,0 +1,28 @@
package host
import (
"math"
"testing"
)
func TestDarwinMemoryUsageExcludesReclaimablePages(t *testing.T) {
const page = 16384
for _, tc := range []struct {
name string
total, anon, purge, wired, compressed uint64
want uint64
ok bool
}{
{"cache is excluded", 100 * page, 40, 5, 15, 10, 60 * page, true},
{"purgeable cannot underflow", 100 * page, 10, 15, 3, 2, 5 * page, true},
{"usage exceeds physical RAM", 100 * page, 80, 0, 40, 0, 0, false},
{"counter overflow", 100 * page, math.MaxUint64, 0, 2, 0, 0, false},
} {
t.Run(tc.name, func(t *testing.T) {
got, ok := darwinMemoryBytes(tc.total, page, tc.anon, tc.purge, tc.wired, tc.compressed)
if got != tc.want || ok != tc.ok {
t.Fatalf("usage = (%d, %v), want (%d, %v)", got, ok, tc.want, tc.ok)
}
})
}
}
+35
View File
@@ -0,0 +1,35 @@
package host
import (
"math"
"path/filepath"
"golang.org/x/sys/unix"
)
func inspectPlatformResources(report *Report) {
if cores, err := unix.SysctlUint32("hw.physicalcpu"); err == nil {
report.PhysicalCores = int(cores)
}
if memory, err := unix.SysctlUint64("hw.memsize"); err == nil && memory > 0 {
const gib = 1 << 30
report.TotalRAMGB = float64(memory) / gib
if used, ok := darwinUsedMemory(memory); ok {
report.AvailRAMGB = float64(memory-used) / gib
report.MemoryLoadPct = int(math.Round(float64(used) / float64(memory) * 100))
report.MemoryUsageKnown = true
}
}
report.FreeDiskGB = darwinDataFreeGB(report.DataRoot, FreeGB)
}
func darwinDataFreeGB(path string, probe func(string) (float64, bool)) float64 {
for dir := filepath.Clean(path); ; dir = filepath.Dir(dir) {
if free, ok := probe(dir); ok {
return free
}
if filepath.Dir(dir) == dir {
return 0
}
}
}
+30
View File
@@ -0,0 +1,30 @@
package host
import (
"reflect"
"testing"
)
func TestDarwinDataFreeGBFallsBackToNearestProbeableParent(t *testing.T) {
var paths []string
got := darwinDataFreeGB("/data/private/vms", func(path string) (float64, bool) {
paths = append(paths, path)
return 20, path == "/data"
})
if want := []string{"/data/private/vms", "/data/private", "/data"}; got != 20 || !reflect.DeepEqual(paths, want) {
t.Fatalf("got %g GiB and probed %v; want 20 GiB and %v", got, paths, want)
}
}
func TestDarwinDataFreeGBStopsOnKnownZeroOrRoot(t *testing.T) {
for _, path := range []string{"/full", "/"} {
count := 0
got := darwinDataFreeGB(path, func(string) (float64, bool) {
count++
return 0, path == "/full"
})
if got != 0 || count != 1 {
t.Fatalf("%s: got %g GiB and %d probes; want 0 GiB and one probe", path, got, count)
}
}
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !windows && !darwin
package host
func inspectPlatformResources(_ *Report) {}
+3 -1
View File
@@ -17,7 +17,7 @@ func Inspect(dataRoot string) Report {
displays := probeDisplays()
primary := PrimaryDisplayOf(displays)
presets, rec := RecommendDisplayPresets(primary)
return Report{
report := Report{
OS: runtime.GOOS,
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
@@ -33,6 +33,8 @@ func Inspect(dataRoot string) Report {
ProcessorScheduling: probeProcessorScheduling(),
Audio: ProbeAudio(),
}
inspectPlatformResources(&report)
return report
}
func ConfigureVulkanDrivers() {}
+68 -2
View File
@@ -36,6 +36,12 @@ var catalog = map[Locale]map[string]string{
"cli.start.running_in_tray": "{name} 已在启动中(Reims-Go 在托盘运行)。",
"cli.start.spawning_tray": "在后台拉起 Reims-Go(托盘)来启动 {name}…",
"cli.start.timeout": "Reims-Go 在 {timeout} 内没有回报 {name} 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)",
"cli.usage.apple.create": " vm create --ipsw <path> <name> 从本地 Apple 恢复镜像创建虚拟机",
"cli.usage.apple.delete": " vm delete [--keep-files] <name> 删除已关机的虚拟机",
"cli.usage.apple.doctor": " doctor 检查 Apple 虚拟化环境",
"cli.usage.apple.header": "reims-go - Apple 芯片 Mac 实验性虚拟机管理器",
"cli.usage.apple.start": " vm start <name> 启动虚拟机并打开窗口",
"cli.usage.apple.stop": " vm stop [--force] <name> 关闭虚拟机",
"cli.usage.cmd_doctor": " doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)",
"cli.usage.cmd_inst_cached": " installer cached 查看已下载的安装包及占用空间",
"cli.usage.cmd_inst_del": " installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)",
@@ -68,7 +74,7 @@ var catalog = map[Locale]map[string]string{
"cli.usage.section_usage": "用法:",
"close": "关闭",
"closeDownloadsConfirm": "退出",
"closeDownloadsDesc": "仍有下载正在进行,退出会中断它们。",
"closeDownloadsDesc": "退出会中断正在进行的下载或 macOS 安装。",
"closeDownloadsTitle": "退出 Reims-Go?",
"closeWindow": "关闭",
"collapseLogs": "收起日志",
@@ -88,6 +94,8 @@ var catalog = map[Locale]map[string]string{
"delete": "删除…",
"deleteEllipsis": "删除…",
"displays": "显示器数量",
"doctor.apple_virtualization.ready": "可用",
"doctor.apple_virtualization.unavailable": "不可用",
"doctor.cow_chain": "CoW 磁盘派生链体检",
"doctor.cow_chain.broken": "虚拟机 {vm} 的系统盘 CoW 链存在缺失父镜像(深度 {depth} 层,{path})",
"doctor.cow_chain.item": "虚拟机 {vm} 的系统盘 CoW 链深度为 {depth} 层(≥ {warn}),未分配簇读穿透会拖慢小文件 I/O,建议合并或基于基础镜像重新派生",
@@ -113,6 +121,7 @@ var catalog = map[Locale]map[string]string{
"doctor.pcores.detail": "{count} 核,掩码 {mask}(CPU {cpus})",
"doctor.ram": "宿主机内存",
"doctor.ram.detail": "共 {total, number, .1} GB / 可用 {avail, number, .1} GB",
"doctor.ram.total_only": "共 {total, number, .1} GB(可用内存未知)",
"doctor.runtime": "便携运行时",
"doctor.runtime.active": "当前激活:{commit}({dir})",
"doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)",
@@ -193,6 +202,8 @@ var catalog = map[Locale]map[string]string{
"err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR",
"err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。",
"err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。",
"err.restore_catalog_unavailable": "暂时无法读取 Apple 的恢复镜像目录,可重试或选择本地 IPSW。",
"err.restore_catalog_unsupported": "当前 Nivfold 版本不支持查询恢复镜像,可更新 Nivfold 或选择本地 IPSW。",
"err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。",
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
"err.snapshot.name_empty": "请输入恢复点名称",
@@ -402,6 +413,24 @@ var catalog = map[Locale]map[string]string{
"maximize": "最大化",
"menuBar": "菜单栏",
"menuHelp": "帮助",
"menuMacCut": "剪切",
"menuMacDelete": "删除",
"menuMacEdit": "编辑",
"menuMacFullScreen": "进入全屏幕",
"menuMacHide": "隐藏 Reims-Go",
"menuMacHideOthers": "隐藏其他应用",
"menuMacPaste": "粘贴",
"menuMacPasteMatchStyle": "粘贴并匹配样式",
"menuMacQuit": "退出 Reims-Go",
"menuMacRedo": "重做",
"menuMacSelectAll": "全选",
"menuMacShowAll": "显示全部",
"menuMacSpeech": "朗读",
"menuMacStartSpeaking": "开始朗读",
"menuMacStopSpeaking": "停止朗读",
"menuMacUndo": "撤销",
"menuMacWindow": "窗口",
"menuMacZoom": "缩放",
"menuVM": "虚拟机",
"menuView": "视图",
"minimize": "最小化",
@@ -586,6 +615,7 @@ var catalog = map[Locale]map[string]string{
"taskDownload": "下载 macOS {v}",
"taskPluginDownload": "下载 {name}",
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
"taskRestoreVM": "在 {name} 上安装 macOS",
"taskRuntime": "安装运行时 {v}",
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
"themeDark": "深色",
@@ -712,6 +742,8 @@ var catalog = map[Locale]map[string]string{
"window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"window.close.suspend": "挂起",
"window.close.title": "关闭「{name}」?",
"wizardDriverListFailed": "无法加载客体驱动",
"wizardNoDriver": "没有可用的客体驱动",
},
EnUS: {
"affinity.applied.all": "[CPU] Set QEMU (PID {pid}) affinity to all CPUs ({count} logical CPUs, mask {mask}{eco})",
@@ -746,6 +778,12 @@ var catalog = map[Locale]map[string]string{
"cli.start.running_in_tray": "{name} is starting (Reims-Go is running in the tray).",
"cli.start.spawning_tray": "Starting Reims-Go in the tray to run {name}...",
"cli.start.timeout": "Reims-Go did not report starting {name} within {timeout}; check its log panel (quit it first if it is an older version)",
"cli.usage.apple.create": " vm create --ipsw <path> <name> Create from a local Apple restore image",
"cli.usage.apple.delete": " vm delete [--keep-files] <name> Remove a stopped VM",
"cli.usage.apple.doctor": " doctor Check Apple Virtualization support",
"cli.usage.apple.header": "reims-go - Experimental Apple silicon VM manager",
"cli.usage.apple.start": " vm start <name> Start a VM and open its viewer",
"cli.usage.apple.stop": " vm stop [--force] <name> Shut down a VM",
"cli.usage.cmd_doctor": " doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)",
"cli.usage.cmd_inst_cached": " installer cached List downloaded installers and the space they take",
"cli.usage.cmd_inst_del": " installer delete <name> Delete a downloaded installer (refused if in use or downloading)",
@@ -778,7 +816,7 @@ var catalog = map[Locale]map[string]string{
"cli.usage.section_usage": "Usage:",
"close": "Close",
"closeDownloadsConfirm": "Quit",
"closeDownloadsDesc": "Downloads are still running. Quitting stops them.",
"closeDownloadsDesc": "Quitting stops any downloads or macOS installations in progress.",
"closeDownloadsTitle": "Quit Reims-Go?",
"closeWindow": "Close",
"collapseLogs": "Hide logs",
@@ -798,6 +836,8 @@ var catalog = map[Locale]map[string]string{
"delete": "Delete…",
"deleteEllipsis": "Delete…",
"displays": "Displays",
"doctor.apple_virtualization.ready": "Ready",
"doctor.apple_virtualization.unavailable": "Unavailable",
"doctor.cow_chain": "CoW Disk Backing Chain Check",
"doctor.cow_chain.broken": "VM {vm} system disk CoW backing chain has a missing parent image (depth {depth}, {path})",
"doctor.cow_chain.item": "VM {vm} system disk has a {depth}-layer CoW backing chain (>= {warn}); read-through slows small-file I/O — consider flattening or re-deriving from the base image",
@@ -823,6 +863,7 @@ var catalog = map[Locale]map[string]string{
"doctor.pcores.detail": "{count, plural, one {# core} other {# cores}}, mask {mask} (CPUs {cpus})",
"doctor.ram": "Host Memory",
"doctor.ram.detail": "{total, number, .1} GB total / {avail, number, .1} GB avail",
"doctor.ram.total_only": "{total, number, .1} GB total (available memory unknown)",
"doctor.runtime": "Portable Runtime",
"doctor.runtime.active": "Active: {commit} ({dir})",
"doctor.runtime.none": "Not installed (run `reims-go runtime install <archive>`)",
@@ -903,6 +944,8 @@ var catalog = map[Locale]map[string]string{
"err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.",
"err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.",
"err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.",
"err.restore_catalog_unavailable": "Apple’s restore image catalog is unavailable. Retry or choose a local IPSW.",
"err.restore_catalog_unsupported": "This Nivfold version cannot query restore images. Update Nivfold or choose a local IPSW.",
"err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.",
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
"err.snapshot.name_empty": "Enter a restore point name",
@@ -1112,6 +1155,24 @@ var catalog = map[Locale]map[string]string{
"maximize": "Maximize",
"menuBar": "Menu bar",
"menuHelp": "Help",
"menuMacCut": "Cut",
"menuMacDelete": "Delete",
"menuMacEdit": "Edit",
"menuMacFullScreen": "Enter Full Screen",
"menuMacHide": "Hide Reims-Go",
"menuMacHideOthers": "Hide Others",
"menuMacPaste": "Paste",
"menuMacPasteMatchStyle": "Paste and Match Style",
"menuMacQuit": "Quit Reims-Go",
"menuMacRedo": "Redo",
"menuMacSelectAll": "Select All",
"menuMacShowAll": "Show All",
"menuMacSpeech": "Speech",
"menuMacStartSpeaking": "Start Speaking",
"menuMacStopSpeaking": "Stop Speaking",
"menuMacUndo": "Undo",
"menuMacWindow": "Window",
"menuMacZoom": "Zoom",
"menuVM": "VM",
"menuView": "View",
"minimize": "Minimize",
@@ -1296,6 +1357,7 @@ var catalog = map[Locale]map[string]string{
"taskDownload": "Downloading macOS {v}",
"taskPluginDownload": "Downloading {name}",
"taskRecoveryDownload": "Downloading online recovery for {name}",
"taskRestoreVM": "Installing macOS on {name}",
"taskRuntime": "Installing runtime {v}",
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
"themeDark": "Dark",
@@ -1422,6 +1484,8 @@ var catalog = map[Locale]map[string]string{
"window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.",
"window.close.suspend": "Suspend",
"window.close.title": "Close “{name}”?",
"wizardDriverListFailed": "Could not load guest drivers",
"wizardNoDriver": "No eligible guest driver is available",
},
}
@@ -1459,6 +1523,7 @@ var paramOrder = map[string][]string{
"doctor.gpu.warn.amd_rdna2": {"ref"},
"doctor.pcores.detail": {"count", "mask", "cpus"},
"doctor.ram.detail": {"total", "avail"},
"doctor.ram.total_only": {"total"},
"doctor.runtime.active": {"commit", "dir"},
"elevateActionFallbackTitle": {"action"},
"elevateSource": {"name"},
@@ -1576,6 +1641,7 @@ var paramOrder = map[string][]string{
"taskDownload": {"v"},
"taskPluginDownload": {"name"},
"taskRecoveryDownload": {"name"},
"taskRestoreVM": {"name"},
"taskRuntime": {"v"},
"tasksRunning": {"n"},
"toastAffinityApplied": {"count", "mask"},
+216
View File
@@ -0,0 +1,216 @@
package applevz
import (
"context"
"encoding/json"
"fmt"
"maps"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
)
const (
minCPUs = 2
maxCPUs = 64
minMemoryMiB = 4096
maxMemoryMiB = 1024 * 1024
minDiskGiB = 64
maxDiskGiB = 16 * 1024
)
var vmNamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)
func validName(name string) bool { return vmNamePattern.MatchString(name) }
// vmConfig is the on-disk contract with the native runner. The restore path is
// passed to the installer only and is not saved once provisioning begins.
type vmConfig struct {
Name string `json:"name"`
CPUs int `json:"cpu_count"`
MemoryMiB int `json:"memory_mib"`
DiskGiB int `json:"disk_gib"`
}
func defaultConfig(name string) vmConfig {
return vmConfig{Name: name, CPUs: 4, MemoryMiB: 8192, DiskGiB: 64}
}
func (*Driver) CreateSchema() *plugin.SettingsSchema {
defaults := defaultConfig("")
return &plugin.SettingsSchema{
Order: []string{"restore_path", "cpus", "memory", "disk_size"},
Properties: map[string]plugin.SettingProperty{
"restore_path": {
Type: "string", Title: plugin.LocalizedText{ZhCN: "macOS 恢复映像", EnUS: "macOS restore image"},
Description: plugin.LocalizedText{ZhCN: "选择本机上的 .ipsw 文件", EnUS: "Choose a local .ipsw file"},
Required: true, FilePattern: "*.ipsw",
},
"cpus": cpuProperty(defaults.CPUs),
"memory": memoryProperty(formatMemory(defaults.MemoryMiB)),
"disk_size": {
Type: "string", Title: plugin.LocalizedText{ZhCN: "磁盘容量", EnUS: "Disk size"},
Description: plugin.LocalizedText{ZhCN: "至少 64 GiB,例如 128G", EnUS: "At least 64 GiB, for example 128G"},
Default: fmt.Sprintf("%dG", defaults.DiskGiB),
},
},
}
}
func (*Driver) SettingsSchema() *plugin.SettingsSchema {
return &plugin.SettingsSchema{
Scope: "vm", Order: []string{"cpus", "memory"},
Properties: map[string]plugin.SettingProperty{
"cpus": cpuProperty(nil), "memory": memoryProperty(nil),
},
}
}
func cpuProperty(value any) plugin.SettingProperty {
lo, hi := float64(minCPUs), float64(maxCPUs)
return plugin.SettingProperty{
Type: "integer", Title: plugin.LocalizedText{ZhCN: "虚拟处理器", EnUS: "Virtual CPUs"},
Default: value, Minimum: &lo, Maximum: &hi, Effect: "next_start",
}
}
func memoryProperty(value any) plugin.SettingProperty {
return plugin.SettingProperty{
Type: "string", Title: plugin.LocalizedText{ZhCN: "内存", EnUS: "Memory"},
Description: plugin.LocalizedText{ZhCN: "使用 G 或 M,例如 8G 或 8192M", EnUS: "Use G or M, for example 8G or 8192M"},
Default: value, Effect: "next_start",
}
}
func (d *Driver) ValidateCreate(ctx context.Context, req driver.CreateRequest) []driver.ValidationIssue {
_, _, issues := d.createConfig(ctx, req)
return issues
}
func (d *Driver) createConfig(ctx context.Context, req driver.CreateRequest) (vmConfig, string, []driver.ValidationIssue) {
cfg := defaultConfig(req.Name)
if err := ctx.Err(); err != nil {
return cfg, "", []driver.ValidationIssue{issue("", err)}
}
var issues []driver.ValidationIssue
if req.DriverID != "" && req.DriverID != ID {
issues = append(issues, issue("driver_id", fmt.Errorf("incorrect driver %q", req.DriverID)))
}
if !validName(cfg.Name) {
issues = append(issues, issue("name", fmt.Errorf("the VM name must contain 1–63 letters, digits, dots, underscores or hyphens and start with a letter or digit")))
}
if req.Dir != "" {
issues = append(issues, issue("dir", fmt.Errorf("Apple virtual machines must be created in the driver data folder")))
}
issues = append(issues, cfg.apply(req.Options, true)...)
restore, err := restorePath(req.Options["restore_path"])
if err != nil {
issues = append(issues, issue("restore_path", err))
}
return cfg, restore, issues
}
func (cfg *vmConfig) apply(changes map[string]any, creating bool) []driver.ValidationIssue {
var issues []driver.ValidationIssue
for _, field := range slices.Sorted(maps.Keys(changes)) {
value := changes[field]
var err error
switch field {
case "cpus":
cfg.CPUs, err = parseQuantity(value, "", minCPUs, maxCPUs)
case "memory":
cfg.MemoryMiB, err = parseQuantity(value, "MiB", minMemoryMiB, maxMemoryMiB)
case "disk_size":
if creating {
cfg.DiskGiB, err = parseQuantity(value, "GiB", minDiskGiB, maxDiskGiB)
} else {
err = fmt.Errorf("disk size cannot be changed after installation")
}
case "restore_path":
if !creating {
err = fmt.Errorf("restore image cannot be changed after installation")
}
default:
err = fmt.Errorf("setting %q is not supported by the Apple virtualization driver", field)
}
if err != nil {
issues = append(issues, issue(field, err))
}
}
return issues
}
func parseQuantity(value any, unit string, minimum, maximum int) (int, error) {
factor := 1
var n int64
var err error
switch typed := value.(type) {
case int:
n = int64(typed)
case float64:
if typed >= 0 && typed <= float64(maximum) && typed == float64(int64(typed)) {
n = int64(typed)
}
case json.Number:
n, err = typed.Int64()
case string:
text := strings.ToUpper(strings.TrimSpace(typed))
if unit == "MiB" {
switch {
case strings.HasSuffix(text, "GIB"):
text, factor = strings.TrimSuffix(text, "GIB"), 1024
case strings.HasSuffix(text, "G"):
text, factor = strings.TrimSuffix(text, "G"), 1024
default:
text = strings.TrimSuffix(strings.TrimSuffix(text, "MIB"), "M")
}
} else if unit == "GiB" {
text = strings.TrimSuffix(strings.TrimSuffix(text, "GIB"), "G")
}
n, err = strconv.ParseInt(strings.TrimSpace(text), 10, 64)
}
if err != nil || n < 1 || n > int64(maximum/factor) || n*int64(factor) < int64(minimum) {
message := fmt.Sprintf("enter a whole number from %d to %d", minimum, maximum)
if unit != "" {
message += " " + unit
}
return 0, fmt.Errorf("%s", message)
}
return int(n) * factor, nil
}
func restorePath(value any) (string, error) {
path, _ := value.(string)
if !filepath.IsAbs(path) || !strings.EqualFold(filepath.Ext(path), ".ipsw") {
return "", fmt.Errorf("choose a local .ipsw file using its absolute path")
}
path, err := filepath.EvalSymlinks(path)
if err != nil {
return "", fmt.Errorf("open macOS restore image: %w", err)
}
info, err := os.Stat(path)
if err != nil {
return "", fmt.Errorf("open macOS restore image: %w", err)
}
if !info.Mode().IsRegular() || info.Size() == 0 {
return "", fmt.Errorf("the macOS restore image must be a non-empty regular file")
}
return path, nil
}
func formatMemory(mib int) string {
if mib%1024 == 0 {
return fmt.Sprintf("%dG", mib/1024)
}
return fmt.Sprintf("%dM", mib)
}
func issue(field string, err error) driver.ValidationIssue {
return driver.ValidationIssue{Field: field, Message: err.Error()}
}
+147
View File
@@ -0,0 +1,147 @@
// Package applevz adapts the native Apple virtualization runner as a hosted driver.
package applevz
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
)
const (
ID = "builtin.driver.apple-vz"
VMRoot = "apple-vz"
)
// Options selects the current application data root and a trusted runner. An
// empty RunnerPath looks only alongside the current executable, never in PATH.
type Options struct {
DataRoot func() string
RunnerPath string
}
// Driver is independent of the Windows runtime and owns no host-side VM process API.
type Driver struct{ opts Options }
var (
_ driver.Driver = (*Driver)(nil)
_ driver.LogDriver = (*Driver)(nil)
_ driver.WindowDriver = (*Driver)(nil)
)
func New(opts Options) *Driver { return &Driver{opts: opts} }
func (*Driver) ID() string { return ID }
func (*Driver) DisplayName() plugin.LocalizedText {
return plugin.LocalizedText{ZhCN: "macOS(Apple 虚拟化)", EnUS: "macOS (Apple virtualization)"}
}
func (*Driver) RuntimeKind() string { return "external" }
func (*Driver) RuntimeAPIRange() string { return "" }
func (*Driver) Capabilities() []string { return []string{driver.CapHosted, driver.CapWindow} }
// Inventory lists registered instances even when the native driver is inactive.
func Inventory(dataRoot string) ([]driver.VMInfo, error) {
d := New(Options{DataRoot: func() string { return dataRoot }})
return d.List(context.Background())
}
func (d *Driver) List(ctx context.Context) ([]driver.VMInfo, error) {
root, err := d.root(false)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
entries, err := os.ReadDir(root)
if err != nil {
return nil, err
}
out := make([]driver.VMInfo, 0, len(entries))
for _, entry := range entries {
if err := ctx.Err(); err != nil {
return nil, err
}
if !entry.IsDir() || !validName(entry.Name()) {
continue
}
vm := instance{dir: filepath.Join(root, entry.Name()), name: entry.Name()}
if !vm.owned() {
continue
}
out = append(out, d.info(vm))
}
return out, nil
}
func (d *Driver) Show(ctx context.Context, name string) (driver.VMInfo, error) {
if err := ctx.Err(); err != nil {
return driver.VMInfo{}, err
}
vm, err := d.find(name)
if err != nil {
return driver.VMInfo{}, err
}
return d.info(vm), nil
}
func (d *Driver) info(vm instance) driver.VMInfo {
info := driver.VMInfo{
Name: vm.name, DriverID: ID, DriverName: d.DisplayName().EnUS,
Directory: vm.dir, Capabilities: d.Capabilities(), Network: true,
GuestOS: &driver.GuestOSInfo{Family: driver.GuestFamilyMacOS, Arch: "arm64"},
State: "broken", Phase: driver.PhaseNormal,
}
cfg, err := vm.config()
if err != nil {
return info
}
info.Name, info.CPUs, info.Memory = cfg.Name, cfg.CPUs, formatMemory(cfg.MemoryMiB)
info.DiskSummary = fmt.Sprintf("%d GiB", cfg.DiskGiB)
info.DriverData = map[string]any{"cpus": cfg.CPUs, "memory": info.Memory}
if vm.installed() == nil {
info.DiskPath = vm.path(machineDirectory, "disk.img")
info.State = "stopped"
}
if status, err := vm.status(); err == nil {
switch status.State {
case "installing":
info.State, info.Phase = "starting", driver.PhaseInstaller
case "starting", "running", "stopping":
info.State = status.State
}
} else {
info.State = "broken"
}
return info
}
func (d *Driver) ReadLogs(ctx context.Context, name string, serial bool) (string, error) {
if serial {
return "", errors.ErrUnsupported
}
if err := ctx.Err(); err != nil {
return "", err
}
vm, err := d.find(name)
if err != nil {
return "", err
}
return vm.logTail(128 << 10)
}
// ShowWindow reopens or brings forward the runner's native viewer.
func (d *Driver) ShowWindow(ctx context.Context, name string) error {
return d.control(ctx, name, "show", false, nil, nil)
}
func (d *Driver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error {
return d.control(ctx, name, "stop", force, stdout, stderr)
}
+176
View File
@@ -0,0 +1,176 @@
package applevz
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/driver"
)
func (d *Driver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error {
cfg, restore, issues := d.createConfig(ctx, req)
if len(issues) > 0 {
return errors.New(issues[0].Message)
}
bounds, err := d.probe(ctx)
if err != nil {
return err
}
if err := bounds.validate(cfg); err != nil {
return err
}
root, err := d.root(true)
if err != nil {
return err
}
op, err := lockOperations(root, cfg.Name)
if err != nil {
return err
}
defer op.Close()
vm, err := createInstance(root, cfg)
if err != nil {
return err
}
if err := d.invoke(ctx, vm, stdout, stderr, "install", "--ipsw", restore); err != nil {
return fmt.Errorf("install macOS into %q (see the VM logs): %w", vm.name, err)
}
return vm.installed()
}
func createInstance(root string, cfg vmConfig) (instance, error) {
if existing, err := namedInstance(root, cfg.Name); err == nil {
return retryUnpublished(existing, cfg)
} else if !errors.Is(err, os.ErrNotExist) {
return instance{}, err
}
vm := instance{dir: filepath.Join(root, cfg.Name), name: cfg.Name}
if err := os.Mkdir(vm.dir, 0o700); err != nil {
return instance{}, err
}
if err := atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600); err != nil {
return instance{}, errors.Join(err, os.Remove(vm.dir))
}
if err := atomicfile.Write(vm.path(driver.OwnerMarkerFile), []byte(ID+"\n"), 0o600); err != nil {
return instance{}, errors.Join(err, os.Remove(vm.path(configFile)), os.Remove(vm.dir))
}
return vm, nil
}
func retryUnpublished(vm instance, cfg vmConfig) (instance, error) {
if err := requireDirectory(vm.dir); err != nil || !vm.owned() {
return instance{}, fmt.Errorf("an unmanaged directory already exists for %q", cfg.Name)
}
lock, err := acquireLock(vm.path(runnerLock), true)
if err != nil {
return instance{}, err
}
if lock == nil {
return instance{}, fmt.Errorf("VM %q is already in use", cfg.Name)
}
defer lock.Close()
for _, name := range []string{machineDirectory, ".applevz-installing"} {
if _, err := os.Lstat(vm.path(name)); err == nil {
if name == machineDirectory {
return instance{}, fmt.Errorf("VM %q already has a published machine", cfg.Name)
}
return instance{}, fmt.Errorf("VM %q has interrupted staging data; delete the incomplete VM before retrying", cfg.Name)
} else if !errors.Is(err, os.ErrNotExist) {
return instance{}, err
}
}
if _, err := vm.config(); err != nil {
return instance{}, err
}
cfg.Name = vm.name
return vm, atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600)
}
func (d *Driver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue {
if err := ctx.Err(); err != nil {
return []driver.ValidationIssue{issue("", err)}
}
vm, err := d.find(req.Name)
if err == nil {
var cfg vmConfig
cfg, err = vm.config()
if err == nil {
return cfg.apply(req.Changes, false)
}
}
return []driver.ValidationIssue{issue("name", err)}
}
func (d *Driver) Set(ctx context.Context, req driver.SetRequest, _, _ io.Writer) error {
vm, release, err := d.lockStopped(ctx, req.Name)
if err != nil {
return err
}
defer release()
if err := vm.installed(); err != nil {
return err
}
cfg, err := vm.config()
if err != nil {
return err
}
if issues := cfg.apply(req.Changes, false); len(issues) > 0 {
return errors.New(issues[0].Message)
}
bounds, err := d.probe(ctx)
if err != nil {
return err
}
bounds, err = vm.applyGuestMinimum(bounds)
if err != nil {
return err
}
if err := bounds.validate(cfg); err != nil {
return err
}
return atomicfile.WriteJSON(vm.path(configFile), cfg, 0o600)
}
func (d *Driver) Delete(ctx context.Context, name string, keepFiles bool, _, _ io.Writer) error {
vm, release, err := d.lockStopped(ctx, name)
if err != nil {
return err
}
defer release()
if keepFiles {
return os.Remove(vm.path(driver.OwnerMarkerFile))
}
// lockStopped re-resolved the owned, non-symlink child of the driver root.
return os.RemoveAll(vm.dir)
}
func (d *Driver) lockStopped(ctx context.Context, name string) (instance, func(), error) {
if err := ctx.Err(); err != nil {
return instance{}, nil, err
}
root, err := d.root(false)
if err != nil {
return instance{}, nil, err
}
op, err := lockOperations(root, name)
if err != nil {
return instance{}, nil, err
}
vm, err := ownedInstance(root, name)
if err == nil {
var runtime *os.File
runtime, err = acquireLock(vm.path(runnerLock), true)
if runtime != nil {
return vm, func() { runtime.Close(); op.Close() }, nil
}
if err == nil {
err = fmt.Errorf("shut down VM %q before changing or deleting it", name)
}
}
return instance{}, nil, errors.Join(err, op.Close())
}
+35
View File
@@ -0,0 +1,35 @@
package applevz
import (
"os"
"os/exec"
"syscall"
)
const safeOpenFlags = syscall.O_NOFOLLOW | syscall.O_NONBLOCK
func sharedFile(info os.FileInfo) bool {
st, ok := info.Sys().(*syscall.Stat_t)
return !ok || st.Nlink != 1
}
func tryStatusLock(file *os.File) (bool, error) {
err := syscall.Flock(int(file.Fd()), syscall.LOCK_SH|syscall.LOCK_NB)
if err == syscall.EWOULDBLOCK {
return false, nil
}
return err == nil, err
}
func detachRunner(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
func interruptInstaller(process *os.Process) error {
if err := process.Signal(syscall.SIGTERM); err != nil {
return err
}
// A successful atomic publication wins over a racing cancellation. A
// cancelled installer still exits nonzero and its context error is retained.
return os.ErrProcessDone
}
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more