Merge upstream main and adapt Npcap networking to VMRef lifecycle
This commit is contained in:
commit
bb4c876e25
283 files changed
+13696
-4591
No files matched your search
@@ -69,6 +69,8 @@
|
||||
- [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点
|
||||
- [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界
|
||||
- [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案)
|
||||
- [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查
|
||||
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
|
||||
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
|
||||
- [`docs/guest-plugin-migration.md`](docs/guest-plugin-migration.md) — 客体插件化与 macOS 剥离的迁移路径
|
||||
- [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁
|
||||
+36
-1
@@ -17,6 +17,8 @@
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><img src="https://img.shields.io/github/v/release/Nwflower/Reims-Go?label=release&color=3b8cff" alt="release" /></a>
|
||||
<a href="https://github.com/Nwflower/Reims-Go/stargazers"><img src="https://img.shields.io/github/stars/Nwflower/Reims-Go?style=flat&label=stars&logo=github&color=ffb86b" alt="GitHub stars" /></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-ff7a9a" alt="license Apache-2.0" /></a>
|
||||
<a href="https://discord.gg/Tj682rW5rS"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20Group-1136042744-12B7F5?logo=qq&logoColor=white" alt="QQ Group 1136042744" /></a>
|
||||
<!-- Go daily list: uncomment after making it; replace %23N with the rank
|
||||
<a href="https://github.com/trending/go?since=daily"><img src="https://img.shields.io/badge/Trending-%23N%20Go%20Repo%20of%20the%20Day-00ADD8?logo=go&logoColor=white" alt="GitHub Trending: Go Repo of the Day" /></a>
|
||||
-->
|
||||
@@ -32,7 +34,9 @@
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>Download</strong></a> ·
|
||||
<a href="#quick-start">Quick Start</a> ·
|
||||
<a href="#screenshots">Screenshots</a> ·
|
||||
<a href="./docs/roadmap.md">Roadmap</a>
|
||||
<a href="#plugin-development">Plugins</a> ·
|
||||
<a href="./docs/roadmap.md">Roadmap</a> ·
|
||||
<a href="#organization-and-community">Community</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -155,6 +159,37 @@ The binary is written to `build\bin\reims-go.exe`.
|
||||
|
||||
</details>
|
||||
|
||||
## Plugin Development
|
||||
|
||||
Reims-Go ships an out-of-process plugin system with zero external runtime dependencies. Browse and install plugins from the built-in **Plugins** page or import a local `.zip` archive; if a third-party plugin breaks startup, launch with `reims-go --safe-mode` to skip all third-party plugins.
|
||||
|
||||
- **L1 declarative plugins** (JSON + static assets): UI themes backed by the versioned [UI contract](./frontend/ui-contract.json), language packs (domain JSON + optional `.woff2` fonts), VM templates, runtime sources, input filters and rule hooks.
|
||||
- **L3 sidecar plugins** (standalone executables in any language): one isolated process per plugin speaking `Content-Length`-framed JSON-RPC 2.0 over stdin/stdout for custom guest drivers (such as non-macOS VMs), lifecycle hooks, custom commands and diagnostics; Go authors can use the zero-dependency SDK in [`pkg/pluginsdk`](./pkg/pluginsdk).
|
||||
- **Declarative UI extensions**: render native plugin settings from `settings` JSON Schema and contribute menu items, cards and status items to declared host slots.
|
||||
|
||||
<details>
|
||||
<summary>Plugin development CLI</summary>
|
||||
|
||||
```powershell
|
||||
reims-go plugin link <dir> | Out-Host # Link a local plugin directory for development
|
||||
reims-go plugin doctor --contract frontend/ui-contract.json <dir|zip> | Out-Host # Run static security, manifest and UI contract checks
|
||||
reims-go plugin locale init ja-JP --out <dir> | Out-Host # Scaffold a language pack
|
||||
reims-go plugin locale check <dir> | Out-Host # Validate language pack coverage and syntax
|
||||
reims-go plugin pack <dir> | Out-Host # Verify and pack a .zip with SHA256SUMS (optional --sign-key)
|
||||
reims-go plugin search | Out-Host # Browse the official plugin market
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- Full architecture, `plugin.json` manifest reference, permission tiers and protocol spec: [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)
|
||||
- Official plugin market index and submissions: [`reims-go/plugins`](https://github.com/reims-go/plugins)
|
||||
|
||||
## Organization and Community
|
||||
|
||||
- **GitHub Organization**: [`reims-go`](https://github.com/reims-go) — Maintains the official plugin market index ([`reims-go/plugins`](https://github.com/reims-go/plugins)) and ecosystem repositories; the desktop launcher repository lives at [`Nwflower/Reims-Go`](https://github.com/Nwflower/Reims-Go)
|
||||
- **Discord**: [Join the Discord server](https://discord.gg/Tj682rW5rS) — Bilingual chat, troubleshooting, hardware compatibility reports, alpha testing and plugin development
|
||||
- **QQ Group**: [1136042744](https://qm.qq.com/q/TBmRJlVbSo) — Chinese community chat and feedback
|
||||
|
||||
## License & Notice
|
||||
|
||||
- Reims-Go is licensed under [Apache-2.0](./LICENSE). Runtime components such as QEMU ship as separate programs; their licenses are in [`NOTICE.md`](./NOTICE.md), and every runtime release includes the matching source.
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><img src="https://img.shields.io/github/v/release/Nwflower/Reims-Go?label=release&color=3b8cff" alt="release" /></a>
|
||||
<a href="https://github.com/Nwflower/Reims-Go/stargazers"><img src="https://img.shields.io/github/stars/Nwflower/Reims-Go?style=flat&label=stars&logo=github&color=ffb86b" alt="GitHub stars" /></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-ff7a9a" alt="license Apache-2.0" /></a>
|
||||
<a href="https://discord.gg/Tj682rW5rS"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://qm.qq.com/q/TBmRJlVbSo"><img src="https://img.shields.io/badge/QQ%20群-1136042744-12B7F5?logo=qq&logoColor=white" alt="QQ 交流群 1136042744" /></a>
|
||||
<!-- Go 日榜:上榜后取消注释,把 %23N 改成名次
|
||||
<a href="https://github.com/trending/go?since=daily"><img src="https://img.shields.io/badge/Trending-%23N%20Go%20日榜-00ADD8?logo=go&logoColor=white" alt="GitHub Trending: Go 日榜" /></a>
|
||||
-->
|
||||
@@ -32,7 +34,9 @@
|
||||
<a href="https://github.com/Nwflower/Reims-Go/releases"><strong>下载</strong></a> ·
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#界面">界面</a> ·
|
||||
<a href="./docs/roadmap.md">路线图</a>
|
||||
<a href="#插件与开发">插件与开发</a> ·
|
||||
<a href="./docs/roadmap.md">路线图</a> ·
|
||||
<a href="#项目组与社区">项目组与社区</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -155,6 +159,37 @@ wails build
|
||||
|
||||
</details>
|
||||
|
||||
## 插件与开发
|
||||
|
||||
Reims-Go 内置进程外隔离的插件体系,零外部运行时依赖。可以在应用的「插件」页直接浏览安装官方市场插件或导入本地 `.zip` 包;如插件引发启动异常,可用 `reims-go --safe-mode` 跳过全部第三方插件恢复。
|
||||
|
||||
- **L1 声明式插件**(纯 JSON + 静态资源):界面主题(基于稳定的 [UI 契约](./frontend/ui-contract.json))、多语种语言包(分域 JSON 与可选 `.woff2` 字体)、虚拟机模板、运行时源、输入过滤与规则 Hook。
|
||||
- **L3 Sidecar 插件**(任意语言独立可执行文件):每插件独立进程,通过 stdin/stdout `Content-Length` 分帧 JSON-RPC 2.0 通信,可用于非 macOS 虚拟机驱动、生命周期 Hook、自定义命令与排障采集;Go 开发者可直接使用零依赖 SDK [`pkg/pluginsdk`](./pkg/pluginsdk)。
|
||||
- **声明式 UI 扩展**:通过 `settings` JSON Schema 原生渲染插件设置页,向宿主预定义槽位贡献菜单项、卡片与状态项。
|
||||
|
||||
<details>
|
||||
<summary>插件开发常用命令</summary>
|
||||
|
||||
```powershell
|
||||
reims-go plugin link <dir> | Out-Host # 链接本地插件目录用于开发调试
|
||||
reims-go plugin doctor --contract frontend/ui-contract.json <dir|zip> | Out-Host # 静态安全扫描与清单/UI 契约校验
|
||||
reims-go plugin locale init ja-JP --out <dir> | Out-Host # 生成多语种语言包脚手架
|
||||
reims-go plugin locale check <dir> | Out-Host # 校验语言包覆盖率与格式
|
||||
reims-go plugin pack <dir> | Out-Host # 校验并打包 .zip(自动生成 SHA256SUMS,支持 --sign-key)
|
||||
reims-go plugin search | Out-Host # 浏览官方插件市场
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- 完整插件架构、清单字段(`plugin.json`)、权限分级与协议规范见 [`docs/plugin-architecture.md`](./docs/plugin-architecture.md)
|
||||
- 官方插件市场索引与投稿发布见 [`reims-go/plugins`](https://github.com/reims-go/plugins)
|
||||
|
||||
## 项目组与社区
|
||||
|
||||
- **GitHub 项目组**:[`reims-go`](https://github.com/reims-go) — 维护官方插件市场索引([`reims-go/plugins`](https://github.com/reims-go/plugins))及周边生态项目;桌面客户端主仓库位于 [`Nwflower/Reims-Go`](https://github.com/Nwflower/Reims-Go)
|
||||
- **Discord 社区**:[加入 Discord 服务器](https://discord.gg/Tj682rW5rS) — 中英双语交流、排障求助、硬件兼容性实测、Alpha 测试与插件开发
|
||||
- **QQ 交流群**:[1136042744](https://qm.qq.com/q/TBmRJlVbSo) — 中文日常交流与使用反馈
|
||||
|
||||
## 许可与声明
|
||||
|
||||
- Reims-Go 采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 都附带对应源码。
|
||||
|
||||
+23
-12
@@ -54,23 +54,27 @@ flowchart TB
|
||||
| :--- | :--- |
|
||||
| `main.go`、`console_*.go` | 统一入口:无参数启动 Wails GUI,带子命令进入 `internal/cli`;处理 GUI 子系统下的父控制台句柄接管 |
|
||||
| `internal/app` | Wails 绑定与桌面编排(启停、安装、快照、CoW 派生、磁盘扩容/回收、SSH、脱敏排障包、任务状态、运行监视) |
|
||||
| `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 |
|
||||
| `internal/vmstart` | 通用启动辅助:提交内存等待、启动后 CPU 绑核、亲和性配置与命令行日志 |
|
||||
| `internal/macos/startprep` | macOS 启动前准备:WHPX/内存检查、离线辅助盘、恢复模式引导、客体语言重放与兼容处理 |
|
||||
| `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` |
|
||||
| `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 |
|
||||
| `internal/packetbridge`、`internal/networkmsg` | 基于 Npcap 的独立有线/WLAN 出口、运行中更换出口及虚拟机网络事务恢复,以及复用 i18n 词条、参数和 CodedError 的网络提示;行为、依赖和验收边界见 [网络管理](networking.md) |
|
||||
| `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 |
|
||||
| `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 |
|
||||
| `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 |
|
||||
| `internal/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
|
||||
| `internal/driver/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
|
||||
| `internal/macos/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 |
|
||||
| `internal/macos/reims` | `reims-ctl` 与 `qemu-img` 受控子进程包装、输出解析、快照/派生/导入操作、日志与配置脱敏 |
|
||||
| `internal/macos/macosdriver` | 把 `internal/macos/reims` 适配为通用 `driver.Driver`(内置驱动 `builtin.driver.reims-macos`) |
|
||||
| `internal/macos/guest` | 内置可选插件 `builtin.guest.macos`:静态驱动声明、宿主体检、启动与兼容 Hook、安装引导服务,以及数据布局 v2 的状态与参数账本迁移 |
|
||||
| `internal/macos/installguide` | 虚拟机窗口旁的 macOS 安装与恢复分步引导(Win32 浮层) |
|
||||
| `internal/qmp` | QMP 客户端:键盘键入、截屏与 Win10 冷重启监视 |
|
||||
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
|
||||
| `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/macos/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
|
||||
| `locales/`、`cmd/i18ngen` | 单一事实源分域 JSON 词表(含译者上下文 `$comment` 与 Apple macOS 官方多语种词汇表)及编译期前后端字典代码生成器 |
|
||||
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
|
||||
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`macos/`(macOS 专属页面与组件)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
|
||||
|
||||
---
|
||||
@@ -78,8 +82,8 @@ flowchart TB
|
||||
## 4. 关键机制与安全边界
|
||||
|
||||
### 4.1 启动编排与单实例交接
|
||||
- `internal/vmstart` 承载 GUI 与 CLI 共用的启动步骤;只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
|
||||
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。
|
||||
- `internal/lifecycle` 统一 GUI、CLI 与窗口交接的 VM 列表、详情、设置、启动、停止、重启、删除、介质动作和日志读取:按 `VMRef` 解析所属驱动,先收集第三方 Hook,否决时不调用驱动,成功后再发事件。macOS 的启动前检查、参数账本与磁盘准备由 `internal/macos/macosdriver` 自己完成,准备失败即中止;`internal/vmstart` 保留共享检查与旧回退。只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。
|
||||
- CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。交接同时携带 `--start-driver=`,裸名称不再作为跨驱动的完整身份。
|
||||
- 仅在 CLI 显式指定 `--data-root` 时由命令进程直接启动,此时不包含 Guest Tools 桥接与 Win10 冷重启监视。
|
||||
- `reims-go.exe` 编译为 Windows GUI 子系统程序,命令行模式下保留调用方管道/文件句柄,缺失时通过 `AttachConsole` 挂载父控制台;在交互式 PowerShell/cmd 中加 `| Out-Host` 可等待命令执行完毕。
|
||||
|
||||
@@ -88,13 +92,13 @@ flowchart TB
|
||||
- **Win10 冷重启监视通道**:Windows 10 19045 缺少 `WHvResetPartition`,客体热重启会导致 WHPX 退出异常。在 Win10 宿主上,启动时附加 `-no-reboot` 并另开一条独立的 `AF_UNIX` QMP 通道监听重启退出事件,干净退出后自动重新拉起。使用 `AF_UNIX` 而非 TCP,避免客体经 SLIRP 的 `10.0.2.2` 访问宿主机监控接口。
|
||||
|
||||
### 4.3 Guest Tools 与宿客安全边界
|
||||
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。
|
||||
- Guest Tools 服务仅监听 `127.0.0.1`,每台虚拟机分配独立的 256-bit 随机 Token(Bearer / Basic 鉴权)。注册表、连接状态、剪贴板策略、文本输入与 WebDAV handler 按 `driver.VMRef.Key()` 隔离;token 认证同时识别驱动与名称,既有客体 URL 不变。
|
||||
- WebDAV 共享目录(`/dav/<vm>/`)严格校验路径防目录穿越;Windows 盘符只读共享(`/dav/<vm>/drives/<盘符>/`)默认全部关闭,服务端同时限制 HTTP 写方法与只读打开标志、校验持久化 Volume GUID 防盘符漂移、限制 `PROPFIND Depth` 并校验 Junction/符号链接解析目标仍在授权盘符内。
|
||||
|
||||
### 4.4 宿主机体检与硬件调优
|
||||
- **免提权 WHPX 检测**:通过 `WinHvPlatform.dll`(`WHvGetCapability`)与系统功能查询判断状态,仅在缺失且用户确认时通过 `ShellExecuteW(..., "runas", ...)` 触发 UAC 启用。
|
||||
- **提交内存预检**:通过 `GlobalMemoryStatusEx` 检查可用提交内存(`AvailPageFile`),因为 QEMU 在 Windows 上会一次性提交整块客体内存;建机时推荐安全档位,启动前余量不足时提前拦截。
|
||||
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。
|
||||
- **GPU 与大小核**:扫描注册表 Vulkan ICD 并过滤虚拟显示适配器;解析 `GetLogicalProcessorInformationEx` 识别 P / E / LP-E 三层混合核心,支持按 VM 实时调整进程亲和性,避免超售卡顿。宿主只评估通用硬件事实;`kernel_irqchip`、冷重启等 macOS/WHPX 建议由所属驱动的 `driver.OptimizationAdvisor` 提供,与启动准备共用运行时判定。
|
||||
|
||||
### 4.5 应用内更新
|
||||
- 界面启动后检查一次新版本,之后每 6 小时检查一次(后端缓存 10 分钟),只看 `vX.Y.Z` 正式版,忽略草稿与预发布。有新版本时侧栏顶部显示更新胶囊卡片,关于页提供同样的操作。
|
||||
@@ -104,16 +108,23 @@ flowchart TB
|
||||
- 开发构建(`wails dev`,`dev` 标签)与非 Windows 平台不支持应用内更新;程序所在目录不可写(如未提权的 `Program Files`)时提示改为手动更新。
|
||||
|
||||
### 4.6 资源回收与内存约束
|
||||
- 按 VM 生命周期分配的状态(缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、绑核记录、文本队列与 worker)在删除 VM 或轮询发现外部删除时立即回收。
|
||||
- 按 VM 生命周期分配的状态(过渡态、待生效设置、冷重启监视、磁盘路径缓存、进程采样、缩略图与键入锁、文本队列与 worker)以 `driver.VMRef.Key()` 隔离,并在删除 VM 或轮询发现外部删除时立即回收;VM 日志来源也使用规范键。
|
||||
- 日志监视器对单行无换行输出设 **64 KiB** 内存上限(原始日志文件完整保留);已结束任务在 10 分钟后从前后端状态中清理。
|
||||
- 4K 屏幕预览采用按行流式缩放降低单帧分配;手动复制截图仍保留全分辨率。不在热路径中人为调用 `debug.FreeOSMemory`。
|
||||
|
||||
### 4.7 数据目录版本与迁移
|
||||
- `<DataRoot>\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。
|
||||
- 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。
|
||||
- 数据目录的版本高于本程序所知时(降级运行),不做任何改动,只记一条日志。
|
||||
- GUI 启动、首次设置、切换数据目录与 CLI 都经 `internal/dataroot` 打开数据目录:先不加锁读取版本戳,需要迁移时才取 `<DataRoot>.reims-go.lock` 并在锁内重读版本戳,两个进程同时打开同一目录时迁移只执行一次。
|
||||
- 数据目录由更新版本写入、版本戳无法解析、迁移失败或另一进程长时间持锁时,以只读模式打开,不创建或修改任何文件(包括锁文件):GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台;CLI 只放行 `version`、`help` 与 `doctor`。版本戳损坏时可由用户显式修复,从 v0 重新执行全部步骤。
|
||||
- 首次设置选定目录之前,宿主不写入默认建议目录:不迁移、不启动插件、不轮询,界面中的选择只保存在内存里,由 `CompleteSetup` 写入选定的目录。
|
||||
- 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。
|
||||
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」。
|
||||
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」;v3 一次性把正式版 `builtin.core` 的设置、`builtin.install-guide` 的启停和已知参数账本条目迁入 `builtin.guest.macos`,把按裸 VM 名的插件设置键改为 `driverID:vmName`,并补扫无归属标记的 VM。`state.json` 只加载、保存一次,原始 `.bak` 不被中间布局覆盖;功能分支上的 v2 仍可直升,未公开发布过的旧插件 ID 不做长期迁移。
|
||||
|
||||
### 4.8 macOS 代码边界
|
||||
- macOS 专属代码集中在 `internal/macos/` 与 `frontend/src/macos/`,最终作为独立插件移出本仓库;宿主只应经驱动层(`driver.Router`)与宿主服务使用它。
|
||||
- 三个棘轮测试守住边界:`internal/archtest` 分别检查宿主到 macOS、macOS 到宿主私有 Go 包的依赖,`frontend/scripts/test-macos-boundary.mjs` 检查前端文件。只有列入清单的包或文件可以跨界;新增引用、或清单中的条目已不再引用时,测试都会失败,所以清单只能缩短。
|
||||
- 宿主到 macOS 的例外包括 GUI 与 CLI 的组装入口、数据布局 v2 的迁移,以及仍混有宿主与 macOS 逻辑、待拆分的 `internal/guesttools`。反向清单记录 macOS 对宿主私有包的现有依赖,随公开接口建设逐步清零。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# 客体插件化与 macOS 剥离方案
|
||||
|
||||
> 状态:待评审。本文描述从现有代码走到"与客体无关的主程序 + macOS 外部插件"的路径。[plugin-architecture.md](plugin-architecture.md) 记录的是插件系统当前的权威设计;本文的每一步合入时,同步修改该文对应章节(§3.2、§5.3、§5.4、§12 等),两份文档不得长期并存矛盾。
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
- **终态**:主程序是与客体无关的本地虚拟机工作台。macOS 能力作为外部插件(独立仓库、独立发布)提供;主程序的源码、文档、语言词表、发布物与运行时流水线不含 macOS 专属内容。
|
||||
- **过渡态**:macOS 先成为内置插件 `builtin.guest.macos`,仍随 `reims-go.exe` 编译。过渡期只保证两件事,以免外置时再做一次迁移:
|
||||
- **职责与数据按终态划分**:设置、参数账本、VM 归属、启动准备从一开始就归 macOS 插件与它的驱动所有。
|
||||
- **调用面按终态收敛**:macOS 代码只经驱动接口、Hook 与宿主服务使用宿主;它对宿主 Go 包的依赖逐步收敛到可公开的 `pkg/` 包(第 6 节的反向棘轮)。
|
||||
- 界面是唯一允许的例外:过渡期可挂载原生页面,步骤 5 替换。
|
||||
- **特权按角色而不是按 ID 前缀**:宿主内置插件(留在主程序的部分)保留现有特权;拥有某台 VM 的驱动,对该 VM 的启动参数拥有完整控制(含 `-drive`、`-chardev`、`-qmp` 等),无论它是内置还是外部。外部驱动本身是 L3 原生程序,拥有完整账户权限,这不构成提权;第三方 Hook 仍受现有脱敏、超时与参数族限制。
|
||||
- **Linux 驱动**用于验证接口通用性,按 plugin-architecture.md Phase 4 以独立仓库的 L3 插件实现。Android 只预留接口。
|
||||
- **不在本方案内**:常驻后台服务、OCI 分发、运行态热迁移、整盘导出导入、稳定 VM ID(第 8 节)。
|
||||
- 哪些内容构成法律风险、需剥离到什么程度,不由本文判断,见第 9 节。
|
||||
|
||||
## 2. 现状
|
||||
|
||||
macOS 代码已集中到 `internal/macos/`(`installer`、`opencore`、`installguide`、`reims`、`macosdriver`)与 `frontend/src/macos/`,宿主到 macOS 的 import 由两处棘轮测试守住([architecture.md](architecture.md) §4.8)。仍需解决的问题:
|
||||
|
||||
### 2.1 身份与数据
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| 驱动 ID 与旧插件 ID 混用 | `builtin.driver.reims-macos` 同时列在 `builtin.RetiredIDs` 中,不能直接拿来做新插件 ID |
|
||||
| 设置迁移不原子 | `MigrateRetired` 先落盘删除旧记录,再单独落盘新设置;两次写盘之间退出会丢失用户关闭过的选项 |
|
||||
| 安装引导独立成插件 | `builtin.install-guide` 是独立可选插件,内容是纯 macOS 的安装与恢复引导 |
|
||||
| 使用中保护依赖静态声明 | 使用中检查经 `DeclaredDriverIDs` 读取清单的 `guestDrivers`;`builtin.core` 在激活时动态注册驱动,未静态声明。核心插件不可停用所以目前无害,macOS 插件可停用后会失效 |
|
||||
| VM 以裸名称索引 | `PluginRecord.VMSettings` 以 VM 名为键;宿主内存态(`transitions`、`pendingChanges`、`rebootWatchers`、`diskPaths`、`procSamples`)、Guest Tools 注册表、缩略图与键入锁、日志来源同样以名称索引;界面进程交接参数 `--start-vm=` 不带驱动 |
|
||||
| VM 目录只有一个根 | 路由与"驱动不可用"扫描只看 `<DataRoot>/data/reims-ctl/vms` |
|
||||
| 运行时只能选一个 | `config.ActiveRuntime` 是单个字符串;非默认种类直接取已安装列表第一项;已装多个 reims-vgpu 运行时且未选定时,所有依赖运行时的功能失败 |
|
||||
|
||||
### 2.2 数据目录写入
|
||||
|
||||
GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁移失败时 GUI 只记日志、CLI 只打印警告;`SetDataRoot` 先保存配置再迁移;首次设置完成前,宿主已把默认建议目录当作数据目录读写;版本戳损坏时按 v0 重跑;没有跨进程写锁。
|
||||
|
||||
### 2.3 启动链路
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| 启动入口 | GUI 的 `App.StartVM` 直接取 reims 客户端、自做 WHPX 检查,启动事件写死 macOS 驱动 ID 与能力;CLI 有直接启动(`startVM`)与交给界面进程(`startInWindow`)两条路径 |
|
||||
| 启动准备放在公共 Hook | `builtin.core` 的 `vm.beforeStart` 依次执行离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启五步;恢复与语言两步在回调里直接写恢复标记、改写 OpenCore 镜像,后续插件否决时磁盘已被改动 |
|
||||
| 特权按前缀 | `BuiltinOnlyQEMUOptionFamilies`(`-drive`、`-chardev`、`-qmp`、`-fw_cfg`、`-global`、`-object`)、宿主环境变量白名单与 `PostStart` 动作都按 `builtin.` 前缀放行;外部插件的 `vm.beforeStart` 拿不到 `VMDir`、`ExtraArgs`、`InstallerPath`,单个回调限时 2 秒 |
|
||||
| 驱动接口缺参数 | `Driver.Start` 只收 VM 名,不接收合并后的参数、环境变量与启动后动作;参数账本的合并结果在 `StartVM` 中经 `reims-ctl set --extra-args` 写入;`stripLegacyManagedExtraArgs` 在 `internal/app` 中直接调用 macOS 代码 |
|
||||
| 调优不分驱动 | `host.EvaluateOptimizations` 一次算出绑核、irqchip、冷重启、独显与 CoW 建议 |
|
||||
|
||||
### 2.4 路由与界面
|
||||
|
||||
列表、详情、设置、停止、删除、日志等十余处直接调用 reims 客户端;`Router.ListAllVMs` 没有调用方且按名称去重;`Router.ResolveVM` 返回第一个同名结果;CLI 只有 `vm create --driver` 走驱动层;前端类型直接使用 `reims.VMDetail`,`CreateWizard`、`SettingsModal`、`lib/tasks.ts` 含 OpenCore、恢复、引导语言、无边框、安装包等字段与交互(不经 import,棘轮看不到)。
|
||||
|
||||
### 2.5 外置障碍
|
||||
|
||||
| 问题 | 现状 |
|
||||
| :--- | :--- |
|
||||
| Go 可见性 | `internal/macos/*` 导入宿主的 `internal/config`、`host`、`i18n`、`driver`、`plugin`、`runtime`、`vmstart`;外部仓库不能导入别的模块的 `internal/` 包 |
|
||||
| SDK | `pkg/pluginsdk` 只有 JSON-RPC 骨架 |
|
||||
| 反向宿主接口 | Sidecar 只能调用 `notify`、`audit`、`vm.spawn`、`vm.stop`、`vm.isRunning`;没有运行时查询、内存预检、绑核、日志与任务、进程退出、窗口信息等服务 |
|
||||
| 外部界面 | 外部插件不能贡献整页界面;沙箱 iframe 没有文件选择、流式任务进度、弹窗与尺寸协调等桥接 |
|
||||
| 非 import 耦合 | 全局脱敏器(`i18n.SetDetailRedactor`、插件管理器 `RedactFn`、排障包、界面错误上报)都直接用 `reims.RedactText`;`internal/runtime` 内置 `DefaultKind = "reims-vgpu"`、`reims-ctl` / `reims-util` 路径、reims 专用环境变量、按补丁推断能力与发布源;`locales/*/macos-glossary.json` 与 `internal/i18n/glossary.go`,以及 `vm`、`wizard`、`settings` 等词表中的 macOS 文案;`internal/app/macos_release.go`(`.reims-go-macos`);数据目录禁止逗号源于 `reims-util`;`internal/host` 中面向 reims-vgpu / metal2vulkan 的显卡兼容判断;CLI 顶层 `installer` 子命令 |
|
||||
| 外围文件 | `patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` |
|
||||
|
||||
## 3. 身份模型
|
||||
|
||||
| 身份 | 作用 | 规则 |
|
||||
| :--- | :--- | :--- |
|
||||
| 插件 ID | 启停、设置、贡献、参数账本归属 | 过渡期 `builtin.guest.macos`;外部插件不可使用 `builtin.` 前缀,换新 ID,经声明式承接接收旧 ID 的数据(见下) |
|
||||
| 驱动 ID | 一台 VM 由谁管理,写在 VM 目录的 `.reims-go-driver` | 过渡期保留 `builtin.driver.reims-macos`;外部驱动换新 ID,并把旧 ID 声明为别名,已有标记不改写 |
|
||||
| 运行时种类 | 安装哪套可执行程序、驱动要求的接口版本 | 每种类单独选定活跃运行时(步骤 3.5) |
|
||||
| VM 引用 `VMRef` | 一次操作、一份设置或一项内存状态针对哪台 VM | `{驱动 ID, 驱动内名称}`,自步骤 2 起贯穿宿主;稳定 VM ID 见第 8 节 |
|
||||
| VM 目录根 | 驱动的 VM 放在哪里 | 驱动在清单中静态声明自己的 VM 根目录(相对 DataRoot);macOS 驱动声明现有的 `data/reims-ctl/vms`。停用的驱动清单仍可读,宿主据此扫描"驱动不可用"的 VM,两个驱动的同名 VM 不会在磁盘上冲突 |
|
||||
|
||||
**声明式承接**:外部插件在清单中声明 `replaces`(它承接的旧插件 ID)与驱动 `aliases`(它承接的旧驱动 ID)。宿主在**安装或首次激活该插件时**把旧 ID 名下的设置、参数账本条目与按 VM 设置转给它,并让带旧驱动 ID 标记的 VM 归它管理。约束:
|
||||
|
||||
- 宿主在旧插件消失后保留其 `state.json` 记录与账本条目,直到有插件承接,期间这些 VM 显示"驱动不可用"。
|
||||
- 承接 `builtin.*` ID 只允许信任等级为 `official` 的包,或经用户逐项确认,防止任意插件接管已有 VM。
|
||||
- 主程序不硬编码任何 macOS 新旧 ID 映射。数据迁移带入的 `driver.RenamedDriverIDs` 只用于主程序内部的内置驱动改名,外部插件改名一律走 `aliases`。
|
||||
|
||||
驱动 ID 从此与插件 ID 分开:步骤 1 将 `builtin.driver.reims-macos` 移出 `RetiredIDs`,只有正式发布过的旧记录进入迁移清单:`builtin.core` 的设置与账本,以及 `builtin.install-guide` 的启停。未公开发布过的独立 theme/driver、compat/prep 插件记录不迁移、不删除。
|
||||
|
||||
## 4. 分步方案
|
||||
|
||||
每一步单独合入、单独发布,完成后对应的棘轮例外缩短(第 6 节)。
|
||||
|
||||
### 步骤 0:数据目录写入保护
|
||||
|
||||
后续每一步的数据迁移都依赖它;不依赖第 3 节的任何决定,可以立即开始。
|
||||
|
||||
- **统一打开入口**:新增宿主包(暂名 `internal/dataroot`),GUI 启动(`config.Resolve`)、首次设置(`CompleteSetup`)、切换目录(`SetDataRoot`)与 CLI 都经它进入。顺序为:
|
||||
1. 不加锁读取版本戳。版本高于本程序、或版本戳无法解析时,以只读模式返回,**不创建锁文件、不写任何文件**。
|
||||
2. 需要迁移或即将写入时,才创建并获取写锁,**拿锁后重新读取版本戳**,再决定是否迁移。另一个进程已完成迁移时直接返回。
|
||||
3. 迁移完成、版本戳写入后释放写锁。
|
||||
- **写锁**:把 `internal/macos/installer` 中基于 `LockFileEx` 的文件锁上提为宿主公共实现(`internal/filelock`),锁文件放在数据目录内,只在迁移时持有。配置与 `state.json` 都以临时文件加改名的方式原子写入,单次写入不会留下残缺文件,因此不为单次写入加锁;GUI 与 CLI 同时修改同一份配置时的相互覆盖不在本步解决。
|
||||
- **只读诊断模式**:GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台,说明原因与详细信息,可选择其他目录;版本记录损坏时提供显式"修复(从 v0 重新迁移)",另一进程升级中或升级失败时提供"重试"。CLI 只放行 `version`、`help` 与 `doctor`,其他命令以非零退出码拒绝。
|
||||
- **写入点清单**(只读模式与首次设置前全部拦截):`reims-go.json`、`plugins/state.json` 与其备份、市场索引缓存、版本戳、启动哨兵 `.startup-sentinel`、`cli-start-*.json`、界面健康日志 `logs/ui-health.log`、应用更新后对更新下载目录的清理、VM 目录内的参数账本与归属标记。`CompleteSetup` 对候选目录的可写性探测(`.write-test-*`)只针对用户已选定的目录,保留。
|
||||
- **首次设置前零写入**:`needsSetup` 期间不把默认建议目录当作数据目录,数据迁移、插件状态与配置保存都要等目录选定。`REIMS_GO_FIRST_RUN` 测试模式必须同时指定隔离的数据目录,否则拒绝启动。
|
||||
- **CLI 交给界面进程**:`location.json` 位于数据目录之外。CLI 未指定数据目录、经单实例交给界面进程时,以界面进程当前打开的目录为准;该目录处于只读模式时,写命令被拒绝并说明原因。
|
||||
- **`MigrateRetired` 一次落盘**:删除旧记录与写入新设置合并为一次 `state.json` 原子替换。
|
||||
|
||||
**验收**
|
||||
- 高版本或版本戳损坏的数据目录:GUI 进入只读模式、CLI 写命令被拒,目录内无任何文件(含锁文件)被创建或修改。
|
||||
- 首次设置测试模式与设置完成前,默认建议目录内无任何文件被创建或修改。
|
||||
- 在 `MigrateRetired` 两步之间模拟退出,重启后用户关闭的选项仍为关闭。
|
||||
- GUI 与 CLI 同时启动并触发迁移,迁移只执行一次,结果一致。
|
||||
|
||||
### 步骤 1:macOS 插件身份与元数据迁移(已落地,合并至 v3)
|
||||
|
||||
- 新增内置插件 `builtin.guest.macos`,注册代码放在 `internal/macos/guest` 内,由 GUI 与 CLI 组装入口注册。`builtin.core` 只保留客体无关的默认主题。过渡期 macOS 插件默认启用,以保留存量 VM 的升级行为。
|
||||
- **安装引导并入**:`builtin.install-guide` 并入 `builtin.guest.macos`,成为它的一个可开关功能;旧 ID 退役,用户原来的启用状态转为新插件的对应设置。外部 macOS 插件因此只是一个包。
|
||||
- **静态声明驱动**:新插件在清单 `guestDrivers` 中静态声明 `builtin.driver.reims-macos`,运行中检查才能阻止在 macOS VM 运行时停用它,使用中检查才能阻止在仍有 macOS VM 时卸载它。
|
||||
- **设置迁移**:`whpx_fallback`、`win10_cold_reboot` 从 `builtin.core` 转给新插件,合并顺序为"新插件显式值 → 旧插件显式值 → 默认值"。
|
||||
- **参数账本迁移**:每台 VM 的账本中,只把已知由 macOS 启动步骤写入的条目转给新插件;用户手动参数与其他插件的条目保持原所有者。无账本的旧 VM(老版本或 CLI 直接启动过)由 `stripLegacyManagedExtraArgs` 兜底,该函数随之迁入 macOS 代码。
|
||||
- **迁移方式**:在写锁下先备份受影响的小文件,一次替换 `state.json`,各步可重复执行,全部校验通过后才写版本戳 v3;与步骤 2a 的 VMRef 设置键转换共用一次 `state.json` 读取和写入,保留升级前原始备份。VM 目录、磁盘、快照、CoW 父盘与 `vm.toml` 不移动。
|
||||
- **反向棘轮**:新增"`internal/macos/` 只能导入列入清单的宿主包"的测试,清单从现状开始,只减不增。
|
||||
|
||||
**验收**
|
||||
- 从 v0.2.x 直升:用户关闭过的兼容选项与安装引导开关保持原值,手动设置的 `kernel-irqchip` 仍优先。
|
||||
- 迁移中途退出后重启,迁移可继续,结果与一次完成相同。
|
||||
- 同一台 VM 连续启动两次,参数不重复追加,辅助盘不重复挂载。
|
||||
|
||||
### 步骤 2:VM 引用与启动链路
|
||||
|
||||
**2a. `VMRef` 身份、内部索引与 list/start/stop 用户入口已落地**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM)
|
||||
|
||||
- 引入 `VMRef{DriverID, Name}`;`Router.ResolveVM` 遇到多个同名结果时返回歧义错误;`ListAllVMs` 不再按名称去重。
|
||||
- 驱动在清单中声明 VM 根目录(第 3 节),路由与"驱动不可用"扫描遍历所有已声明的根。
|
||||
- 宿主内存态、Guest Tools 注册表、缩略图与键入锁、日志来源改为按 `VMRef` 索引;对客体已经暴露的访问路径保留兼容。
|
||||
- `PluginRecord.VMSettings` 的键改为 `VMRef` 的规范字符串,与步骤 1 共用版本 v3 的一次写入:已有键全部归属 `builtin.driver.reims-macos`。
|
||||
- 界面进程交接参数增加驱动;只给名称且不重名时仍可用。
|
||||
|
||||
**2b. 驱动自有准备与第三方意图分开(已落地)**
|
||||
|
||||
- `Driver.Start` 改为接收启动请求:`VMRef`、第三方插件经 `vm.beforeStart` 给出的意图(参数片段、环境变量、启动后动作),以及日志输出。
|
||||
- 启动前检查(WHPX、运行时兼容)与启动准备由驱动自己完成。macOS 的离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启、Guest Tools 辅助盘从 `vm.beforeStart` 移入 macOS 驱动的 `Start`,"先准备恢复环境,再写引导语言"的顺序由驱动保证。
|
||||
- 参数账本的合并与写入(对 reims 即 `reims-ctl set --extra-args`)由驱动执行,宿主以公共函数提供账本合并逻辑。
|
||||
- `vm.beforeStart` 只留给第三方插件,继续脱敏、限时、限参数族。驱动在完成全部第三方 Hook、无人否决之后才改动磁盘,因此不需要通用回滚:准备步骤保持可重复执行,任一步失败即中止启动并明确报错;用户选择恢复启动而准备失败时,不悄悄转为普通启动。
|
||||
- 特权按第 1 节的角色规则判定:驱动对自己的 VM 拥有完整参数控制;宿主内置插件保留现有白名单;其他插件按现有限制。
|
||||
|
||||
**2c. 统一入口与职责拆分(已落地)**
|
||||
|
||||
- 新增生命周期模块(暂名 `internal/lifecycle`),GUI 的 `StartVM` 与 CLI 的 `startVM` 都调用它,`startInWindow` 交给界面进程后同样进入它。宿主负责按 `VMRef` 解析驱动、串行化同一台 VM 的操作、派发事件(驱动 ID、运行时与能力取自该 VM)、任务与日志、进程退出监视。
|
||||
- **拆分 `vmstart`**:提交内存检查、P 核绑核、亲和性配置留在宿主;离线辅助盘、恢复标记与 OpenCore 相关步骤迁入 `internal/macos/`。
|
||||
- **拆分 Guest Tools**:传输、剪贴板与共享目录留在宿主(`guest-tools.transport` 服务),macOS 客体代理与辅助盘镜像(`BuildToolsDiskImage` 等)迁入 `internal/macos/`;镜像构建由 macOS 驱动在全部启动 Hook 通过后执行。
|
||||
- **拆分调优判定**:宿主只报告探测事实;驱动针对选中的 VM 结合运行时能力给出建议,设置页与实际启动共用同一份判定。`kernel-irqchip`、WHPX 兼容降级与冷重启补偿的策略归 macOS 驱动。
|
||||
|
||||
**验收**
|
||||
- 升级后用原有 macOS VM 验证:恢复引导、离线辅助盘、引导语言、冷重启监视、Guest Tools 与升级前行为一致;按 VM 的插件设置不丢失。
|
||||
- 第三方插件否决启动时,VM 目录与 OpenCore 镜像未被修改。
|
||||
- 测试驱动在相同宿主探测结果下,不会收到 OpenCore、辅助盘或冷重启参数。
|
||||
|
||||
### 步骤 3:其余入口统一路由(通用 App/CLI 已去 reims 直调,原生 macOS 流程按文件例外隔离)
|
||||
|
||||
- **后端**:VM 列表与轮询、详情、创建、设置、停止、重启、删除、日志、弹出安装介质,以及快照、克隆、磁盘、缩略图、统计、排障采集、亲和性等流程,全部经生命周期模块按 `VMRef` 路由。
|
||||
- **CLI**:`vm` 子命令全部走驱动层,重名时要求 `--driver`。顶层 `installer` 子命令改由 macOS 插件经 `commands` 扩展点贡献,宿主 CLI 提供插件命令转发。
|
||||
- **前端**:改用通用 VM 模型(名称、驱动、状态、CPU、内存、磁盘摘要、可用操作),按驱动能力位显示入口,后端执行时同样校验能力。`CreateWizard`、`SettingsModal` 中的 macOS 字段改为驱动的 `CreateSchema` / `SettingsSchema` 或插件页面。
|
||||
- **macOS 界面**:安装包页、在线恢复、版本图、OpenCore 设置由 macOS 插件贡献;过渡期经同一处注册表挂载 `frontend/src/macos/` 内的原生页面。
|
||||
|
||||
**验收**
|
||||
- 在测试装配中不注册 macOS 插件:工作台仍可用测试驱动完成"创建 → 启动 → 停止 → 删除"。
|
||||
- 两个驱动各有一台名为 `dev` 的 VM:两台都出现在列表、各自的按 VM 设置互不覆盖;停止其中一台只调用其所属驱动。
|
||||
- 恢复 macOS 插件后,原有 macOS VM 沿原路径启动,无需转换磁盘或重建配置。
|
||||
|
||||
### 步骤 3.5:宿主服务与按种类的运行时
|
||||
|
||||
Linux 驱动(步骤 4)与 macOS 外置(步骤 5)共同的前置条件,可在步骤 2 之后与步骤 3 并行开发。
|
||||
|
||||
- **按种类选定运行时**:配置改为每个运行时种类各记一个活跃运行时,随数据版本迁移现有的单值;只读操作在未选定时临时使用该种类最新安装的运行时、不写回配置,启动与创建前要求选定(待决,见第 9 节)。
|
||||
- **运行时与 reims 解耦**:`internal/runtime` 只保留按种类的通用安装、校验、切换与环境构造;reims-vgpu 的默认种类、`reims-ctl` / `reims-util` 路径、专用环境变量、按补丁推断能力与发布源,改由运行时种类声明提供(过渡期由 macOS 插件声明)。
|
||||
- **反向宿主接口扩充**(同时进入 `pkg/pluginsdk` 的公开类型):运行时查询(按种类返回路径与能力)、提交内存预检、绑核、日志与任务进度、进程退出通知、QMP 访问、VM 窗口信息与宿主明暗主题事件(安装引导浮层需要)。每项按权限校验。
|
||||
- **脱敏注册**:宿主提供通用脱敏层,插件可注册自己的脱敏规则;全局脱敏器、插件管理器、排障包与界面错误上报改用它。macOS 的规则由 macOS 插件注册。
|
||||
|
||||
### 步骤 4:Linux 最小驱动与驱动契约测试
|
||||
|
||||
- 新增与具体驱动无关的契约测试集(暂名 `internal/driver/drivertest`),对每个驱动运行同一组用例:生命周期调用的幂等与可重试边界、错误分类,以及"进程已启动 / 控制通道可用 / 客体已就绪"三种状态的区分。
|
||||
- Linux 驱动以独立仓库的 L3 插件实现,只依赖 `pkg/pluginsdk` 与反向宿主接口;先跑通一种镜像的创建、启动、停止与删除,再按 plugin-architecture.md Phase 4 的验收标准补齐。
|
||||
- 只有出现两份以上重复实现时,才从中提取磁盘或 QEMU 公共模块。
|
||||
|
||||
**验收**:契约测试同时覆盖 macOS 内置驱动与 Linux 驱动;Linux 驱动不修改主程序源码即可接入。
|
||||
|
||||
### 步骤 5:macOS 外置
|
||||
|
||||
前置条件:
|
||||
|
||||
- **外部插件页面**:整页插件页面(iframe,插件自带前端包,宿主提供主题令牌与到插件自身 Sidecar 的桥接)、创建向导步骤槽位、VM 详情分区槽位。桥接至少提供:宿主文件与目录选择(返回宿主路径交给插件 Sidecar,iframe 内不可见)、长任务的注册与流式进度(下载、取消、退出前拦截活跃任务)、由宿主绘制的对话框、iframe 高度自适应与焦点和快捷键传递。
|
||||
- **运行时需求声明**:插件在清单中声明需要的运行时种类与版本范围;缺少时宿主引导用户安装。运行时包不随插件安装事务自动拉取,插件之间的安装期依赖等出现真实用例再设计。
|
||||
- **语言与文案**:`macos-glossary.json`、`internal/i18n/glossary.go` 与各词表中的 macOS 文案迁入 macOS 插件的 `l10n`;第三方语言包对 macOS 文案的翻译改为针对该插件的 `pluginOverrides`。
|
||||
- **反向棘轮清零**:`internal/macos/` 不再导入任何宿主 `internal/` 包,只依赖 `pkg/`。
|
||||
- **声明式承接可用**:`replaces` 与 `aliases`(第 3 节)已实现并有测试。
|
||||
|
||||
外置本身:
|
||||
|
||||
- 迁出清单:`internal/macos/`、`frontend/src/macos/`、macOS 词表、`patches/`、`.github/workflows/build-runtime.yml`、`scripts/` 中的运行时打包与补丁脚本、`docs/portable-runtime-spec.md` 中 reims-vgpu 专属部分。用 `git filter-repo` 按清单生成 macOS 插件仓库,保留这部分历史;主仓库一次提交删除,并改写 README 与 AGENTS 中的产品定位。若历史本身也需剥离,改为反向拆分(第 9 节)。
|
||||
- 发布不含 macOS 的主程序:已有 macOS VM 因归属标记与 macOS 驱动声明的 VM 根仍在列表中,显示"需要安装对应驱动插件",由用户自行安装;主程序不自动安装、不默认推荐。用户安装外部 macOS 插件后,经声明式承接取回设置、账本与 VM 归属。
|
||||
|
||||
**验收**
|
||||
- 主仓库删除迁出清单后,构建、测试与两处棘轮全部通过;对 `macOS`、`OpenCore`、`reims`、`Apple` 等词的全仓检索只剩明确列出的例外(如"驱动不可用"提示中的通用说法)。
|
||||
- 安装外部 macOS 插件后,原有 macOS VM 无需转换即可启动,用户关闭过的选项保持关闭。
|
||||
|
||||
## 5. 顺序与并行
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S0["步骤 0\n数据目录写入保护"] --> S1["步骤 1\nmacOS 插件身份\n与 v3 迁移"]
|
||||
S1 --> S2["步骤 2\nVMRef 与启动链路"]
|
||||
S2 --> S3["步骤 3\n其余入口统一路由"]
|
||||
S2 --> S35["步骤 3.5\n宿主服务与\n按种类的运行时"]
|
||||
S3 --> S4["步骤 4\nLinux 最小驱动"]
|
||||
S35 --> S4
|
||||
S3 --> S5["步骤 5\nmacOS 外置"]
|
||||
S35 --> S5
|
||||
P5["外部插件页面 · 承接机制\n语言迁出 · 反向棘轮清零"] --> S5
|
||||
```
|
||||
|
||||
- 步骤 0 不依赖其他决定,可以立即开始;步骤 1、2 开始前需定下第 3 节的身份模型与第 1 节的特权规则。
|
||||
- 步骤 3 与 3.5 可并行;外部插件页面、承接机制与语言迁出可在步骤 2 之后并行开发。
|
||||
- 以法律目标为准时,最快路径仍要经过步骤 1–3.5;跳过它们会让外置时再做一次数据与职责迁移。
|
||||
|
||||
## 6. 棘轮与检查
|
||||
|
||||
**宿主 → macOS**(现有,`internal/archtest` 与 `frontend/scripts/test-macos-boundary.mjs`):
|
||||
|
||||
| 例外 | 移除时机 |
|
||||
| :--- | :--- |
|
||||
| `internal/plugin/builtin`(仅源码的 Guest Tools 参数辅助) | 步骤 2:客体代理与辅助盘镜像迁出后移除;注册与测试例外已在步骤 1 移除 |
|
||||
| `internal/datamigrate` | 步骤 5:历史 v3 迁移改为不依赖 macOS 实现的通用数据迁移后移除 |
|
||||
| `internal/guesttools`(源码与测试) | 步骤 2:客体代理与辅助盘镜像迁出 |
|
||||
| `internal/plugin`(仅测试) | 步骤 3:Sidecar 测试改用通用测试替身 |
|
||||
| `internal/app`、`internal/cli` | 步骤 3:只剩一个组装文件注册 macOS 插件,例外细化到该文件 |
|
||||
| 前端 `App.tsx`、`Sidebar.tsx`、`VMPage.tsx` | 步骤 3:改为插件贡献 |
|
||||
| 组装文件 | 步骤 5:macOS 外置后删除 |
|
||||
|
||||
**macOS → 宿主 `internal/`**(步骤 1 新增):清单从现状开始,随步骤 2 与 3.5 把依赖改到 `pkg/`,步骤 5 前清零。
|
||||
|
||||
**非 import 耦合**:import 棘轮看不到第 2.5 节所列的词表、脱敏、运行时、前端字段等耦合。不为它们另建常驻检查;各自在所属步骤内迁移,步骤 5 以一次全仓检索作为验收。
|
||||
|
||||
## 7. 风险
|
||||
|
||||
| 风险 | 应对 |
|
||||
| :--- | :--- |
|
||||
| 迁移改坏用户数据 | 步骤 0 的写锁、只读模式与一次落盘;迁移前备份小文件;只动元数据,不动磁盘 |
|
||||
| 升级后 macOS VM 行为变化 | 每步以原有 macOS VM 做回归:恢复引导、辅助盘、引导语言、冷重启监视、Guest Tools、绑核 |
|
||||
| 特权模型改变引入越权 | "驱动对自己的 VM 拥有完整参数控制"只授予 VM 的所属驱动;`builtin.*` 的承接只允许 `official` 包或用户逐项确认;改动单独评审 |
|
||||
| `VMRef` 迁移遗漏某处按名索引的状态 | 步骤 2a 以"两台同名 VM"作为贯穿测试用例,覆盖设置、内存态、Guest Tools 与交接参数 |
|
||||
| 新旧版本混用 | 只读模式只保护新版本;降级支持的最低版本需明确公布(第 9 节) |
|
||||
| 步骤之间长期停留在半迁移状态 | 每步自成闭环、可单独发布;棘轮清单只减不增 |
|
||||
| 外部插件界面体验不及原生 | 过渡期保留原生页面;外置前以安装包页与恢复向导做可用性验收 |
|
||||
|
||||
## 8. 后续(不在本方案内)
|
||||
|
||||
触发条件出现时再立项:
|
||||
|
||||
- **稳定 VM ID**:VM 改名需要保持设置与历史、PID 复用或 CLI 超时重试出现实际问题时,引入 VM ID、一次开机的运行 ID 与一次长操作的操作 ID(参考 libvirt 的 UUID 与 containerd 将对象与运行分离的做法)。`VMRef` 届时作为人读入口保留。
|
||||
- **重新接管**:管理进程重启后重新连接正在运行的 VM,GUI 退出后 CLI 能找回同一次运行。
|
||||
- **常驻服务**:需要"GUI 退出后任务继续""多客户端订阅同一状态"或第三方程序调用时,再把生命周期模块放到用户级后台进程后,经 Windows 命名管道提供带版本的接口。
|
||||
- **整盘迁移**:换盘、换电脑做成停机导出与导入;验收为原数据目录完全不可访问时,目标机仍能从带 CoW 子盘的副本启动。
|
||||
- **升级交接**:进行中的创建、克隆、快照绑定发起时的驱动版本,运行中 VM 的控制权在重连验证后移交(参考 Magpie 插件宿主升级时的处理)。
|
||||
- **插件间安装期依赖**:出现"插件 A 必须与插件 B 一起安装"的真实用例后再设计,届时优先考虑只提示、不自动求解。
|
||||
|
||||
## 9. 待决事项
|
||||
|
||||
步骤 1 开始前需要定下:
|
||||
|
||||
1. **特权规则**:是否接受第 1 节"按角色授予特权"的规则,替代现有按 `builtin.` 前缀放行。
|
||||
2. **承接的信任要求**:承接 `builtin.*` ID 是只允许 `official` 包,还是也允许用户逐项确认。
|
||||
3. **过渡期 macOS 插件是否默认启用**:步骤 1 暂取默认启用,保证升级无感;默认关闭更贴近剥离方向,但存量用户升级后会看到"驱动不可用"。最终实现仍待评审。
|
||||
|
||||
可在后续步骤前决定:
|
||||
|
||||
4. **多运行时未选定时的行为**(步骤 3.5):建议只读操作临时使用最新安装的运行时、不写回配置,启动与创建前要求选定。
|
||||
5. **降级支持**(步骤 0 发布前):可安全退回的最低版本,以及只读模式的提示文案。
|
||||
6. **剥离范围**(步骤 5):法律风险具体涉及哪些内容(OpenCore 与 SMBIOS 处理、Apple 安装包下载、产品定位中的 macOS 字样、reims-vgpu 运行时),决定迁出清单的范围。
|
||||
7. **官方市场是否上架 macOS 插件**(步骤 5):上架方便用户,但官方索引仍与 macOS 产生关联。
|
||||
8. **代码历史**(步骤 5):只删除当前代码,还是让主程序以新仓库重新开始历史、本仓库保留为 macOS 插件仓库。
|
||||
+89
-20
@@ -60,7 +60,7 @@
|
||||
flowchart TB
|
||||
subgraph Exe["reims-go.exe(可信核心)"]
|
||||
Reg["扩展点注册表\n依赖解析 · 可逆副作用 · Reconcile"]
|
||||
Builtin["内置扩展(编译期注册)\n核心:reims 驱动 · 默认主题 · 启动准备 · 兼容补偿\n可选:宿客桥接 · 剪贴板 · 输入服务 · 窗口安装引导 · reims-vgpu 运行时种类"]
|
||||
Builtin["内置扩展(编译期注册)\n核心:默认主题\n可选:macOS 客体驱动 · 宿客桥接 · 剪贴板 · 输入服务 · reims-vgpu 运行时种类"]
|
||||
Mgr["插件管理器\n清单校验 · 事务安装 · 状态 · 安全模式"]
|
||||
Broker["Host API 代理\n权限校验 · 脱敏 · 限流 · 审计"]
|
||||
Sup["进程监管器\nJob Object · 重启退避 · 健康检查"]
|
||||
@@ -106,10 +106,11 @@ flowchart TB
|
||||
|
||||
扩展点先由内置功能使用一遍再对外开放。内置功能分两类,判断标准是用户关掉它之后,是「少了一项功能」还是「已有功能坏掉」:
|
||||
|
||||
- **核心** `builtin.core`:Reims-Go 离开它就无法运行 macOS 虚拟机的部分,包括 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、默认主题(主题 id 仍为 `builtin.theme.default`)、启动准备(离线辅助盘、恢复模式引导切换、引导语言重放)与宿主兼容补偿(WHPX 降级、Win10 冷重启)。它是**系统插件**:始终启用,不能停用或卸载,插件页显示为一行「始终启用」,不参与「使用中」检查。两项兼容补偿作为核心的应用级设置保留开关,仅供排障。启动准备在同一个 `vm.beforeStart` 处理器里按固定顺序执行,引导语言重放必须在恢复模式切换(可能重建 OpenCore)之后。
|
||||
- **核心** `builtin.core`:只保留客体无关的默认主题(主题 id 为 `builtin.theme.default`)。它是**系统插件**:始终启用,不能停用或卸载,不出现在插件页与 `plugin list` 中(按 ID 查询仍可见),不参与「使用中」检查。
|
||||
- **macOS 客体插件** `builtin.guest.macos`:注册代码位于 `internal/macos/guest`,静态声明 reims 驱动(驱动 id 仍为 `builtin.driver.reims-macos`)、宿主体检、启动准备、WHPX 降级、Win10 冷重启和安装引导。它是可停用插件,过渡期默认启用以保留升级行为;有 VM 运行时不能停用,停用后宿主内的 macOS 原生页面与流程(创建、设置、Guest Tools 挂载、安装与恢复等)一并拒绝执行,直到重新启用。安装引导保留独立应用级开关。启动准备暂经 `vm.beforeStart`,下一步改由驱动自己执行,见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
- **可选内置扩展**:Guest Tools 传输服务、剪贴板互通、宿主输入服务、虚拟机窗口安装引导。经同一注册表注册、可独立启停、停用后零残留,停用即真正停止(不被其他调用方重新拉起)。首批示例为默认开启的剪贴板互通(见 §5.4)。
|
||||
|
||||
核心由曾经拆开的七个内置插件合并而来(`builtin.RetiredIDs`)。启动时删除 `state.json` 中这些旧 ID 的记录,关闭过的兼容补偿转为对应的核心设置;启动 VM 时,参数归属账本中旧 ID 名下的片段移交给核心,继续沿用而不是被当作已卸载插件的残留剥离。
|
||||
旧版曾把 macOS 驱动、兼容补偿、安装引导与准备步骤拆成多个内置插件。数据布局 v2 的迁移删除这些旧 ID 的记录:显式设置与旧安装引导启停状态转入 `builtin.guest.macos`,参数账本中已知 macOS 条目也转给该插件;无关插件与宿主参数保持原所有者。
|
||||
|
||||
---
|
||||
|
||||
@@ -119,7 +120,8 @@ flowchart TB
|
||||
|
||||
- 每个已启用插件(含内置)拥有一个作用域,所有注册行为(提供服务、贡献扩展点、订阅事件、后台服务、Win32 钩子、QMP 监视)都登记一个释放函数;停用、卸载或升级时**逆序释放**,激活中途失败则回滚已登记项。
|
||||
- 插件声明 `requires` / `provides`(服务名 + 版本范围)。Reconcile 先关后开:先释放不再需要的插件及依赖其服务的插件,再按依赖求不动点激活。状态为 `off / pending / active / degraded / failed`。
|
||||
- **使用中不可移除**:仍有 VM 归属的驱动、仍被 VM 使用的运行时,不可停用或卸载;使用情况查询失败按「使用中」处理。
|
||||
- **使用中不可移除**:仍有 VM 归属的驱动不可卸载,仍被 VM 使用的运行时不可删除;使用情况查询失败按「使用中」处理。
|
||||
- **运行中不可停用**:驱动的 VM 只要有一台处于停止、挂起或损坏以外的状态,就不能停用其插件;状态查询失败同样拒绝。VM 都已停止或挂起时可以停用:VM 文件与挂起状态保留,显示为「驱动不可用」,不能启动、恢复或修改,重新启用后恢复。插件页停用这类插件前先弹窗说明。
|
||||
- 内置扩展通过 `pluginApi` 版本做兼容检查;激活 panic 转为 `failed` 并回滚。
|
||||
|
||||
### 4.2 扩展点目录
|
||||
@@ -137,10 +139,11 @@ flowchart TB
|
||||
| `hooks` | Builtin · L1 · L2 · L3 | 有序列表 | 按事件模式(§4.3) |
|
||||
| `commands` | Builtin · L2 · L3 | 按 id | 报错并提示 |
|
||||
| `menus` / `vmCards` / `settingsPages` / `statusItems` | 声明式 | 列表,设数量上限 | 隐藏该项 |
|
||||
| `panels` | L4 iframe | 限定槽位 | 错误占位 + 重试 |
|
||||
| `panels` | L4 iframe,嵌在槽位内 | 限定槽位,限高 | 错误占位 + 重试 |
|
||||
| `views` | L4 iframe,整页或标签页(§5.6) | 按位置设数量上限 | 错误页 + 重试;不影响其他视图 |
|
||||
| `diagnostics` | Builtin · L3 | 列表 | 跳过;输出强制脱敏 |
|
||||
|
||||
UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`、`settings.plugin`,后续按真实需求再增加 `sidebar.footer`、`statusbar.right`、`create.source`;插件只能向已声明槽位贡献。
|
||||
UI 槽位采用「声明即占有」:插件只能向宿主槽位目录(§5.1)中的槽位贡献。目录中的每个槽位、每种视图位置都必须由宿主实际渲染,前端构建检查覆盖这一点;不能出现可以声明、界面上却不显示的位置(§6.3)。
|
||||
|
||||
### 4.3 Hook 事件与分发模式
|
||||
|
||||
@@ -185,11 +188,14 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| 契约 | 内容 |
|
||||
| :--- | :--- |
|
||||
| 设计令牌 | 单一来源(令牌数据同时生成 CSS 变量与前端常量),覆盖颜色、字体排印、形状、阴影、动效时长与缓动、层级;动效档位(含系统「减少动态效果」)在一处解析为文档属性,样式与脚本读同一个值 |
|
||||
| 部件 | 关键区域与控件挂稳定的部件类名(如 `rg-p-sidebar`、`rg-p-vm-header`、`rg-p-statusbar`),每个部件一个独立类名,便于浏览器按类名分桶匹配;主题选择器只允许使用部件、状态属性与令牌,不得依赖内部类名或界面文字 |
|
||||
| 状态属性 | 文档与区域上的只读状态:外观、当前视图、VM 显示状态、忙碌态、是否有错误、侧栏折叠 |
|
||||
| 槽位锚点 | 装饰与扩展内容的挂载点(如侧栏底部、VM 预览四角、状态栏、空状态区) |
|
||||
| 部件 | 区域与控件挂稳定的部件类名,每个部件一个独立类名,便于浏览器按类名分桶匹配;主题选择器只允许使用部件、状态属性与令牌,不得依赖内部类名或界面文字。区域级:`rg-p-shell`、`rg-p-titlebar`、`rg-p-sidebar`、`rg-p-nav`、`rg-p-main`、`rg-p-vm-page`、`rg-p-statusbar`、`rg-p-logpanel`、`rg-p-settings` 等;控件级:`rg-p-nav-group`、`rg-p-nav-item`、`rg-p-button`、`rg-p-icon-button`、`rg-p-card`、`rg-p-badge`、`rg-p-tabs`、`rg-p-tab`、`rg-p-menu`、`rg-p-menu-item`、`rg-p-dialog`、`rg-p-toast`、`rg-p-tooltip`、`rg-p-input`、`rg-p-switch`、`rg-p-progress`、`rg-p-vm-actions`、`rg-p-plugin-view` |
|
||||
| 状态属性 | 文档级只读状态:外观、动效档位、语种与书写方向、当前视图、侧栏折叠、安全模式、布局选项;逐项状态:导航项与 VM 区域带 `data-vm-state`、`data-driver`、`data-selected`、`data-busy`,按钮带 `data-variant`、`data-busy`,对话框与提示条带 `data-tone`。主题可据此为单个 VM 条目做动效,不必解析界面文字 |
|
||||
| 槽位目录 | 每个槽位声明上限与可挂内容(装饰、SDK 挂载、`panels`、`menus`、`statusItems`):`titlebar.center`、`sidebar.header`、`sidebar.footer`、`nav.item.trailing`(逐个 VM 条目)、`vm.header.trailing`、`vm.toolbar`、`vm.card`、`vm.preview.tl/tr/bl/br`、`statusbar.left`、`statusbar.right`、`empty.state`、`create.source`、`settings.plugin` |
|
||||
| 图层 | 全窗口背景层 `layer.background` 与前景装饰层 `layer.overlay`:不拦截指针、不参与焦点,「减少动态效果」时停播动画;用于动态壁纸、粒子与满屏吉祥物 |
|
||||
| 布局选项 | 主题清单的 `layout` 声明:侧栏位置(左/右)、侧栏形态(完整/图标窄栏/悬浮)、密度(紧凑/常规/宽松)、标题栏样式。只改摆放与尺寸,不能隐藏操作入口 |
|
||||
| 图标 | 宿主公开图标名清单(如 `start`、`stop`、`settings`、`plugin`、`vm.state.running`);主题以 `icons` 映射到包内单色 SVG,宿主按令牌着色 |
|
||||
|
||||
契约内的部件、状态属性与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件仍由某个组件输出。
|
||||
契约内的部件、状态属性、槽位、图层、布局选项、图标名与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件、槽位与图层都由某个组件输出(§6.3)。
|
||||
|
||||
**三档主题能力**
|
||||
|
||||
@@ -203,6 +209,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
- 生命周期:主题脚本导出装载函数,所有订阅、计时器与挂载都登记释放函数;切换或停用主题时逆序拆除,单个功能抛错不影响其余功能。
|
||||
- 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。
|
||||
- 事件流:VM 状态变化(含过渡态)、任务开始/进度/结束、提示条出现、视图切换,供主题做转场动画,不必轮询状态。
|
||||
- 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。
|
||||
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。
|
||||
- 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。
|
||||
@@ -214,7 +221,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
- 样式清洗:禁止外部 `url()` 与远程 `@import`,资源只能引用包内清单中的文件;窗口拖拽区、焦点环与最小点击热区等可用性属性由宿主在更高层保留,不被主题覆盖。
|
||||
- 同一时刻只启用一个主题包,切换时先停用旧主题再装载新主题;安全模式一律回到内置主题。
|
||||
- 首帧前按当前主题内联令牌防闪烁;无边框窗口的标题栏由前端绘制,可随主题变化。
|
||||
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。
|
||||
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。布局选项可以挪动区域、改变侧栏形态,但 VM 列表、新建、设置与插件入口始终可达。
|
||||
- 主题不提供功能页面;需要自有界面的插件走 §5.6 的视图,不经 `ui:script`。
|
||||
- 需要读写用户文件或常驻服务的主题,以同包 L3 Sidecar 实现。
|
||||
- 开发支持:`reims-go plugin link` 链接本地目录并热重载;`reims-go plugin doctor` 校验样式只使用契约内的部件、状态属性与令牌。
|
||||
|
||||
@@ -228,16 +236,17 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
### 5.3 非 macOS 虚拟机(客体驱动,L3)
|
||||
|
||||
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/driver/reims` 的具体类型。抽象后:
|
||||
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/macos/reims` 的具体类型。抽象后:
|
||||
|
||||
| 层 | 内容 |
|
||||
| :--- | :--- |
|
||||
| 通用 VM 模型 | 驱动 id + 名称、状态(`stopped / running / broken` 与过渡态)、CPU / 内存 / 磁盘摘要、目录、能力位 |
|
||||
| 驱动专有数据 | 不透明扩展字段 + 驱动提供的创建/设置 JSON Schema(宿主原生渲染,标注生效时机) |
|
||||
| 能力位 | `snapshot`、`cow_clone`、`resize`、`qmp`、`ssh`、`guest_tools`、`affinity`、`opencore`、`recovery`、`cloud_init`、`uefi_iso` 等;UI 与 CLI 按能力位显隐操作 |
|
||||
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选快照、派生、扩容与通用 `InvokeAction` |
|
||||
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选 `SnapshotDriver`、`CloneDriver`、`DiskDriver` 与通用 `InvokeAction`;存储调用由生命周期先解析 `VMRef`,结果使用 `driver.DiskSnapshot / DiskResizeResult / DiskCompactResult` |
|
||||
|
||||
- **VM 归属**:VM 目录内的标记文件 `.reims-go-driver` 记录驱动 id;无标记的存量 VM 归属 `builtin.driver.reims-macos`,并由数据迁移补写标记([architecture.md](architecture.md) §4.7)。有标记的 VM 在其驱动缺席时仍以「驱动不可用」列出。驱动迁到另一个插件、id 随之改变时(市场插件不能使用 `builtin.` 前缀),在 `driver.RenamedDriverIDs` 登记旧 id 到新 id 的映射;标记文件不改写,降级后旧版本仍能识别。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
|
||||
- **VM 引用与根目录**:`driver.VMRef{DriverID, Name}` 的规范键为 `driverID:vmName`;`Router.ListAllVMs` 按完整引用去重,裸名称解析遇到跨驱动同名时返回歧义错误,调用方须显式指定驱动。每个 `guestDrivers` 条目用 `vmRoots` 声明相对 `<DataRoot>` 的斜杠路径,绝对路径、反斜杠与 `..` 均被拒绝;路由遍历所有已声明根(包括停用驱动)以保留「驱动不可用」条目。按 VM 的插件设置也以规范键持久化。
|
||||
- **宿主共享服务**(驱动经反向调用复用):体检报告、提交内存预检、大小核绑核、QMP 截屏与键入、缩略图、Guest Tools 注册、进程退出监视、任务进度、日志通道、托盘菜单。
|
||||
- **VM 进程归宿主托管**:驱动不直接派生 QEMU,而是请求宿主代为启动并返回 PID。这样 VM 进程不随驱动进程的 Job Object 被回收(驱动崩溃或重启不误杀 VM),绑核、退出监视与冷重启补偿也只在宿主实现一份。
|
||||
- **配置写入**:`reims-ctl set` 铁律约束 reims 管理的 VM;Linux 驱动自管配置文件,同样不允许 UI 拼接原始命令行。
|
||||
@@ -269,8 +278,10 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| :--- | :--- | :--- |
|
||||
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
|
||||
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
|
||||
| `builtin.install-guide` | `internal/installguide`、`internal/app/install_guide.go` | 提供 `ui.install-guide` 服务 + `vm.afterStop` / `vm.deleted` 观察钩子;在虚拟机窗口悬浮展示安装与恢复引导,停用时立即关闭全部浮层并回退主界面恢复卡片 |
|
||||
| `builtin.core`(系统插件) | `driver/reims_adapter.go`、`vmstart.Prepare` 各步骤、`app.go` 冷重启监视 | `guestDrivers` + `themes` + `host.preflight` + 一个按序执行全部启动准备的 `vm.beforeStart`(离线辅助盘 → 恢复模式引导 → 引导语言 → WHPX 降级 → Win10 冷重启)+ `vm.afterStart` / `vm.afterStop`(冷重启监视);设置 `whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.guest.macos` | `internal/macos/guest`、`internal/macos/installguide`、`macosdriver`、`vmstart.Prepare` 各步骤 | 静态 `guestDrivers` + `host.preflight` + 驱动内启动准备与冷重启意图 + 条件提供的 `ui.install-guide` 服务;设置 `install_guide`、`whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.core`(系统插件) | `internal/plugin/builtin/core.go` | `themes`:默认主题 |
|
||||
|
||||
> 下一步:Guest Tools 的 macOS 客体代理与辅助盘镜像迁入 macOS 插件,传输服务留在宿主;启动准备改由驱动自己执行。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
|
||||
### 5.5 与上游补丁队列的边界
|
||||
|
||||
@@ -280,6 +291,44 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
|
||||
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
|
||||
|
||||
### 5.6 插件自有界面
|
||||
|
||||
插件需要界面时按以下顺序选择形式,能用前一种就不用后一种:
|
||||
|
||||
| 形式 | 适用 | 渲染与信任 |
|
||||
| :--- | :--- | :--- |
|
||||
| **声明式界面** | 应用与按 VM 设置、VM 卡片信息、工具栏按钮与菜单、状态栏项、通知、确认框、表单对话框、任务进度 | 宿主原生渲染,自动跟随主题、语种、键盘操作与无障碍;只需低、中危权限 |
|
||||
| **视图(`views`)与面板(`panels`)** | 自定义可视化、控制台、多步向导、需要自绘交互的页面 | 沙箱 iframe(不透明源),只经插件界面桥(bridge)与宿主通信,能力由权限约束 |
|
||||
| **交互主题脚本** | 仅限主题的视觉与交互增强 | 主窗口受信任脚本(`ui:script`);功能插件不得使用 |
|
||||
|
||||
**视图位置**(`views[].location`;面板仍按槽位嵌入,限高):
|
||||
|
||||
| 位置 | 呈现 | 上限 |
|
||||
| :--- | :--- | :--- |
|
||||
| `sidebar` | 侧栏「扩展」分组中的导航项,点击后在主区域整页打开;导航项的图标、标题、角标与选中态由宿主绘制 | 每插件 2 个;超出部分折叠进「更多」 |
|
||||
| `vm.tab` | VM 页内的标签页;以 `when` 限定驱动或能力位(如只对某驱动的 VM 显示控制台) | 每个 VM 页 4 个 |
|
||||
| `settings` | 设置中的独立分节,用于放不进 Schema 表单的复杂设置 | 每插件 1 个 |
|
||||
| `dialog` | 不常驻;由命令或 bridge 的 `ui.openView` 以模态打开,可返回结果 | 同一时刻 1 个 |
|
||||
|
||||
视图字段:`id`、`title`、`icon`(包内单色 SVG,宿主按令牌着色)、`location`、`entry`(包内 HTML)、`order`、`when`、`minWidth`。宿主负责外框:标题、返回、加载与错误占位、重试、尺寸、焦点进出与快捷键。视图惰性加载;同一时刻保持存活的视图有上限,切走的视图超过上限即卸载,插件停用时全部卸载。
|
||||
|
||||
**插件界面桥(`bridgeApi` 1.0)**:iframe 与宿主之间的请求/响应与事件消息,宿主只应答来源窗口为该 iframe 的消息,每个方法在 Go 侧按权限二次校验并限流。
|
||||
|
||||
| 命名空间 | 方法与事件 | 权限 |
|
||||
| :--- | :--- | :--- |
|
||||
| 握手 | `hello`:返回 `bridgeApi`、`features`、语种与书写方向、完整契约令牌、视图上下文(位置、所在 VM 的 `VMRef`) | 无 |
|
||||
| `ui` | `notify`、`confirm`(宿主原生确认框)、`showForm`(以 Schema 弹出原生表单并返回值)、`setTitle`、`setBadge`、`openView`、`close`(`dialog` 返回结果)、`navigate`(只限宿主路由白名单)、`openExternal`(宿主确认后用系统浏览器打开) | `ui:notify` / `ui:slot` |
|
||||
| `vm` | `list`、`get`(通用 VM 模型,不含敏感字段);事件 `vm.stateChanged` | `vm:read` |
|
||||
| `command` | `invoke`:只能调用本插件声明的命令;VM 启停等动作由命令处理方经 `vm:control` 执行 | `ui:slot` |
|
||||
| `settings` | 读写本插件的应用级与按 VM 设置 | 无(限本插件) |
|
||||
| `storage` | 本插件私有键值存储,位于 `data/<id>/`,有配额 | `fs:plugin_data` |
|
||||
| `file` | `pick` / `save` 弹出宿主文件对话框,只返回不透明句柄;按句柄分块读写,不暴露路径 | `fs:pick` |
|
||||
| `task` | 开始、更新、结束任务;在宿主任务区显示进度并可取消 | `task:progress` |
|
||||
| `net` | `fetch` 经宿主代理发出(iframe 自身 `connect-src 'none'`) | `net:<origin>` |
|
||||
| `events` | 订阅主题与语种变化、视图可见性、任务事件 | 无 |
|
||||
|
||||
大对象分块传输,单条消息设大小上限。宿主以 `/plugin-ui-kit/<uiApi>/` 提供界面套件(令牌样式表与常用控件样式),主题或语种变化时经 bridge 推送新令牌,插件界面因此与宿主外观一致,不必自带一套设计系统。
|
||||
|
||||
---
|
||||
|
||||
## 6. 插件包与清单
|
||||
@@ -305,7 +354,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| `name` / `description` | 多语种本地化文本(内置 `zh-CN` / `en-US` 及任意 BCP-47 扩展键),**无需执行插件代码即可读取** |
|
||||
| `l10n` | 可选的包内私有词表目录(如 `"locales"`),存放 `<locale>.json` 供插件自身 UI、iframe 面板与 Sidecar 使用;独立语言包可通过 `pluginOverrides` 在外部补充或覆盖任意第三方插件的清单字段与私有词条 |
|
||||
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
|
||||
| `engines` | `reims-go` 版本范围与 `pluginApi` 范围,**下载前预检** |
|
||||
| `engines` | `reims-go` 版本范围,以及所依赖契约面的范围:`pluginApi`、`uiApi`(主题与面板样式)、`bridgeApi`(视图与面板);**下载前与激活前预检**(§6.3) |
|
||||
| `platforms` | 如 `windows-x64` |
|
||||
| `entry` | Sidecar 可执行文件、脚本文件、面板 HTML 根目录;层级由内容推导,不信任自报 |
|
||||
| `contributes` | 各扩展点贡献(§4.2) |
|
||||
@@ -316,6 +365,24 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| `defaultEnabled` | 安装或首次启动时的默认启用状态;仅内置扩展与随主程序附带的插件可为 `true` |
|
||||
| `provenance` | **运行时包必填**:上游仓库与 commit、补丁清单与哈希、源码包文件名 |
|
||||
|
||||
### 6.3 契约版本与演进规则
|
||||
|
||||
公开契约分三个版本面,各自按 SemVer 演进,插件在 `engines` 中声明依赖范围:
|
||||
|
||||
| 版本面 | 范围 |
|
||||
| :--- | :--- |
|
||||
| `pluginApi` | 清单字段、扩展点、Hook 事件与载荷、权限名、Sidecar JSON-RPC 协议 |
|
||||
| `uiApi` | 主题可依赖的界面契约:令牌、部件、状态属性、槽位目录、图层、布局选项、图标名、UI SDK |
|
||||
| `bridgeApi` | 视图与面板的消息协议(§5.6) |
|
||||
|
||||
- **契约先于生态定全**:扩展点、槽位目录、视图位置与 bridge 方法在第三方插件依赖它们之前一次定全。目前生态只有语言包(只依赖 `pluginApi`),`uiApi` 与 `bridgeApi` 在首个第三方主题或界面插件出现前定稿为 `uiApi` 2.0 与 `bridgeApi` 1.0,定稿前可做不兼容清理。
|
||||
- **公开即实现**:每个公开的扩展点、槽位、视图位置、图层与 bridge 方法在发布前都要有宿主实现和契约测试。前端构建检查每个槽位、视图位置与图层都被渲染;Go 测试检查每个扩展点都有消费者。尚未落地的项在清单 Schema 中标 `x-experimental`:`plugin doctor` 警告,不受兼容承诺约束,市场不允许稳定版插件依赖它。
|
||||
- **主版本内只增不改**:新增字段一律可选,缺省时保持旧行为;新增枚举值(事件、视图位置、bridge 方法)只投递给声明了相应次版本的插件。改名、删除或改变语义只在主版本发生。
|
||||
- **按特性协商,不按版本号猜**:宿主在 Sidecar 握手、bridge 握手与 UI SDK 中下发 `features` 列表(如 `view.sidebar`、`bridge.file.pick`、`layer.overlay`),插件据此降级。
|
||||
- **未知字段**:宿主忽略清单中的未知字段并由 `plugin doctor` 警告,插件因此可以使用新字段同时兼容旧宿主;`engines` 下限高于宿主版本时拒绝安装与激活。
|
||||
- **命名空间**:`builtin.*` 插件 id、`rg-` 前缀的类名、`data-rg-` 属性与契约令牌归宿主;插件自有 CSS 变量使用 `--x-<插件短名>-` 前缀;命令 id 由宿主自动加上插件 id 前缀。
|
||||
- **弃用**:先在至少一个次版本中给出 `plugin doctor` 警告与替代项,下一个主版本再删除;契约文件(`ui-contract.json`、bridge 类型定义)随版本发布,作者可在本地校验。
|
||||
|
||||
---
|
||||
|
||||
## 7. 权限、信任与安全边界
|
||||
@@ -325,7 +392,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| 等级 | 权限 | 审批 |
|
||||
| :--- | :--- | :--- |
|
||||
| **低** | `vm:read`(通用模型,不含敏感字段)、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示说明 |
|
||||
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则) | 首次启用逐项确认 |
|
||||
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则)、`fs:pick`(经宿主文件对话框读写用户选中的文件) | 首次启用逐项确认 |
|
||||
| **高** | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 强提示(展示可执行文件或脚本路径、SHA-256、发布者、许可证)并显式勾选;升级新增高危权限时暂停并要求重新批准 |
|
||||
| **不存在** | 敏感字段读取、UAC 提权、重启 Windows、直写 `vm.toml` | 插件只能请求宿主发起人工确认流程 |
|
||||
|
||||
@@ -339,7 +406,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
### 7.3 UI 与本地接口安全
|
||||
|
||||
- 插件资源经 Wails AssetServer 的独立路由提供,路径带每次运行随机生成的令牌,校验目录穿越,附 `X-Content-Type-Options: nosniff` 与 CSP;SVG 一律禁脚本。
|
||||
- iframe 面板(后置):`sandbox="allow-scripts"`、`connect-src 'none'`;bridge 只应答来源窗口为自身 iframe 的消息,所有读取在 Go 侧按 `permissions` 二次校验并限流;主题令牌经 bridge 下发。
|
||||
- iframe 视图与面板:`sandbox="allow-scripts"`(不加 `allow-same-origin`、`allow-popups`、`allow-top-navigation`)、`connect-src 'none'`;bridge 只应答来源窗口为自身 iframe 的消息,所有读写在 Go 侧按 `permissions` 二次校验并限流;文件只以句柄交换,网络只经宿主代理;主题令牌经 bridge 下发。
|
||||
- 宿主本地 HTTP 接口(如 Guest Tools)拒绝 `Origin: null`、跨站请求与 `Sec-Fetch-Dest: iframe` 请求,防止被沙箱 iframe 或外部网页借道调用。
|
||||
|
||||
---
|
||||
@@ -392,7 +459,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| 入口 | 内容 |
|
||||
| :--- | :--- |
|
||||
| CLI | `reims-go plugin list / search / install <zip\|id> / update [id] / pack <dir> / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale <init\|check> / run <id> <command>`;`vm create --driver <id>` |
|
||||
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
|
||||
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):系统插件(核心)不列出;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
|
||||
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
|
||||
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
|
||||
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
|
||||
@@ -420,6 +487,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
## 12. 分阶段演进与验收标准
|
||||
|
||||
从现有代码走到这里所述的客体驱动形态、并将 macOS 外置为插件的具体路径,见 [guest-plugin-migration.md](guest-plugin-migration.md)。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
P0["Phase 0\n内部抽象\n(不对外)"] --> P1["Phase 1\n插件底座 + L1\n(主题/模板/运行时源/规则 Hook)"]
|
||||
@@ -436,7 +505,7 @@ flowchart LR
|
||||
| **Phase 2** | 运行时种类注册表、`runtime_api` 与 `capabilities`、来源展示 | 第二种运行时与官方运行时并存切换;不兼容组合被拦截并给出提示 |
|
||||
| **Phase 3** | JSON-RPC 协议 v1、进程监管、反向 Host API、权限审批、代码 Hook、插件命令、排障采集、轻量 Go SDK | 死循环或崩溃的示例 Sidecar 不影响主窗口与运行中 VM;退出或禁用后无孤儿进程 |
|
||||
| **Phase 4** | 独立仓库的官方 Linux 驱动 | 不修改主程序源码,经 GUI 与 CLI 完成 Linux VM 创建、WHPX 启动、绑核、截屏、SSH 与快照;真机验证 |
|
||||
| **Phase 5** | 签名体系与市场索引、iframe 面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 第三方插件经审核上架;iframe 面板无法越权读取或联网;参照 dsh-claude-style 的功能清单逐项确认可由三档主题能力承载或列出缺口 |
|
||||
| **Phase 5** | 签名体系与市场索引、`uiApi` 2.0 与 `bridgeApi` 1.0 定稿(§5.1、§5.6、§6.3)、iframe 视图与面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 契约检查覆盖全部槽位、视图位置、图层与 bridge 方法,无「可声明但不渲染」项;第三方插件经审核上架;iframe 视图无法越权读取、联网或拿到文件路径;参照 dsh-claude-style 的功能清单逐项确认可由三档主题能力承载或列出缺口 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# PR 变更归属审查
|
||||
|
||||
> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。
|
||||
|
||||
## 1. 确认归属
|
||||
|
||||
以 PR 实际目标分支与提交的差异为准。使用 GitHub 的「Files changed」或本地 `git diff <base>...<head>`,同时检查生成文件对应的源文件、补丁目标、依赖锁定和 CI 变更。先从用户入口沿调用链找到行为的实现,再按下表归属。
|
||||
|
||||
| 类别 | 行为或改动 | 实现归属 |
|
||||
| :--- | :--- | :--- |
|
||||
| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 |
|
||||
| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 |
|
||||
| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 |
|
||||
| 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)。按运行时锁定的提交定位。 |
|
||||
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
|
||||
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时规范](portable-runtime-spec.md)。 |
|
||||
|
||||
同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。
|
||||
|
||||
## 2. 审查客户端独立性
|
||||
|
||||
- **构建与发布**:客户端 CI 仅从 `Reims-Go` 源码检出完成前端构建、Go 检查和应用产物构建。运行时源码、编译工具链和运行时发布产物由运行时仓库管理。客户端自行发布应用,并在虚拟机运行前下载、校验或导入兼容的独立运行时。
|
||||
- **接口边界**:客户端通过约定的子进程接口和协议调用运行时。配置写入沿用 [`reims-ctl set`](design-guidelines.md#2-配置原语)。需要新增命令、参数、字段或能力时,在负责组件实现,并在客户端附上对应接口证据。
|
||||
- **运行时兼容**:客户端 PR 写明验证使用的运行时与最低要求。若依赖新能力,优先使用运行时明确声明的能力或版本,在旧版、缺失运行时和不支持该能力的场景下明确禁用、提示或保留既有流程。客户端合入与运行时发布各自按其流程验收,用户默认仍走受支持的 `stable` 通道。
|
||||
- **跨仓交付**:按归属拆分 PR。客户端 PR 链接底层 PR、提交或运行时版本,列出合并顺序和兼容路径。临时依赖补丁由运行时仓库记录,注明目标仓库、适用提交和退役条件。跨仓定位以源码、依赖锁定和产物清单为证据。
|
||||
|
||||
## 3. PR 描述与合并检查
|
||||
|
||||
提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。
|
||||
|
||||
```markdown
|
||||
## 变更归属
|
||||
|
||||
- 用户可见行为
|
||||
- 变更位置与责任仓库
|
||||
- 上游证据(仓库、commit、文件及行号)
|
||||
- 跨仓依赖(关联 PR、合并顺序、运行时要求)
|
||||
- 旧版或缺失运行时的表现
|
||||
|
||||
## 验证
|
||||
|
||||
- 已通过的检查及运行时版本
|
||||
- 待验证场景及其影响
|
||||
```
|
||||
|
||||
审查者在合并前核对以下各项。
|
||||
|
||||
- [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。
|
||||
- [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。
|
||||
- [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](portable-runtime-spec.md#5-发布通道alpha--stable)。
|
||||
- [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test scripts/test-i18n.mjs",
|
||||
"test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs",
|
||||
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
||||
@@ -1 +1 @@
|
||||
58f4fafea894c5f7c1c6ebefde51e110
|
||||
963b18fba33337becedb9d93549f159f
|
||||
@@ -141,6 +141,86 @@ test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and t
|
||||
}
|
||||
})
|
||||
|
||||
test('Static Guard (CRITICAL-3): Radix Presence .menu/.tooltip animations never replay on close', () => {
|
||||
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||||
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
const titleMenus = fs.readFileSync(path.join(srcDir, 'components', 'TitleMenus.tsx'), 'utf8')
|
||||
|
||||
// Unconditional `.menu` / `.tooltip` animation (including animation-name inside
|
||||
// comma-separated selector lists or reduced-motion media queries) causes Radix
|
||||
// Presence to detect an animationName change on close and flash for 160ms.
|
||||
for (const m of css.matchAll(/([^{}@]+)\{([^{}]+)\}/g)) {
|
||||
const selectors = m[1].split(',').map((s) => s.trim()).filter(Boolean)
|
||||
const decls = m[2]
|
||||
if (!/\banimation(?:-name)?\s*:(?!\s*none\b)/.test(decls)) continue
|
||||
for (const sel of selectors) {
|
||||
assert.doesNotMatch(
|
||||
sel,
|
||||
/\.menu(?![a-zA-Z0-9_-])(?!\[data-state="open"\])/,
|
||||
`Non-open .menu selector "${sel}" must not apply an active animation`,
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
sel,
|
||||
/\.tooltip(?![a-zA-Z0-9_-])(?!\[data-state="delayed-open"\])/,
|
||||
`Non-delayed-open .tooltip selector "${sel}" must not apply an active animation`,
|
||||
)
|
||||
}
|
||||
}
|
||||
assert.match(
|
||||
css,
|
||||
/\.menu\[data-state="open"\]\s*\{[^}]*animation\s*:/,
|
||||
'.menu[data-state="open"] must define the menu enter animation',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.menu\[data-state="open"\]\[data-menubar-switch="true"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||||
'.menu[data-state="open"][data-menubar-switch="true"] must disable enter animation',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.menu\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||||
'.menu[data-state="closed"] must explicitly disable animation so Radix Presence unmounts immediately',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.tooltip\[data-state="closed"\][^\{]*\{[^}]*animation\s*:\s*none/,
|
||||
'.tooltip[data-state="closed"] must explicitly disable animation',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/@media\s*\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)\s*\{[\s\S]*?\.toast\[data-state="closed"\][^{]*\{[^}]*animation-name\s*:\s*fade-out/,
|
||||
'Reduced-motion .toast[data-state="closed"] must use fade-out',
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
titleMenus,
|
||||
/data-menubar-switch=\{\s*menuState\.id\s*===\s*id\s*&&\s*menuState\.switched/,
|
||||
'TitleMenus must not strip data-menubar-switch from the outgoing sibling menu on switch',
|
||||
)
|
||||
})
|
||||
|
||||
test('Static Guard (CRITICAL-4): software-composited UI avoids backdrop-filter and slow pre shaping', () => {
|
||||
const rawCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||||
const css = rawCss.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
|
||||
// main.go sets WebviewGpuIsDisabled: true (software compositing), where
|
||||
// backdrop-filter blurs stall CPU rasterization on animations and scrolling.
|
||||
assert.doesNotMatch(
|
||||
css,
|
||||
/(?:-webkit-)?backdrop-filter\s*:/i,
|
||||
'app.css must not apply backdrop-filter under software compositing',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.license-pre\s*\{[^}]*contain\s*:\s*content/,
|
||||
'.license-pre should isolate scroll/layout repaints with contain: content',
|
||||
)
|
||||
assert.match(
|
||||
css,
|
||||
/\.license-pre\s*\{[^}]*text-rendering\s*:\s*auto/,
|
||||
'.license-pre should opt out of global optimizeLegibility for long monospace texts',
|
||||
)
|
||||
})
|
||||
|
||||
test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => {
|
||||
const mod = await loadBundledTS(`
|
||||
import './i18n/domains/wizard.gen'
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// macOS UI lives under src/macos so it can leave the app as a plugin. Host
|
||||
// files may import from it only while listed below; the test fails when a new
|
||||
// file starts importing it and when a listed file stops, so the list only
|
||||
// shrinks (same ratchet as internal/archtest on the Go side).
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
|
||||
const srcDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src')
|
||||
const macosDir = path.join(srcDir, 'macos')
|
||||
|
||||
const MACOS_IMPORTERS = {
|
||||
'App.tsx': 'mounts the installers page and online-recovery dialog; macOS release names in the VM list',
|
||||
'components/Sidebar.tsx': 'macOS version art next to each VM',
|
||||
'components/VMPage.tsx': 'macOS version art in the VM header',
|
||||
}
|
||||
|
||||
function walk(dir) {
|
||||
const out = []
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name)
|
||||
if (e.isDirectory()) {
|
||||
if (p !== macosDir) out.push(...walk(p))
|
||||
} else if (/\.(?:[cm]?[jt]s|[jt]sx)$/.test(e.name)) {
|
||||
out.push(p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('host frontend reaches src/macos only from listed files', () => {
|
||||
const importers = new Set()
|
||||
for (const file of walk(srcDir)) {
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
|
||||
let target
|
||||
if (fileName.startsWith('.')) target = path.resolve(path.dirname(file), fileName)
|
||||
else if (fileName.startsWith('/src/')) target = path.resolve(srcDir, fileName.slice(5))
|
||||
else continue
|
||||
if (target === macosDir || target.startsWith(macosDir + path.sep)) {
|
||||
importers.add(path.relative(srcDir, file).split(path.sep).join('/'))
|
||||
}
|
||||
}
|
||||
}
|
||||
const unexpected = [...importers].filter((f) => !(f in MACOS_IMPORTERS)).sort()
|
||||
const stale = Object.keys(MACOS_IMPORTERS).filter((f) => !importers.has(f)).sort()
|
||||
assert.deepEqual(unexpected, [], `host files import src/macos without being listed in MACOS_IMPORTERS: ${unexpected.join(', ')}`)
|
||||
assert.deepEqual(stale, [], `listed files no longer import src/macos; remove them from MACOS_IMPORTERS: ${stale.join(', ')}`)
|
||||
})
|
||||
+107
-70
@@ -3,21 +3,23 @@ import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from
|
||||
import type { WizardDraft } from './components/CreateWizard'
|
||||
import { DeleteDialog } from './components/DeleteDialog'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
|
||||
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import type { ThemeMode } from './components/AppSettingsPage'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } 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'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
import { macOSMajor } from './lib/macosRelease'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
import { ConfirmDialog, Modal } from './ui/dialog'
|
||||
@@ -32,7 +34,7 @@ const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) =
|
||||
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
|
||||
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
|
||||
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
|
||||
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
|
||||
const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage })))
|
||||
const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage })))
|
||||
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
|
||||
@@ -85,11 +87,11 @@ export const App: React.FC = () => {
|
||||
const [showWizard, setShowWizard] = useState(false)
|
||||
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
|
||||
const [affinityTarget, setAffinityTarget] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [affinityVersion, setAffinityVersion] = useState(0)
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
@@ -197,8 +199,8 @@ export const App: React.FC = () => {
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
if (PAGE_IDS.includes(cur)) return cur
|
||||
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
|
||||
if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID
|
||||
})
|
||||
if (reloadDetail) setDetailRevision((revision) => revision + 1)
|
||||
} catch (e) {
|
||||
@@ -267,15 +269,15 @@ export const App: React.FC = () => {
|
||||
}, [refresh])
|
||||
|
||||
const vms = state?.vms ?? []
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[vmRefKey(v)] ?? v.state) === 'running').length
|
||||
const selectedVM = !PAGE_IDS.includes(selected)
|
||||
? vms.find((v) => v.name === selected)
|
||||
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setDetail(null); return }
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision])
|
||||
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, state?.transitions[selectedVM ? vmRefKey(selectedVM) : ''], detailRevision])
|
||||
|
||||
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
|
||||
// name in the sidebar and page title; the name itself stays the identifier.
|
||||
@@ -332,8 +334,8 @@ export const App: React.FC = () => {
|
||||
|
||||
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
|
||||
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
|
||||
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
|
||||
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
|
||||
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
||||
const canSuspend = state?.can_suspend ?? false
|
||||
|
||||
@@ -451,6 +453,9 @@ export const App: React.FC = () => {
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || 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
|
||||
|
||||
// UI Contract v1 read-only document state attributes (§5.1).
|
||||
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
|
||||
@@ -468,7 +473,7 @@ export const App: React.FC = () => {
|
||||
hasError: hasAnyError,
|
||||
sidebarCollapsed: !sidebarOpen,
|
||||
safeMode: !!state?.safe_mode,
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[vmRefKey(v)] ?? v.state })),
|
||||
})
|
||||
uiStateRef.current = {
|
||||
appearance: theme,
|
||||
@@ -482,7 +487,7 @@ export const App: React.FC = () => {
|
||||
hasError: hasAnyError,
|
||||
sidebarCollapsed: !sidebarOpen,
|
||||
safeMode: !!state?.safe_mode,
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
|
||||
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[vmRefKey(v)] ?? v.state })),
|
||||
}
|
||||
useEffect(() => {
|
||||
const el = document.documentElement
|
||||
@@ -529,7 +534,8 @@ export const App: React.FC = () => {
|
||||
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
|
||||
if (!name) return
|
||||
try {
|
||||
const text = await api.ReadVMLogs(name, serial)
|
||||
const logDriverID = vms.find((v) => v.name === name)?.driver_id ?? ''
|
||||
const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial)
|
||||
if (serial) setSerialLog(text)
|
||||
else setQemuLog(text)
|
||||
} catch (e) {
|
||||
@@ -661,6 +667,9 @@ export const App: React.FC = () => {
|
||||
}
|
||||
|
||||
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
|
||||
const actionVM = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
const actionDriverID = actionVM?.driver_id ?? ''
|
||||
name = actionVM?.name ?? name
|
||||
if (!canSuspend && (action === 'suspend' || action === 'resume')) return
|
||||
const activeBusy = activeVMBusy(name)
|
||||
if (
|
||||
@@ -672,21 +681,21 @@ export const App: React.FC = () => {
|
||||
return
|
||||
}
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(name, action, () => api.StartVM(name))
|
||||
case 'suspend': return runVMAction(name, action, () => api.SuspendVM(name), tr('toastSuspended', { name }))
|
||||
case 'resume': return runVMAction(name, action, () => api.ResumeVM(name), tr('toastResumed', { name }))
|
||||
case 'discardSuspend': return setDiscardSuspendTarget(name)
|
||||
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'start': return runVMAction(name, action, () => api.StartVMWithDriver(actionDriverID, name))
|
||||
case 'suspend': return runVMAction(name, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name }))
|
||||
case 'resume': return runVMAction(name, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name }))
|
||||
case 'discardSuspend': return setDiscardSuspendTarget(actionVM ? vmRefKey(actionVM) : name)
|
||||
case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'fullscreen':
|
||||
return runVMAction(name, action, async () => {
|
||||
const isFullscreen = await api.ToggleVMFullscreen(name)
|
||||
refreshVMStats(name, { window_fullscreen: isFullscreen })
|
||||
const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name)
|
||||
refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen })
|
||||
})
|
||||
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
|
||||
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
|
||||
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name))
|
||||
case 'eject': return runVMAction(name, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected'))
|
||||
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
||||
case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
|
||||
case 'attachInstaller': return attachInstaller(name, isRunning)
|
||||
@@ -697,29 +706,29 @@ export const App: React.FC = () => {
|
||||
case 'upgradeNVMe':
|
||||
return runVMAction(name, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
||||
case 'exportDiagnostics':
|
||||
return runVMAction(name, action, async () => { await api.ExportDiagnostics(name) }, tr('toastDiagExported'))
|
||||
return runVMAction(name, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported'))
|
||||
case 'cloneVM':
|
||||
return setCloneSource(name)
|
||||
return setCloneSource({ name, driverID: actionDriverID })
|
||||
case 'type': return typeInto(name, () => api.TypeClipboard(name))
|
||||
case 'sendText': return setSendTextTarget(name)
|
||||
case 'openFolder':
|
||||
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
case 'delete': return setDeleteTarget(name)
|
||||
case 'delete': return setDeleteTarget(actionVM ? vmRefKey(actionVM) : name)
|
||||
}
|
||||
}
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
|
||||
return onVMActionFor(vmRefKey(selectedVM), action, selectedVM.state === 'running')
|
||||
}
|
||||
|
||||
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
|
||||
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
|
||||
if (action === 'settings') {
|
||||
if (st === 'suspended' || st === 'suspending' || st === 'resuming') return
|
||||
setSelected(name)
|
||||
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
api.GetVMDetail(vm?.name ?? name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
return
|
||||
}
|
||||
onVMActionFor(name, action, st === 'running')
|
||||
@@ -728,24 +737,31 @@ export const App: React.FC = () => {
|
||||
// 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.
|
||||
const primaryAction = (name: string) => {
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
if (!vm || activeVMBusy(name)) return
|
||||
const st = state?.transitions[name] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(name, 'start', false)
|
||||
else if (st === 'suspended') onVMActionFor(name, 'resume', false)
|
||||
else if (st === 'running') onVMActionFor(name, 'focus', true)
|
||||
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
if (!vm || activeVMBusy(vm.name)) return
|
||||
const key = vmRefKey(vm)
|
||||
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)
|
||||
}
|
||||
|
||||
const confirmDelete = (keepFiles: boolean) => {
|
||||
const name = deleteTarget
|
||||
const target = deleteTarget
|
||||
setDeleteTarget(null)
|
||||
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
|
||||
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
|
||||
const name = targetVM?.name ?? target
|
||||
const driverID = targetVM?.driver_id ?? ''
|
||||
if (name) runVMAction(name, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name }))
|
||||
}
|
||||
|
||||
const confirmDiscardSuspend = () => {
|
||||
const name = discardSuspendTarget
|
||||
const target = discardSuspendTarget
|
||||
setDiscardSuspendTarget(null)
|
||||
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspend(name), tr('toastDiscardSuspend', { name }))
|
||||
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
|
||||
const name = targetVM?.name ?? target
|
||||
const driverID = targetVM?.driver_id ?? ''
|
||||
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name }))
|
||||
}
|
||||
|
||||
const confirmOnlineRecovery = () => {
|
||||
@@ -761,9 +777,9 @@ export const App: React.FC = () => {
|
||||
const src = cloneSource
|
||||
setCloneSource(null)
|
||||
if (!src) return
|
||||
runVMAction(src, 'cloneVM', async () => {
|
||||
await api.CloneVMCoW(src, cloneName)
|
||||
setSelected(cloneName)
|
||||
runVMAction(src.name, 'cloneVM', async () => {
|
||||
await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName)
|
||||
setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID }))
|
||||
}, tr('toastCloned', { name: cloneName }))
|
||||
}
|
||||
|
||||
@@ -891,7 +907,7 @@ export const App: React.FC = () => {
|
||||
|
||||
// Global shortcuts (docs/design-guidelines.md §6). Dialogs own the keyboard while open.
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
const appDialogOpen = showSetup || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
@@ -902,7 +918,7 @@ export const App: React.FC = () => {
|
||||
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
|
||||
else if (k === 'l') { e.preventDefault(); toggleLogs() }
|
||||
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(vmRefKey(selectedVM)) }
|
||||
}
|
||||
useEffect(() => {
|
||||
const h = (e: KeyboardEvent) => shortcutRef.current(e)
|
||||
@@ -969,7 +985,7 @@ export const App: React.FC = () => {
|
||||
<TooltipProvider>
|
||||
<div className="app-shell rg-p-shell">
|
||||
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
{showSetup || !state ? (
|
||||
{showSetup || showReadOnly || !state ? (
|
||||
<div className="brand rg-p-brand">
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
Reims-Go
|
||||
@@ -987,6 +1003,7 @@ export const App: React.FC = () => {
|
||||
onThemeMode={setThemeMode}
|
||||
vm={selectedVM ? {
|
||||
name: selectedVM.name,
|
||||
driver_id: selectedVM.driver_id,
|
||||
state: effectiveState,
|
||||
busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name),
|
||||
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
||||
@@ -1050,6 +1067,14 @@ export const App: React.FC = () => {
|
||||
onImportRuntime={importRuntime}
|
||||
/>
|
||||
</Suspense>
|
||||
) : showReadOnly && state ? (
|
||||
<DataRootReadOnly
|
||||
locale={locale}
|
||||
status={state.data_root_status}
|
||||
message={state.data_root_message ?? ''}
|
||||
onChanged={() => { void refresh() }}
|
||||
onError={fail}
|
||||
/>
|
||||
) : (
|
||||
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
|
||||
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
|
||||
@@ -1061,7 +1086,12 @@ export const App: React.FC = () => {
|
||||
selected={selected}
|
||||
hostReady={hostReady}
|
||||
canSuspend={canSuspend}
|
||||
onSelect={setSelected}
|
||||
onSelect={(id) => {
|
||||
setSelected(id)
|
||||
if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) {
|
||||
toggleSidebar()
|
||||
}
|
||||
}}
|
||||
displayNames={displayNames}
|
||||
macosMajors={macosMajors}
|
||||
onActivate={primaryAction}
|
||||
@@ -1115,6 +1145,7 @@ export const App: React.FC = () => {
|
||||
<VMPage
|
||||
locale={locale}
|
||||
name={selectedVM.name}
|
||||
driverID={selectedVM.driver_id ?? ''}
|
||||
displayName={displayNames[selectedVM.name] ?? ''}
|
||||
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
|
||||
macosMajor={macosMajors[selectedVM.name] ?? null}
|
||||
@@ -1128,7 +1159,7 @@ export const App: React.FC = () => {
|
||||
busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined}
|
||||
onAction={onVMAction}
|
||||
onSettings={() => setShowSettings(true)}
|
||||
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
|
||||
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
|
||||
onDelete={() => setDeleteTarget(selectedVM.name)}
|
||||
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
||||
onCopy={copy}
|
||||
@@ -1255,13 +1286,14 @@ export const App: React.FC = () => {
|
||||
<SettingsModal
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
stats={latestVMStats(detail.name)}
|
||||
driverID={selectedVM?.driver_id ?? ''}
|
||||
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
|
||||
host={state.host}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onCopy={copy}
|
||||
onDiskChanged={refresh}
|
||||
onOpenAffinity={() => setAffinityTarget(detail.name)}
|
||||
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
|
||||
affinityVersion={affinityVersion}
|
||||
onHostChanged={refresh}
|
||||
onClose={() => setShowSettings(false)}
|
||||
@@ -1278,8 +1310,9 @@ export const App: React.FC = () => {
|
||||
<Suspense fallback={null}>
|
||||
<AffinityDialog
|
||||
locale={locale}
|
||||
vmName={affinityTarget}
|
||||
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
|
||||
vmName={affinityTarget.name}
|
||||
driverID={affinityTarget.driverID}
|
||||
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4}
|
||||
host={state.host}
|
||||
globalAutoPin={state.config.auto_pin_pcores}
|
||||
onClose={() => setAffinityTarget(null)}
|
||||
@@ -1324,22 +1357,26 @@ export const App: React.FC = () => {
|
||||
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
{discardSuspendTarget && (
|
||||
<ConfirmDialog
|
||||
title={tr('discardSuspendTitle', { name: displayNames[discardSuspendTarget] || discardSuspendTarget })}
|
||||
description={tr('discardSuspendDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('discardSuspendConfirm')}
|
||||
onCancel={() => setDiscardSuspendTarget(null)}
|
||||
onConfirm={confirmDiscardSuspend}
|
||||
/>
|
||||
)}
|
||||
{discardSuspendTarget && (() => {
|
||||
const targetVM = vms.find((v) => vmRefKey(v) === discardSuspendTarget) ?? vms.find((v) => v.name === discardSuspendTarget)
|
||||
const targetName = targetVM?.name ?? discardSuspendTarget
|
||||
return (
|
||||
<ConfirmDialog
|
||||
title={tr('discardSuspendTitle', { name: displayNames[targetName] || targetName })}
|
||||
description={tr('discardSuspendDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('discardSuspendConfirm')}
|
||||
onCancel={() => setDiscardSuspendTarget(null)}
|
||||
onConfirm={confirmDiscardSuspend}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{cloneSource && (
|
||||
<CloneDialog
|
||||
locale={locale}
|
||||
sourceName={cloneSource}
|
||||
defaultCloneName={`${cloneSource}-clone`}
|
||||
sourceName={cloneSource.name}
|
||||
defaultCloneName={`${cloneSource.name}-clone`}
|
||||
onCancel={() => setCloneSource(null)}
|
||||
onConfirm={confirmClone}
|
||||
/>
|
||||
@@ -1358,7 +1395,7 @@ export const App: React.FC = () => {
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendTextTarget}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
guestToolsConnected={Boolean(latestVMStatsWithDriver(selectedVM?.driver_id ?? '', sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
onCancel={() => setSendTextTarget(null)}
|
||||
onConfirm={(text) => {
|
||||
const target = sendTextTarget
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Copy, Download, ExternalLink, RotateCw, Scale } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
@@ -11,6 +11,7 @@ import { api } from '../wails'
|
||||
import { REPO_URL } from './TitleMenus'
|
||||
import type { UpdatePhase } from './UpdateCapsule'
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
|
||||
export type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
@@ -34,7 +35,7 @@ interface Props {
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** About page: version and updates, project links and the community group. */
|
||||
/** About page: version and updates, project links and community channels. */
|
||||
export const AboutPage: React.FC<Props> = ({
|
||||
locale, appVersion, appUpdateChannel, onAppUpdateChannel, appUpdate, onAppUpdate, updatePhase, updateTask, installing,
|
||||
onDownloadUpdate, onCancelUpdate, onInstallUpdate, onCopy, onError,
|
||||
@@ -49,14 +50,34 @@ export const AboutPage: React.FC<Props> = ({
|
||||
const [licenseOpen, setLicenseOpen] = useState(false)
|
||||
const [licenseTab, setLicenseTab] = useState<'notice' | 'license'>('notice')
|
||||
const [licenses, setLicenses] = useState<{ license: string; notice: string } | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const loadingLicensesRef = useRef(false)
|
||||
const licensePreRef = useRef<HTMLPreElement>(null)
|
||||
|
||||
const openLicenses = () => {
|
||||
setLicenseOpen(true)
|
||||
if (!licenses) {
|
||||
api.GetLicenseTexts()
|
||||
.then((res) => setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' }))
|
||||
.catch((e) => onError(tr('failGeneric'), e))
|
||||
const openLicenses = async () => {
|
||||
if (licenses) {
|
||||
setLicenseOpen(true)
|
||||
return
|
||||
}
|
||||
if (loadingLicensesRef.current) return
|
||||
loadingLicensesRef.current = true
|
||||
try {
|
||||
// Load embedded license text before mounting the modal so the dialog opens
|
||||
// with its final content on frame 1 instead of reflowing mid-animation.
|
||||
const res = await api.GetLicenseTexts()
|
||||
if (!mountedRef.current) return
|
||||
setLicenses({ license: res?.license ?? '', notice: res?.notice ?? '' })
|
||||
setLicenseOpen(true)
|
||||
} catch (e) {
|
||||
if (mountedRef.current) onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
loadingLicensesRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleLicenseTabChange = (next: 'notice' | 'license') => {
|
||||
setLicenseTab(next)
|
||||
if (licensePreRef.current) licensePreRef.current.scrollTop = 0
|
||||
}
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
@@ -72,12 +93,16 @@ export const AboutPage: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
if (!appUpdate) void runUpdateCheck(false)
|
||||
let cancelled = false
|
||||
api.CanOpenQQGroup()
|
||||
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
|
||||
.catch(() => { if (!cancelled) setQQInstalled(false) })
|
||||
return () => { cancelled = true }
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const openURL = (url: string) => {
|
||||
@@ -244,7 +269,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-sub">{tr('aboutLicensesSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={openLicenses}>
|
||||
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={() => void openLicenses()}>
|
||||
{tr('aboutLicensesView')}
|
||||
</Button>
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(`${REPO_URL}/blob/main/NOTICE.md`)}>
|
||||
@@ -252,6 +277,25 @@ export const AboutPage: React.FC<Props> = ({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('aboutDiscord')}</div>
|
||||
<div className="row-sub">{tr('aboutDiscordSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('aboutCopyDiscord')}
|
||||
icon={<Copy size={14} aria-hidden="true" />}
|
||||
onClick={() => onCopy(DISCORD_INVITE_URL)}
|
||||
/>
|
||||
)}
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(DISCORD_INVITE_URL)}>
|
||||
{tr('aboutJoinDiscord')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
@@ -303,16 +347,23 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<Segmented
|
||||
label={tr('aboutLicensesTitle')}
|
||||
value={licenseTab}
|
||||
onChange={setLicenseTab}
|
||||
onChange={handleLicenseTabChange}
|
||||
options={[
|
||||
{ value: 'notice', label: tr('aboutLicensesTabNotice') },
|
||||
{ value: 'license', label: tr('aboutLicensesTabLicense') },
|
||||
]}
|
||||
/>
|
||||
<pre className="license-pre">
|
||||
<pre
|
||||
ref={licensePreRef}
|
||||
className="license-pre"
|
||||
dir="ltr"
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label={licenseTab === 'notice' ? tr('aboutLicensesTabNotice') : tr('aboutLicensesTabLicense')}
|
||||
>
|
||||
{licenses
|
||||
? (licenseTab === 'notice' ? licenses.notice : licenses.license)
|
||||
: '…'}
|
||||
: ''}
|
||||
</pre>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
|
||||
@@ -11,6 +11,7 @@ import { api } from '../wails'
|
||||
interface Props {
|
||||
locale: Locale
|
||||
vmName: string
|
||||
driverID: string
|
||||
vcpus: number
|
||||
host: HostReport
|
||||
globalAutoPin: boolean
|
||||
@@ -79,7 +80,7 @@ export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus |
|
||||
}
|
||||
|
||||
export const AffinityDialog: React.FC<Props> = ({
|
||||
locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied,
|
||||
locale, vmName, driverID, vcpus, host, globalAutoPin, onClose, onApplied,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const topology = useMemo(() => buildTopology(host), [host])
|
||||
@@ -99,7 +100,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
let live = true
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api.GetVMAffinity(vmName)
|
||||
api.GetVMAffinityWithDriver(driverID, vmName)
|
||||
.then((st) => {
|
||||
if (!live) return
|
||||
setStatus(st)
|
||||
@@ -205,7 +206,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
setSaving(true)
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api.SetVMAffinity(vmName, {
|
||||
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
|
||||
mode,
|
||||
cpus: mode === 'custom' ? selected : [],
|
||||
disable_eco_qos: disableEcoQoS,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from 'react'
|
||||
import { PowerOff } from 'lucide-react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { getLocaleOptions, I18nKey, t } from '../i18n'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
@@ -27,9 +28,13 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { host, config, optimizations } = state
|
||||
const quitMode = state.quit_mode
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const missingFontScript = state.missing_font_hint || ''
|
||||
const memSpecLabel = host.memory_spec?.speed_mhz
|
||||
? `${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
|
||||
: ''
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
@@ -45,6 +50,14 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const forceQuit = async () => {
|
||||
try {
|
||||
await api.ForceQuitApp()
|
||||
} catch (e) {
|
||||
onError(tr('quitFailed'), e)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page rg-p-settings">
|
||||
<header className="page-head">
|
||||
@@ -84,6 +97,24 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('syncHostMemorySMBIOS')}</div>
|
||||
<div className="row-sub">
|
||||
{memSpecLabel
|
||||
? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel })
|
||||
: tr('syncHostMemorySMBIOSUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('syncHostMemorySMBIOS')}
|
||||
disabled={!memSpecLabel}
|
||||
checked={!!memSpecLabel && !!config.sync_host_memory_smbios}
|
||||
onChange={(checked) => guard(() => api.SetSyncHostMemorySMBIOS(checked))()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('minimizeToTray')}</div>
|
||||
@@ -97,6 +128,17 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('forceQuitAppTitle')}</div>
|
||||
<div className="row-sub">{tr('forceQuitAppSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button variant="danger" onClick={forceQuit} busy={quitMode === 'force'} icon={<PowerOff size={14} aria-hidden="true" />}>
|
||||
{tr(quitMode === 'force' ? 'forceQuitInProgress' : 'forceQuitAppButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ interface Props {
|
||||
|
||||
const REVIEW_STEP = 5
|
||||
|
||||
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
|
||||
// Which wizard step owns each ValidationIssue.field (internal/macos/reims/reims.go ValidateCreate).
|
||||
const STEP_OF_FIELD: Record<string, number> = {
|
||||
installer: 1, disk: 1, macos: 1, guest_lang: 1,
|
||||
cpus: 2, memory: 2,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { FolderOpen } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
status: AppState['data_root_status']
|
||||
/** Localized reason from the backend (dataroot.Error). */
|
||||
message: string
|
||||
/** The folder changed or reopened; the app reloads its state. */
|
||||
onChanged: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown instead of the workspace while the data folder is open read-only
|
||||
* (written by a newer release, damaged version record, failed or concurrent
|
||||
* upgrade). Nothing in the folder has been changed; the user can repair it,
|
||||
* try again, or pick another folder.
|
||||
*/
|
||||
export const DataRootReadOnly: React.FC<Props> = ({ locale, status, message, onChanged, onError }) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const [busy, setBusy] = useState<'' | 'repair' | 'retry' | 'choose'>('')
|
||||
|
||||
const run = async (kind: 'repair' | 'retry' | 'choose', fn: () => Promise<unknown>) => {
|
||||
setBusy(kind)
|
||||
try {
|
||||
await fn()
|
||||
onChanged()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const choose = () => run('choose', async () => {
|
||||
const dir = await api.PickDirectory(tr('dataRootChooseTitle'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const canRepair = status.reason === 'damaged'
|
||||
const canRetry = status.reason === 'busy' || status.reason === 'migration_failed'
|
||||
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
<div className="setup-head">
|
||||
<h1>{tr('dataRootReadOnlyTitle')}</h1>
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('dataRootReadOnlyFolder')}</div>
|
||||
<div className="row-sub mono selectable">{status.dir}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{status.detail && (
|
||||
<details className="dataroot-detail">
|
||||
<summary>{tr('dataRootReadOnlyDetail')}</summary>
|
||||
<pre className="mono selectable">{status.detail}</pre>
|
||||
</details>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<span className="hstack">
|
||||
{canRepair && (
|
||||
<Button busy={busy === 'repair'} disabled={!!busy} onClick={() => void run('repair', () => api.ReopenDataRoot(true))}>
|
||||
{tr('dataRootRepair')}
|
||||
</Button>
|
||||
)}
|
||||
{canRetry && (
|
||||
<Button busy={busy === 'retry'} disabled={!!busy} onClick={() => void run('retry', () => api.ReopenDataRoot(false))}>
|
||||
{tr('dataRootRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
<Button variant="primary" icon={<FolderOpen size={14} aria-hidden="true" />} busy={busy === 'choose'} disabled={!!busy} onClick={() => void choose()}>
|
||||
{tr('dataRootChooseOther')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -135,7 +135,12 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
{tr('hostRAM')}
|
||||
</div>
|
||||
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
|
||||
<div className="tile-sub">{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}</div>
|
||||
<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 className="tile">
|
||||
<div className="tile-head">
|
||||
|
||||
@@ -103,6 +103,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
|
||||
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
|
||||
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
|
||||
const [disableTarget, setDisableTarget] = useState<PluginInfo | null>(null)
|
||||
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
|
||||
|
||||
// Static risk scan modal state (pre-install .zip preview or installed plugin scan)
|
||||
@@ -171,7 +172,12 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
|
||||
useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab])
|
||||
|
||||
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
|
||||
const togglePlugin = async (p: PluginInfo, enable: boolean, confirmed = false) => {
|
||||
// Disabling a plugin that still owns VMs leaves them "driver unavailable": say so first.
|
||||
if (!enable && p.in_use && !confirmed) {
|
||||
setDisableTarget(p)
|
||||
return
|
||||
}
|
||||
if (enable && p.needs_approval) {
|
||||
setApproveChecked(false)
|
||||
setApproveReport(null)
|
||||
@@ -365,11 +371,8 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q)
|
||||
}
|
||||
|
||||
// The always-on core goes first; the optional builtins keep backend order.
|
||||
const builtins = useMemo(
|
||||
() => plugins.filter((p) => p.source === 'builtin').sort((a, b) => Number(!!b.system) - Number(!!a.system)),
|
||||
[plugins],
|
||||
)
|
||||
// System plugins are part of the host and never listed; builtins keep backend order.
|
||||
const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [plugins])
|
||||
const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins])
|
||||
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
|
||||
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
|
||||
@@ -472,7 +475,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
) : (
|
||||
<Switch
|
||||
label={locText(p.name, locale, p.id)}
|
||||
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
|
||||
disabled={busyID === p.id || (!!safeMode && !isBuiltin)}
|
||||
checked={p.enabled}
|
||||
onChange={(checked) => void togglePlugin(p, checked)}
|
||||
/>
|
||||
@@ -922,6 +925,35 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{disableTarget && (
|
||||
<Modal
|
||||
title={tr('pluginDisableInUseTitle')}
|
||||
subtitle={locText(disableTarget.name, locale, disableTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setDisableTarget(null)}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
{tr('pluginDisableInUseBody')}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setDisableTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = disableTarget
|
||||
setDisableTarget(null)
|
||||
void togglePlugin(target, false, true)
|
||||
}}
|
||||
>
|
||||
{tr('pluginDisable')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{removeTarget && (
|
||||
<Modal
|
||||
title={tr('pluginRemove')}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
|
||||
import { CircleAlert, Copy, Cpu, Eye, EyeOff, HardDrive, Info, Keyboard, LucideIcon, Monitor, Shuffle, Wrench } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, parseAppError, t } from '../i18n'
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
|
||||
@@ -82,6 +82,13 @@ const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
|
||||
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
|
||||
const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase()
|
||||
|
||||
function maskIdentity(v: string | undefined, head = 4, tail = 4): string {
|
||||
const s = (v ?? '').trim()
|
||||
if (!s) return '—'
|
||||
if (s.length <= head + tail) return '•'.repeat(s.length)
|
||||
return `${s.slice(0, head)}••••${s.slice(-tail)}`
|
||||
}
|
||||
|
||||
/** Whether two values of a field mean the same thing to reims-ctl. */
|
||||
function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
|
||||
switch (field) {
|
||||
@@ -125,6 +132,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
|
||||
interface Props {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
driverID: string
|
||||
stats?: VMStats | null
|
||||
host: HostReport
|
||||
optimizations?: Optimization[]
|
||||
@@ -139,7 +147,7 @@ interface Props {
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => {
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const base = useMemo(() => baseline(detail, host), [detail, host])
|
||||
@@ -162,11 +170,20 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
|
||||
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
|
||||
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
|
||||
const vmSettingsKey = `${driverID}:${detail.name}`
|
||||
const [smbios, setSmbios] = useState<SMBIOSIdentity | null>(null)
|
||||
const [smbiosErr, setSmbiosErr] = useState('')
|
||||
const [smbiosReveal, setSmbiosReveal] = useState(false)
|
||||
const [smbiosOpen, setSmbiosOpen] = useState(false)
|
||||
const [smbiosDraft, setSmbiosDraft] = useState<SMBIOSIdentity | null>(null)
|
||||
const [smbiosBusy, setSmbiosBusy] = useState<'' | 'generate' | 'apply'>('')
|
||||
const [smbiosModalErr, setSmbiosModalErr] = useState('')
|
||||
const [smbiosApplied, setSmbiosApplied] = useState(false)
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(detail.name)])
|
||||
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmSettingsKey)])
|
||||
.then(([list, vals]) => {
|
||||
if (!live) return
|
||||
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
|
||||
@@ -175,11 +192,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
})
|
||||
.catch(() => {})
|
||||
return () => { live = false }
|
||||
}, [detail.name])
|
||||
}, [driverID, detail.name])
|
||||
|
||||
const updateVMPluginSetting = (pluginID: string, next: Record<string, unknown>) => {
|
||||
setVmPluginVals((prev) => ({ ...prev, [pluginID]: next }))
|
||||
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(parseAppError(e).summary))
|
||||
void api.SetPluginSettings(pluginID, vmSettingsKey, next).catch((e) => setErr(parseAppError(e).summary))
|
||||
}
|
||||
|
||||
const renderVMPluginGroup = (group: string) => {
|
||||
@@ -276,12 +293,76 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
api.GetVMAffinity(detail.name)
|
||||
api.GetVMAffinityWithDriver(driverID, detail.name)
|
||||
.then((st) => { if (active) setAffinityStatus(st) })
|
||||
.catch(() => {})
|
||||
return () => { active = false }
|
||||
}, [detail.name, running, affinityVersion])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setSmbios(null)
|
||||
setSmbiosErr('')
|
||||
setSmbiosReveal(false)
|
||||
setSmbiosApplied(false)
|
||||
if (!detail.has_opencore) return () => { active = false }
|
||||
api.GetVMSMBIOS(detail.name)
|
||||
.then((id) => { if (active) setSmbios(id) })
|
||||
.catch((e) => { if (active) setSmbiosErr(parseAppError(e).summary) })
|
||||
return () => { active = false }
|
||||
}, [detail.name, detail.has_opencore])
|
||||
|
||||
const smbiosLocked = running || detail.state === 'suspended' || !!detail.suspend_info
|
||||
|
||||
const handleGenerateSmbios = async (modelOverride?: string) => {
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosBusy('generate')
|
||||
try {
|
||||
const generated = await api.GenerateVMSMBIOS(modelOverride ?? smbios?.model ?? '')
|
||||
setSmbiosDraft({
|
||||
model: smbios?.model || generated.model,
|
||||
serial: generated.serial,
|
||||
mlb: generated.mlb,
|
||||
uuid: generated.uuid,
|
||||
rom: smbios?.rom || '',
|
||||
})
|
||||
} catch (e) {
|
||||
setSmbiosModalErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSmbiosBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const openSmbiosRotate = () => {
|
||||
if (smbiosLocked) return
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosApplied(false)
|
||||
setSmbiosOpen(true)
|
||||
void handleGenerateSmbios(smbios?.model ?? '')
|
||||
}
|
||||
|
||||
const handleApplySmbios = async () => {
|
||||
if (smbiosLocked || smbiosBusy || !smbiosDraft) return
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosBusy('apply')
|
||||
try {
|
||||
const updated = await api.ApplyVMSMBIOS(detail.name, {
|
||||
model: smbios?.model || smbiosDraft.model || '',
|
||||
serial: smbiosDraft.serial,
|
||||
mlb: smbiosDraft.mlb,
|
||||
uuid: smbiosDraft.uuid,
|
||||
rom: smbios?.rom || '',
|
||||
})
|
||||
setSmbios(updated)
|
||||
setSmbiosOpen(false)
|
||||
setSmbiosApplied(true)
|
||||
} catch (e) {
|
||||
setSmbiosModalErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSmbiosBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
|
||||
if (driveBusyRef.current || !driveSettings) return
|
||||
driveBusyRef.current = true
|
||||
@@ -387,13 +468,66 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
<SetGroup note={tr('platformReadonly')}>
|
||||
<SetGroup note={!detail.has_opencore ? tr('platformReadonly') : undefined}>
|
||||
<SetValue title={tr('vmName')} value={detail.name} />
|
||||
<SetValue title={tr('fieldKind')} value={detail.kind || '—'} />
|
||||
<SetValue title={tr('fieldCPUModel')} value={detail.cpu_model || '—'} mono />
|
||||
<SetValue title={tr('opencore')} value={detail.has_opencore ? tr('configured') : '—'} />
|
||||
<SetValue title={tr('fieldDir')} value={detail.directory} mono />
|
||||
</SetGroup>
|
||||
{detail.has_opencore && (
|
||||
<SetGroup title={tr('smbiosTitle')} note={tr('smbiosCheckHint')}>
|
||||
<SetRow
|
||||
title={tr('smbiosTitle')}
|
||||
desc={tr('smbiosDesc')}
|
||||
disabled={smbiosLocked}
|
||||
reason={tr('smbiosStopRequired')}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Shuffle size={13} aria-hidden="true" />}
|
||||
disabled={smbiosLocked || !smbios}
|
||||
onClick={openSmbiosRotate}
|
||||
>
|
||||
{tr('smbiosRotateBtn')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{smbiosErr && <div className="notice notice-error" role="alert">{tr('smbiosLoadFailed')}: {smbiosErr}</div>}
|
||||
{smbiosApplied && <div className="notice" role="status">{tr('smbiosApplied')}</div>}
|
||||
{smbios && (
|
||||
<>
|
||||
<SetValue title={tr('smbiosModel')} value={smbios.model || '—'} mono />
|
||||
<SetValue
|
||||
title={tr('smbiosSerial')}
|
||||
mono
|
||||
value={
|
||||
<span className="hstack">
|
||||
<span>{smbiosReveal ? smbios.serial : maskIdentity(smbios.serial, 4, 4)}</span>
|
||||
<IconButton
|
||||
small
|
||||
label={smbiosReveal ? tr('smbiosHide') : tr('smbiosShow')}
|
||||
icon={smbiosReveal ? <EyeOff size={13} /> : <Eye size={13} />}
|
||||
onClick={() => setSmbiosReveal((v) => !v)}
|
||||
/>
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('smbiosCopySerial')}
|
||||
icon={<Copy size={13} />}
|
||||
onClick={() => onCopy(smbios.serial)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<SetValue title={tr('smbiosMLB')} value={smbiosReveal ? smbios.mlb : maskIdentity(smbios.mlb, 4, 4)} mono />
|
||||
<SetValue title={tr('smbiosUUID')} value={smbiosReveal ? smbios.uuid : maskIdentity(smbios.uuid, 4, 4)} mono />
|
||||
{smbios.rom && <SetValue title={tr('smbiosROM')} value={smbiosReveal ? smbios.rom : maskIdentity(smbios.rom, 5, 5)} mono />}
|
||||
</>
|
||||
)}
|
||||
</SetGroup>
|
||||
)}
|
||||
{renderVMPluginGroup('collaboration')}
|
||||
</>
|
||||
)
|
||||
@@ -660,7 +794,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setErr('')
|
||||
setDiskOpBusy('resize')
|
||||
try {
|
||||
const res = await api.ResizeVMDisk(detail.name, resizeInput.trim())
|
||||
const res = await api.ResizeVMDiskWithDriver(driverID, detail.name, resizeInput.trim())
|
||||
setResizeResult(res)
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
@@ -675,7 +809,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setErr('')
|
||||
setDiskOpBusy('compact')
|
||||
try {
|
||||
const res = await api.CompactVMDisk(detail.name)
|
||||
const res = await api.CompactVMDiskWithDriver(driverID, detail.name)
|
||||
setCompactResult(res)
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
@@ -1068,6 +1202,119 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
{smbiosOpen && (
|
||||
<Modal
|
||||
title={tr('smbiosDialogTitle')}
|
||||
subtitle={tr('smbiosDialogSub')}
|
||||
closeLabel={tr('close')}
|
||||
dismissable={smbiosBusy !== 'apply'}
|
||||
onClose={() => setSmbiosOpen(false)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<div className="notice">
|
||||
<span className="warn-text">{tr('smbiosWarning')}</span>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Shuffle size={13} aria-hidden="true" />}
|
||||
busy={smbiosBusy === 'generate'}
|
||||
disabled={smbiosBusy === 'apply'}
|
||||
onClick={() => void handleGenerateSmbios(smbios?.model ?? '')}
|
||||
>
|
||||
{tr('smbiosGenerate')}
|
||||
</Button>
|
||||
{onCopy && smbiosDraft?.serial && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Copy size={13} aria-hidden="true" />}
|
||||
disabled={!!smbiosBusy}
|
||||
onClick={() => onCopy(smbiosDraft.serial)}
|
||||
>
|
||||
{tr('smbiosCopySerial')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosSerial')}</span>
|
||||
<input
|
||||
className="input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={12}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.serial ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: e.target.value.toUpperCase(),
|
||||
mlb: prev?.mlb ?? '',
|
||||
uuid: prev?.uuid ?? '',
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosMLB')}</span>
|
||||
<input
|
||||
className="input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={17}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.mlb ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: prev?.serial ?? '',
|
||||
mlb: e.target.value.toUpperCase(),
|
||||
uuid: prev?.uuid ?? '',
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosUUID')}</span>
|
||||
<input
|
||||
className="input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={36}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.uuid ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: prev?.serial ?? '',
|
||||
mlb: prev?.mlb ?? '',
|
||||
uuid: e.target.value.toUpperCase(),
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
{smbios?.rom && (
|
||||
<div className="srow-desc">
|
||||
{tr('smbiosROM')}: <code className="inline-code">{smbios.rom}</code>
|
||||
</div>
|
||||
)}
|
||||
<div className="srow-desc">{tr('smbiosCheckHint')}</div>
|
||||
{smbiosModalErr && <div className="notice notice-error" role="alert">{smbiosModalErr}</div>}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" disabled={smbiosBusy === 'apply'} onClick={() => setSmbiosOpen(false)}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={smbiosBusy === 'apply'}
|
||||
disabled={smbiosLocked || smbiosBusy === 'generate' || !smbiosDraft?.serial.trim() || !smbiosDraft?.mlb.trim() || !smbiosDraft?.uuid.trim()}
|
||||
onClick={() => void handleApplySmbios()}
|
||||
>
|
||||
{tr('smbiosApply')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -203,7 +203,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
const whpxOK = host.whpx === 'ready'
|
||||
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
|
||||
const gpuHint = gpuCompatHint(locale, gpu)
|
||||
const gpuOK = !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
|
||||
const gpuOK = !host.vulkan_probe_error && !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
|
||||
const recMem = recommendedMemoryGB(host)
|
||||
return (
|
||||
<>
|
||||
@@ -236,7 +236,10 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('setupGPU')}</div>
|
||||
<div className="row-sub">{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}</div>
|
||||
{gpu && <div className="row-sub">{shortGPUName(gpu.name)}</div>}
|
||||
{host.vulkan_probe_error ? (
|
||||
<div className="row-sub warn-text">{tr('vulkanProbeFailed', { detail: host.vulkan_probe_error })}</div>
|
||||
) : !gpu && <div className="row-sub">{tr('setupNoGPU')}</div>}
|
||||
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import * as Ctx from '@radix-ui/react-context-menu'
|
||||
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from './VersionArt'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
@@ -51,7 +52,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ctxOpenedByPointerRef = useRef(false)
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -117,7 +118,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
<div className="nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
|
||||
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
const st = transitions[vmRefKey(vm)] ?? vm.state
|
||||
const running = st === 'running'
|
||||
const stopped = st === 'stopped'
|
||||
const suspended = st === 'suspended'
|
||||
@@ -126,17 +127,17 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const vmBusy = !!busyAction
|
||||
const label = displayNames[vm.name] || vm.name
|
||||
const trigger = navBtn(
|
||||
vm.name,
|
||||
vmRefKey(vm),
|
||||
label,
|
||||
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
|
||||
'nav-icon-art',
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vm.name) : undefined,
|
||||
onActivate ? () => onActivate(vmRefKey(vm)) : undefined,
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vm.name}>
|
||||
<Ctx.Root key={vmRefKey(vm)} dir={localeDir(locale)}>
|
||||
<Ctx.Trigger
|
||||
asChild
|
||||
onContextMenu={(e) => {
|
||||
@@ -158,67 +159,67 @@ export const Sidebar: React.FC<Props> = ({
|
||||
}}
|
||||
>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'start')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{suspended && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vm.name, 'resume')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
|
||||
<Play size={14} /> {tr('resume')}
|
||||
</Ctx.Item>
|
||||
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'discardSuspend')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
|
||||
<Power size={14} /> {tr('discardSuspend')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'focus')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'fullscreen')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
|
||||
<Maximize2 size={14} /> {tr('toggleFullscreen')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
{canSuspend && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'suspend')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
|
||||
<Pause size={14} /> {tr('suspend')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'stop')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'restart')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vm.name, 'settings')}>
|
||||
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Check, PanelLeft } from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { Locale } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
@@ -27,7 +27,7 @@ interface Props {
|
||||
canDark?: boolean
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
/** The selected VM and its current state, or null on the system pages. */
|
||||
vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
|
||||
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
|
||||
onNewVM: () => void
|
||||
onVMAction: (action: VMAction) => void
|
||||
onVMSettings: () => void
|
||||
@@ -66,7 +66,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
|
||||
const vmBusy = !vm || vm.busy
|
||||
const canFullscreen = running && vm?.graphics !== 'vmware-svga'
|
||||
const stats = useVMStats(canFullscreen && vm ? vm.name : null, running)
|
||||
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
|
||||
const fullscreenLabel = !canFullscreen || !stats?.running
|
||||
? tr('toggleFullscreen')
|
||||
: stats.window_fullscreen
|
||||
@@ -90,6 +90,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
// `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
|
||||
dir={localeDir(locale)}
|
||||
modal={false}
|
||||
open={menuState.id === id}
|
||||
onOpenChange={(o) => {
|
||||
@@ -146,7 +147,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
|
||||
data-menubar-switch={menuState.id === id && menuState.switched ? 'true' : undefined}
|
||||
data-menubar-switch={menuState.switched ? 'true' : undefined}
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
collisionPadding={8}
|
||||
@@ -159,8 +160,10 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
pointerClosedRef.current = false
|
||||
}}
|
||||
onPointerDownOutside={(e) => {
|
||||
const target = e.target as Node | null
|
||||
if (target && navRef.current?.contains(target)) {
|
||||
const orig = e.detail.originalEvent
|
||||
const target = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement ?? null
|
||||
const trigger = target?.closest('button.titlebar-menu') ?? null
|
||||
if (orig.button === 0 && !orig.ctrlKey && trigger && navRef.current?.contains(trigger)) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Archive,
|
||||
Camera,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Code2,
|
||||
Copy,
|
||||
@@ -42,7 +43,7 @@ import {
|
||||
UserRound,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useId, useRef, useState } from 'react'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import { I18nKey, localeDir, locText, t } from '../i18n'
|
||||
import {
|
||||
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
|
||||
parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand,
|
||||
@@ -52,7 +53,7 @@ import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions,
|
||||
import { api } from '../wails'
|
||||
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
import { VersionArt } from './VersionArt'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
|
||||
export type VMAction =
|
||||
| 'start'
|
||||
@@ -90,6 +91,7 @@ interface Props {
|
||||
locale: Locale
|
||||
/** The VM's identifier (folder, CLI, reims-ctl). */
|
||||
name: string
|
||||
driverID: string
|
||||
/** What the user calls it (its note); empty shows `name`. */
|
||||
displayName: string
|
||||
onDisplayNameSaved: (displayName: string) => void
|
||||
@@ -126,6 +128,40 @@ type Tone = '' | ' warn' | ' high'
|
||||
const meterTone = (pct: number, warn = 75, high = 90): Tone => (pct >= high ? ' high' : pct >= warn ? ' warn' : '')
|
||||
const clampPct = (v: number) => Math.min(100, Math.max(0, v))
|
||||
|
||||
function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' | 'busyAction' | 'onAction'>) {
|
||||
const [mode, setMode] = useState<'stop' | 'forceStop'>('stop')
|
||||
const forced = mode === 'forceStop'
|
||||
const variant = forced ? 'danger' : 'secondary'
|
||||
const label = t(locale, 'shutdownMode')
|
||||
const Icon = forced ? Power : Square
|
||||
|
||||
return (
|
||||
<div className="shutdown-button" role="group" aria-label={label}>
|
||||
<Button variant={variant} icon={<Icon size={13} aria-hidden="true" />} busy={busyAction === mode}
|
||||
disabled={!!busyAction} onClick={() => onAction(mode)}>{t(locale, mode)}</Button>
|
||||
<Menu.Root dir={localeDir(locale)}>
|
||||
<Menu.Trigger asChild>
|
||||
<Button variant={variant} disabled={!!busyAction} aria-label={label} title={label}>
|
||||
<ChevronDown size={13} aria-hidden="true" />
|
||||
</Button>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content className="menu" align="end" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.RadioGroup value={mode} onValueChange={(v) => setMode(v === 'forceStop' ? 'forceStop' : 'stop')}>
|
||||
{(['stop', 'forceStop'] as const).map((action) => (
|
||||
<Menu.RadioItem key={action} value={action} className={`menu-item menu-item-check${action === 'forceStop' ? ' danger' : ''}`}>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
{t(locale, action)}
|
||||
</Menu.RadioItem>
|
||||
))}
|
||||
</Menu.RadioGroup>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface Spec {
|
||||
key: string
|
||||
/** Shown only in the wide, single-column layout. */
|
||||
@@ -138,7 +174,7 @@ interface Spec {
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
@@ -150,23 +186,23 @@ export const VMPage: React.FC<Props> = ({
|
||||
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
|
||||
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
|
||||
// Polled here rather than in App so each tick re-renders only this page.
|
||||
const stats = useVMStats(name, running)
|
||||
const stats = useVMStats(driverID, name, running)
|
||||
|
||||
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
|
||||
// runs, otherwise the last frame saved. Skipped while this window is hidden;
|
||||
// the backend also skips it while the VM's own window is in front.
|
||||
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
|
||||
useEffect(() => { setThumb(null) }, [name])
|
||||
useEffect(() => { setThumb(null) }, [driverID, name])
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const pull = () => {
|
||||
if (document.hidden) return
|
||||
api.GetVMThumbnail(name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
|
||||
api.GetVMThumbnailWithDriver(driverID, name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
|
||||
}
|
||||
pull()
|
||||
const timer = running ? window.setInterval(pull, 15000) : undefined
|
||||
return () => { live = false; if (timer) window.clearInterval(timer) }
|
||||
}, [name, running])
|
||||
}, [driverID, name, running])
|
||||
|
||||
// Display name, stored as the VM's note (.reims-go-note). Clicking the title
|
||||
// edits it in place; clearing it (or typing the name) falls back to the name.
|
||||
@@ -206,29 +242,29 @@ export const VMPage: React.FC<Props> = ({
|
||||
setMoreMenuOpen(false)
|
||||
setSshMenuOpen(false)
|
||||
setSshUserDialog(false)
|
||||
}, [name])
|
||||
}, [driverID, name])
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.GetVMSSHUser(name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
api.GetVMSSHUserWithDriver(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
return () => { live = false }
|
||||
}, [name])
|
||||
}, [driverID, name])
|
||||
|
||||
const openSSHTerminal = () => {
|
||||
api.OpenSSHTerminal(name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
api.OpenSSHTerminalWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const writeSSHConfig = () => {
|
||||
api.WriteSSHConfig(name, sshUser)
|
||||
api.WriteSSHConfigWithDriver(driverID, name, sshUser)
|
||||
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
|
||||
.catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const openVSCodeSSH = () => {
|
||||
api.OpenVSCodeSSH(name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
api.OpenVSCodeSSHWithDriver(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const saveSSHUser = async () => {
|
||||
const next = sshUserDraft.trim()
|
||||
setSshUserDialog(false)
|
||||
try {
|
||||
await api.SetVMSSHUser(name, next)
|
||||
await api.SetVMSSHUserWithDriver(driverID, name, next)
|
||||
setSshUser(next)
|
||||
onToast(tr('toastSSHUserSaved'))
|
||||
} catch (e) {
|
||||
@@ -266,7 +302,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
|
||||
const loadSnapshots = () => {
|
||||
if (!showSnapshots) { setSnapshots([]); return }
|
||||
api.ListSnapshots(name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
api.ListSnapshotsWithDriver(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
}
|
||||
useEffect(() => {
|
||||
setCreatingSnap(false)
|
||||
@@ -274,14 +310,14 @@ export const VMPage: React.FC<Props> = ({
|
||||
setRestoreTarget(null)
|
||||
loadSnapshots()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [name, showSnapshots, state])
|
||||
}, [driverID, name, showSnapshots, state])
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
const label = snapDraft.trim()
|
||||
if (!label) return
|
||||
setSnapBusy('create')
|
||||
try {
|
||||
await api.CreateSnapshot(name, label)
|
||||
await api.CreateSnapshotWithDriver(driverID, name, label)
|
||||
setSnapDraft('')
|
||||
setCreatingSnap(false)
|
||||
onToast(tr('toastSnapshotCreated', { name: label }))
|
||||
@@ -296,7 +332,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
setRestoreTarget(null)
|
||||
setSnapBusy(`restore:${snapName}`)
|
||||
try {
|
||||
await api.RestoreSnapshot(name, snapName)
|
||||
await api.RestoreSnapshotWithDriver(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotRestored', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
@@ -308,7 +344,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
const handleDeleteSnapshot = async (snapName: string) => {
|
||||
setSnapBusy(`delete:${snapName}`)
|
||||
try {
|
||||
await api.DeleteSnapshot(name, snapName)
|
||||
await api.DeleteSnapshotWithDriver(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotDeleted', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
@@ -378,7 +414,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
{tr('suspend')}
|
||||
</Button>
|
||||
)}
|
||||
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
|
||||
<ShutdownButton key={name} locale={locale} busyAction={busyAction} onAction={onAction} />
|
||||
</>
|
||||
)
|
||||
} else if (state === 'broken') {
|
||||
@@ -388,6 +424,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
// "More" menu, grouped by purpose; destructive items last (docs/design-guidelines.md §5.2).
|
||||
const menu = (
|
||||
<Menu.Root
|
||||
dir={localeDir(locale)}
|
||||
open={moreMenuOpen}
|
||||
onOpenChange={(o) => {
|
||||
if (o) morePointerClosed.current = false
|
||||
@@ -979,6 +1016,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
{tr('sshOpenTerminal')}
|
||||
</Button>
|
||||
<Menu.Root
|
||||
dir={localeDir(locale)}
|
||||
open={sshMenuOpen}
|
||||
onOpenChange={(o) => {
|
||||
if (o) sshPointerClosed.current = false
|
||||
|
||||
@@ -14,6 +14,13 @@ export const coreZh: Record<string, string> = {
|
||||
"collapseLogs": "收起日志",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"dataRootChooseOther": "选择其他数据目录",
|
||||
"dataRootChooseTitle": "选择数据目录",
|
||||
"dataRootReadOnlyDetail": "详细信息",
|
||||
"dataRootReadOnlyFolder": "数据目录",
|
||||
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
|
||||
"dataRootRepair": "修复版本记录",
|
||||
"dataRootRetry": "重试",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"displays": "显示器数量",
|
||||
@@ -39,7 +46,7 @@ export const coreZh: Record<string, string> = {
|
||||
"footerMemTip": "系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, other {# 台运行中}}",
|
||||
"forceStop": "强制关机",
|
||||
"forceStop": "硬关机",
|
||||
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
|
||||
@@ -108,6 +115,8 @@ export const coreZh: Record<string, string> = {
|
||||
"panelLoadFailed": "面板加载失败",
|
||||
"pauseDownload": "暂停下载",
|
||||
"pluginSafeModeShort": "安全模式",
|
||||
"quitFailed": "已取消退出",
|
||||
"quitInProgress": "正在退出…",
|
||||
"refresh": "刷新",
|
||||
"resLooksLike": "看起来像 {w} × {h}",
|
||||
"resizeLogPanel": "拖动调整日志高度",
|
||||
@@ -122,6 +131,7 @@ export const coreZh: Record<string, string> = {
|
||||
"shortcutBarFullscreen": "切换全屏",
|
||||
"shortcutBarRelease": "释放键盘和鼠标",
|
||||
"showSidebar": "显示侧边栏",
|
||||
"shutdownMode": "关机方式",
|
||||
"sidebarHost": "内核",
|
||||
"sidebarInstallers": "安装包",
|
||||
"sidebarItemAria": "{label},{state}",
|
||||
@@ -196,6 +206,13 @@ export const coreEn: Record<string, string> = {
|
||||
"collapseLogs": "Hide logs",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"dataRootChooseOther": "Choose another data folder",
|
||||
"dataRootChooseTitle": "Choose data folder",
|
||||
"dataRootReadOnlyDetail": "Details",
|
||||
"dataRootReadOnlyFolder": "Data folder",
|
||||
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
|
||||
"dataRootRepair": "Repair version record",
|
||||
"dataRootRetry": "Try again",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"displays": "Displays",
|
||||
@@ -290,6 +307,8 @@ export const coreEn: Record<string, string> = {
|
||||
"panelLoadFailed": "Panel failed to load",
|
||||
"pauseDownload": "Pause download",
|
||||
"pluginSafeModeShort": "Safe mode",
|
||||
"quitFailed": "Quit canceled",
|
||||
"quitInProgress": "Quitting…",
|
||||
"refresh": "Refresh",
|
||||
"resLooksLike": "Looks like {w} × {h}",
|
||||
"resizeLogPanel": "Drag to resize log panel",
|
||||
@@ -304,6 +323,7 @@ export const coreEn: Record<string, string> = {
|
||||
"shortcutBarFullscreen": "Toggle full screen",
|
||||
"shortcutBarRelease": "Release keyboard and mouse",
|
||||
"showSidebar": "Show sidebar",
|
||||
"shutdownMode": "Shutdown mode",
|
||||
"sidebarHost": "Engine",
|
||||
"sidebarInstallers": "Installers",
|
||||
"sidebarItemAria": "{label}, {state}",
|
||||
|
||||
@@ -14,6 +14,9 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
"pluginDeleteScheme": "删除方案",
|
||||
"pluginDisable": "停用",
|
||||
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。",
|
||||
"pluginDisableInUseTitle": "停用仍有虚拟机的插件",
|
||||
"pluginDone": "完成",
|
||||
"pluginEnableLater": "暂不启用",
|
||||
"pluginEnableNow": "启用",
|
||||
@@ -134,6 +137,9 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
"pluginDeleteScheme": "Delete scheme",
|
||||
"pluginDisable": "Disable",
|
||||
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.",
|
||||
"pluginDisableInUseTitle": "Disable a plugin that still has VMs",
|
||||
"pluginDone": "Done",
|
||||
"pluginEnableLater": "Not now",
|
||||
"pluginEnableNow": "Enable",
|
||||
|
||||
@@ -3,8 +3,12 @@ import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const settingsZh: Record<string, string> = {
|
||||
"aboutCommunity": "社区与支持",
|
||||
"aboutCopyDiscord": "复制邀请链接",
|
||||
"aboutCopyQQGroup": "复制群号",
|
||||
"aboutDiscord": "Discord 社区",
|
||||
"aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发",
|
||||
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
|
||||
"aboutJoinDiscord": "加入服务器",
|
||||
"aboutJoinQQGroup": "加入群聊",
|
||||
"aboutLicensesOpenGitHub": "在 GitHub 查看",
|
||||
"aboutLicensesSub": "Apache-2.0 协议与第三方开源组件声明(离线可查)",
|
||||
@@ -159,6 +163,10 @@ export const settingsZh: Record<string, string> = {
|
||||
"footerDisk": "磁盘可用 {gb} GB",
|
||||
"footerMem": "内存 {pct}%",
|
||||
"footerMemAvail": "可用 {avail} GB",
|
||||
"forceQuitAppButton": "强制退出",
|
||||
"forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。",
|
||||
"forceQuitAppTitle": "强制退出 Reims-Go",
|
||||
"forceQuitInProgress": "正在强制退出…",
|
||||
"fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放",
|
||||
"fullscreenLaunch": "无边框全屏启动",
|
||||
"fullscreenLaunchHint": "启动后直接进入无边框全屏",
|
||||
@@ -302,6 +310,26 @@ export const settingsZh: Record<string, string> = {
|
||||
"settingsAppearance": "外观与语言",
|
||||
"settingsGeneral": "常规",
|
||||
"settingsTitle": "{name}",
|
||||
"smbiosApplied": "已写入新的 OpenCore 设备码,下次启动虚拟机生效",
|
||||
"smbiosApply": "写入新设备码",
|
||||
"smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。",
|
||||
"smbiosCopySerial": "复制序列号",
|
||||
"smbiosDesc": "写入 OpenCore 的序列号、主板号 (MLB) 与 UUID,用于 Apple 服务识别。ROM 与虚拟网卡 MAC 保持同步,换码时不会修改。",
|
||||
"smbiosDialogSub": "只修改序列号、MLB 与 SystemUUID,保留原 ROM(网卡 MAC)与 NVRAM",
|
||||
"smbiosDialogTitle": "更换 OpenCore 设备码",
|
||||
"smbiosGenerate": "随机生成一组",
|
||||
"smbiosHide": "隐藏",
|
||||
"smbiosLoadFailed": "无法读取 OpenCore 设备码",
|
||||
"smbiosMLB": "主板号 (MLB)",
|
||||
"smbiosModel": "机型",
|
||||
"smbiosROM": "网卡 ROM",
|
||||
"smbiosRotateBtn": "一键换码…",
|
||||
"smbiosSerial": "序列号",
|
||||
"smbiosShow": "显示完整码",
|
||||
"smbiosStopRequired": "请先彻底关机(不能处于运行或休眠状态)",
|
||||
"smbiosTitle": "设备身份 (SMBIOS)",
|
||||
"smbiosUUID": "系统 UUID",
|
||||
"smbiosWarning": "换码前请先在 macOS 中退出 Apple 账户并彻底关机;换码后首次开机可能弹出「设置助理」,iCloud / App Store 需重新登录。",
|
||||
"sourceDisk": "已有虚拟磁盘(.qcow2)",
|
||||
"sourceInstaller": "本地安装器镜像(.img / .dmg)",
|
||||
"sshForward": "SSH 端口转发",
|
||||
@@ -322,6 +350,9 @@ export const settingsZh: Record<string, string> = {
|
||||
"storageInstallers": "安装包",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"syncHostMemorySMBIOS": "同步宿主机内存规格",
|
||||
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
|
||||
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
|
||||
"themeLabel": "外观",
|
||||
"themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用",
|
||||
"themePluginLightDisabled": "当前主题仅支持深色外观",
|
||||
@@ -349,8 +380,12 @@ export const settingsZh: Record<string, string> = {
|
||||
|
||||
export const settingsEn: Record<string, string> = {
|
||||
"aboutCommunity": "Community \u0026 support",
|
||||
"aboutCopyDiscord": "Copy invite link",
|
||||
"aboutCopyQQGroup": "Copy group ID",
|
||||
"aboutDiscord": "Discord community",
|
||||
"aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins",
|
||||
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
|
||||
"aboutJoinDiscord": "Join server",
|
||||
"aboutJoinQQGroup": "Join group",
|
||||
"aboutLicensesOpenGitHub": "View on GitHub",
|
||||
"aboutLicensesSub": "Apache-2.0 license and third-party notices (available offline)",
|
||||
@@ -505,6 +540,10 @@ export const settingsEn: Record<string, string> = {
|
||||
"footerDisk": "Disk {gb} GB free",
|
||||
"footerMem": "Memory {pct}%",
|
||||
"footerMemAvail": "{avail} GB free",
|
||||
"forceQuitAppButton": "Force quit",
|
||||
"forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.",
|
||||
"forceQuitAppTitle": "Force quit Reims-Go",
|
||||
"forceQuitInProgress": "Force quitting…",
|
||||
"fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU",
|
||||
"fullscreenLaunch": "Launch borderless fullscreen",
|
||||
"fullscreenLaunchHint": "Opens macOS in borderless full screen",
|
||||
@@ -648,6 +687,26 @@ export const settingsEn: Record<string, string> = {
|
||||
"settingsAppearance": "Appearance \u0026 language",
|
||||
"settingsGeneral": "General",
|
||||
"settingsTitle": "{name}",
|
||||
"smbiosApplied": "Updated OpenCore SMBIOS identity. Applies on next start",
|
||||
"smbiosApply": "Write new codes",
|
||||
"smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.",
|
||||
"smbiosCopySerial": "Copy serial",
|
||||
"smbiosDesc": "Serial, MLB and UUID written to OpenCore for Apple services. ROM stays synced with the virtual NIC MAC and is left unchanged.",
|
||||
"smbiosDialogSub": "Updates Serial, MLB and SystemUUID only; keeps ROM (NIC MAC) and NVRAM intact",
|
||||
"smbiosDialogTitle": "Rotate OpenCore SMBIOS",
|
||||
"smbiosGenerate": "Generate random",
|
||||
"smbiosHide": "Hide",
|
||||
"smbiosLoadFailed": "Could not read OpenCore SMBIOS",
|
||||
"smbiosMLB": "MLB",
|
||||
"smbiosModel": "Model",
|
||||
"smbiosROM": "NIC ROM",
|
||||
"smbiosRotateBtn": "Rotate codes…",
|
||||
"smbiosSerial": "Serial",
|
||||
"smbiosShow": "Reveal",
|
||||
"smbiosStopRequired": "Shut down the VM completely first (not running or suspended)",
|
||||
"smbiosTitle": "Device identity (SMBIOS)",
|
||||
"smbiosUUID": "System UUID",
|
||||
"smbiosWarning": "Sign out of Apple Account in macOS and shut down completely before rotating. First boot may show Setup Assistant and require signing in to iCloud / App Store again.",
|
||||
"sourceDisk": "Existing virtual disk (.qcow2)",
|
||||
"sourceInstaller": "Local installer image (.img / .dmg)",
|
||||
"sshForward": "SSH port forwarding",
|
||||
@@ -668,6 +727,9 @@ export const settingsEn: Record<string, string> = {
|
||||
"storageInstallers": "Installers",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "VM files",
|
||||
"syncHostMemorySMBIOS": "Sync host memory specs",
|
||||
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
|
||||
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
|
||||
"themeLabel": "Appearance",
|
||||
"themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable",
|
||||
"themePluginLightDisabled": "The active theme supports dark appearance only",
|
||||
|
||||
@@ -79,6 +79,7 @@ export const wizardZh: Record<string, string> = {
|
||||
"summarySource": "来源",
|
||||
"validationChecking": "正在检查…",
|
||||
"validationPassed": "可以创建",
|
||||
"vulkanProbeFailed": "Vulkan 探测失败({detail})。请运行 vulkaninfo --summary 检查驱动。",
|
||||
"wizChooseFile": "选择…",
|
||||
"wizNoFile": "还没有选择文件",
|
||||
"wizOptions": "选项",
|
||||
@@ -166,6 +167,7 @@ export const wizardEn: Record<string, string> = {
|
||||
"summarySource": "Source",
|
||||
"validationChecking": "Checking…",
|
||||
"validationPassed": "Ready to create",
|
||||
"vulkanProbeFailed": "Vulkan probe failed ({detail}). Run vulkaninfo --summary to check the driver.",
|
||||
"wizChooseFile": "Choose…",
|
||||
"wizNoFile": "No file chosen",
|
||||
"wizOptions": "Options",
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
|
||||
export type I18nKey =
|
||||
| "aboutCommunity"
|
||||
| "aboutCopyDiscord"
|
||||
| "aboutCopyQQGroup"
|
||||
| "aboutDiscord"
|
||||
| "aboutDiscordSub"
|
||||
| "aboutIssueSub"
|
||||
| "aboutJoinDiscord"
|
||||
| "aboutJoinQQGroup"
|
||||
| "aboutLicensesOpenGitHub"
|
||||
| "aboutLicensesSub"
|
||||
@@ -145,6 +149,13 @@ export type I18nKey =
|
||||
| "cpuRecHint"
|
||||
| "createNow"
|
||||
| "createStartedHint"
|
||||
| "dataRootChooseOther"
|
||||
| "dataRootChooseTitle"
|
||||
| "dataRootReadOnlyDetail"
|
||||
| "dataRootReadOnlyFolder"
|
||||
| "dataRootReadOnlyTitle"
|
||||
| "dataRootRepair"
|
||||
| "dataRootRetry"
|
||||
| "delete"
|
||||
| "deleteConfirm"
|
||||
| "deleteDesc"
|
||||
@@ -274,6 +285,10 @@ export type I18nKey =
|
||||
| "footerMemTip"
|
||||
| "footerMemValue"
|
||||
| "footerRunningVMs"
|
||||
| "forceQuitAppButton"
|
||||
| "forceQuitAppSub"
|
||||
| "forceQuitAppTitle"
|
||||
| "forceQuitInProgress"
|
||||
| "forceStop"
|
||||
| "fullscreenDecoupledHint"
|
||||
| "fullscreenLaunch"
|
||||
@@ -535,6 +550,9 @@ export type I18nKey =
|
||||
| "pluginColorSchemes"
|
||||
| "pluginColorSchemesHint"
|
||||
| "pluginDeleteScheme"
|
||||
| "pluginDisable"
|
||||
| "pluginDisableInUseBody"
|
||||
| "pluginDisableInUseTitle"
|
||||
| "pluginDone"
|
||||
| "pluginEnableLater"
|
||||
| "pluginEnableNow"
|
||||
@@ -641,6 +659,8 @@ export type I18nKey =
|
||||
| "pluginTrustOfficial"
|
||||
| "pluginTrustVerified"
|
||||
| "pluginViewLog"
|
||||
| "quitFailed"
|
||||
| "quitInProgress"
|
||||
| "recommendedBadge"
|
||||
| "refresh"
|
||||
| "resCustom"
|
||||
@@ -720,6 +740,7 @@ export type I18nKey =
|
||||
| "showInstallGuide"
|
||||
| "showSidebar"
|
||||
| "showWindow"
|
||||
| "shutdownMode"
|
||||
| "sidebarHost"
|
||||
| "sidebarInstallers"
|
||||
| "sidebarItemAria"
|
||||
@@ -728,6 +749,26 @@ export type I18nKey =
|
||||
| "sidebarSettings"
|
||||
| "sidebarSystem"
|
||||
| "sidebarVMs"
|
||||
| "smbiosApplied"
|
||||
| "smbiosApply"
|
||||
| "smbiosCheckHint"
|
||||
| "smbiosCopySerial"
|
||||
| "smbiosDesc"
|
||||
| "smbiosDialogSub"
|
||||
| "smbiosDialogTitle"
|
||||
| "smbiosGenerate"
|
||||
| "smbiosHide"
|
||||
| "smbiosLoadFailed"
|
||||
| "smbiosMLB"
|
||||
| "smbiosModel"
|
||||
| "smbiosROM"
|
||||
| "smbiosRotateBtn"
|
||||
| "smbiosSerial"
|
||||
| "smbiosShow"
|
||||
| "smbiosStopRequired"
|
||||
| "smbiosTitle"
|
||||
| "smbiosUUID"
|
||||
| "smbiosWarning"
|
||||
| "snapshotCreate"
|
||||
| "snapshotDelete"
|
||||
| "snapshotEmpty"
|
||||
@@ -825,6 +866,9 @@ export type I18nKey =
|
||||
| "suspendedNoticeDescWithTime"
|
||||
| "suspendedNoticeTitle"
|
||||
| "suspendedSettingsHint"
|
||||
| "syncHostMemorySMBIOS"
|
||||
| "syncHostMemorySMBIOSSub"
|
||||
| "syncHostMemorySMBIOSUnavailable"
|
||||
| "taskAppUpdate"
|
||||
| "taskCreate"
|
||||
| "taskDownload"
|
||||
@@ -923,6 +967,7 @@ export type I18nKey =
|
||||
| "viewLogs"
|
||||
| "vmDir"
|
||||
| "vmName"
|
||||
| "vulkanProbeFailed"
|
||||
| "welcomeCheckHost"
|
||||
| "welcomeSub"
|
||||
| "welcomeTitle"
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface VMRefLike {
|
||||
name: string
|
||||
driver_id?: string
|
||||
}
|
||||
|
||||
/** Matches driver.VMRef.Key while tolerating pre-VMRef test/host snapshots. */
|
||||
export function vmRefKey(vm: VMRefLike): string {
|
||||
return vm.driver_id ? `${vm.driver_id}:${vm.name}` : vm.name
|
||||
}
|
||||
+37
-39
@@ -2,13 +2,8 @@ import { useEffect, useState } from 'react'
|
||||
import { VMStats } from '../types'
|
||||
import { api } from '../wails'
|
||||
|
||||
// Shared VM stats poller (stats_flow.go). Components that show stats
|
||||
// subscribe with useVMStats, so a tick re-renders only them, not the whole
|
||||
// App. One timer per VM however many subscribe; it pauses while the window
|
||||
// is hidden and samples once on return.
|
||||
|
||||
// Shared VM stats poller, keyed by VMRef so same-name VMs never share samples.
|
||||
const RUNNING_MS = 3000
|
||||
// A stopped VM only changes disk usage, so it is sampled rarely.
|
||||
const STOPPED_MS = 30000
|
||||
|
||||
interface Entry {
|
||||
@@ -21,14 +16,14 @@ interface Entry {
|
||||
}
|
||||
|
||||
const entries = new Map<string, Entry>()
|
||||
const statsKey = (driverID: string, name: string) => `${driverID}:${name}`
|
||||
|
||||
function sample(name: string, entryRef: Entry) {
|
||||
if (entries.get(name) !== entryRef) return
|
||||
function sample(key: string, driverID: string, name: string, entryRef: Entry) {
|
||||
if (entries.get(key) !== entryRef) return
|
||||
const reqSeq = ++entryRef.seq
|
||||
api.GetVMStats(name)
|
||||
api.GetVMStatsWithDriver(driverID, name)
|
||||
.then((s) => {
|
||||
if (entries.get(name) !== entryRef) return
|
||||
if (reqSeq <= entryRef.appliedSeq) return
|
||||
if (entries.get(key) !== entryRef || reqSeq <= entryRef.appliedSeq) return
|
||||
entryRef.appliedSeq = reqSeq
|
||||
entryRef.last = s
|
||||
entryRef.subs.forEach((f) => f(s))
|
||||
@@ -36,81 +31,84 @@ function sample(name: string, entryRef: Entry) {
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
function schedule(name: string, e: Entry) {
|
||||
function schedule(key: string, driverID: string, name: string, e: Entry) {
|
||||
if (e.timer) window.clearInterval(e.timer)
|
||||
e.timer = undefined
|
||||
if (document.hidden || e.subs.size === 0) return
|
||||
e.timer = window.setInterval(() => sample(name, e), e.running ? RUNNING_MS : STOPPED_MS)
|
||||
e.timer = window.setInterval(() => sample(key, driverID, name, e), e.running ? RUNNING_MS : STOPPED_MS)
|
||||
}
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
entries.forEach((e, name) => {
|
||||
if (!document.hidden && e.subs.size > 0) sample(name, e)
|
||||
schedule(name, e)
|
||||
entries.forEach((e, key) => {
|
||||
const split = key.indexOf(':')
|
||||
const driverID = key.slice(0, split)
|
||||
const name = key.slice(split + 1)
|
||||
if (!document.hidden && e.subs.size > 0) sample(key, driverID, name, e)
|
||||
schedule(key, driverID, name, e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
|
||||
export function latestVMStats(name: string | undefined | null): VMStats | null {
|
||||
return name ? entries.get(name)?.last ?? null : null
|
||||
export function latestVMStatsWithDriver(driverID: string, name: string | undefined | null): VMStats | null {
|
||||
return name ? entries.get(statsKey(driverID, name))?.last ?? null : null
|
||||
}
|
||||
export function latestVMStats(name: string | undefined | null): VMStats | null { return latestVMStatsWithDriver('', name) }
|
||||
|
||||
/** Immediately patch cached stats (if any) and re-sample a VM's stats. */
|
||||
export function refreshVMStats(name: string, patch?: Partial<VMStats>) {
|
||||
const e = entries.get(name)
|
||||
export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: Partial<VMStats>) {
|
||||
const key = statsKey(driverID, name)
|
||||
const e = entries.get(key)
|
||||
if (!e) return
|
||||
// Invalidate any in-flight samples started before this refresh/patch.
|
||||
e.appliedSeq = ++e.seq
|
||||
if (patch && e.last) {
|
||||
e.last = { ...e.last, ...patch }
|
||||
e.subs.forEach((f) => f(e.last!))
|
||||
}
|
||||
sample(name, e)
|
||||
sample(key, driverID, name, e)
|
||||
}
|
||||
export function refreshVMStats(name: string, patch?: Partial<VMStats>) { refreshVMStatsWithDriver('', name, patch) }
|
||||
|
||||
/** Re-sample all currently subscribed VMs (e.g. after a tray-triggered state change). */
|
||||
export function refreshSubscribedVMStats() {
|
||||
entries.forEach((e, name) => {
|
||||
if (e.subs.size > 0) {
|
||||
e.appliedSeq = ++e.seq
|
||||
sample(name, e)
|
||||
}
|
||||
entries.forEach((e, key) => {
|
||||
if (e.subs.size === 0) return
|
||||
const split = key.indexOf(':')
|
||||
e.appliedSeq = ++e.seq
|
||||
sample(key, key.slice(0, split), key.slice(split + 1), e)
|
||||
})
|
||||
}
|
||||
|
||||
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
|
||||
export function useVMStats(name: string | null, running: boolean): VMStats | null {
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(name))
|
||||
|
||||
export function useVMStats(driverID: string, name: string | null, running: boolean): VMStats | null {
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStatsWithDriver(driverID, name))
|
||||
useEffect(() => {
|
||||
if (!name) { setStats(null); return }
|
||||
let e = entries.get(name)
|
||||
const key = statsKey(driverID, name)
|
||||
let e = entries.get(key)
|
||||
if (!e) {
|
||||
e = { subs: new Set(), running, last: null, seq: 0, appliedSeq: 0 }
|
||||
entries.set(name, e)
|
||||
entries.set(key, e)
|
||||
}
|
||||
setStats(e.last)
|
||||
const sub = (s: VMStats) => setStats(s)
|
||||
e.subs.add(sub)
|
||||
// A state change (start/stop) samples at once and re-paces the timer.
|
||||
if (e.running !== running) {
|
||||
e.running = running
|
||||
e.appliedSeq = ++e.seq
|
||||
}
|
||||
sample(name, e)
|
||||
schedule(name, e)
|
||||
sample(key, driverID, name, e)
|
||||
schedule(key, driverID, name, e)
|
||||
return () => {
|
||||
const cur = entries.get(name)
|
||||
const cur = entries.get(key)
|
||||
if (!cur || cur !== e) return
|
||||
cur.subs.delete(sub)
|
||||
if (cur.subs.size === 0) {
|
||||
if (cur.timer) window.clearInterval(cur.timer)
|
||||
entries.delete(name)
|
||||
entries.delete(key)
|
||||
}
|
||||
}
|
||||
}, [name, running])
|
||||
|
||||
}, [driverID, name, running])
|
||||
return stats
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { macOSMajor } from '../lib/macosRelease'
|
||||
import { macOSMajor } from './macosRelease'
|
||||
import {
|
||||
ActiveInstallerMatch,
|
||||
findActiveCachedTask,
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+74
-36
@@ -82,15 +82,15 @@ h1, h2, h3, p { margin: 0; }
|
||||
|
||||
/* Left of the title bar: sidebar toggle + a small menu bar. Controls and the
|
||||
menu bar group opt out of window dragging so sweeping across menus stays smooth. */
|
||||
.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; margin-left: calc(var(--sp-2) * -1); }
|
||||
.titlebar-left { display: flex; align-items: center; gap: 2px; height: 100%; min-width: 0; margin-inline-start: calc(var(--sp-2) * -1); }
|
||||
.titlebar-icon, .titlebar-menu {
|
||||
--wails-draggable: no-drag;
|
||||
height: 28px; border: none; border-radius: var(--r-sm);
|
||||
background: transparent; color: var(--text-2); cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
.titlebar-icon { width: 32px; display: grid; place-items: center; margin-right: 4px; }
|
||||
.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); }
|
||||
.titlebar-icon { width: 32px; display: grid; place-items: center; margin-inline-end: 4px; flex-shrink: 0; }
|
||||
.titlebar-menu { padding: 0 10px; font-size: var(--fs-13); font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; }
|
||||
.titlebar-icon:hover, .titlebar-menu:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.titlebar-menu[data-state="open"] { background: var(--surface-active); color: var(--text); }
|
||||
.titlebar-icon:active, .titlebar-menu:active { transform: scale(0.96); }
|
||||
@@ -100,7 +100,7 @@ h1, h2, h3, p { margin: 0; }
|
||||
/* Menu rows with a trailing shortcut, check marks and group labels. */
|
||||
.menu-label { flex: 1; min-width: 0; white-space: nowrap; }
|
||||
.menu-shortcut {
|
||||
margin-left: 24px; font-family: var(--font-sans); font-size: var(--fs-12);
|
||||
margin-inline-start: 24px; font-family: var(--font-sans); font-size: var(--fs-12);
|
||||
color: var(--text-3); font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); }
|
||||
@@ -109,7 +109,7 @@ h1, h2, h3, p { margin: 0; }
|
||||
.menu-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
|
||||
.menu-group-label { padding: 6px 10px 2px; font-size: 11.5px; font-weight: var(--fw-medium); color: var(--text-3); user-select: none; }
|
||||
.theme-toggle {
|
||||
width: 30px; height: 28px; margin-right: var(--sp-1);
|
||||
width: 30px; height: 28px; margin-inline-end: var(--sp-1);
|
||||
border: 1px solid var(--border); border-radius: var(--r-md);
|
||||
background: var(--surface-1); color: var(--text-2);
|
||||
display: grid; place-items: center; cursor: pointer;
|
||||
@@ -138,11 +138,16 @@ h1, h2, h3, p { margin: 0; }
|
||||
display: flex; overflow: hidden;
|
||||
background: var(--surface-sidebar-rail);
|
||||
border-inline-end: 1px solid var(--border);
|
||||
transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out);
|
||||
transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), visibility 0s linear 0s;
|
||||
}
|
||||
/* Hidden sidebar (Ctrl+B): slides shut; the card keeps its width so its
|
||||
contents don't reflow while the rail narrows. */
|
||||
.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; }
|
||||
contents don't reflow while the rail narrows, and visibility: hidden removes
|
||||
off-screen buttons from the keyboard Tab order. */
|
||||
.workspace.sidebar-hidden .sidebar-wrap {
|
||||
width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent;
|
||||
visibility: hidden; pointer-events: none;
|
||||
transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out), visibility 0s linear var(--dur-modal);
|
||||
}
|
||||
.sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); }
|
||||
.sidebar {
|
||||
flex: 1; min-height: 0;
|
||||
@@ -529,6 +534,11 @@ h1, h2, h3, p { margin: 0; }
|
||||
box-shadow: 0 1px 3px rgba(255, 59, 48, 0.28), inset 0 1px 0 rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) { filter: brightness(1.06); background: var(--danger); }
|
||||
.shutdown-button { display: inline-flex; }
|
||||
.shutdown-button > .btn:first-child { border-start-end-radius: 0; border-end-end-radius: 0; }
|
||||
.shutdown-button > .btn:last-child {
|
||||
padding-inline: 6px; border-start-start-radius: 0; border-end-start-radius: 0; border-inline-start: 0;
|
||||
}
|
||||
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); box-shadow: none; }
|
||||
.btn-ghost:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
|
||||
|
||||
@@ -716,11 +726,14 @@ h1, h2, h3, p { margin: 0; }
|
||||
.about-hero-text h1 { font-size: 22px; font-weight: var(--fw-strong); letter-spacing: -0.02em; color: var(--text); }
|
||||
.about-hero-text p { margin: 0; font-size: var(--fs-13); color: var(--text-2); line-height: 1.5; }
|
||||
.license-modal-body { gap: var(--sp-3); }
|
||||
.license-modal-body > .seg { align-self: flex-start; flex-shrink: 0; }
|
||||
.license-pre {
|
||||
margin: 0; padding: 14px 16px; min-height: 260px; max-height: 52vh; overflow: auto;
|
||||
margin: 0; padding: 14px 16px; flex: 0 1 auto; height: min(440px, 50vh); min-height: 120px; overflow: auto;
|
||||
overscroll-behavior: contain; contain: content;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border); background: var(--surface-1);
|
||||
font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.55; color: var(--text-2);
|
||||
white-space: pre-wrap; word-break: break-word; user-select: text;
|
||||
text-rendering: auto; text-autospace: no-autospace;
|
||||
}
|
||||
.section-count { min-width: 20px; padding: 1px 7px; border-radius: 999px; background: var(--surface-active); color: var(--text-3); font-size: 11px; font-weight: var(--fw-medium); text-align: center; }
|
||||
.installer-row { min-height: 62px; }
|
||||
@@ -886,6 +899,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-2) var(--sp-4);
|
||||
font-family: var(--font-mono); font-size: var(--fs-12); line-height: 1.6; color: var(--text-code);
|
||||
white-space: pre-wrap; word-break: break-word; user-select: text;
|
||||
text-rendering: auto; text-autospace: no-autospace;
|
||||
}
|
||||
.log-line { display: flex; gap: var(--sp-3); }
|
||||
.log-ts { color: var(--text-3); flex-shrink: 0; font-variant-numeric: tabular-nums; }
|
||||
@@ -895,27 +909,30 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.jump-latest { position: absolute; inset-inline-end: var(--sp-4); bottom: var(--sp-3); }
|
||||
|
||||
/* ── Overlays: dialog, menu, tooltip, toast ────────────── */
|
||||
.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(5px); z-index: 40; }
|
||||
/* No backdrop-filter: main.go sets WebviewGpuIsDisabled: true (software
|
||||
compositing), where per-frame CPU Gaussian blur over modals/overlays stutters
|
||||
badly during enter animations and inner scrolling. */
|
||||
.overlay { position: fixed; inset: 0; background: var(--scrim); z-index: 40; }
|
||||
.dialog {
|
||||
position: fixed; z-index: 41; left: 50%; top: 50%; transform: translate(-50%, -50%);
|
||||
width: 720px; max-width: calc(100vw - 48px); max-height: calc(100vh - 80px);
|
||||
display: flex; flex-direction: column; overflow: hidden;
|
||||
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border); border-radius: var(--r-xl);
|
||||
box-shadow: var(--shadow-overlay), var(--highlight-top);
|
||||
}
|
||||
.dialog.sm { width: 420px; }
|
||||
.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: 14px 14px 14px 22px; border-bottom: 1px solid var(--border); }
|
||||
.dialog-head { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-block: 14px; padding-inline: 22px 14px; border-bottom: 1px solid var(--border); }
|
||||
.dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; }
|
||||
.dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; }
|
||||
.dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); }
|
||||
.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); }
|
||||
.dialog-foot { flex-shrink: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); }
|
||||
.dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); }
|
||||
.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; }
|
||||
|
||||
.menu {
|
||||
min-width: 188px; padding: 5px; z-index: 50;
|
||||
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-overlay), var(--highlight-top);
|
||||
}
|
||||
@@ -936,7 +953,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
.tooltip {
|
||||
z-index: 60; padding: 5px 9px; border-radius: var(--r-sm);
|
||||
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border-strong); color: var(--text);
|
||||
font-size: var(--fs-12); box-shadow: 0 8px 22px rgba(15, 23, 42, 0.16);
|
||||
display: flex; gap: var(--sp-2); align-items: center;
|
||||
@@ -947,7 +964,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.toast-viewport { position: fixed; inset-inline-end: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 380px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; }
|
||||
.toast {
|
||||
display: flex; flex-direction: column; gap: var(--sp-2); padding: var(--sp-3);
|
||||
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-overlay), var(--highlight-top);
|
||||
}
|
||||
@@ -968,7 +985,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.toast-title { font-size: var(--fs-13); font-weight: var(--fw-strong); }
|
||||
.toast-code {
|
||||
font-family: var(--font-mono); font-size: var(--fs-11); padding: 1px 5px;
|
||||
border-radius: 4px; background: var(--surface-active); color: var(--text-3);
|
||||
border-radius: 4px; background: var(--surface-active); color: var(--text-2);
|
||||
}
|
||||
.toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.toast-footer { display: flex; flex-direction: column; gap: var(--sp-2); padding-inline-start: 28px; width: 100%; min-width: 0; }
|
||||
@@ -1263,6 +1280,14 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.setup-head h1 { font-size: var(--fs-24); font-weight: var(--fw-strong); letter-spacing: -0.02em; text-wrap: balance; }
|
||||
.setup-head p { margin-top: var(--sp-1); color: var(--text-2); font-size: var(--fs-14); }
|
||||
.setup-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); }
|
||||
/* Read-only data folder screen (DataRootReadOnly) */
|
||||
.dataroot-detail { font-size: var(--fs-12); color: var(--text-2); }
|
||||
.dataroot-detail summary { cursor: pointer; }
|
||||
.dataroot-detail pre {
|
||||
margin: var(--sp-2) 0 0; padding: var(--sp-3); border-radius: var(--r-md);
|
||||
background: var(--surface-1); border: 1px solid var(--border);
|
||||
white-space: pre-wrap; word-break: break-word; max-height: 160px; overflow: auto;
|
||||
}
|
||||
/* First-run offer of a market language pack for the OS language */
|
||||
.setup-langpack {
|
||||
display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4);
|
||||
@@ -1323,6 +1348,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
/* ── Motion (emil-design-eng & apple-design) ───────────── */
|
||||
@keyframes rise-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
|
||||
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
|
||||
@keyframes fade-out { from { opacity: 1; } to { opacity: 0; } }
|
||||
@keyframes pop-in { from { opacity: 0; transform: translate(-50%, -49%) scale(0.96); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
|
||||
@keyframes menu-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } }
|
||||
@keyframes tip-in { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } }
|
||||
@@ -1334,10 +1360,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.page { animation: rise-in var(--dur) var(--ease-out) both; }
|
||||
.overlay { animation: fade-in var(--dur) var(--ease-out) both; }
|
||||
.dialog { animation: pop-in var(--dur-modal) var(--ease-out) both; }
|
||||
.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); animation: menu-in 160ms var(--ease-out) both; }
|
||||
.menu[data-menubar-switch="true"] { animation: none; }
|
||||
.tooltip { animation: tip-in 125ms var(--ease-out) both; }
|
||||
.tooltip[data-state="instant-open"] { animation-duration: 0ms; }
|
||||
.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); }
|
||||
.menu[data-state="open"] { animation: menu-in 160ms var(--ease-out) both; }
|
||||
.menu[data-state="open"][data-menubar-switch="true"],
|
||||
.menu[data-state="closed"] { animation: none; }
|
||||
.tooltip[data-state="delayed-open"] { animation: tip-in 125ms var(--ease-out) both; }
|
||||
.tooltip[data-state="instant-open"],
|
||||
.tooltip[data-state="closed"] { animation: none; }
|
||||
.pane-anim { display: flex; flex-direction: column; gap: 20px; animation: rise-in var(--dur) var(--ease-out) both; }
|
||||
.step-anim { display: flex; flex-direction: column; gap: var(--sp-4); animation: rise-in var(--dur) var(--ease-out) both; }
|
||||
|
||||
@@ -1385,7 +1414,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
width: max-content; max-width: calc(100% - 20px); padding: 0 12px;
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
|
||||
height: 26px; border-radius: 999px; pointer-events: none;
|
||||
background: rgba(20, 21, 26, 0.72); color: #fff; backdrop-filter: blur(10px);
|
||||
background: rgba(20, 21, 26, 0.84); color: #fff;
|
||||
font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
opacity: 0; transform: translateX(-50%) translateY(4px);
|
||||
@@ -1485,13 +1514,19 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
/* Reduced motion: stop decorative loops & positional motion */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.status-busy, .vm-screen-live, .skeleton-bar { animation: none; }
|
||||
.status-busy, .vm-screen-live, .skeleton-bar, .market-progress.is-indeterminate .market-progress-fill { animation: none; }
|
||||
.vm-display-unit, .vm-display-unit.is-actionable:hover, .vm-display-unit.is-actionable:active { transform: none; }
|
||||
.vm-screen-img, .vm-spec-meter .meter-fill { transition: none; }
|
||||
.page, .dialog, .menu, .tooltip, .pane-anim, .step-anim, .toast[data-state="open"], .toast[data-state="closed"] {
|
||||
.page, .dialog, .menu[data-state="open"]:not([data-menubar-switch="true"]), .tooltip[data-state="delayed-open"], .pane-anim, .step-anim, .toast[data-state="open"] {
|
||||
animation-name: fade-in;
|
||||
animation-duration: 140ms;
|
||||
}
|
||||
.toast[data-state="closed"],
|
||||
.toast[data-swipe="end"],
|
||||
:root[dir="rtl"] .toast[data-swipe="end"] {
|
||||
animation-name: fade-out;
|
||||
animation-duration: 140ms;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── v0.2.6 Enhancements: Screenshot, Note, Dropzone, Snapshots, Log Filter, Welcome ── */
|
||||
@@ -1500,14 +1535,13 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
position: absolute; right: 8px; bottom: 8px; z-index: 3;
|
||||
width: 30px; height: 30px; border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 8px;
|
||||
display: grid; place-items: center; cursor: pointer;
|
||||
background: rgba(20, 22, 28, 0.68); color: #ffffff;
|
||||
backdrop-filter: blur(10px);
|
||||
background: rgba(20, 22, 28, 0.82); color: #ffffff;
|
||||
opacity: 0; transform: translateY(3px);
|
||||
transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.vm-screen:hover .vm-screen-shot,
|
||||
.vm-screen-shot:focus-visible { opacity: 1; transform: translateY(0); }
|
||||
.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.88); }
|
||||
.vm-screen-shot:hover { background: rgba(20, 22, 28, 0.94); }
|
||||
.vm-screen-shot:active { transform: scale(0.94); }
|
||||
|
||||
/* The title is the display name; click to rename in place. The pencil hangs
|
||||
@@ -1561,9 +1595,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
position: sticky; top: 0; z-index: 20;
|
||||
display: flex; align-items: center; justify-content: center; gap: 8px;
|
||||
padding: 12px 16px; border-radius: var(--r-lg);
|
||||
background: var(--accent-soft); border: 1.5px dashed var(--accent);
|
||||
background: color-mix(in srgb, var(--surface-canvas) 89%, var(--accent)); border: 1.5px dashed var(--accent);
|
||||
color: var(--accent-soft-text); font-size: var(--fs-13); font-weight: var(--fw-medium);
|
||||
backdrop-filter: var(--blur-overlay);
|
||||
}
|
||||
|
||||
/* Interactive install stepper */
|
||||
@@ -1831,7 +1864,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.plugin-risk.is-high .plugin-risk-icon { background: var(--warn-soft); color: var(--warn-text); }
|
||||
.plugin-scan-section { display: flex; flex-direction: column; gap: 6px; }
|
||||
.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-semibold); color: var(--text-2); }
|
||||
.plugin-scan-section-title { font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-2); }
|
||||
.plugin-scan-section-title.is-danger { color: var(--danger-text); }
|
||||
.plugin-scan-examples { margin-top: 4px; font-size: var(--fs-11); color: var(--text-2); display: flex; flex-direction: column; gap: 2px; }
|
||||
|
||||
@@ -1897,6 +1930,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
max-height: 180px; overflow: auto;
|
||||
background: var(--surface-0); border: 1px solid var(--border);
|
||||
white-space: pre-wrap; word-break: break-word;
|
||||
text-rendering: auto; text-autospace: no-autospace;
|
||||
}
|
||||
.error-boundary-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; }
|
||||
|
||||
@@ -1911,7 +1945,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.sidebar-backdrop {
|
||||
display: block; position: absolute;
|
||||
inset: 0;
|
||||
background: var(--scrim); backdrop-filter: blur(3px); z-index: 31;
|
||||
background: var(--scrim); z-index: 31;
|
||||
}
|
||||
.sidebar-wrap {
|
||||
position: absolute; z-index: 32;
|
||||
@@ -1933,18 +1967,22 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.settings-pane { padding: 16px; }
|
||||
}
|
||||
|
||||
@container (max-width: 520px) {
|
||||
.row, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); }
|
||||
.row-main, .srow-text { flex: 1 1 220px; }
|
||||
.row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.source-cards, .field-row, .review-groups { grid-template-columns: 1fr; }
|
||||
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
|
||||
.vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; }
|
||||
.affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; }
|
||||
.conn-ctrl { flex-wrap: wrap; max-width: 100%; }
|
||||
.conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); }
|
||||
.row-main, .srow-text { flex: 1 1 220px; }
|
||||
.conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; }
|
||||
.plugins-search { width: 100%; }
|
||||
}
|
||||
@container (max-width: 560px) {
|
||||
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -90,17 +90,19 @@
|
||||
--surface-statusbar: #eef3fa;
|
||||
--surface-1: #f5f6f8;
|
||||
--surface-card-elevated: #ffffff;
|
||||
--surface-2: rgba(255, 255, 255, 0.94);
|
||||
--surface-2: rgba(255, 255, 255, 0.98);
|
||||
--surface-input: #ffffff;
|
||||
--surface-hover: rgba(15, 23, 42, 0.048);
|
||||
--surface-active: rgba(15, 23, 42, 0.085);
|
||||
--border: rgba(15, 23, 42, 0.08);
|
||||
--border-strong: rgba(15, 23, 42, 0.14);
|
||||
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.85);
|
||||
--scrim: rgba(15, 23, 42, 0.28);
|
||||
--scrim: rgba(15, 23, 42, 0.34);
|
||||
--shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.7);
|
||||
--shadow-card: 0 1px 2px rgba(15, 23, 42, 0.025);
|
||||
--shadow-overlay: 0 22px 58px rgba(15, 23, 42, 0.18), 0 4px 14px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--shadow-overlay: 0 16px 36px rgba(15, 23, 42, 0.16), 0 3px 10px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
/* Retained for UI Contract v1 (uiApi 1.0.0) theme compatibility; unused by default
|
||||
base styles while main.go runs WebView2 in software compositing mode. */
|
||||
--blur-chrome: blur(20px) saturate(180%);
|
||||
--blur-overlay: blur(18px) saturate(165%);
|
||||
|
||||
@@ -167,17 +169,17 @@
|
||||
--surface-statusbar: #18191e;
|
||||
--surface-1: rgba(255, 255, 255, 0.048);
|
||||
--surface-card-elevated: rgba(255, 255, 255, 0.075);
|
||||
--surface-2: rgba(42, 43, 50, 0.94);
|
||||
--surface-2: rgba(42, 43, 50, 0.98);
|
||||
--surface-input: rgba(0, 0, 0, 0.28);
|
||||
--surface-hover: rgba(255, 255, 255, 0.075);
|
||||
--surface-active: rgba(255, 255, 255, 0.12);
|
||||
--border: rgba(255, 255, 255, 0.085);
|
||||
--border-strong: rgba(255, 255, 255, 0.16);
|
||||
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
--scrim: rgba(0, 0, 0, 0.56);
|
||||
--scrim: rgba(0, 0, 0, 0.58);
|
||||
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.18);
|
||||
--shadow-overlay: 0 26px 68px rgba(0, 0, 0, 0.58), 0 0 0 1px rgba(255, 255, 255, 0.09);
|
||||
--shadow-overlay: 0 18px 40px rgba(0, 0, 0, 0.52), 0 0 0 1px rgba(255, 255, 255, 0.09);
|
||||
|
||||
--text: #f5f5f7;
|
||||
--text-2: #c2c2ca;
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
// Single source of truth for UI Contract v1 (docs/plugin-architecture.md §5.1).
|
||||
// Renaming or removing any part, state attribute, or token here is a uiApi major bump.
|
||||
// Single source of truth for UI Contract v2 (docs/plugin-architecture.md §5.1, §6.3).
|
||||
// Renaming or removing any stable entry here is a uiApi major bump.
|
||||
//
|
||||
// Every entry is either stable or experimental. Stable entries must be emitted
|
||||
// by the host (scripts/check-ui-contract.mjs fails the build otherwise) and are
|
||||
// covered by the compatibility promise. Experimental entries are part of the
|
||||
// published shape so plugins can be written against it, but the host does not
|
||||
// render them yet: `plugin doctor` warns, and they carry no compatibility
|
||||
// promise until promoted. Promote an entry by moving it into the stable list
|
||||
// in the same change that renders it. The Go side mirrors slots, layout
|
||||
// options, icon names and view locations in internal/plugin/contract.go, and a
|
||||
// Go test keeps both in step.
|
||||
|
||||
export const UI_API_VERSION = '1.0.0' as const
|
||||
export const UI_API_VERSION = '2.0.0' as const
|
||||
|
||||
export const UI_CONTRACT_PARTS = [
|
||||
'rg-p-shell',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Backend types come from the Wails-generated models (wailsjs/go/models.ts,
|
||||
// regenerated by `wails dev` / `wails build`). This file only adds what Go
|
||||
// cannot say: string unions, and `| null` for slices Go may send as nil.
|
||||
import { app, config, driver, host, installer, plugin, reims, runtime, version } from '../wailsjs/go/models'
|
||||
import { app, config, driver, host, installer, opencore, plugin, reims, runtime, version } from '../wailsjs/go/models'
|
||||
|
||||
/** A generated class as a plain data shape (no convertValues helper). */
|
||||
type Model<T> = Omit<T, 'convertValues'>
|
||||
@@ -47,7 +47,8 @@ export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
channel: 'stable' | 'alpha'
|
||||
}
|
||||
|
||||
export type VMListItem = Model<reims.VMListItem> & {
|
||||
export type VMListItem = Model<driver.VMListItem> & {
|
||||
driver_id?: string
|
||||
state: 'running' | 'stopped' | 'suspended' | 'broken'
|
||||
}
|
||||
|
||||
@@ -65,6 +66,7 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
|
||||
export type AppUpdateInfo = version.UpdateInfo
|
||||
export type SuspendInfo = reims.SuspendInfo
|
||||
export type VMDetail = reims.VMDetail
|
||||
export type SMBIOSIdentity = opencore.SMBIOSIdentity
|
||||
export type VMStats = app.VMStats
|
||||
export type VMNetworkSettings = Model<app.VMNetworkSettings>
|
||||
export type VMNetworkPlan = Model<app.VMNetworkPlan>
|
||||
@@ -82,9 +84,9 @@ export type VMAffinityStatus = Omit<Model<app.VMAffinityStatus>, 'mode' | 'effec
|
||||
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
|
||||
export type VMThumbnail = app.VMThumbnail
|
||||
export type ValidationIssue = reims.ValidationIssue
|
||||
export type DiskResizeResult = reims.DiskResizeResult
|
||||
export type DiskCompactResult = reims.DiskCompactResult
|
||||
export type DiskSnapshot = reims.DiskSnapshot
|
||||
export type DiskResizeResult = driver.DiskResizeResult
|
||||
export type DiskCompactResult = driver.DiskCompactResult
|
||||
export type DiskSnapshot = driver.DiskSnapshot
|
||||
export type StorageBreakdown = Model<app.StorageBreakdown>
|
||||
export type SetOpts = reims.SetOpts
|
||||
|
||||
|
||||
+82
-56
@@ -14,30 +14,44 @@ interface ConfirmDialogProps {
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{title}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{description}</Alert.Description>
|
||||
{children}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><Button>{cancelLabel}</Button></Alert.Cancel>
|
||||
<Alert.Action asChild><Button variant="danger" onClick={onConfirm}>{confirmLabel}</Button></Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => {
|
||||
const prevFocusRef = React.useRef<HTMLElement | null>(
|
||||
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null,
|
||||
)
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content
|
||||
className="dialog sm"
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
const prev = prevFocusRef.current
|
||||
if (prev?.isConnected) prev.focus({ preventScroll: true })
|
||||
}}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{title}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{description}</Alert.Description>
|
||||
{children}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><Button>{cancelLabel}</Button></Alert.Cancel>
|
||||
<Alert.Action asChild><Button variant="danger" onClick={onConfirm}>{confirmLabel}</Button></Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
subtitle?: string
|
||||
closeLabel: string
|
||||
/** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */
|
||||
/** While false, Esc / ✕ are ignored (e.g. during a create). */
|
||||
dismissable?: boolean
|
||||
onClose: () => void
|
||||
/** Extra class on the dialog box, e.g. a wider variant. */
|
||||
@@ -46,41 +60,53 @@ interface Props {
|
||||
}
|
||||
|
||||
/** Modal frame: head with title and ✕; children supply body/steps/foot sections. */
|
||||
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => (
|
||||
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
|
||||
<RDialog.Portal>
|
||||
<RDialog.Overlay className="overlay" />
|
||||
<RDialog.Content
|
||||
className={className ? `dialog ${className}` : 'dialog'}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
// Focus the first enabled form field, or the dialog container itself when there is
|
||||
// none, so the top-right ✕ close button's tooltip never pops on open.
|
||||
onOpenAutoFocus={(e) => {
|
||||
const root = e.currentTarget as HTMLElement | null
|
||||
if (!root) return
|
||||
e.preventDefault()
|
||||
const first = root.querySelector<HTMLElement>(
|
||||
'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)',
|
||||
)
|
||||
if (first) {
|
||||
first.focus({ preventScroll: true })
|
||||
}
|
||||
if (!root.contains(document.activeElement)) {
|
||||
root.focus({ preventScroll: true })
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="dialog-head">
|
||||
<div>
|
||||
<RDialog.Title className="dialog-title">{title}</RDialog.Title>
|
||||
{subtitle ? <RDialog.Description className="dialog-desc">{subtitle}</RDialog.Description> : <RDialog.Description />}
|
||||
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => {
|
||||
const prevFocusRef = React.useRef<HTMLElement | null>(
|
||||
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null,
|
||||
)
|
||||
return (
|
||||
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
|
||||
<RDialog.Portal>
|
||||
<RDialog.Overlay className="overlay" />
|
||||
<RDialog.Content
|
||||
className={className ? `dialog ${className}` : 'dialog'}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
// Focus the first enabled form field, or the dialog container itself when there is
|
||||
// none, so the top-right ✕ close button's tooltip never pops on open.
|
||||
onOpenAutoFocus={(e) => {
|
||||
const root = e.currentTarget as HTMLElement | null
|
||||
if (!root) return
|
||||
e.preventDefault()
|
||||
const first = root.querySelector<HTMLElement>(
|
||||
'input:not(:disabled):not([type="hidden"]):not([type="radio"]:not(:checked)), select:not(:disabled), textarea:not(:disabled)',
|
||||
)
|
||||
if (first) {
|
||||
first.focus({ preventScroll: true })
|
||||
}
|
||||
if (!root.contains(document.activeElement)) {
|
||||
root.focus({ preventScroll: true })
|
||||
}
|
||||
}}
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
const prev = prevFocusRef.current
|
||||
if (prev?.isConnected) prev.focus({ preventScroll: true })
|
||||
}}
|
||||
>
|
||||
<div className="dialog-head">
|
||||
<div>
|
||||
<RDialog.Title className="dialog-title">{title}</RDialog.Title>
|
||||
{subtitle ? <RDialog.Description className="dialog-desc">{subtitle}</RDialog.Description> : <RDialog.Description />}
|
||||
</div>
|
||||
<RDialog.Close asChild>
|
||||
<IconButton label={closeLabel} icon={<X size={16} />} disabled={!dismissable} />
|
||||
</RDialog.Close>
|
||||
</div>
|
||||
<RDialog.Close asChild>
|
||||
<IconButton label={closeLabel} icon={<X size={16} />} disabled={!dismissable} />
|
||||
</RDialog.Close>
|
||||
</div>
|
||||
{children}
|
||||
</RDialog.Content>
|
||||
</RDialog.Portal>
|
||||
</RDialog.Root>
|
||||
)
|
||||
{children}
|
||||
</RDialog.Content>
|
||||
</RDialog.Portal>
|
||||
</RDialog.Root>
|
||||
)
|
||||
}
|
||||
@@ -122,7 +122,10 @@ export function Segmented<V extends string | number>({ options, value, onChange,
|
||||
return next
|
||||
})
|
||||
}
|
||||
useLayoutEffect(measure, [value, options])
|
||||
const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}`).join('\x1e')
|
||||
const docDir = typeof document !== 'undefined' ? document.documentElement.dir : ''
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useLayoutEffect(measure, [value, optionsSig, wide, docDir])
|
||||
useEffect(() => {
|
||||
if (!box.current || typeof ResizeObserver === 'undefined') return
|
||||
let raf = 0
|
||||
@@ -142,12 +145,13 @@ export function Segmented<V extends string | number>({ options, value, onChange,
|
||||
}, [])
|
||||
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' && e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
|
||||
e.preventDefault()
|
||||
const enabled = options.filter((o) => !o.disabled)
|
||||
const i = enabled.findIndex((o) => o.value === value)
|
||||
const isRTL = box.current ? getComputedStyle(box.current).direction === 'rtl' : false
|
||||
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
|
||||
const forward = e.key === 'ArrowDown' || (e.key === 'ArrowRight' && !isRTL) || (e.key === 'ArrowLeft' && isRTL)
|
||||
const delta = forward ? 1 : -1
|
||||
const next = enabled[(i + delta + enabled.length) % enabled.length]
|
||||
if (next) {
|
||||
onChange(next.value)
|
||||
@@ -384,8 +388,9 @@ export function PopupSelect<V extends string>({ value, options, onChange, label,
|
||||
id?: string
|
||||
}) {
|
||||
const cur = options.find((o) => o.value === value)
|
||||
const dir: 'ltr' | 'rtl' = typeof document !== 'undefined' && document.documentElement.dir === 'rtl' ? 'rtl' : 'ltr'
|
||||
return (
|
||||
<Menu.Root modal={false}>
|
||||
<Menu.Root dir={dir} modal={false}>
|
||||
<Menu.Trigger asChild>
|
||||
<button type="button" id={id} className={`popup-btn${wide ? ' popup-wide' : ''}`} aria-label={label}>
|
||||
<span className="popup-value">
|
||||
|
||||
@@ -154,6 +154,8 @@ export const api = {
|
||||
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
|
||||
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
|
||||
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
|
||||
|
||||
Vendored
+77
-3
@@ -1,6 +1,7 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
import {app} from '../models';
|
||||
import {opencore} from '../models';
|
||||
import {reims} from '../models';
|
||||
import {plugin} from '../models';
|
||||
import {version} from '../models';
|
||||
@@ -8,9 +9,12 @@ import {driver} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
import {http} from '../models';
|
||||
import {dataroot} from '../models';
|
||||
|
||||
export function ApplyVMNetwork(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkSettings>;
|
||||
|
||||
export function ApplyVMSMBIOS(arg1:string,arg2:opencore.SMBIOSIdentity):Promise<opencore.SMBIOSIdentity>;
|
||||
|
||||
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
|
||||
|
||||
export function AttachGuestTools(arg1:string):Promise<void>;
|
||||
@@ -29,14 +33,22 @@ export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
|
||||
|
||||
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
|
||||
export function CloneVMCoWWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CompactVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshot(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshotWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
export function CreateVMWithDriver(arg1:driver.CreateRequest):Promise<void>;
|
||||
@@ -47,8 +59,12 @@ export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DeleteVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function DeliverFileToGuest(arg1:string):Promise<string>;
|
||||
|
||||
export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Array<string>>;
|
||||
@@ -59,6 +75,8 @@ export function DisablePlugin(arg1:string):Promise<void>;
|
||||
|
||||
export function DiscardSuspend(arg1:string):Promise<void>;
|
||||
|
||||
export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
|
||||
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
|
||||
@@ -71,6 +89,8 @@ export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function EnableWHPX():Promise<void>;
|
||||
@@ -79,10 +99,18 @@ export function EnterRecovery(arg1:string):Promise<void>;
|
||||
|
||||
export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function ExportDiagnosticsWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindow(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindowWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ForceQuitApp():Promise<void>;
|
||||
|
||||
export function GenerateVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
|
||||
|
||||
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
|
||||
|
||||
export function GetLicenseTexts():Promise<app.LicenseTexts>;
|
||||
@@ -99,10 +127,14 @@ export function GetTasks():Promise<Array<app.Task>>;
|
||||
|
||||
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
|
||||
|
||||
export function GetVMMacOS(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkPlan>;
|
||||
@@ -113,12 +145,20 @@ export function GetVMNote(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
|
||||
|
||||
export function GetVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
|
||||
|
||||
export function GetVMSSHUser(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMSSHUserWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMStatsWithDriver(arg1:string,arg2:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function InspectPluginArchive(arg1:string):Promise<plugin.ScanReport>;
|
||||
|
||||
export function InstallAppUpdate():Promise<void>;
|
||||
@@ -151,7 +191,9 @@ export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
|
||||
|
||||
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
|
||||
export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
@@ -159,6 +201,8 @@ export function OpenQQGroup():Promise<void>;
|
||||
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenSSHTerminalWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
@@ -167,6 +211,8 @@ export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
|
||||
|
||||
export function PeekPluginMarket(arg1:string,arg2:string):Promise<plugin.MarketBrowseResult>;
|
||||
@@ -185,20 +231,32 @@ export function ReadPluginLog(arg1:string):Promise<string>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
|
||||
|
||||
export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<string>;
|
||||
|
||||
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function RemoveRuntime(arg1:string):Promise<void>;
|
||||
|
||||
export function ReopenDataRoot(arg1:boolean):Promise<dataroot.Status>;
|
||||
|
||||
export function RequestClose():Promise<void>;
|
||||
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskResizeResult>;
|
||||
|
||||
export function ResizeVMDiskWithDriver(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
|
||||
|
||||
export function RestartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function RestartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function ResumeVM(arg1:string):Promise<void>;
|
||||
|
||||
export function ResumeVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
|
||||
|
||||
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
|
||||
@@ -221,30 +279,44 @@ export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, an
|
||||
|
||||
export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function ShowMainWindow():Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
|
||||
|
||||
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
|
||||
|
||||
export function SuspendVM(arg1:string):Promise<void>;
|
||||
|
||||
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
|
||||
|
||||
export function ToggleVMFullscreenWithDriver(arg1:string,arg2:string):Promise<boolean>;
|
||||
|
||||
export function TypeClipboard(arg1:string):Promise<number>;
|
||||
|
||||
export function TypeText(arg1:string,arg2:string):Promise<number>;
|
||||
@@ -258,3 +330,5 @@ export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.Valida
|
||||
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function WriteSSHConfigWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
@@ -6,6 +6,10 @@ export function ApplyVMNetwork(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ApplyVMNetwork'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ApplyVMSMBIOS(arg1, arg2) {
|
||||
return window['go']['app']['App']['ApplyVMSMBIOS'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ApplyVMSettings(arg1) {
|
||||
return window['go']['app']['App']['ApplyVMSettings'](arg1);
|
||||
}
|
||||
@@ -42,10 +46,18 @@ export function CloneVMCoW(arg1, arg2) {
|
||||
return window['go']['app']['App']['CloneVMCoW'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CloneVMCoWWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CloneVMCoWWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CompactVMDisk(arg1) {
|
||||
return window['go']['app']['App']['CompactVMDisk'](arg1);
|
||||
}
|
||||
|
||||
export function CompactVMDiskWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CompleteSetup(arg1) {
|
||||
return window['go']['app']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
@@ -54,10 +66,18 @@ export function CopyVMScreenshot(arg1) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
|
||||
}
|
||||
|
||||
export function CopyVMScreenshotWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['CopyVMScreenshotWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CreateSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['app']['App']['CreateVM'](arg1);
|
||||
}
|
||||
@@ -78,10 +98,18 @@ export function DeleteSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeleteSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeleteVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteVMWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeliverFileToGuest(arg1) {
|
||||
return window['go']['app']['App']['DeliverFileToGuest'](arg1);
|
||||
}
|
||||
@@ -102,6 +130,10 @@ export function DiscardSuspend(arg1) {
|
||||
return window['go']['app']['App']['DiscardSuspend'](arg1);
|
||||
}
|
||||
|
||||
export function DiscardSuspendWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['DiscardSuspendWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['app']['App']['DismissTask'](arg1);
|
||||
}
|
||||
@@ -126,6 +158,10 @@ export function EjectInstaller(arg1) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstallerWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['EjectInstallerWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function EnablePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['EnablePlugin'](arg1, arg2);
|
||||
}
|
||||
@@ -142,6 +178,10 @@ export function ExportDiagnostics(arg1) {
|
||||
return window['go']['app']['App']['ExportDiagnostics'](arg1);
|
||||
}
|
||||
|
||||
export function ExportDiagnosticsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ExportDiagnosticsWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function FinishInstall(arg1) {
|
||||
return window['go']['app']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
@@ -150,6 +190,18 @@ export function FocusVMWindow(arg1) {
|
||||
return window['go']['app']['App']['FocusVMWindow'](arg1);
|
||||
}
|
||||
|
||||
export function FocusVMWindowWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['FocusVMWindowWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ForceQuitApp() {
|
||||
return window['go']['app']['App']['ForceQuitApp']();
|
||||
}
|
||||
|
||||
export function GenerateVMSMBIOS(arg1) {
|
||||
return window['go']['app']['App']['GenerateVMSMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function GetActiveTheme() {
|
||||
return window['go']['app']['App']['GetActiveTheme']();
|
||||
}
|
||||
@@ -182,6 +234,10 @@ export function GetVMAffinity(arg1) {
|
||||
return window['go']['app']['App']['GetVMAffinity'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMAffinityWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['app']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
@@ -190,6 +246,10 @@ export function GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMInfo(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMInfo'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMMacOS(arg1) {
|
||||
return window['go']['app']['App']['GetVMMacOS'](arg1);
|
||||
}
|
||||
@@ -210,18 +270,34 @@ export function GetVMPluginSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMPluginSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSMBIOS(arg1) {
|
||||
return window['go']['app']['App']['GetVMSMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSSHUser(arg1) {
|
||||
return window['go']['app']['App']['GetVMSSHUser'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSSHUserWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMSSHUserWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMStats(arg1) {
|
||||
return window['go']['app']['App']['GetVMStats'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMStatsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMStatsWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMThumbnail(arg1) {
|
||||
return window['go']['app']['App']['GetVMThumbnail'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMThumbnailWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMThumbnailWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function InspectPluginArchive(arg1) {
|
||||
return window['go']['app']['App']['InspectPluginArchive'](arg1);
|
||||
}
|
||||
@@ -290,6 +366,10 @@ export function ListSnapshots(arg1) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1);
|
||||
}
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
@@ -302,6 +382,10 @@ export function OpenSSHTerminal(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenSSHTerminalWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenSSHTerminalWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
return window['go']['app']['App']['OpenSharedFolder'](arg1);
|
||||
}
|
||||
@@ -318,6 +402,10 @@ export function OpenVSCodeSSH(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenVSCodeSSHWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function PanelBridgeCall(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3);
|
||||
}
|
||||
@@ -354,6 +442,10 @@ export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ReadVMLogsWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ReadVMLogsWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function RemovePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['RemovePlugin'](arg1, arg2);
|
||||
}
|
||||
@@ -362,6 +454,10 @@ export function RemoveRuntime(arg1) {
|
||||
return window['go']['app']['App']['RemoveRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ReopenDataRoot(arg1) {
|
||||
return window['go']['app']['App']['ReopenDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function RequestClose() {
|
||||
return window['go']['app']['App']['RequestClose']();
|
||||
}
|
||||
@@ -370,18 +466,34 @@ export function ResizeVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ResizeVMDiskWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ResizeVMDiskWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function RestartVM(arg1) {
|
||||
return window['go']['app']['App']['RestartVM'](arg1);
|
||||
}
|
||||
|
||||
export function RestartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestartVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestoreSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestoreSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['RestoreSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ResumeVM(arg1) {
|
||||
return window['go']['app']['App']['ResumeVM'](arg1);
|
||||
}
|
||||
|
||||
export function ResumeVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResumeVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SaveCustomThemeScheme(arg1) {
|
||||
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
|
||||
}
|
||||
@@ -426,10 +538,18 @@ export function SetRuntimeChannel(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
|
||||
}
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1) {
|
||||
return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function SetVMAffinity(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMAffinityWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
@@ -442,6 +562,10 @@ export function SetVMSSHUser(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMSSHUserWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMSSHUserWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ShowMainWindow() {
|
||||
return window['go']['app']['App']['ShowMainWindow']();
|
||||
}
|
||||
@@ -450,10 +574,18 @@ export function StartVM(arg1) {
|
||||
return window['go']['app']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['StartVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['StopVMWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SuggestDataRoots() {
|
||||
return window['go']['app']['App']['SuggestDataRoots']();
|
||||
}
|
||||
@@ -466,6 +598,10 @@ export function SuspendVM(arg1) {
|
||||
return window['go']['app']['App']['SuspendVM'](arg1);
|
||||
}
|
||||
|
||||
export function SuspendVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ToggleBorderless(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
|
||||
}
|
||||
@@ -474,6 +610,10 @@ export function ToggleVMFullscreen(arg1) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreen'](arg1);
|
||||
}
|
||||
|
||||
export function ToggleVMFullscreenWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreenWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeClipboard(arg1) {
|
||||
return window['go']['app']['App']['TypeClipboard'](arg1);
|
||||
}
|
||||
@@ -501,3 +641,7 @@ export function ValidateSet(arg1) {
|
||||
export function WriteSSHConfig(arg1, arg2) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function WriteSSHConfigWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['WriteSSHConfigWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
+212
-82
@@ -1,18 +1,21 @@
|
||||
export namespace app {
|
||||
|
||||
export class AppState {
|
||||
quit_mode?: string;
|
||||
config?: config.Config;
|
||||
host: host.Report;
|
||||
optimizations: host.Optimization[];
|
||||
runtimes: runtime.Installed[];
|
||||
active_runtime?: runtime.Installed;
|
||||
can_suspend: boolean;
|
||||
vms: reims.VMListItem[];
|
||||
vms: driver.VMListItem[];
|
||||
transitions: Record<string, string>;
|
||||
pending_changes: Record<string, Array<PendingChange>>;
|
||||
active_guides?: string[];
|
||||
install_guide_enabled?: boolean;
|
||||
needs_setup: boolean;
|
||||
data_root_status: dataroot.Status;
|
||||
data_root_message?: string;
|
||||
app_version: string;
|
||||
safe_mode?: boolean;
|
||||
plugin_crash_detected?: boolean;
|
||||
@@ -26,18 +29,21 @@ export namespace app {
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.quit_mode = source["quit_mode"];
|
||||
this.config = this.convertValues(source["config"], config.Config);
|
||||
this.host = this.convertValues(source["host"], host.Report);
|
||||
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
|
||||
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.can_suspend = source["can_suspend"];
|
||||
this.vms = this.convertValues(source["vms"], reims.VMListItem);
|
||||
this.vms = this.convertValues(source["vms"], driver.VMListItem);
|
||||
this.transitions = source["transitions"];
|
||||
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
|
||||
this.active_guides = source["active_guides"];
|
||||
this.install_guide_enabled = source["install_guide_enabled"];
|
||||
this.needs_setup = source["needs_setup"];
|
||||
this.data_root_status = this.convertValues(source["data_root_status"], dataroot.Status);
|
||||
this.data_root_message = source["data_root_message"];
|
||||
this.app_version = source["app_version"];
|
||||
this.safe_mode = source["safe_mode"];
|
||||
this.plugin_crash_detected = source["plugin_crash_detected"];
|
||||
@@ -181,11 +187,11 @@ export namespace app {
|
||||
description: string;
|
||||
status: string;
|
||||
speed: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new NetworkAdapter(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.index = source["index"];
|
||||
@@ -421,11 +427,11 @@ export namespace app {
|
||||
export class VMNetworkPlan {
|
||||
npcap_installed: boolean;
|
||||
running_vms: string[];
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMNetworkPlan(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.npcap_installed = source["npcap_installed"];
|
||||
@@ -441,11 +447,11 @@ export namespace app {
|
||||
notes: string[];
|
||||
mode: string;
|
||||
running: boolean;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMNetworkSettings(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.adapters = this.convertValues(source["adapters"], NetworkAdapter);
|
||||
@@ -457,7 +463,7 @@ export namespace app {
|
||||
this.mode = source["mode"];
|
||||
this.running = source["running"];
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -553,6 +559,7 @@ export namespace config {
|
||||
runtime_channel?: string;
|
||||
app_update_channel?: string;
|
||||
minimize_to_tray?: boolean;
|
||||
sync_host_memory_smbios?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Config(source);
|
||||
@@ -568,6 +575,36 @@ export namespace config {
|
||||
this.runtime_channel = source["runtime_channel"];
|
||||
this.app_update_channel = source["app_update_channel"];
|
||||
this.minimize_to_tray = source["minimize_to_tray"];
|
||||
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace dataroot {
|
||||
|
||||
export class Status {
|
||||
dir: string;
|
||||
read_only: boolean;
|
||||
reason?: string;
|
||||
detail?: string;
|
||||
version: number;
|
||||
known: number;
|
||||
migrated?: string[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Status(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.dir = source["dir"];
|
||||
this.read_only = source["read_only"];
|
||||
this.reason = source["reason"];
|
||||
this.detail = source["detail"];
|
||||
this.version = source["version"];
|
||||
this.known = source["known"];
|
||||
this.migrated = source["migrated"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,6 +630,60 @@ export namespace driver {
|
||||
this.options = source["options"];
|
||||
}
|
||||
}
|
||||
export class DiskCompactResult {
|
||||
path: string;
|
||||
before_bytes: number;
|
||||
after_bytes: number;
|
||||
reclaimed_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskCompactResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.before_bytes = source["before_bytes"];
|
||||
this.after_bytes = source["after_bytes"];
|
||||
this.reclaimed_bytes = source["reclaimed_bytes"];
|
||||
}
|
||||
}
|
||||
export class DiskResizeResult {
|
||||
path: string;
|
||||
old_virtual_bytes: number;
|
||||
new_virtual_bytes: number;
|
||||
guest_expand_cmd: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskResizeResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.old_virtual_bytes = source["old_virtual_bytes"];
|
||||
this.new_virtual_bytes = source["new_virtual_bytes"];
|
||||
this.guest_expand_cmd = source["guest_expand_cmd"];
|
||||
}
|
||||
}
|
||||
export class DiskSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: number;
|
||||
vm_state_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskSnapshot(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.name = source["name"];
|
||||
this.created_at = source["created_at"];
|
||||
this.vm_state_bytes = source["vm_state_bytes"];
|
||||
}
|
||||
}
|
||||
export class DriverSummary {
|
||||
id: string;
|
||||
name: plugin.LocalizedText;
|
||||
@@ -637,6 +728,66 @@ export namespace driver {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class VMInfo {
|
||||
name: string;
|
||||
driver_id: string;
|
||||
driver_name?: string;
|
||||
state: string;
|
||||
pid?: number;
|
||||
cpus?: number;
|
||||
memory?: string;
|
||||
disk_summary?: string;
|
||||
disk_path?: string;
|
||||
directory?: string;
|
||||
network?: boolean;
|
||||
ssh_port?: number;
|
||||
capabilities?: string[];
|
||||
driver_data?: Record<string, any>;
|
||||
driver_unavailable?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.driver_id = source["driver_id"];
|
||||
this.driver_name = source["driver_name"];
|
||||
this.state = source["state"];
|
||||
this.pid = source["pid"];
|
||||
this.cpus = source["cpus"];
|
||||
this.memory = source["memory"];
|
||||
this.disk_summary = source["disk_summary"];
|
||||
this.disk_path = source["disk_path"];
|
||||
this.directory = source["directory"];
|
||||
this.network = source["network"];
|
||||
this.ssh_port = source["ssh_port"];
|
||||
this.capabilities = source["capabilities"];
|
||||
this.driver_data = source["driver_data"];
|
||||
this.driver_unavailable = source["driver_unavailable"];
|
||||
}
|
||||
}
|
||||
export class VMListItem {
|
||||
name: string;
|
||||
driver_id?: string;
|
||||
dir: string;
|
||||
pid?: number;
|
||||
state: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMListItem(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.driver_id = source["driver_id"];
|
||||
this.dir = source["dir"];
|
||||
this.pid = source["pid"];
|
||||
this.state = source["state"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -754,6 +905,22 @@ export namespace host {
|
||||
this.compat_detail = source["compat_detail"];
|
||||
}
|
||||
}
|
||||
export class HostMemorySpec {
|
||||
speed_mhz?: number;
|
||||
memory_type?: number;
|
||||
type_name?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new HostMemorySpec(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.speed_mhz = source["speed_mhz"];
|
||||
this.memory_type = source["memory_type"];
|
||||
this.type_name = source["type_name"];
|
||||
}
|
||||
}
|
||||
export class LogicalCPUInfo {
|
||||
index: number;
|
||||
core_index: number;
|
||||
@@ -832,6 +999,7 @@ export namespace host {
|
||||
total_ram_gb: number;
|
||||
avail_ram_gb: number;
|
||||
memory_load_pct: number;
|
||||
memory_spec?: HostMemorySpec;
|
||||
commit_avail_gb: number;
|
||||
commit_limit_gb: number;
|
||||
data_root: string;
|
||||
@@ -842,6 +1010,7 @@ export namespace host {
|
||||
whpx_caps: WHPXCapabilities;
|
||||
needs_cold_reboot_workaround: boolean;
|
||||
gpus: GPUInfo[];
|
||||
vulkan_probe_error?: string;
|
||||
recommended_gpu?: GPUInfo;
|
||||
displays?: DisplayInfo[];
|
||||
primary_display?: DisplayInfo;
|
||||
@@ -877,6 +1046,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_spec = this.convertValues(source["memory_spec"], HostMemorySpec);
|
||||
this.commit_avail_gb = source["commit_avail_gb"];
|
||||
this.commit_limit_gb = source["commit_limit_gb"];
|
||||
this.data_root = source["data_root"];
|
||||
@@ -887,6 +1057,7 @@ export namespace host {
|
||||
this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities);
|
||||
this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"];
|
||||
this.gpus = this.convertValues(source["gpus"], GPUInfo);
|
||||
this.vulkan_probe_error = source["vulkan_probe_error"];
|
||||
this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo);
|
||||
this.displays = this.convertValues(source["displays"], DisplayInfo);
|
||||
this.primary_display = this.convertValues(source["primary_display"], DisplayInfo);
|
||||
@@ -972,6 +1143,31 @@ export namespace installer {
|
||||
|
||||
}
|
||||
|
||||
export namespace opencore {
|
||||
|
||||
export class SMBIOSIdentity {
|
||||
model: string;
|
||||
serial: string;
|
||||
mlb: string;
|
||||
uuid: string;
|
||||
rom?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new SMBIOSIdentity(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.model = source["model"];
|
||||
this.serial = source["serial"];
|
||||
this.mlb = source["mlb"];
|
||||
this.uuid = source["uuid"];
|
||||
this.rom = source["rom"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace plugin {
|
||||
|
||||
export class CustomThemeScheme {
|
||||
@@ -2280,60 +2476,6 @@ export namespace reims {
|
||||
this.start = source["start"];
|
||||
}
|
||||
}
|
||||
export class DiskCompactResult {
|
||||
path: string;
|
||||
before_bytes: number;
|
||||
after_bytes: number;
|
||||
reclaimed_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskCompactResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.before_bytes = source["before_bytes"];
|
||||
this.after_bytes = source["after_bytes"];
|
||||
this.reclaimed_bytes = source["reclaimed_bytes"];
|
||||
}
|
||||
}
|
||||
export class DiskResizeResult {
|
||||
path: string;
|
||||
old_virtual_bytes: number;
|
||||
new_virtual_bytes: number;
|
||||
guest_expand_cmd: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskResizeResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.old_virtual_bytes = source["old_virtual_bytes"];
|
||||
this.new_virtual_bytes = source["new_virtual_bytes"];
|
||||
this.guest_expand_cmd = source["guest_expand_cmd"];
|
||||
}
|
||||
}
|
||||
export class DiskSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: number;
|
||||
vm_state_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskSnapshot(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.name = source["name"];
|
||||
this.created_at = source["created_at"];
|
||||
this.vm_state_bytes = source["vm_state_bytes"];
|
||||
}
|
||||
}
|
||||
export class SetOpts {
|
||||
name: string;
|
||||
cpus?: number;
|
||||
@@ -2523,7 +2665,7 @@ export namespace reims {
|
||||
this.guest_lang = source["guest_lang"];
|
||||
this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -2542,24 +2684,6 @@ export namespace reims {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class VMListItem {
|
||||
name: string;
|
||||
dir: string;
|
||||
pid?: number;
|
||||
state: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMListItem(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.dir = source["dir"];
|
||||
this.pid = source["pid"];
|
||||
this.state = source["state"];
|
||||
}
|
||||
}
|
||||
export class ValidationIssue {
|
||||
field: string;
|
||||
code?: string;
|
||||
@@ -2722,6 +2846,9 @@ export namespace runtime {
|
||||
name_en: string;
|
||||
required_files?: string[];
|
||||
default_api_version?: string;
|
||||
control_executable?: string;
|
||||
utility_executable?: string;
|
||||
control_qemu_env?: string;
|
||||
builtin?: boolean;
|
||||
plugin_id?: string;
|
||||
|
||||
@@ -2737,6 +2864,9 @@ export namespace runtime {
|
||||
this.name_en = source["name_en"];
|
||||
this.required_files = source["required_files"];
|
||||
this.default_api_version = source["default_api_version"];
|
||||
this.control_executable = source["control_executable"];
|
||||
this.utility_executable = source["utility_executable"];
|
||||
this.control_qemu_env = source["control_qemu_env"];
|
||||
this.builtin = source["builtin"];
|
||||
this.plugin_id = source["plugin_id"];
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
@@ -57,7 +57,7 @@ func (a *App) findRunningVMPID(ctx context.Context, name string) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
cfg := vmstart.ReadVMAffinity(detail.Directory)
|
||||
res := vmstart.ResolveVMAffinity(cfg, globalAutoPin, rep, detail.CPUs)
|
||||
savedCPUs := cfg.CPUs
|
||||
@@ -98,7 +98,14 @@ func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin
|
||||
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
|
||||
// effective CPU set, and live QEMU process affinity mask when running.
|
||||
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
return a.GetVMAffinityWithDriver("", name)
|
||||
}
|
||||
func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
detail := vm
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
@@ -109,7 +116,12 @@ func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
rep := host.Inspect(root)
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
if listed, ok := a.polledVMForDriver(vm.DriverID, name); ok && listed.PID != nil {
|
||||
pid = *listed.PID
|
||||
}
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
}
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
@@ -117,7 +129,14 @@ func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
// SetVMAffinity saves a VM's processor affinity mapping and immediately applies
|
||||
// it (plus EcoQoS power-throttling control) to the running QEMU process if active.
|
||||
func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
return a.SetVMAffinityWithDriver("", name, req)
|
||||
}
|
||||
func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
detail := vm
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
@@ -142,12 +161,17 @@ func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus
|
||||
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
if listed, ok := a.polledVMForDriver(vm.DriverID, name); ok && listed.PID != nil {
|
||||
pid = *listed.PID
|
||||
}
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
}
|
||||
if pid > 0 {
|
||||
line, applyErr := vmstart.ApplyVMAffinity(loc, rep, detail.Directory, globalAutoPin, pid, detail.CPUs, true)
|
||||
if line != "" {
|
||||
a.emitLog(name, line)
|
||||
a.emitVMLogForDriver(driverID, name, line)
|
||||
}
|
||||
if applyErr != nil {
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
@@ -21,7 +21,7 @@ func TestBuildVMAffinityStatus(t *testing.T) {
|
||||
}
|
||||
|
||||
rep := host.Report{LogicalCPUs: 16}
|
||||
st := buildVMAffinityStatus(reims.VMDetail{
|
||||
st := buildVMAffinityStatus(driver.VMInfo{
|
||||
Name: "test-vm",
|
||||
Directory: dir,
|
||||
CPUs: 6,
|
||||
|
||||
+171
-794
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestPolledVMsReusesFreshPoll(t *testing.T) {
|
||||
@@ -82,11 +82,11 @@ func TestReleaseVMTypingDrainsAndRemovesQueue(t *testing.T) {
|
||||
a := &App{}
|
||||
typing.mu.Lock()
|
||||
ch := make(chan remoteTextItem)
|
||||
typing.remoteQueues[name] = ch
|
||||
typing.lastHintAt[name] = time.Now()
|
||||
typing.remoteQueues[vmKey(name)] = ch
|
||||
typing.lastHintAt[vmKey(name)] = time.Now()
|
||||
typing.mu.Unlock()
|
||||
go func() {
|
||||
a.runRemoteTextQueue(name, ch)
|
||||
a.runRemoteTextQueue(vmKey(name), name, ch)
|
||||
close(done)
|
||||
}()
|
||||
releaseVMTyping(name)
|
||||
|
||||
@@ -17,14 +17,14 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/fetch"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/selfupdate"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
// appUpdateTaskKind is the task kind the frontend watches for update progress.
|
||||
// appUpdateTaskKind is the task kind the frontend watches for update host.
|
||||
const appUpdateTaskKind = "app-update"
|
||||
|
||||
// appUpdateReady is the verified download InstallAppUpdate swaps in.
|
||||
@@ -68,11 +68,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
if err := a.updateSupported(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
a.mu.Unlock()
|
||||
return "", errors.New("choose a data folder first")
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -100,8 +99,8 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
go func() {
|
||||
defer cancel()
|
||||
path, sum, err := downloadAppUpdate(ctx, info, appUpdateDir(dataRoot), func(done, total int64) {
|
||||
tasks.update(id, installer.Update{
|
||||
Kind: installer.KindProgress, Step: "downloading " + info.AssetName,
|
||||
tasks.update(id, host.Update{
|
||||
Kind: host.KindProgress, Step: "downloading " + info.AssetName,
|
||||
Done: done, Total: total, Percent: percent(done, total),
|
||||
})
|
||||
})
|
||||
@@ -228,7 +227,7 @@ func (a *App) finishAppUpdateWithExe(exe string) {
|
||||
if a.launch.WaitPID == 0 {
|
||||
return
|
||||
}
|
||||
if !keepOld && dataRoot != "" {
|
||||
if !keepOld && dataRoot != "" && a.dataRootUsable() {
|
||||
_ = os.RemoveAll(appUpdateDir(dataRoot))
|
||||
}
|
||||
if keepOld {
|
||||
|
||||
+15
-138
@@ -1,153 +1,30 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"errors"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// CloneVMCoW derives a new VM instantaneously from a stopped source VM using a
|
||||
// qcow2 copy-on-write overlay (`qemu-img create -f qcow2 -b <src> -F qcow2`)
|
||||
// so the source golden disk is never mutated while the clone gets its own fresh
|
||||
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
|
||||
// CloneVMCoW derives a VM through the source VM's owning driver.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
loc := a.locale()
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if cloneName == "" {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_EMPTY_NAME", "err.clone.missing_name", nil, nil)
|
||||
}
|
||||
if strings.EqualFold(sourceName, cloneName) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_SAME_NAME", "err.clone.same_name", nil, nil)
|
||||
}
|
||||
return a.CloneVMCoWWithDriver("", sourceName, cloneName)
|
||||
}
|
||||
|
||||
func (a *App) CloneVMCoWWithDriver(driverID, sourceName, cloneName string) error {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
cfgCopy.Locale = loc
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ref := driver.VMRef{DriverID: driverID, Name: sourceName}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(driverID, cloneName, line) })
|
||||
if err := svc.CloneCoW(a.baseCtx(), ref, cloneName, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
src, release, err := vmstart.LockVM(ctx, c, sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
a.populateVMDetail(&src)
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if a.isVMSuspended(src) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if src.HasInstaller {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
srcDisk := src.Disk
|
||||
if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" {
|
||||
srcDisk = filepath.Join(src.Directory, srcDisk)
|
||||
}
|
||||
if srcDisk == "" {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if _, err := os.Stat(srcDisk); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_DISK_MISSING", "err.clone.disk_missing", i18n.Vars{"path": srcDisk}, err)
|
||||
}
|
||||
|
||||
// Validate clone name and check for name collisions.
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
nameCheck := reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, loc)
|
||||
for _, iss := range nameCheck {
|
||||
if iss.Field == "name" {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_INVALID_NAME", "validate."+iss.Code, i18n.Vars{"name": cloneName}, nil)
|
||||
}
|
||||
}
|
||||
if existing, err := c.List(ctx); err == nil {
|
||||
for _, vm := range existing {
|
||||
if strings.EqualFold(vm.Name, cloneName) {
|
||||
return i18n.NewCodedError(loc, "E_VM_NAME_TAKEN", "validate.name_taken", i18n.Vars{"name": cloneName}, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_OVERLAY_EXISTS", "err.clone.overlay_exists", i18n.Vars{"path": overlayPath}, nil)
|
||||
}
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
|
||||
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
audio := src.Audio
|
||||
network := src.Network || src.NetworkMode == "bridge"
|
||||
logs := src.Logs
|
||||
capture := src.Capture
|
||||
createOpts := reims.CreateOpts{
|
||||
Name: cloneName,
|
||||
SourceMode: "disk",
|
||||
Disk: overlayPath,
|
||||
DiskMode: "in-place",
|
||||
DiskController: src.DiskController,
|
||||
CPUs: src.CPUs,
|
||||
Memory: src.Memory,
|
||||
Graphics: src.Graphics,
|
||||
GPU: src.GPU,
|
||||
Resolution: src.Resolution,
|
||||
Displays: src.Displays,
|
||||
Capture: &capture,
|
||||
Audio: &audio,
|
||||
Network: &network,
|
||||
Logs: &logs,
|
||||
Start: false,
|
||||
}
|
||||
if err := c.Create(ctx, createOpts, w, w); err != nil {
|
||||
_ = os.Remove(overlayPath)
|
||||
return err
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
|
||||
if src.GuestLang != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
}
|
||||
}
|
||||
if werr := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); werr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy macOS release: %v", werr))
|
||||
}
|
||||
if vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if _, aerr := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); aerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy CPU affinity setting: %v", aerr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
+38
-23
@@ -9,11 +9,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -25,6 +26,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
err = networkmsg.Localize(err, a.locale())
|
||||
}
|
||||
}()
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return err
|
||||
}
|
||||
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
@@ -59,13 +63,13 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
finishTask(err)
|
||||
return err
|
||||
}
|
||||
a.emitLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
|
||||
|
||||
existingVMs, _ := c.List(ctx)
|
||||
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
|
||||
a.emitLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
||||
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
||||
} else if removed != "" {
|
||||
a.emitLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
||||
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
||||
}
|
||||
|
||||
// Ensure any requested macOS installer is downloaded via installer.Client
|
||||
@@ -86,15 +90,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
if derr != nil {
|
||||
if errors.Is(derr, context.Canceled) || ctx.Err() != nil {
|
||||
finishTask(context.Canceled)
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
return context.Canceled
|
||||
}
|
||||
finishTask(derr)
|
||||
a.emitLog(opts.Name, "Create error: "+derr.Error())
|
||||
a.emitVMLog(opts.Name, "Create error: "+derr.Error())
|
||||
return derr
|
||||
}
|
||||
if res != nil && res.Image != "" {
|
||||
a.emitLog(opts.Name, "Installer ready: "+res.Image)
|
||||
a.emitVMLog(opts.Name, "Installer ready: "+res.Image)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,17 +110,17 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) {
|
||||
if !loggedPrefetch && u.Kind == installer.KindStep {
|
||||
loggedPrefetch = true
|
||||
a.emitLog(opts.Name, opts.Name+": "+u.Message)
|
||||
a.emitVMLog(opts.Name, opts.Name+": "+u.Message)
|
||||
}
|
||||
tasks.update(taskID, u)
|
||||
})
|
||||
if perr != nil {
|
||||
if errors.Is(perr, context.Canceled) || ctx.Err() != nil {
|
||||
finishTask(context.Canceled)
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
return context.Canceled
|
||||
}
|
||||
a.emitLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
||||
a.emitVMLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +129,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) {
|
||||
convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix()))
|
||||
defer os.Remove(convertedTmp)
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if cerr := reims.ConvertDiskToQCOW2(ctx, active.QemuImgPath(), env, opts.Disk, convertedTmp, w, w); cerr != nil {
|
||||
if ctx.Err() != nil {
|
||||
@@ -133,9 +137,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
}
|
||||
finishTask(cerr)
|
||||
if errors.Is(cerr, context.Canceled) {
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
} else {
|
||||
a.emitLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
||||
a.emitVMLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
||||
}
|
||||
return cerr
|
||||
}
|
||||
@@ -150,12 +154,23 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
}
|
||||
finishTask(err)
|
||||
if errors.Is(err, context.Canceled) {
|
||||
a.emitLog(opts.Name, "Create canceled.")
|
||||
a.emitVMLog(opts.Name, "Create canceled.")
|
||||
} else {
|
||||
a.emitLog(opts.Name, "Create error: "+err.Error())
|
||||
a.emitVMLog(opts.Name, "Create error: "+err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
createdDir := strings.TrimSpace(opts.Dir)
|
||||
if det, serr := c.Show(ctx, opts.Name); serr == nil && det.Directory != "" {
|
||||
createdDir = det.Directory
|
||||
}
|
||||
if createdDir == "" {
|
||||
createdDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
||||
}
|
||||
if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil {
|
||||
finishTask(err)
|
||||
return fmt.Errorf("record VM driver ownership: %w", err)
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
@@ -164,9 +179,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
if postSet.Capture != nil && !*postSet.Capture {
|
||||
parts = append(parts, "capture=off")
|
||||
}
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
||||
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
||||
}
|
||||
}
|
||||
guestLang := strings.TrimSpace(opts.GuestLang)
|
||||
@@ -187,7 +202,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
}
|
||||
}
|
||||
if werr := writeVMMacOS(vmDir, release); werr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
|
||||
}
|
||||
if guestLang != "" {
|
||||
prep, lerr := a.prep(opts.Name)
|
||||
@@ -195,7 +210,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
|
||||
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
|
||||
}
|
||||
}
|
||||
if opts.NetworkMode == "bridge" {
|
||||
@@ -210,12 +225,12 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
}
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
if startAfterCreate && ctx.Err() == nil {
|
||||
return a.StartVM(opts.Name)
|
||||
return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// openDataRoot opens the current data folder (dataroot.Open: version check,
|
||||
// migration under the folder lock) and records whether it may be written.
|
||||
func (a *App) openDataRoot() dataroot.Status {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
return st
|
||||
}
|
||||
|
||||
func (a *App) logDataRoot(st dataroot.Status) {
|
||||
switch {
|
||||
case st.ReadOnly:
|
||||
msg := fmt.Sprintf("Data folder %s opened read-only (%s)", st.Dir, st.Reason)
|
||||
if st.Detail != "" {
|
||||
msg += ": " + st.Detail
|
||||
}
|
||||
a.emitLog("app", msg)
|
||||
case len(st.Migrated) > 0:
|
||||
a.emitLog("app", fmt.Sprintf("Data folder upgraded to layout v%d (%s)", st.Version, strings.Join(st.Migrated, ", ")))
|
||||
}
|
||||
}
|
||||
|
||||
// dataRootUsable reports whether anything may read the data folder through
|
||||
// reims-ctl or write to it: not before first-run setup has chosen a folder,
|
||||
// and not while the folder is open read-only.
|
||||
func (a *App) dataRootUsable() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return !a.needsSetup && !a.root.ReadOnly
|
||||
}
|
||||
|
||||
// requireWritableDataRoot is the guard for bindings that change the data
|
||||
// folder and can be reached without the main window, such as a VM start
|
||||
// handed over from the CLI.
|
||||
func (a *App) requireWritableDataRoot() error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.needsSetup {
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
|
||||
}
|
||||
return dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root)
|
||||
}
|
||||
|
||||
// saveConfigLocked persists a.cfg; a.mu must be held. Before first-run setup
|
||||
// a.cfg points at a suggested folder the user has not chosen, so changes stay
|
||||
// in memory until CompleteSetup writes them into the chosen folder. A folder
|
||||
// open read-only refuses the write.
|
||||
func (a *App) saveConfigLocked() error {
|
||||
if a.needsSetup {
|
||||
return nil
|
||||
}
|
||||
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
|
||||
return err
|
||||
}
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// ReopenDataRoot opens the current data folder again: after another process
|
||||
// finished upgrading it, after a failed upgrade, or with repair set, to rebuild
|
||||
// a damaged version record on the user's request. When the folder becomes
|
||||
// writable, the parts that were held back start.
|
||||
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
st := a.root
|
||||
a.mu.Unlock()
|
||||
return st, nil
|
||||
}
|
||||
dir := a.cfg.DataRoot
|
||||
wasReadOnly := a.root.ReadOnly
|
||||
a.mu.Unlock()
|
||||
|
||||
var st dataroot.Status
|
||||
if repair {
|
||||
st = dataroot.Repair(dir, version.Version)
|
||||
} else {
|
||||
st = dataroot.Open(dir, version.Version)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
|
||||
if wasReadOnly && st.Writable() {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// dataRootMessage is the localized explanation the read-only screen shows,
|
||||
// without the error code and raw detail (shown separately).
|
||||
func dataRootMessage(loc i18n.Locale, st dataroot.Status) string {
|
||||
var ce *i18n.CodedError
|
||||
if errors.As(dataroot.Error(loc, st), &ce) {
|
||||
return ce.Summary(loc)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func dirEntries(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
_ = filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil && p != dir {
|
||||
out = append(out, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Before first-run setup a.cfg only suggests a folder. Picking a language on
|
||||
// the setup screen or starting plugins must not write anything into it.
|
||||
func TestNothingWrittenBeforeSetup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dir
|
||||
a := &App{cfg: cfg, needsSetup: true}
|
||||
|
||||
if err := a.SetLocale("en-US"); err != nil {
|
||||
t.Fatalf("SetLocale before setup: %v", err)
|
||||
}
|
||||
if a.cfg.Locale != "en-US" {
|
||||
t.Fatalf("locale not kept in memory: %q", a.cfg.Locale)
|
||||
}
|
||||
a.initPlugins()
|
||||
if a.pluginMgr != nil {
|
||||
t.Fatal("plugins started before setup")
|
||||
}
|
||||
a.appendUICrashLog("renderer unresponsive")
|
||||
if got := dirEntries(t, dir); len(got) != 0 {
|
||||
t.Fatalf("suggested folder written before setup: %v", got)
|
||||
}
|
||||
if err := a.StartVM("mac"); err == nil {
|
||||
t.Fatal("StartVM before setup must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
// A folder written by a newer release opens read-only: settings, VM starts
|
||||
// and plugins are all refused, and the folder is left as it was.
|
||||
func TestReadOnlyFolderRefusesWrites(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
if err := os.WriteFile(cfgPath, []byte(`{"data_root": "x", "locale": "zh-CN"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, datamigrate.StampFile), []byte(`{"data_version": 999}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := dirEntries(t, dir)
|
||||
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dir
|
||||
a := &App{cfg: cfg, root: dataroot.Open(dir, version.Version)}
|
||||
if !a.root.ReadOnly {
|
||||
t.Fatalf("root = %+v, want read-only", a.root)
|
||||
}
|
||||
|
||||
if err := a.SetLocale("en-US"); err == nil {
|
||||
t.Fatal("SetLocale on a read-only folder must fail")
|
||||
}
|
||||
if raw, _ := os.ReadFile(cfgPath); string(raw) != `{"data_root": "x", "locale": "zh-CN"}` {
|
||||
t.Fatalf("config rewritten: %s", raw)
|
||||
}
|
||||
if err := a.StartVM("mac"); err == nil {
|
||||
t.Fatal("StartVM on a read-only folder must be refused")
|
||||
}
|
||||
a.initPlugins()
|
||||
if a.pluginMgr != nil {
|
||||
t.Fatal("plugins started on a read-only folder")
|
||||
}
|
||||
a.appendUICrashLog("renderer unresponsive")
|
||||
if got := dirEntries(t, dir); len(got) != len(before) {
|
||||
t.Fatalf("read-only folder changed: before %v, after %v", before, got)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
@@ -20,7 +20,8 @@ type diagnosticsBundle struct {
|
||||
HostReport host.Report
|
||||
Optimizations []host.Optimization
|
||||
Runtime *rt.Installed
|
||||
VMDetail *reims.VMDetail
|
||||
VMDetail any // legacy test/export payload; production uses VMInfo
|
||||
VMInfo *driver.VMInfo
|
||||
SerialLog string
|
||||
QEMULog string
|
||||
AppLogs []string
|
||||
@@ -41,7 +42,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write([]byte(reims.RedactText(content)))
|
||||
_, err = w.Write([]byte(host.RedactText(content)))
|
||||
return err
|
||||
}
|
||||
addJSON := func(name string, v any) error {
|
||||
@@ -57,7 +58,7 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
"host": b.HostReport,
|
||||
"optimizations": b.Optimizations,
|
||||
}
|
||||
if code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" {
|
||||
if code, detail := host.DiagnoseGPULog(b.QEMULog); code != "" {
|
||||
hostSummary["gpu_diagnosis"] = map[string]string{
|
||||
"code": code,
|
||||
"detail": detail,
|
||||
@@ -76,10 +77,14 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
}
|
||||
}
|
||||
if b.VMDetail != nil {
|
||||
sanitized := *b.VMDetail
|
||||
sanitized.NetworkSummary = reims.RedactLogLine(sanitized.NetworkSummary)
|
||||
sanitized.ExtraArgs = reims.RedactLogLine(sanitized.ExtraArgs)
|
||||
if err := addJSON("vm-detail.json", sanitized); err != nil {
|
||||
if err := addJSON("vm-detail.json", b.VMDetail); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if b.VMInfo != nil {
|
||||
if err := addJSON("vm-info.json", b.VMInfo); err != nil {
|
||||
_ = zw.Close()
|
||||
_ = f.Close()
|
||||
return err
|
||||
@@ -120,52 +125,48 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// ExportDiagnostics collects a redacted troubleshooting zip bundle (host probe,
|
||||
// runtime manifest, VM detail, serial/QEMU logs, and recent app logs) into
|
||||
// `<DataRoot>/reports/` and opens the folder in File Explorer.
|
||||
// ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver.
|
||||
func (a *App) ExportDiagnostics(name string) (string, error) {
|
||||
return a.ExportDiagnosticsWithDriver("", name)
|
||||
}
|
||||
func (a *App) ExportDiagnosticsWithDriver(driverID, name string) (string, error) {
|
||||
var vm driver.VMInfo
|
||||
var err error
|
||||
if strings.TrimSpace(name) != "" {
|
||||
vm, err = a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
appLogs := append([]string(nil), a.recentLogs...)
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
var active *rt.Installed
|
||||
var patchNames []string
|
||||
if inst, err := rt.ResolveActive(&cfgCopy); err == nil {
|
||||
active = inst
|
||||
for _, p := range inst.Manifest.Patches {
|
||||
patchNames = append(patchNames, p.Name)
|
||||
}
|
||||
}
|
||||
bundle := diagnosticsBundle{
|
||||
HostReport: rep,
|
||||
Optimizations: host.EvaluateOptimizations(rep, patchNames),
|
||||
Runtime: active,
|
||||
AppLogs: appLogs,
|
||||
PluginDiagnostics: a.collectPluginDiagnostics(context.Background(), name),
|
||||
}
|
||||
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
bundle := diagnosticsBundle{}
|
||||
label := "host"
|
||||
if strings.TrimSpace(name) != "" {
|
||||
label = name
|
||||
if c, err := a.client(); err == nil {
|
||||
ctx := context.Background()
|
||||
if d, derr := a.GetVMDetail(name); derr == nil {
|
||||
bundle.VMDetail = &d
|
||||
}
|
||||
if serial, serr := c.ReadLogs(ctx, name, true); serr == nil {
|
||||
bundle.SerialLog = serial
|
||||
}
|
||||
if qemuLog, qerr := c.ReadLogs(ctx, name, false); qerr == nil {
|
||||
bundle.QEMULog = qemuLog
|
||||
}
|
||||
pluginKey := ""
|
||||
var info *driver.VMInfo
|
||||
if vm.Name != "" {
|
||||
info = &vm
|
||||
label = vm.Name
|
||||
ref := vm.Ref()
|
||||
pluginKey = ref.Key()
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
label = sshHostAliasForDriver(ref.DriverID, vm.Name)
|
||||
}
|
||||
if serial, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, true); err == nil {
|
||||
bundle.SerialLog = serial
|
||||
}
|
||||
if qemuLog, err := a.ReadVMLogsWithDriver(ref.DriverID, vm.Name, false); err == nil {
|
||||
bundle.QEMULog = qemuLog
|
||||
}
|
||||
}
|
||||
|
||||
bundle.HostReport, bundle.Optimizations, bundle.Runtime, bundle.AppLogs = rep, a.evaluateOptimizations(rep), active, appLogs
|
||||
bundle.VMInfo, bundle.PluginDiagnostics = info, a.collectPluginDiagnostics(context.Background(), pluginKey)
|
||||
reportsDir := filepath.Join(cfgCopy.DataRoot, "reports")
|
||||
zipName := fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405"))
|
||||
zipPath := filepath.Join(reportsDir, zipName)
|
||||
zipPath := filepath.Join(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s.zip", label, time.Now().Format("20060102-150405")))
|
||||
if err := writeDiagnosticsZip(zipPath, bundle); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
|
||||
|
||||
+38
-86
@@ -2,115 +2,67 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
)
|
||||
|
||||
// ResizeVMDisk expands a stopped VM's virtual disk via `qemu-img resize` and
|
||||
// returns the macOS `diskutil` command needed to grow the APFS container inside
|
||||
// the guest.
|
||||
func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) {
|
||||
// ResizeVMDisk expands a stopped VM's virtual disk through its owning driver.
|
||||
func (a *App) ResizeVMDisk(name, newSize string) (driver.DiskResizeResult, error) {
|
||||
return a.ResizeVMDiskWithDriver("", name, newSize)
|
||||
}
|
||||
func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.DiskResizeResult, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
if svc == nil {
|
||||
return driver.DiskResizeResult{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
|
||||
}
|
||||
if a.isVMSuspended(d) {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("resume or discard suspend state for %s before resizing its disk", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
|
||||
taskCtx, cancel := context.WithCancel(ctx)
|
||||
ref := driver.VMRef{DriverID: driverID, Name: name}
|
||||
taskCtx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", name, cancel)
|
||||
a.emitLog(name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
res, err := reims.ResizeDisk(taskCtx, active.QemuImgPath(), env, diskPath, newSize, w, w)
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", ref.Key(), cancel)
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
|
||||
res, err := svc.ResizeDisk(taskCtx, ref, newSize, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(name, "Disk resize error: "+err.Error())
|
||||
return reims.DiskResizeResult{}, err
|
||||
a.emitVMLogForDriver(driverID, name, "Disk resize error: "+err.Error())
|
||||
return driver.DiskResizeResult{}, err
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB (run diskutil inside macOS to expand APFS)",
|
||||
name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB", name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// CompactVMDisk rewrites a stopped VM's standalone qcow2 image into a freshly
|
||||
// compacted sparse qcow2 file to reclaim unused/TRIMmed host disk space.
|
||||
func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
|
||||
// CompactVMDisk reclaims unused host space through the owning driver.
|
||||
func (a *App) CompactVMDisk(name string) (driver.DiskCompactResult, error) {
|
||||
return a.CompactVMDiskWithDriver("", name)
|
||||
}
|
||||
func (a *App) CompactVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
if svc == nil {
|
||||
return driver.DiskCompactResult{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
|
||||
}
|
||||
if a.isVMSuspended(d) {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("resume or discard suspend state for %s before reclaiming disk space", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
|
||||
taskCtx, cancel := context.WithCancel(ctx)
|
||||
ref := driver.VMRef{DriverID: driverID, Name: name}
|
||||
taskCtx, cancel := context.WithCancel(a.baseCtx())
|
||||
defer cancel()
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", name, cancel)
|
||||
a.emitLog(name, fmt.Sprintf("Compacting qcow2 disk for %s to reclaim unused space...", name))
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
res, err := reims.CompactDisk(taskCtx, active.QemuImgPath(), env, diskPath, w, w)
|
||||
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", ref.Key(), cancel)
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Compacting disk for %s to reclaim unused space...", name))
|
||||
res, err := svc.CompactDisk(taskCtx, ref, w, w)
|
||||
if err != nil {
|
||||
finishTask(err)
|
||||
a.emitLog(name, "Disk compact error: "+err.Error())
|
||||
return reims.DiskCompactResult{}, err
|
||||
a.emitVMLogForDriver(driverID, name, "Disk compact error: "+err.Error())
|
||||
return driver.DiskCompactResult{}, err
|
||||
}
|
||||
finishTask(nil)
|
||||
a.emitLog(name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)",
|
||||
name,
|
||||
float64(res.BeforeBytes)/float64(1<<30),
|
||||
float64(res.AfterBytes)/float64(1<<30),
|
||||
float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return res, nil
|
||||
}
|
||||
@@ -179,7 +179,7 @@ func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
a.emitLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
|
||||
a.emitVMLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
const vmNoteFileName = ".reims-go-note"
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestParseDiskSnapshotsJSON(t *testing.T) {
|
||||
|
||||
@@ -10,10 +10,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
@@ -34,6 +35,20 @@ func (a *App) guestToolsImagePath(name string) string {
|
||||
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
|
||||
}
|
||||
|
||||
// buildGuestToolsImage runs in the macOS driver after all start hooks pass.
|
||||
func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
|
||||
_, port, _, err := a.startGuestToolsServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, vmName, a.vmSharedDir(vmName), port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg = validatedDriveConfig(cfg)
|
||||
return guesttools.BuildToolsDiskImage(a.guestToolsImagePath(vmName), cfg)
|
||||
}
|
||||
|
||||
// startGuestToolsServer starts the shared localhost HTTP bridge once. Only the
|
||||
// Guest Tools plugin and the no-plugin-manager fallback may call it; created
|
||||
// reports whether this call made a new server.
|
||||
@@ -46,14 +61,14 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
|
||||
} else {
|
||||
srv = guesttools.NewServer(nil)
|
||||
}
|
||||
srv.SetHostTextHandler(func(vmName, text string) {
|
||||
srv.SetHostTextHandler(func(vmKey, vmName, text string) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr != nil && !mgr.Registry().IsActive(builtin.IDInput) {
|
||||
return
|
||||
}
|
||||
a.injectRemoteText(vmName, "", text)
|
||||
a.injectRemoteTextRef(vmKey, vmName, "", text)
|
||||
})
|
||||
a.guestTools = srv
|
||||
created = true
|
||||
@@ -199,13 +214,13 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail)
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
return
|
||||
}
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
cfg, err = guesttools.LoadOrCreateVMConfig(cur.Directory, name, sharedDir, port)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged := reims.StripGuestToolsNetworkArgs(cur.ExtraArgs)
|
||||
@@ -251,7 +266,7 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -275,7 +290,7 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
if merged != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, w, w); err != nil {
|
||||
@@ -284,14 +299,14 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "detached",
|
||||
To: "attached",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
|
||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -305,21 +320,21 @@ func (a *App) DetachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
|
||||
ctx := context.Background()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
if stripped != d.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "guest_tools",
|
||||
From: "attached",
|
||||
To: "ejected",
|
||||
@@ -327,7 +342,7 @@ func (a *App) DetachGuestTools(name string) error {
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
|
||||
a.emitVMLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -368,7 +383,7 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
srv.SetPreventSleep(name, enabled)
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
|
||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -454,6 +469,6 @@ func (a *App) deliverHostFile(name, picked string) (string, error) {
|
||||
_ = os.Remove(tmpName)
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
|
||||
a.emitVMLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
|
||||
return base, nil
|
||||
}
|
||||
+161
-49
@@ -10,8 +10,10 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -26,7 +28,7 @@ func isRecoveryModeActive(d reims.VMDetail) bool {
|
||||
if d.HasInstaller {
|
||||
return true
|
||||
}
|
||||
m := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
m := startprep.ReadRecoveryMarker(d.Directory)
|
||||
return m == "on" || m == "want"
|
||||
}
|
||||
|
||||
@@ -71,46 +73,77 @@ func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d r
|
||||
return false
|
||||
}
|
||||
|
||||
// EnterRecovery routes the macOS recovery action through the lifecycle service.
|
||||
// The legacy path remains available for minimal embedding without a plugin manager.
|
||||
func (a *App) EnterRecovery(name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.enterRecoveryLegacy(name)
|
||||
}
|
||||
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, _ := raw.(map[string]any)
|
||||
running, _ := result["running"].(bool)
|
||||
if running {
|
||||
scheduled, _ := result["scheduled"].(bool)
|
||||
if scheduled {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{Field: "recovery", From: "off", To: "on"})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
} else {
|
||||
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnterRecovery enables OpenCore's boot picker (--boot-selection=true) so the
|
||||
// VM can boot macOS's built-in Recovery volume without needing an external
|
||||
// installer image (upstream reims-util 7867384 sets HideAuxiliary=false).
|
||||
// If the VM is running, the change is queued for the next start/restart.
|
||||
func (a *App) EnterRecovery(name string) error {
|
||||
func (a *App) enterRecoveryLegacy(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
marker := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
marker := startprep.ReadRecoveryMarker(d.Directory)
|
||||
if marker != "on" {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "want")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "want")
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "recovery",
|
||||
From: "off",
|
||||
To: "on",
|
||||
})
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
||||
} else {
|
||||
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
a.emitVMLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "on")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "on")
|
||||
if prep, err := a.prep(name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, d.Directory)
|
||||
}
|
||||
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
@@ -127,11 +160,23 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
var d reims.VMDetail
|
||||
if svc == nil {
|
||||
var release func()
|
||||
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
} else {
|
||||
d, err = c.Show(a.baseCtx(), name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
defer release()
|
||||
path := strings.TrimSpace(installerPath)
|
||||
if path == "" {
|
||||
path, err = a.pickCachedRecoveryInstaller()
|
||||
@@ -142,17 +187,22 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
return "", errors.New("no cached installer image found")
|
||||
}
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
base := filepath.Base(path)
|
||||
a.emitLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if err := c.Insert(ctx, name, path, w, w); err != nil {
|
||||
a.emitVMLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if svc != nil {
|
||||
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
|
||||
} else {
|
||||
err = c.Insert(ctx, name, path, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "installer",
|
||||
From: "ejected",
|
||||
To: "attached",
|
||||
@@ -192,7 +242,7 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
|
||||
}
|
||||
ctx, cancel := context.WithCancel(base)
|
||||
id := tasks.start("recovery-download", name, name, cancel)
|
||||
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
||||
a.emitVMLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
||||
go func() {
|
||||
defer cancel()
|
||||
res, err := a.ensureInstallerForTask(ctx, id, "recovery-download", name, "online", v, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
|
||||
@@ -200,10 +250,10 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
|
||||
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
|
||||
a.emitVMLog(name, "Online recovery download paused; starting again continues where it stopped")
|
||||
tasks.finish(id, "", context.Canceled)
|
||||
} else {
|
||||
a.emitLog(name, "Online recovery download error: "+err.Error())
|
||||
a.emitVMLog(name, "Online recovery download error: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
}
|
||||
return
|
||||
@@ -216,34 +266,79 @@ func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, err
|
||||
})
|
||||
attached, err := a.AttachInstaller(name, res.Image)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Failed to attach online recovery image: "+err.Error())
|
||||
a.emitVMLog(name, "Failed to attach online recovery image: "+err.Error())
|
||||
tasks.finish(id, "", err)
|
||||
return
|
||||
}
|
||||
a.emitLog(name, "Online recovery image attached: "+attached)
|
||||
a.emitVMLog(name, "Online recovery image attached: "+attached)
|
||||
tasks.finish(id, attached, nil)
|
||||
}()
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// FinishInstall exits recovery through the owning driver and mirrors deferred
|
||||
// changes into the existing App pending-change model.
|
||||
func (a *App) FinishInstall(name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.finishInstallLegacy(name)
|
||||
}
|
||||
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "finish_install", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, _ := raw.(map[string]any)
|
||||
running, _ := result["running"].(bool)
|
||||
if running {
|
||||
var diffs []PendingChange
|
||||
if value, _ := result["installer_ejected"].(bool); value {
|
||||
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
|
||||
}
|
||||
if value, _ := result["network_enabled"].(bool); value {
|
||||
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
|
||||
}
|
||||
if value, _ := result["upgraded_nvme"].(bool); value {
|
||||
from, _ := result["disk_controller_from"].(string)
|
||||
if from == "" {
|
||||
from = "ahci"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"})
|
||||
}
|
||||
if value, _ := result["recovery_pending"].(bool); value {
|
||||
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitVMLog(name, "Exited recovery mode")
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// FinishInstall exits recovery mode: ejects any attached installer, removes
|
||||
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
|
||||
// (--boot-selection=false) if recovery mode enabled the boot picker.
|
||||
func (a *App) FinishInstall(name string) error {
|
||||
func (a *App) finishInstallLegacy(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
if d.HasInstaller {
|
||||
a.emitLog(name, "Ejecting installer from "+name+"...")
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(ctx, name, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -256,13 +351,13 @@ func (a *App) FinishInstall(name string) error {
|
||||
on := true
|
||||
setOpts.Network = &on
|
||||
needSet = true
|
||||
a.emitLog(name, "Turning the network on for "+name+"...")
|
||||
a.emitVMLog(name, "Turning the network on for "+name+"...")
|
||||
}
|
||||
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
|
||||
setOpts.DiskController = "nvme"
|
||||
needSet = true
|
||||
upgradedNVMe = true
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
|
||||
a.emitVMLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
|
||||
}
|
||||
if stripped != d.ExtraArgs {
|
||||
setOpts.ExtraArgs = &stripped
|
||||
@@ -275,7 +370,7 @@ func (a *App) FinishInstall(name string) error {
|
||||
}
|
||||
|
||||
running := a.isVMRunning(ctx, c, name, d)
|
||||
marker := vmstart.ReadRecoveryMarker(d.Directory)
|
||||
marker := startprep.ReadRecoveryMarker(d.Directory)
|
||||
if running {
|
||||
var diffs []PendingChange
|
||||
if d.HasInstaller {
|
||||
@@ -289,32 +384,32 @@ func (a *App) FinishInstall(name string) error {
|
||||
}
|
||||
switch marker {
|
||||
case "want":
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "")
|
||||
case "on":
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "restore")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "restore")
|
||||
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
if marker == "on" || marker == "restore" {
|
||||
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
a.emitVMLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
||||
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
|
||||
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
a.emitVMLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
||||
} else {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "")
|
||||
if prep, err := a.prep(name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, d.Directory)
|
||||
}
|
||||
}
|
||||
} else if marker != "" {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, "")
|
||||
startprep.WriteRecoveryMarker(d.Directory, "")
|
||||
}
|
||||
}
|
||||
a.emitLog(name, "Exited recovery mode")
|
||||
a.emitVMLog(name, "Exited recovery mode")
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -328,26 +423,43 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
var d reims.VMDetail
|
||||
if svc == nil {
|
||||
var release func()
|
||||
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
} else {
|
||||
d, err = c.Show(a.baseCtx(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
defer release()
|
||||
if d.HasInstaller {
|
||||
return errors.New("exit recovery mode (eject installer) before switching disk controller")
|
||||
}
|
||||
if strings.EqualFold(d.DiskController, "nvme") {
|
||||
return nil
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
ctx := context.Background()
|
||||
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
|
||||
a.emitVMLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
||||
if svc != nil {
|
||||
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "upgrade_nvme", nil)
|
||||
} else {
|
||||
err = c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
|
||||
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
||||
Field: "disk_controller",
|
||||
From: d.DiskController,
|
||||
To: "nvme",
|
||||
|
||||
@@ -3,11 +3,12 @@ package app
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -20,7 +21,7 @@ func (a *App) getInstallGuideManager() *installguide.Manager {
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
raw, ok := mgr.Registry().LookupService(builtin.ServiceInstallGuide)
|
||||
raw, ok := mgr.Registry().LookupService(guest.ServiceInstallGuide)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
@@ -39,7 +40,7 @@ func (a *App) guidePreferences() (i18n.Locale, installguide.Theme) {
|
||||
rawLoc := a.cfg.Locale
|
||||
th := a.themeMode
|
||||
a.mu.Unlock()
|
||||
return i18n.EffectiveLocale(rawLoc), th
|
||||
return i18n.EffectiveLocale(rawLoc), installguide.Theme(th)
|
||||
}
|
||||
|
||||
func (a *App) bindGuideEvents(ctx context.Context) {
|
||||
@@ -51,7 +52,7 @@ func (a *App) bindGuideEvents(ctx context.Context) {
|
||||
theme := installguide.Theme(raw)
|
||||
if theme == installguide.ThemeLight || theme == installguide.ThemeDark {
|
||||
a.mu.Lock()
|
||||
a.themeMode = theme
|
||||
a.themeMode = string(theme)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
})
|
||||
@@ -72,13 +73,17 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) {
|
||||
}
|
||||
return installguide.Online, true
|
||||
}
|
||||
return installguide.BuiltIn, vmstart.ReadRecoveryMarker(d.Directory) == "on"
|
||||
return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on"
|
||||
}
|
||||
|
||||
func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, d reims.VMDetail, loc i18n.Locale) bool {
|
||||
func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, vm driver.VMInfo, loc i18n.Locale) bool {
|
||||
if gm == nil || pid <= 0 || gm.HasActive(name, pid) {
|
||||
return false
|
||||
}
|
||||
d, err := macOSDetailFromVMInfo(vm)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
kind, recovery := installGuideKind(d)
|
||||
g := installguide.Guide{
|
||||
Name: name,
|
||||
@@ -137,7 +142,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
_, err := a.AttachInstaller(name, path)
|
||||
return err
|
||||
}
|
||||
g.LogError = func(err error) { a.emitLog(name, "Installation guide: "+err.Error()) }
|
||||
g.LogError = func(err error) { a.emitVMLog(name, "Installation guide: "+err.Error()) }
|
||||
g.AttachTools = func() error {
|
||||
if err := checkBoot(); err != nil {
|
||||
return err
|
||||
@@ -148,12 +153,12 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
if err := checkBoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
stopped, err := a.restartVM(name)
|
||||
stopped, err := a.restartMacOSVM(name)
|
||||
if stopped && err != nil {
|
||||
// The guest window has closed, so report start failures via the tray.
|
||||
loc, _ := a.guidePreferences()
|
||||
title := i18n.M(loc, "guide.err.restart_failed", i18n.Vars{"name": name})
|
||||
a.emitLog(name, title+": "+err.Error())
|
||||
a.emitVMLog(name, title+": "+err.Error())
|
||||
a.mu.Lock()
|
||||
tm := a.trayMgr
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -5,12 +5,13 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func TestInstallGuideFollowsBootMedia(t *testing.T) {
|
||||
@@ -24,7 +25,7 @@ func TestInstallGuideFollowsBootMedia(t *testing.T) {
|
||||
{"on", "", installguide.BuiltIn, true}, {"restore", "", installguide.BuiltIn, false},
|
||||
{"", "BaseSystem.img", installguide.Online, true}, {"", "offline-installer-tahoe.img", installguide.Offline, true},
|
||||
} {
|
||||
vmstart.WriteRecoveryMarker(d.Directory, test.marker)
|
||||
startprep.WriteRecoveryMarker(d.Directory, test.marker)
|
||||
d.HasInstaller, d.InstallerPath = test.path != "", test.path
|
||||
if kind, show := installGuideKind(d); kind != test.want || show != test.show {
|
||||
t.Errorf("%+v: got (%d,%t)", test, kind, show)
|
||||
@@ -46,7 +47,7 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
a := &App{
|
||||
cfg: cfg,
|
||||
pluginMgr: mgr,
|
||||
themeMode: installguide.ThemeDark,
|
||||
themeMode: "dark",
|
||||
pollWake: make(chan struct{}, 1),
|
||||
}
|
||||
|
||||
@@ -58,9 +59,10 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
GetConfig: func() config.Config { return *cfg },
|
||||
SyncInstallGuides: a.wakePoll,
|
||||
}
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, func(id string, def bool) bool {
|
||||
return id == builtin.IDInstallGuide && def
|
||||
}); err != nil {
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
@@ -77,7 +79,7 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
}
|
||||
|
||||
// Disabling the plugin removes the service and closes the guide manager.
|
||||
if err := mgr.Registry().SetDesired(context.Background(), builtin.IDInstallGuide, false); err != nil {
|
||||
if err := mgr.Registry().SetDesired(context.Background(), guest.ID, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.installGuideEnabled() || a.getInstallGuideManager() != nil {
|
||||
@@ -85,7 +87,7 @@ func TestInstallGuideFollowsPluginSwitch(t *testing.T) {
|
||||
}
|
||||
|
||||
// Re-enabling restores the service and wakes pollVMs to attach running VMs.
|
||||
if err := mgr.Registry().SetDesired(context.Background(), builtin.IDInstallGuide, true); err != nil {
|
||||
if err := mgr.Registry().SetDesired(context.Background(), guest.ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !a.installGuideEnabled() {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
type installerDownloadFunc func(ctx context.Context, onUpdate func(installer.Update)) (*installer.Result, error)
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func newTestCoordinator(t *testing.T) {
|
||||
|
||||
@@ -4,7 +4,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
@@ -21,7 +22,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
||||
active := map[string]bool{
|
||||
builtin.IDGuestTools: true,
|
||||
builtin.IDCore: true,
|
||||
guest.ID: true,
|
||||
}
|
||||
intents := []plugin.StartIntent{
|
||||
{
|
||||
@@ -32,12 +33,12 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
}},
|
||||
},
|
||||
{
|
||||
PluginID: builtin.IDCore,
|
||||
PluginID: guest.ID,
|
||||
Args: []plugin.ArgFragment{{
|
||||
PluginID: builtin.IDCore, Key: "reimshelp", Builtin: true, Priority: 85,
|
||||
PluginID: guest.ID, Key: "reimshelp", Builtin: true, Priority: 85,
|
||||
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)),
|
||||
}, {
|
||||
PluginID: builtin.IDCore, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
|
||||
PluginID: guest.ID, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
|
||||
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)),
|
||||
}},
|
||||
},
|
||||
@@ -58,7 +59,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
// Simulate detaching Guest Tools & ejecting offline installer on next start.
|
||||
nextIntents := []plugin.StartIntent{
|
||||
{PluginID: builtin.IDGuestTools, ClearKeys: []string{"reimstools"}},
|
||||
{PluginID: builtin.IDCore, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
|
||||
{PluginID: guest.ID, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
|
||||
}
|
||||
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
|
||||
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents)
|
||||
@@ -81,15 +82,15 @@ func TestStripLegacyPreservesUserNoReboot(t *testing.T) {
|
||||
// stripped as belonging to a gone plugin and the next start could crash.
|
||||
func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
irq := plugin.ArgFragment{
|
||||
PluginID: "builtin.compat.whpx-fallback", Key: "kernel-irqchip", Builtin: true, Priority: 90,
|
||||
PluginID: builtin.IDCore, Key: "kernel-irqchip", Builtin: true, Priority: 90,
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"},
|
||||
}
|
||||
extra := "-cpu host -machine kernel-irqchip=off"
|
||||
active := map[string]bool{builtin.IDCore: true}
|
||||
intents := []plugin.StartIntent{{PluginID: builtin.IDCore}}
|
||||
active := map[string]bool{guest.ID: true}
|
||||
intents := []plugin.StartIntent{{PluginID: guest.ID}}
|
||||
newLedger := func() *plugin.ArgLedger {
|
||||
return &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{
|
||||
"builtin.compat.whpx-fallback": {irq},
|
||||
builtin.IDCore: {irq},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -99,7 +100,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
}
|
||||
|
||||
ledger := newLedger()
|
||||
if !builtin.MigrateLedger(ledger) {
|
||||
if !guest.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger reported no change for a retired owner")
|
||||
}
|
||||
res := plugin.ReconcileStartIntents(extra, ledger, active, intents)
|
||||
@@ -109,7 +110,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
if !strings.Contains(res.ExtraArgs, "-cpu host") {
|
||||
t.Fatalf("user arg lost: %q", res.ExtraArgs)
|
||||
}
|
||||
if builtin.MigrateLedger(ledger) {
|
||||
if guest.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger should be a no-op once migrated")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) emitLifecycleStateChanged() {
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) emitVMLogForDriver(driverID, name, line string) {
|
||||
a.emitLog(vmKeyForDriver(driverID, name), line)
|
||||
}
|
||||
|
||||
func (a *App) startHookPayload(_ context.Context, d driver.Driver, vm driver.VMInfo, base plugin.BeforeStartPayload) (plugin.BeforeStartPayload, error) {
|
||||
if d.ID() != builtin.IDDriverReimsMacOS {
|
||||
return base, nil
|
||||
}
|
||||
prep, err := a.prep(vm.Name)
|
||||
if err != nil {
|
||||
return base, err
|
||||
}
|
||||
caps := prep.Runtime.Manifest.EffectiveCapabilities()
|
||||
rep := host.Inspect(a.currentDataRoot())
|
||||
base.RuntimeKind = prep.Runtime.Manifest.EffectiveKind()
|
||||
base.RuntimeCaps = caps
|
||||
base.HostFacts = buildHostFacts(rep, caps)
|
||||
return base, nil
|
||||
}
|
||||
|
||||
func (a *App) currentDataRoot() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
}
|
||||
|
||||
func (a *App) evaluateOptimizations(rep host.Report) []host.Optimization {
|
||||
core := host.EvaluateCoreOptimizations(rep)
|
||||
a.mu.Lock()
|
||||
router := a.driverRouter
|
||||
a.mu.Unlock()
|
||||
var extra []host.Optimization
|
||||
if router != nil {
|
||||
for _, drv := range router.Drivers() {
|
||||
if advisor, ok := drv.(driver.OptimizationAdvisor); ok {
|
||||
extra = append(extra, advisor.EvaluateOptimizations(context.Background(), rep)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(core) == 0 {
|
||||
return extra
|
||||
}
|
||||
out := append([]host.Optimization{core[0]}, extra...)
|
||||
return append(out, core[1:]...)
|
||||
}
|
||||
|
||||
func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc != nil {
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
return vm, err
|
||||
}
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil
|
||||
}
|
||||
|
||||
func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return driver.VMInfo{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
return vm, err
|
||||
}
|
||||
|
||||
func (a *App) StartVM(name string) error { return a.StartVMWithDriver("", name) }
|
||||
|
||||
func (a *App) StartVMWithDriver(driverID, name string) error {
|
||||
if err := a.beginVMStart(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer a.vmStarts.Done()
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
return a.startVMLegacy(name)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
if vm.State == "suspended" {
|
||||
return a.ResumeVMWithDriver(ref.DriverID, ref.Name)
|
||||
}
|
||||
a.networkMu.Lock()
|
||||
defer a.networkMu.Unlock()
|
||||
key := ref.Key()
|
||||
detail := vm
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "starting"
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
startAt := time.Now()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
rep := host.Inspect(a.currentDataRoot())
|
||||
a.emitStartSummary(ref.Name, detail, rep, "")
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Starting "+ref.Name+"...")
|
||||
result, err := svc.Start(context.Background(), ref, w, w)
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Start error: "+err.Error())
|
||||
a.emitLifecycleStateChanged()
|
||||
return err
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
for _, action := range result.PostStart {
|
||||
if action.Kind != "qmp.watch_cold_reboot" {
|
||||
continue
|
||||
}
|
||||
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
|
||||
a.watchWin10ColdReboot(ref.Name, addr)
|
||||
}
|
||||
}
|
||||
a.startVMMonitor(ref.Name, detail, startAt)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) StopVM(name string, force bool) error { return a.StopVMWithDriver("", name, force) }
|
||||
|
||||
func (a *App) StopVMWithDriver(driverID, name string, force bool) error {
|
||||
return a.stopVMWithDriverCtx(context.Background(), driverID, name, force)
|
||||
}
|
||||
|
||||
func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, force bool) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return errors.New("driver is unavailable without the plugin manager")
|
||||
}
|
||||
return a.stopVMLegacyCtx(ctx, name, force)
|
||||
}
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "stopping"
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Stop(ctx, ref, force, w, w); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) EjectInstaller(name string) error { return a.EjectInstallerWithDriver("", name) }
|
||||
|
||||
func (a *App) EjectInstallerWithDriver(driverID, name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return errors.New("driver is unavailable without the plugin manager")
|
||||
}
|
||||
return a.ejectInstallerLegacy(name)
|
||||
}
|
||||
_, err := svc.InvokeAction(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, "eject", nil)
|
||||
if err == nil {
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.readVMLogsLegacy(name, serial)
|
||||
}
|
||||
return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial)
|
||||
}
|
||||
|
||||
func (a *App) RestartVMWithDriver(driverID, name string) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
var ref driver.VMRef
|
||||
if svc != nil {
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref = vm.Ref()
|
||||
} else {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
ref = driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, name)
|
||||
}
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
if err := a.StopVMWithDriver(ref.DriverID, ref.Name, false); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.StartVMWithDriver(ref.DriverID, ref.Name)
|
||||
}
|
||||
_, err := a.restartMacOSVM(ref.Name)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) DeleteVM(name string, keepFiles bool) error {
|
||||
return a.DeleteVMWithDriver("", name, keepFiles)
|
||||
}
|
||||
|
||||
func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return errors.New("driver is unavailable without the plugin manager")
|
||||
}
|
||||
return a.deleteVMLegacy(name, keepFiles)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Delete(context.Background(), ref, keepFiles, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.stopPacketBridge(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
delete(a.transitions, key)
|
||||
delete(a.diskPaths, key)
|
||||
delete(a.procSamples, key)
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
releaseVMTyping(ref.Name)
|
||||
releaseVMThumbnail(ref.Name)
|
||||
}
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
)
|
||||
|
||||
type appSecondDriver struct {
|
||||
id string
|
||||
vms []driver.VMInfo
|
||||
starts, stops, deletes, sets int
|
||||
actions []string
|
||||
actionResults map[string]any
|
||||
}
|
||||
|
||||
func (d *appSecondDriver) ID() string { return d.id }
|
||||
func (d *appSecondDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: d.id} }
|
||||
func (d *appSecondDriver) RuntimeKind() string { return "test-runtime" }
|
||||
func (d *appSecondDriver) RuntimeAPIRange() string { return "^1.0.0" }
|
||||
func (d *appSecondDriver) Capabilities() []string { return nil }
|
||||
func (d *appSecondDriver) CreateSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, nil }
|
||||
func (d *appSecondDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
|
||||
for _, vm := range d.vms {
|
||||
if vm.Name == name {
|
||||
return vm, nil
|
||||
}
|
||||
}
|
||||
return driver.VMInfo{}, os.ErrNotExist
|
||||
}
|
||||
func (d *appSecondDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error {
|
||||
d.sets++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
|
||||
d.starts++
|
||||
return driver.StartResult{}, nil
|
||||
}
|
||||
func (d *appSecondDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
d.stops++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
d.deletes++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action string, _ map[string]any) (any, error) {
|
||||
d.actions = append(d.actions, action)
|
||||
return d.actionResults[action], nil
|
||||
}
|
||||
|
||||
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"}}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
|
||||
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, driverID, drv)
|
||||
return nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
router := driver.NewRouter(reg, nil)
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, router, nil),
|
||||
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
info, err := a.GetVMInfo(driverID, "ubuntu")
|
||||
if err != nil || info.DriverID != driverID {
|
||||
t.Fatalf("GetVMInfo = %+v, %v", info, err)
|
||||
}
|
||||
vms, err := a.listVMsInternal(context.Background())
|
||||
if err != nil || len(vms) != 1 || vms[0].DriverID != driverID {
|
||||
t.Fatalf("list = %+v, %v", vms, err)
|
||||
}
|
||||
if err := a.StartVMWithDriver(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.StopVMWithDriver(driverID, "ubuntu", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.startHandedVM(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.lifecycleSvc.Set(context.Background(), driver.NewVMRef(driverID, "ubuntu"), map[string]any{"memory": "8G"}, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.RestartVMWithDriver(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.DeleteVMWithDriver(driverID, "ubuntu", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if drv.starts != 3 || drv.stops != 2 || drv.deletes != 1 || drv.sets != 1 {
|
||||
t.Fatalf("starts=%d stops=%d deletes=%d", drv.starts, drv.stops, drv.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppRecoveryActionsUseLifecycle(t *testing.T) {
|
||||
const driverID = driver.BuiltinReimsMacOSDriverID
|
||||
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "running"}}, actionResults: map[string]any{
|
||||
"enter_recovery": map[string]any{"running": true, "scheduled": true},
|
||||
"finish_install": map[string]any{"running": true, "installer_ejected": true, "network_enabled": true, "upgraded_nvme": true, "disk_controller_from": "ahci", "recovery_pending": true},
|
||||
}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.recovery", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, driverID, drv)
|
||||
return nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
if err := a.EnterRecovery("ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 1 || got[0].Field != "recovery" {
|
||||
t.Fatalf("enter pending = %+v", got)
|
||||
}
|
||||
a.pendingChanges = map[string][]PendingChange{}
|
||||
if err := a.FinishInstall("ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 4 {
|
||||
t.Fatalf("finish pending = %+v", got)
|
||||
}
|
||||
if len(drv.actions) != 2 || drv.actions[0] != "enter_recovery" || drv.actions[1] != "finish_install" {
|
||||
t.Fatalf("actions = %v", drv.actions)
|
||||
}
|
||||
}
|
||||
|
||||
// A same-named VM in another driver must not make macOS-native flows or tray
|
||||
// actions ambiguous once the owning driver is known.
|
||||
func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
|
||||
mac := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{Name: "dup", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(), State: "running"}}}
|
||||
lin := &appSecondDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "dup", DriverID: "test.driver.linux", Directory: t.TempDir(), State: "running"}}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
for _, d := range []*appSecondDriver{mac, lin} {
|
||||
d := d
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error { reg.RegisterGuestDriver(sc, d.id, d); return nil }}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
|
||||
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
|
||||
if err := a.StopVM("dup", false); err == nil {
|
||||
t.Fatal("bare-name stop must stay ambiguous")
|
||||
}
|
||||
d, err := a.GetVMDetail("dup")
|
||||
if err != nil || d.Directory != mac.vms[0].Directory {
|
||||
t.Fatalf("GetVMDetail = %+v, %v", d, err)
|
||||
}
|
||||
if err := a.RestartVMWithDriver(driver.BuiltinReimsMacOSDriverID, "dup"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mac.stops != 1 || mac.starts != 1 || lin.stops != 0 || lin.starts != 0 {
|
||||
t.Fatalf("macOS restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
|
||||
}
|
||||
a.trayVMAction(lin.id, "dup", tray.ActRestart)
|
||||
if lin.stops != 1 || lin.starts != 1 || mac.stops != 1 || mac.starts != 1 {
|
||||
t.Fatalf("tray restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
// requireMacOSEnabled refuses native macOS flows while the user has disabled
|
||||
// macOS VM Support: its VMs then show as driver_unavailable, and the native
|
||||
// pages must not act on them behind the plugin's back. It reads the persisted
|
||||
// choice rather than the live driver so startup work racing plugin activation
|
||||
// is not refused.
|
||||
func (a *App) requireMacOSEnabled() error {
|
||||
a.mu.Lock()
|
||||
mgr, loc := a.pluginMgr, a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
if mgr == nil || mgr.DesiredFor(guest.ID, true) {
|
||||
return nil
|
||||
}
|
||||
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "err.macos.disabled"))
|
||||
}
|
||||
|
||||
func (a *App) client() (*reims.Client, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
|
||||
}
|
||||
return reims.NewClient(cfg, *active), nil
|
||||
}
|
||||
|
||||
func enrichMacOSVMListStates(vms []driver.VMListItem) {
|
||||
for i := range vms {
|
||||
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
|
||||
vms[i].State = "suspended"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func resolveVMDiskPath(d reims.VMDetail) string {
|
||||
raw := strings.TrimSpace(d.Disk)
|
||||
if idx := strings.Index(raw, " ("); idx > 0 {
|
||||
raw = strings.TrimSpace(raw[:idx])
|
||||
}
|
||||
if raw != "" {
|
||||
if filepath.IsAbs(raw) {
|
||||
return raw
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, raw)
|
||||
}
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, "disk.qcow2")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// macOSDetailFromVMInfo is the native UI adapter for the built-in macOS driver.
|
||||
func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) {
|
||||
raw, err := json.Marshal(vm.DriverData)
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
var detail reims.VMDetail
|
||||
if err := json.Unmarshal(raw, &detail); err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
detail.Name, detail.Directory, detail.State = vm.Name, vm.Directory, vm.State
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
|
||||
raw, _ := json.Marshal(detail)
|
||||
var data map[string]any
|
||||
_ = json.Unmarshal(raw, &data)
|
||||
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
|
||||
}
|
||||
|
||||
func (a *App) getVMDetailLegacy(name string) (reims.VMDetail, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
d, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
d.RecoveryMode = isRecoveryModeActive(d)
|
||||
a.populateGuestToolsDetail(&d)
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.getVMDetailLegacy(name)
|
||||
}
|
||||
// This adapter only serves the built-in macOS driver, so resolve within it:
|
||||
// a same-named VM in another driver must not make the lookup ambiguous.
|
||||
vm, err := a.GetVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
raw, err := json.Marshal(vm.DriverData)
|
||||
if err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
var d reims.VMDetail
|
||||
if err := json.Unmarshal(raw, &d); err != nil {
|
||||
return reims.VMDetail{}, err
|
||||
}
|
||||
d.Name, d.Directory, d.State = vm.Name, vm.Directory, vm.State
|
||||
d.RecoveryMode = isRecoveryModeActive(d)
|
||||
a.populateGuestToolsDetail(&d)
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func populateSuspendDetail(d *reims.VMDetail) {
|
||||
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
d.State = "suspended"
|
||||
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
|
||||
d.SuspendInfo = info
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
// Disabling macOS VM Support must also stop the native macOS pages from
|
||||
// driving reims-ctl behind the plugin's back.
|
||||
func TestNativeMacOSFlowsRefuseWhilePluginDisabled(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: dataRoot, HostVersion: "0.0.0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dataRoot
|
||||
cfg.Locale = i18n.ZhCN
|
||||
a := &App{cfg: cfg, pluginMgr: mgr, pollWake: make(chan struct{}, 1)}
|
||||
cb := builtin.HostCallbacks{GetConfig: func() config.Config { return *cfg }}
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
t.Fatalf("enabled plugin refused: %v", err)
|
||||
}
|
||||
if err := mgr.Disable(context.Background(), guest.ID); err != nil {
|
||||
t.Fatalf("disable: %v", err)
|
||||
}
|
||||
want := i18n.T(i18n.ZhCN, "err.macos.disabled")
|
||||
for name, call := range map[string]func() error{
|
||||
"client": func() error { _, err := a.client(); return err },
|
||||
"prep": func() error { _, err := a.prep("vm"); return err },
|
||||
"createVM": func() error { return a.CreateVM(reims.CreateOpts{Name: "vm"}) },
|
||||
} {
|
||||
if err := call(); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s while disabled: err = %v, want %q", name, err, want)
|
||||
}
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), guest.ID, false); err != nil {
|
||||
t.Fatalf("enable: %v", err)
|
||||
}
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
t.Fatalf("re-enabled plugin refused: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
const (
|
||||
vmExitWaitTimeout = 12 * time.Second
|
||||
vmMemoryReclaimWaitTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
func (a *App) cachedVMPID(name string) int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, vm := range a.lastVMs {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return *vm.PID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) {
|
||||
if pid <= 0 || timeout <= 0 {
|
||||
return
|
||||
}
|
||||
waitCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
_ = host.WaitProcessExit(waitCtx, uint32(pid), qemuImage)
|
||||
}
|
||||
|
||||
func (a *App) waitForCommitMemoryReclaim(ctx context.Context, c *reims.Client, name, logPrefix string) {
|
||||
if ctx.Err() != nil || c == nil {
|
||||
return
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil || detail.Memory == "" {
|
||||
return
|
||||
}
|
||||
vmstart.WaitForCommitMemory(ctx, detail.Memory, vmMemoryReclaimWaitTimeout, func(availGB, neededGB float64) {
|
||||
a.emitVMLog(name, fmt.Sprintf("%s: waiting for Windows to release VM memory (available %.1f GB, need %.1f GB)...", logPrefix, availGB, neededGB))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) cancelRebootWatcher(name string) { a.cancelRebootWatcherKey(vmKey(name)) }
|
||||
|
||||
func (a *App) cancelRebootWatcherKey(key string) {
|
||||
a.mu.Lock()
|
||||
if entry, ok := a.rebootWatchers[key]; ok {
|
||||
entry.cancel()
|
||||
delete(a.rebootWatchers, key)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
||||
a.cancelRebootWatcher(name)
|
||||
baseCtx := a.ctx
|
||||
if baseCtx == nil {
|
||||
baseCtx = context.Background()
|
||||
}
|
||||
watchCtx, cancel := context.WithCancel(baseCtx)
|
||||
a.mu.Lock()
|
||||
a.nextWatcherID++
|
||||
myID := a.nextWatcherID
|
||||
a.rebootWatchers[vmKey(name)] = rebootWatcherEntry{id: myID, cancel: cancel}
|
||||
a.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
cancel()
|
||||
a.mu.Lock()
|
||||
if cur, ok := a.rebootWatchers[vmKey(name)]; ok && cur.id == myID {
|
||||
delete(a.rebootWatchers, vmKey(name))
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}()
|
||||
|
||||
reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr)
|
||||
if err != nil {
|
||||
if watchCtx.Err() == nil {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
if reason != "guest-reset" {
|
||||
if reason != "" {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting")
|
||||
}
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
tr := a.transitions[vmKey(name)]
|
||||
a.mu.Unlock()
|
||||
if tr == "stopping" || tr == "suspending" {
|
||||
return
|
||||
}
|
||||
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
|
||||
oldPID := a.cachedVMPID(name)
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
|
||||
return
|
||||
}
|
||||
// Wait for QEMU to finish exiting cleanly under -no-reboot. Wait on the
|
||||
// OS process handle when known so we don't race against QEMU teardown
|
||||
// even if `reims-ctl list` reports stopped early.
|
||||
deadline := time.Now().Add(vmExitWaitTimeout)
|
||||
waitedPID := 0
|
||||
if oldPID > 0 {
|
||||
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
|
||||
waitedPID = oldPID
|
||||
}
|
||||
for time.Now().Before(deadline) {
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
vms, err := c.List(watchCtx)
|
||||
if err == nil {
|
||||
stopped := false
|
||||
for _, vm := range vms {
|
||||
if vm.Name != name {
|
||||
continue
|
||||
}
|
||||
if vm.PID != nil && *vm.PID > 0 && oldPID == 0 {
|
||||
oldPID = *vm.PID
|
||||
}
|
||||
if vm.State == "stopped" {
|
||||
stopped = true
|
||||
}
|
||||
break
|
||||
}
|
||||
if stopped {
|
||||
break
|
||||
}
|
||||
if oldPID > 0 && oldPID != waitedPID {
|
||||
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
|
||||
waitedPID = oldPID
|
||||
continue
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-watchCtx.Done():
|
||||
return
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
if oldPID > 0 && oldPID != waitedPID {
|
||||
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
|
||||
}
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
a.waitForCommitMemoryReclaim(watchCtx, c, name, "Win10 WHPX cold-reboot")
|
||||
if watchCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name); err != nil {
|
||||
a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
|
||||
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
|
||||
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
|
||||
// produce duplicate QEMU device IDs on upgrade.
|
||||
func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
s := reims.StripGuestToolsArgs(extraArgs)
|
||||
s = reims.StripGuestToolsNetworkArgs(s)
|
||||
s = reims.StripOfflineHelperArgs(s)
|
||||
s = qmp.StripLegacyWin10RebootArgs(s)
|
||||
s = reims.StripIncomingDeferArgs(s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func (a *App) startVMLegacy(name string) error {
|
||||
a.networkMu.Lock()
|
||||
defer a.networkMu.Unlock()
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := prep.Client
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
tmpDir := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
a.emitVMLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
curDetail, _ := c.Show(context.Background(), name)
|
||||
if err := a.prepareVMNetwork(c, curDetail); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
|
||||
a.emitVMLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
var qmpAddr string
|
||||
if mgr != nil {
|
||||
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
|
||||
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
|
||||
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
|
||||
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
|
||||
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
||||
VMName: name,
|
||||
VMDir: curDetail.Directory,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
ExtraArgs: curDetail.ExtraArgs,
|
||||
HasInstaller: curDetail.HasInstaller,
|
||||
InstallerPath: curDetail.InstallerPath,
|
||||
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
|
||||
RuntimeCaps: rtCaps,
|
||||
HostFacts: buildHostFacts(rep, rtCaps),
|
||||
VMCaps: macosdriver.ReimsMacOSCapabilities,
|
||||
State: curDetail.State,
|
||||
})
|
||||
if blockErr != nil {
|
||||
a.emitVMLog(name, "Start blocked: "+blockErr.Error())
|
||||
return blockErr
|
||||
}
|
||||
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
|
||||
if ledgerErr != nil {
|
||||
a.emitVMLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
|
||||
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
||||
}
|
||||
// Fragments written before the builtins were merged into the core
|
||||
// belong to the core now; carry them instead of re-adding them.
|
||||
guest.MigrateLedger(ledger)
|
||||
// Adopt/strip pre-ledger or out-of-band managed fragments before reconciling
|
||||
// so upgrading existing VMs never duplicates QEMU device IDs (B1).
|
||||
// BeforeStartPayload above already saw the original curDetail.ExtraArgs.
|
||||
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
|
||||
reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents)
|
||||
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
|
||||
for _, warn := range reconciled.Warnings {
|
||||
a.emitVMLog(name, "[plugin] "+warn)
|
||||
}
|
||||
if len(reconciled.Env) > 0 {
|
||||
c.Env = append(c.Env, reconciled.Env...)
|
||||
}
|
||||
if reconciled.Changed {
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
||||
a.emitVMLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
|
||||
} else {
|
||||
curDetail.ExtraArgs = reconciled.ExtraArgs
|
||||
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
|
||||
}
|
||||
} else {
|
||||
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
|
||||
}
|
||||
for _, act := range reconciled.PostStart {
|
||||
if act.Kind == "qmp.watch_cold_reboot" {
|
||||
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
|
||||
qmpAddr = addr
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
a.syncGuestTools(c, name, &curDetail)
|
||||
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
||||
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
|
||||
c.Env = append(c.Env, env...)
|
||||
}
|
||||
}
|
||||
prep.Prepare(context.Background(), name, rep, &curDetail)
|
||||
if rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
||||
a.emitVMLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
||||
} else {
|
||||
qmpAddr = "unix:" + sockPath
|
||||
curDetail.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
||||
host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("client-window-close") {
|
||||
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
a.transitions[vmKey(name)] = "starting"
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
startAt := time.Now()
|
||||
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Starting "+name+"...")
|
||||
if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
||||
a.emitVMLog(name, msg)
|
||||
}); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
a.emitVMLog(name, "Start error: "+err.Error())
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return err
|
||||
}
|
||||
if qmpAddr != "" && mgr == nil {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
VMDir: curDetail.Directory,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
QMPAddr: qmpAddr,
|
||||
})
|
||||
}
|
||||
a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt)
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) stopVMLegacy(name string, force bool) error {
|
||||
return a.stopVMLegacyCtx(context.Background(), name, force)
|
||||
}
|
||||
|
||||
func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.transitions[vmKey(name)] = "stopping"
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
||||
if force {
|
||||
err = c.StopForce(ctx, name, w, w)
|
||||
} else {
|
||||
err = c.Stop(ctx, name, w, w)
|
||||
}
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
a.emitVMLog(name, "Stop error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RestartVM(name string) error { return a.RestartVMWithDriver("", name) }
|
||||
|
||||
// restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU
|
||||
// process and its committed memory to go away before starting again.
|
||||
func (a *App) restartMacOSVM(name string) (stopped bool, err error) {
|
||||
oldPID := a.cachedVMPID(name)
|
||||
if err := a.StopVMWithDriver(driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
|
||||
if c, err := a.client(); err == nil {
|
||||
a.waitForCommitMemoryReclaim(ctx, c, name, "Restart")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return true, a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name)
|
||||
}
|
||||
|
||||
func (a *App) ejectInstallerLegacy(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(context.Background(), name, w, w); err != nil {
|
||||
a.emitVMLog(name, "Eject error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.emitVMLog(name, "Installer ejected.")
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) deleteVMLegacy(name string, keepFiles bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
|
||||
a.emitVMLog(name, "Delete error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
delete(a.transitions, vmKey(name))
|
||||
delete(a.diskPaths, vmKey(name))
|
||||
delete(a.procSamples, vmKey(name))
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
releaseVMTyping(name)
|
||||
releaseVMThumbnail(name)
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delMgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if delMgr != nil {
|
||||
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// OpenVMFolder shows the VM's directory in File Explorer.
|
||||
func (a *App) OpenVMFolder(name string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
return host.OpenFolder(d.Directory)
|
||||
}
|
||||
|
||||
func (a *App) ReadVMLogs(name string, serial bool) (string, error) {
|
||||
return a.ReadVMLogsWithDriver("", name, serial)
|
||||
}
|
||||
|
||||
func (a *App) readVMLogsLegacy(name string, serial bool) (string, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.ReadLogs(context.Background(), name, serial)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ToggleBorderless switches borderless fullscreen startup through the native macOS settings flow.
|
||||
func (a *App) ToggleBorderless(name string, enabled bool) error {
|
||||
v := enabled
|
||||
return a.ApplyVMSettings(reims.SetOpts{Name: name, Borderless: &v})
|
||||
}
|
||||
|
||||
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
a.mu.Unlock()
|
||||
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
|
||||
// reims-ctl refuses a name already registered; say so before the create runs.
|
||||
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
||||
for _, vm := range vms {
|
||||
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
|
||||
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
return reims.PreviewCreateCommand(opts)
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.createVMFlow(opts)
|
||||
}
|
||||
|
||||
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
||||
cur, err := a.GetVMDetail(opts.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil
|
||||
}
|
||||
|
||||
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
|
||||
a.networkMu.Lock()
|
||||
defer a.networkMu.Unlock()
|
||||
cur, err := a.GetVMDetail(opts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if record, err := readNetworkRecord(cur.Directory); err != nil {
|
||||
return err
|
||||
} else if record.Pending {
|
||||
return networkmsg.Localize(networkmsg.Error("packet_pending", nil), a.locale())
|
||||
}
|
||||
if cur.NetworkMode == "bridge" {
|
||||
if opts.Network != nil {
|
||||
return networkmsg.Localize(networkmsg.Error("mode_managed", nil), a.locale())
|
||||
}
|
||||
if opts.ExtraArgs != nil && (reims.NetworkMode(false, *opts.ExtraArgs) != "bridge" || reims.PacketBridgePort(*opts.ExtraArgs) != reims.PacketBridgePort(cur.ExtraArgs)) {
|
||||
return networkmsg.Localize(networkmsg.Error("parameters_managed", nil), a.locale())
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) })
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
|
||||
if svc != nil {
|
||||
raw, _ := json.Marshal(opts)
|
||||
var changes map[string]any
|
||||
_ = json.Unmarshal(raw, &changes)
|
||||
if err := svc.Set(context.Background(), driver.NewVMRef("", opts.Name), changes, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if reims.HasCtlSetChanges(opts) {
|
||||
if err := c.Set(context.Background(), opts, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
if guestLangChanged {
|
||||
prep, err := a.prep(opts.Name)
|
||||
if err == nil {
|
||||
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
|
||||
}
|
||||
if err != nil {
|
||||
a.emitVMLog(opts.Name, "Guest language error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
|
||||
if prep, err := a.prep(opts.Name); err == nil {
|
||||
prep.ReplayGuestLang(context.Background(), cur.Directory)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cur.State == "running" {
|
||||
var diffs []PendingChange
|
||||
if opts.CPUs > 0 && opts.CPUs != cur.CPUs {
|
||||
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)})
|
||||
}
|
||||
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) {
|
||||
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory})
|
||||
}
|
||||
if opts.Resolution != "" && opts.Resolution != cur.Resolution {
|
||||
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution})
|
||||
}
|
||||
if opts.GPU != "" && opts.GPU != cur.GPU {
|
||||
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
|
||||
}
|
||||
if opts.Displays > 0 && opts.Displays != cur.Displays {
|
||||
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
|
||||
}
|
||||
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
|
||||
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
|
||||
}
|
||||
if opts.Audio != nil && *opts.Audio != cur.Audio {
|
||||
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
|
||||
}
|
||||
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
|
||||
from := cur.AudioBackend
|
||||
if from == "" {
|
||||
from = "auto"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
|
||||
}
|
||||
if guestLangChanged {
|
||||
from := cur.GuestLang
|
||||
if from == "" {
|
||||
from = "en-US:0"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(opts.Name)] = append(a.pendingChanges[vmKey(opts.Name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"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/macos/reims"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode.
|
||||
func (a *App) toggleVMFullscreenLegacy(name string) (bool, error) {
|
||||
a.mu.Lock()
|
||||
preference := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(preference)
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err)
|
||||
}
|
||||
fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
a.emitVMLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return fullscreen, nil
|
||||
}
|
||||
|
||||
type fullscreenVMClient interface {
|
||||
Show(context.Context, string) (reims.VMDetail, error)
|
||||
List(context.Context) ([]driver.VMListItem, error)
|
||||
}
|
||||
|
||||
func findRunningVMPID(vms []driver.VMListItem, name string) (uint32, bool) {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return uint32(*vm.PID), true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) {
|
||||
vars := i18n.Vars{"name": name}
|
||||
beforeVMs, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidBefore, ok := findRunningVMPID(beforeVMs, name)
|
||||
if !ok {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
if detail.State != "running" {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
if detail.Graphics == "vmware-svga" {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil)
|
||||
}
|
||||
afterVMs, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidAfter, ok := findRunningVMPID(afterVMs, name)
|
||||
if !ok || pidAfter != pidBefore {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
fullscreen, err := toggleWindow(pidAfter)
|
||||
if errors.Is(err, host.ErrDisplayWindowNotFound) {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err)
|
||||
}
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
return fullscreen, nil
|
||||
}
|
||||
@@ -6,12 +6,28 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
)
|
||||
|
||||
// prepareManagedVMNetwork 由所属驱动在持有虚拟机操作锁时调用。
|
||||
func (a *App) prepareManagedVMNetwork(ctx context.Context, name string, resume bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resume {
|
||||
return a.restoreVMNetworkChannels(c, d)
|
||||
}
|
||||
return a.prepareVMNetwork(c, d)
|
||||
}
|
||||
|
||||
func (a *App) ensureNpcap(ctx context.Context, c networkControlClient, heldDirs ...string) error {
|
||||
if packetbridge.Available() == nil {
|
||||
return nil
|
||||
|
||||
@@ -10,10 +10,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -137,7 +137,7 @@ func (a *App) GetVMNetworkSettings(name string) (result VMNetworkSettings, err e
|
||||
return result, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
transition := a.transitions[name]
|
||||
transition := a.transitions[vmKey(name)]
|
||||
a.mu.Unlock()
|
||||
result.Running = networkVMRunning(reims.VMListItem{}, d, transition)
|
||||
for _, item := range list {
|
||||
@@ -186,7 +186,7 @@ func (a *App) applyVMNetwork(parent context.Context, name, mode, uplink string)
|
||||
if err != nil {
|
||||
return VMNetworkSettings{}, err
|
||||
}
|
||||
d, release, err := vmstart.LockMutableVM(ctx, c, name)
|
||||
d, release, err := startprep.LockMutableVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return VMNetworkSettings{}, err
|
||||
}
|
||||
@@ -199,7 +199,7 @@ func (a *App) applyVMNetwork(parent context.Context, name, mode, uplink string)
|
||||
return VMNetworkSettings{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
transition := a.transitions[name]
|
||||
transition := a.transitions[vmKey(name)]
|
||||
a.mu.Unlock()
|
||||
running := networkVMRunning(reims.VMListItem{}, d, transition)
|
||||
for _, item := range list {
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
)
|
||||
@@ -54,7 +54,7 @@ func (a *App) networkRunningVMs(ctx context.Context, c networkControlClient) ([]
|
||||
if err != nil {
|
||||
return nil, networkmsg.Error("vm_network_check", err, "name", item.Name)
|
||||
}
|
||||
if networkVMRunning(item, detail, transitions[item.Name]) {
|
||||
if networkVMRunning(item, detail, transitions[vmKey(item.Name)]) {
|
||||
running = append(running, item.Name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted
|
||||
@@ -26,9 +30,111 @@ func (a *App) populateGuestLangDetail(d *reims.VMDetail) {
|
||||
|
||||
// prep returns the shared start/OpenCore helpers (internal/vmstart) for one VM,
|
||||
// logging to that VM's log panel.
|
||||
func (a *App) prep(name string) (*vmstart.Prep, error) {
|
||||
func (a *App) prep(name string) (*startprep.Prep, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfg := *a.cfg
|
||||
a.mu.Unlock()
|
||||
return vmstart.New(cfg, func(line string) { a.emitLog(name, line) })
|
||||
return startprep.New(cfg, func(line string) { a.emitVMLog(name, line) })
|
||||
}
|
||||
|
||||
// GetVMSMBIOS reads the VM's OpenCore PlatformInfo > Generic identity
|
||||
// (SystemProductName, SystemSerialNumber, MLB, SystemUUID, and read-only ROM).
|
||||
// Values are returned directly to the UI and never written to app or VM logs.
|
||||
func (a *App) GetVMSMBIOS(name string) (opencore.SMBIOSIdentity, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
d, err := c.Show(a.baseCtx(), name)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
ocPath := opencore.ResolveOpenCorePath(d.Directory)
|
||||
if ocPath == "" {
|
||||
return opencore.SMBIOSIdentity{}, fmt.Errorf("VM %s has no OpenCore image", name)
|
||||
}
|
||||
return opencore.ReadImageSMBIOS(ocPath)
|
||||
}
|
||||
|
||||
// GenerateVMSMBIOS creates a cryptographically random, format-valid Mac SMBIOS
|
||||
// candidate (Serial, Base-34 checksummed MLB, and UUID v4) for the given model
|
||||
// (defaulting to iMac20,1) without modifying disk state.
|
||||
func (a *App) GenerateVMSMBIOS(model string) (opencore.SMBIOSIdentity, error) {
|
||||
return opencore.GenerateSMBIOS(model)
|
||||
}
|
||||
|
||||
// ApplyVMSMBIOS writes new SystemSerialNumber, MLB, and SystemUUID values into
|
||||
// a stopped VM's OpenCore image while keeping ROM untouched so it stays synced
|
||||
// with the VM's network MAC address.
|
||||
func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.SMBIOSIdentity, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
norm, err := opencore.NormalizeAndValidateSMBIOS(id)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := startprep.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return opencore.SMBIOSIdentity{}, fmt.Errorf("stop %s before updating its SMBIOS identity", name)
|
||||
}
|
||||
if d.State == "suspended" {
|
||||
return opencore.SMBIOSIdentity{}, fmt.Errorf("resume or discard suspend state for %s before updating its SMBIOS identity", name)
|
||||
}
|
||||
if info, serr := reims.ReadSuspendInfo(d.Directory); serr == nil && info != nil {
|
||||
return opencore.SMBIOSIdentity{}, fmt.Errorf("resume or discard suspend state for %s before updating its SMBIOS identity", name)
|
||||
}
|
||||
ocPath := opencore.ResolveOpenCorePath(d.Directory)
|
||||
if ocPath == "" {
|
||||
return opencore.SMBIOSIdentity{}, fmt.Errorf("VM %s has no OpenCore image", name)
|
||||
}
|
||||
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
changed, err := opencore.PatchImageSMBIOS(ctx, ocPath, norm, active.QemuImgPath(), env)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
updated, err := opencore.ReadImageSMBIOS(ocPath)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
if changed {
|
||||
modelLabel := updated.Model
|
||||
if modelLabel == "" {
|
||||
modelLabel = "default"
|
||||
}
|
||||
// Never log Serial, MLB, UUID, or ROM into VM/app logs.
|
||||
a.emitVMLog(name, fmt.Sprintf("Updated OpenCore SMBIOS identity (%s)", modelLabel))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
|
||||
@@ -14,12 +14,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
@@ -31,42 +31,45 @@ import (
|
||||
// PluginUIContributions aggregates all active declarative plugin UI contributions
|
||||
// for the frontend in a single round-trip (§4.2, §10).
|
||||
type PluginUIContributions struct {
|
||||
SafeMode bool `json:"safe_mode"`
|
||||
CrashDetected bool `json:"crash_detected"`
|
||||
Menus []plugin.MenuContribution `json:"menus,omitempty"`
|
||||
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
|
||||
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
||||
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
||||
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
||||
SafeMode bool `json:"safe_mode"`
|
||||
CrashDetected bool `json:"crash_detected"`
|
||||
Menus []plugin.MenuContribution `json:"menus,omitempty"`
|
||||
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
|
||||
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
||||
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
||||
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
||||
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
|
||||
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
|
||||
Locales []plugin.ResolvedLocalePack `json:"locales,omitempty"`
|
||||
RuntimeSources []plugin.RuntimeSourceContribution `json:"runtime_sources,omitempty"`
|
||||
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
|
||||
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
|
||||
AssetToken string `json:"asset_token,omitempty"`
|
||||
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
|
||||
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
|
||||
AssetToken string `json:"asset_token,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) initPlugins() {
|
||||
// Plugins keep their state in the data folder. Before setup there is no
|
||||
// chosen folder, and a read-only folder must not be written; the app runs
|
||||
// without a plugin manager then (see startup).
|
||||
if !a.dataRootUsable() {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
safeMode := a.launch.SafeMode
|
||||
a.mu.Unlock()
|
||||
|
||||
// Bring the data folder to this build's layout before anything reads it.
|
||||
if res, err := datamigrate.Run(dataRoot, version.Version); err != nil {
|
||||
a.emitLog("app", "Data migration failed: "+err.Error())
|
||||
} else if res.Newer {
|
||||
a.emitLog("app", fmt.Sprintf("Data folder uses layout v%d from a newer Reims-Go (this build knows v%d); leaving it unchanged", res.From, datamigrate.CurrentVersion))
|
||||
} else if len(res.Applied) > 0 {
|
||||
a.emitLog("app", fmt.Sprintf("Data folder upgraded from layout v%d to v%d (%s)", res.From, res.To, strings.Join(res.Applied, ", ")))
|
||||
// Idempotent fallback for embedders that construct a Manager directly;
|
||||
// normal startup already ran this as data layout v2 in dataroot.Open.
|
||||
if err := guest.MigrateFiles(dataRoot); err != nil {
|
||||
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: reims.RedactText,
|
||||
RedactFn: host.RedactText,
|
||||
LocaleFn: a.locale,
|
||||
Logger: func(source, line string) {
|
||||
a.emitLog(source, line)
|
||||
@@ -86,30 +89,14 @@ func (a *App) initPlugins() {
|
||||
}
|
||||
|
||||
kindReg := rt.NewKindRegistry()
|
||||
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
|
||||
drvRouter := driver.NewRouterWithDataRoot(mgr.Registry(), func() string {
|
||||
a.mu.Lock()
|
||||
dir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms")
|
||||
a.mu.Unlock()
|
||||
return dir
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
})
|
||||
|
||||
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
||||
// Must not call Registry.Info/List here: both invoke this checker,
|
||||
// which recursed until the goroutine stack overflowed at startup.
|
||||
// Check all guest driver IDs declared by this plugin (even when disabled) plus pluginID itself.
|
||||
seen := map[string]bool{}
|
||||
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
||||
for _, did := range candidates {
|
||||
if did == "" || seen[did] {
|
||||
continue
|
||||
}
|
||||
seen[did] = true
|
||||
if inUse, reason, err := drvRouter.CheckDriverInUse(context.Background(), did); err != nil || inUse {
|
||||
return inUse, reason, err
|
||||
}
|
||||
}
|
||||
return false, "", nil
|
||||
})
|
||||
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
|
||||
|
||||
mgr.Broker().SetNotifier(func(pluginID, title, body string) {
|
||||
a.emitLog("plugin:"+pluginID, title+": "+body)
|
||||
@@ -161,6 +148,8 @@ func (a *App) initPlugins() {
|
||||
GuestToolsImg: func(vmName string) string {
|
||||
return a.guestToolsImagePath(vmName)
|
||||
},
|
||||
BuildGuestToolsImage: a.buildGuestToolsImage,
|
||||
PrepareVMNetwork: a.prepareManagedVMNetwork,
|
||||
OnInstallGuidesChanged: func() {
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
@@ -178,8 +167,8 @@ func (a *App) initPlugins() {
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
|
||||
}
|
||||
if err := builtin.MigrateRetired(mgr); err != nil {
|
||||
a.emitLog("plugin", "Could not migrate merged core plugin state: "+err.Error())
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
a.emitLog("plugin", "macOS guest plugin register error: "+err.Error())
|
||||
}
|
||||
if err := mgr.LoadExternal(); err != nil {
|
||||
a.emitLog("plugin", "External plugin load warning: "+err.Error())
|
||||
@@ -199,6 +188,7 @@ func (a *App) initPlugins() {
|
||||
a.mu.Lock()
|
||||
a.pluginMgr = mgr
|
||||
a.driverRouter = drvRouter
|
||||
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
|
||||
a.runtimeKinds = kindReg
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -214,6 +204,8 @@ func (a *App) shutdownPlugins() {
|
||||
mgr := a.pluginMgr
|
||||
a.pluginMgr = nil
|
||||
a.pluginMarket = nil
|
||||
a.lifecycleSvc = nil
|
||||
a.driverRouter = nil
|
||||
a.mu.Unlock()
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
if mgr != nil {
|
||||
@@ -371,8 +363,13 @@ func (a *App) syncInputFilters() {
|
||||
if len(vmNames) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, vmName := range vmNames {
|
||||
vals := mgr.GetSettings(flt.PluginID, vmName, false)
|
||||
for _, vmKey := range vmNames {
|
||||
ref, ok := driver.ParseVMRef(vmKey)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmKey)
|
||||
}
|
||||
vmName := ref.Name
|
||||
vals := mgr.GetSettings(flt.PluginID, vmKey, false)
|
||||
vert := true
|
||||
if flt.VertKey != "" {
|
||||
if v, ok := vals[flt.VertKey].(bool); ok {
|
||||
@@ -394,7 +391,7 @@ func (a *App) syncInputFilters() {
|
||||
axis = ""
|
||||
}
|
||||
rules = append(rules, host.InputFilterRule{
|
||||
ID: flt.ID + ":" + vmName,
|
||||
ID: flt.ID + ":" + ref.Key(),
|
||||
PluginID: flt.PluginID,
|
||||
Event: flt.Event,
|
||||
Axis: axis,
|
||||
@@ -422,9 +419,13 @@ func (a *App) syncClipboardPolicies() {
|
||||
}
|
||||
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
|
||||
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
|
||||
for vmName, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
|
||||
for vmKey, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
|
||||
ref, ok := driver.ParseVMRef(vmKey)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmKey)
|
||||
}
|
||||
pol := clipboardPolicyFromMap(vmVals)
|
||||
gt.SetVMClipboardPolicy(vmName, &pol)
|
||||
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,7 +442,22 @@ func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
|
||||
if vmName == "" {
|
||||
gt.SetGlobalClipboardPolicy(pol)
|
||||
} else {
|
||||
gt.SetVMClipboardPolicy(vmName, &pol)
|
||||
ref, ok := driver.ParseVMRef(vmName)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmName)
|
||||
}
|
||||
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
||||
}
|
||||
}
|
||||
}
|
||||
if pluginID == guest.ID && vmName == "" {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
wantGuide := guest.SettingOn(mgr.GetSettings(guest.ID, "", false), guest.SettingInstallGuide)
|
||||
if wantGuide != a.installGuideEnabled() {
|
||||
a.reloadPlugins()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -519,7 +535,7 @@ func (a *App) collectPluginDiagnostics(ctx context.Context, vmName string) []plu
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
return mgr.Registry().CollectDiagnostics(ctx, vmName, reims.RedactText)
|
||||
return mgr.Registry().CollectDiagnostics(ctx, vmName, host.RedactText)
|
||||
}
|
||||
|
||||
func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
|
||||
@@ -527,7 +543,7 @@ func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
|
||||
if rep.RecommendedGPU != nil {
|
||||
gpuKind = string(rep.RecommendedGPU.Kind)
|
||||
}
|
||||
return map[string]any{
|
||||
facts := map[string]any{
|
||||
"host.os": rep.OS,
|
||||
"host.arch": rep.Arch,
|
||||
"host.whpx": string(rep.WHPX),
|
||||
@@ -537,6 +553,13 @@ func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
|
||||
"host.gpu_kind": gpuKind,
|
||||
"runtime.capabilities": rtCaps,
|
||||
}
|
||||
if rep.MemorySpec != nil && rep.MemorySpec.SpeedMHz > 0 {
|
||||
facts["host.memory_speed_mhz"] = rep.MemorySpec.SpeedMHz
|
||||
if rep.MemorySpec.MemoryType > 0 {
|
||||
facts["host.memory_type"] = rep.MemorySpec.MemoryType
|
||||
}
|
||||
}
|
||||
return facts
|
||||
}
|
||||
|
||||
// --- Wails-bound Plugin & Driver APIs (§10) ---
|
||||
@@ -548,7 +571,7 @@ func (a *App) ListPlugins() []plugin.PluginInfo {
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
return mgr.LocalizePluginInfos(mgr.Registry().List())
|
||||
return mgr.LocalizePluginInfos(mgr.Registry().ListVisible())
|
||||
}
|
||||
|
||||
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
|
||||
@@ -609,34 +632,34 @@ func (a *App) RemovePlugin(id string, purgeData bool) error {
|
||||
return mgr.Remove(context.Background(), id, purgeData)
|
||||
}
|
||||
|
||||
func (a *App) GetPluginSettings(pluginID, vmName string) map[string]any {
|
||||
func (a *App) GetPluginSettings(pluginID, vmKey string) map[string]any {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return mgr.GetSettings(pluginID, vmName, true)
|
||||
return mgr.GetSettings(pluginID, vmKey, true)
|
||||
}
|
||||
|
||||
func (a *App) SetPluginSettings(pluginID, vmName string, values map[string]any) error {
|
||||
func (a *App) SetPluginSettings(pluginID, vmKey string, values map[string]any) error {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return errors.New("plugin manager not initialized")
|
||||
}
|
||||
return mgr.SetSettings(pluginID, vmName, values)
|
||||
return mgr.SetSettings(pluginID, vmKey, values)
|
||||
}
|
||||
|
||||
func (a *App) GetVMPluginSettings(vmName string) map[string]map[string]any {
|
||||
func (a *App) GetVMPluginSettings(vmKey string) map[string]map[string]any {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return map[string]map[string]any{}
|
||||
}
|
||||
return mgr.GetAllVMSettings(vmName)
|
||||
return mgr.GetAllVMSettings(vmKey)
|
||||
}
|
||||
|
||||
func (a *App) GetPluginUIContributions() PluginUIContributions {
|
||||
@@ -748,6 +771,9 @@ func (a *App) ListRuntimeKinds() []rt.KindSpec {
|
||||
}
|
||||
|
||||
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
dr := a.driverRouter
|
||||
mgr := a.pluginMgr
|
||||
@@ -834,7 +860,7 @@ func (a *App) ReadPluginLog(pluginID string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return reims.RedactText(string(raw)), nil
|
||||
return host.RedactText(string(raw)), nil
|
||||
}
|
||||
|
||||
func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) beginVMStart() error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.quitMode != "" || a.allowQuit {
|
||||
return errors.New(i18n.T(a.cfg.Locale, "quitInProgress"))
|
||||
}
|
||||
a.vmStarts.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
// QuitApp exits the desktop app and leaves its guests running.
|
||||
func (a *App) QuitApp() {
|
||||
_ = a.quitApp(false)
|
||||
}
|
||||
|
||||
// ForceQuitApp powers off all running guests before exiting.
|
||||
func (a *App) ForceQuitApp() error {
|
||||
return a.quitApp(true)
|
||||
}
|
||||
|
||||
func (a *App) quitApp(force bool) error {
|
||||
a.mu.Lock()
|
||||
if a.allowQuit || a.quitMode != "" {
|
||||
a.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if force {
|
||||
a.quitMode = "force"
|
||||
a.mu.Unlock()
|
||||
a.emitStateChanged()
|
||||
a.vmStarts.Wait()
|
||||
err := a.forceStopRunningVMs(a.baseCtx())
|
||||
a.mu.Lock()
|
||||
if err != nil {
|
||||
a.quitMode = ""
|
||||
a.mu.Unlock()
|
||||
a.emitStateChanged()
|
||||
return err
|
||||
}
|
||||
}
|
||||
a.allowQuit = true
|
||||
a.mu.Unlock()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.Quit(a.ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) forceStopRunningVMs(ctx context.Context) error {
|
||||
a.mu.Lock()
|
||||
cfg := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(cfg.Locale)
|
||||
list := func(ctx context.Context) ([]driver.VMListItem, error) {
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil && svc == nil {
|
||||
// A fresh installation can quit before its first runtime is installed.
|
||||
_, registryErr := os.Stat(filepath.Join(cfg.XDGConfigDir(), "reims-ctl", "vms.toml"))
|
||||
dirs, dirErr := os.ReadDir(filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms"))
|
||||
if os.IsNotExist(registryErr) && (os.IsNotExist(dirErr) || (dirErr == nil && len(dirs) == 0)) {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return vms, err
|
||||
}
|
||||
return stopListedVMs(ctx, loc, list, func(ctx context.Context, vm driver.VMListItem) error {
|
||||
return a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, true)
|
||||
})
|
||||
}
|
||||
|
||||
const quitVMTimeout = 10 * time.Second
|
||||
|
||||
func stopListedVMs(ctx context.Context, loc i18n.Locale, list func(context.Context) ([]driver.VMListItem, error), stop func(context.Context, driver.VMListItem) error) error {
|
||||
stopped := make(map[string]bool)
|
||||
for {
|
||||
listCtx, cancel := context.WithTimeout(ctx, quitVMTimeout)
|
||||
vms, err := list(listCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var next *driver.VMListItem
|
||||
for i := range vms {
|
||||
vm := vms[i]
|
||||
if vm.State == "running" {
|
||||
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
||||
if stopped[key] {
|
||||
return errors.New(i18n.M(loc, "err.quit.stop_failed", i18n.Vars{"name": vm.Name}))
|
||||
}
|
||||
if next == nil {
|
||||
cp := vm
|
||||
next = &cp
|
||||
}
|
||||
}
|
||||
}
|
||||
if next == nil {
|
||||
return nil
|
||||
}
|
||||
stopCtx, cancel := context.WithTimeout(ctx, quitVMTimeout)
|
||||
err = stop(stopCtx, *next)
|
||||
ctxErr := stopCtx.Err()
|
||||
cancel()
|
||||
if errors.Is(ctxErr, context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return errors.New(i18n.M(loc, "err.quit.timeout", i18n.Vars{"name": next.Name}))
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New(i18n.M(loc, "err.quit.stop_failed", i18n.Vars{"name": next.Name}))
|
||||
}
|
||||
stopped[vmKeyForDriver(next.DriverID, next.Name)] = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestStopListedVMs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, wantErr string
|
||||
}{
|
||||
{name: "all stopped"},
|
||||
{name: "failure", wantErr: "无法关闭虚拟机「two」,已取消退出。"},
|
||||
{name: "still running", wantErr: "无法关闭虚拟机「two」,已取消退出。"},
|
||||
{name: "timeout", wantErr: "虚拟机「two」关机超时,已取消退出。"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
vms := []driver.VMListItem{
|
||||
{Name: "one", State: "running"}, {Name: "off", State: "stopped"},
|
||||
{Name: "two", State: "running"}, {Name: "saved", State: "suspended"}, {Name: "three", State: "running"},
|
||||
}
|
||||
var calls []string
|
||||
err := stopListedVMs(t.Context(), i18n.ZhCN, func(context.Context) ([]driver.VMListItem, error) {
|
||||
return vms, nil
|
||||
}, func(ctx context.Context, vm driver.VMListItem) error {
|
||||
name := vm.Name
|
||||
calls = append(calls, name)
|
||||
if name == "two" {
|
||||
switch tc.name {
|
||||
case "failure":
|
||||
return errors.New("stop failed")
|
||||
case "still running":
|
||||
return nil
|
||||
case "timeout":
|
||||
started := time.Now()
|
||||
<-ctx.Done()
|
||||
if elapsed := time.Since(started); elapsed != 10*time.Second {
|
||||
t.Errorf("shutdown timed out after %v, want 10s", elapsed)
|
||||
}
|
||||
return errors.New("exit status 1")
|
||||
}
|
||||
}
|
||||
for i := range vms {
|
||||
if vms[i].Name == name {
|
||||
vms[i].State = "stopped"
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
want := []string{"one", "two", "three"}
|
||||
if tc.wantErr != "" {
|
||||
want = want[:2]
|
||||
if err == nil || err.Error() != tc.wantErr {
|
||||
t.Fatalf("error = %v, want %q", err, tc.wantErr)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(calls, want) {
|
||||
t.Fatalf("stop calls = %v, want %v", calls, want)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuitAppLeavesVMsRunning(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
a := &App{lastVMs: []driver.VMListItem{{Name: "one", State: "running"}}}
|
||||
if err := a.beginVMStart(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.vmStarts.Done()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
a.QuitApp()
|
||||
close(done)
|
||||
}()
|
||||
synctest.Wait()
|
||||
select {
|
||||
case <-done:
|
||||
if !a.allowQuit || a.quitMode != "" {
|
||||
t.Fatalf("tray exit: allowQuit=%v mode=%q", a.allowQuit, a.quitMode)
|
||||
}
|
||||
default:
|
||||
t.Fatal("tray exit waited for VM operations")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestForceQuitAppWaitsForStartsAndCanRetry(t *testing.T) {
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir(), Locale: i18n.EnUS}}
|
||||
if err := a.beginVMStart(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
quit := make(chan error, 1)
|
||||
go func() { quit <- a.ForceQuitApp() }()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
a.mu.Lock()
|
||||
quitting := a.quitMode != ""
|
||||
a.mu.Unlock()
|
||||
if quitting {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("quit did not start")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
for _, launch := range []func(string) error{a.StartVM, a.ResumeVM} {
|
||||
if err := launch("new"); err == nil || err.Error() != i18n.T(i18n.EnUS, "quitInProgress") {
|
||||
t.Fatalf("launch during shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
a.QuitApp()
|
||||
if !a.beforeClose(context.Background()) {
|
||||
t.Fatal("another close bypassed the pending shutdown")
|
||||
}
|
||||
if err := a.ForceQuitApp(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.quitMode != "force" || a.allowQuit {
|
||||
t.Fatalf("duplicate quit: mode=%q allowQuit=%v", a.quitMode, a.allowQuit)
|
||||
}
|
||||
|
||||
// The in-flight start creates a VM entry after the quit request. Without
|
||||
// a runtime, shutdown must now fail instead of assuming an empty library.
|
||||
dir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms", "starting")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.vmStarts.Done()
|
||||
if err := <-quit; err == nil || a.allowQuit || a.quitMode != "" {
|
||||
t.Fatalf("failed shutdown: err=%v allowQuit=%v mode=%q", err, a.allowQuit, a.quitMode)
|
||||
}
|
||||
if err := os.Remove(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.ForceQuitApp(); err != nil || !a.allowQuit || a.beforeClose(context.Background()) {
|
||||
t.Fatalf("retry with empty library: err=%v allowQuit=%v", err, a.allowQuit)
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,14 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
@@ -80,7 +81,7 @@ func (a *App) SetRuntimeChannel(channel string) error {
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.RuntimeChannel = channel
|
||||
forgetRemoteRuntimes()
|
||||
return config.Save("", a.cfg)
|
||||
return a.saveConfigLocked()
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
@@ -132,7 +133,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
src := rt.DefaultSource()
|
||||
step := func(msg string) {
|
||||
a.emitLog("runtime", msg)
|
||||
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
|
||||
tasks.update(taskID, host.Update{Kind: host.KindStep, Message: msg, Percent: -1})
|
||||
}
|
||||
step("Looking up runtime releases")
|
||||
// An explicit commit may be an alpha even on the stable channel: the
|
||||
@@ -149,8 +150,8 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
if !rt.IsInstalled(cfg, r.Commit) {
|
||||
step("Downloading runtime " + r.Commit)
|
||||
path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) {
|
||||
tasks.update(taskID, installer.Update{
|
||||
Kind: installer.KindProgress, Step: "downloading runtime " + r.Commit,
|
||||
tasks.update(taskID, host.Update{
|
||||
Kind: host.KindProgress, Step: "downloading runtime " + r.Commit,
|
||||
Done: done, Total: total, Percent: percent(done, total),
|
||||
})
|
||||
})
|
||||
@@ -168,7 +169,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
|
||||
a.mu.Lock()
|
||||
a.cfg.ActiveRuntime = r.Commit
|
||||
err = config.Save("", a.cfg)
|
||||
err = a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -203,7 +204,7 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg.AppUpdateChannel = channel
|
||||
err := config.Save("", a.cfg)
|
||||
err := a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -244,15 +245,32 @@ func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func validateExternalHTTPSURL(raw string) (string, error) {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" || strings.ContainsAny(trimmed, " \t\r\n\"'<>\\") {
|
||||
return "", fmt.Errorf("refusing to open invalid URL")
|
||||
}
|
||||
for _, r := range trimmed {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return "", fmt.Errorf("refusing to open invalid URL")
|
||||
}
|
||||
}
|
||||
u, err := url.Parse(trimmed)
|
||||
if err != nil || !strings.EqualFold(u.Scheme, "https") || u.Host == "" || u.User != nil {
|
||||
return "", fmt.Errorf("refusing to open non-HTTPS URL")
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
// OpenURL opens an HTTPS link in the host's default browser.
|
||||
func (a *App) OpenURL(raw string) error {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if !strings.HasPrefix(trimmed, "https://") {
|
||||
return fmt.Errorf("refusing to open non-HTTPS URL")
|
||||
clean, err := validateExternalHTTPSURL(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.ctx == nil {
|
||||
return errors.New("window context not ready")
|
||||
}
|
||||
wailsRuntime.BrowserOpenURL(a.ctx, trimmed)
|
||||
wailsRuntime.BrowserOpenURL(a.ctx, clean)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateExternalHTTPSURL(t *testing.T) {
|
||||
valid := []string{
|
||||
"https://github.com/Nwflower/Reims-Go",
|
||||
" https://discord.gg/Tj682rW5rS ",
|
||||
"https://github.com/Nwflower/Reims-Go/releases/tag/v0.2.10?foo=1#notes",
|
||||
}
|
||||
for _, raw := range valid {
|
||||
if _, err := validateExternalHTTPSURL(raw); err != nil {
|
||||
t.Errorf("validateExternalHTTPSURL(%q) unexpected error: %v", raw, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"",
|
||||
"http://example.com",
|
||||
"javascript:alert(1)",
|
||||
"file:///C:/Windows/System32/calc.exe",
|
||||
"https://",
|
||||
"https://user:pass@example.com/path",
|
||||
"https://example.com/a b",
|
||||
"https://example.com/a\nfoo",
|
||||
"https://example.com/\"quoted\"",
|
||||
"https://example.com/a\x00b",
|
||||
}
|
||||
for _, raw := range invalid {
|
||||
if got, err := validateExternalHTTPSURL(raw); err == nil {
|
||||
t.Errorf("validateExternalHTTPSURL(%q) = %q, want error", raw, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-8
@@ -12,8 +12,10 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -107,6 +109,11 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
if err := validateDataRoot(dir, locale); err != nil {
|
||||
return err
|
||||
}
|
||||
// Check the folder before writing anything into it: one written by a
|
||||
// newer release, or with a damaged version record, is refused untouched.
|
||||
if st := dataroot.Open(dir, version.Version); st.ReadOnly {
|
||||
return dataroot.Error(i18n.EffectiveLocale(locale), st)
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
cfg, err := config.Load(cfgPath)
|
||||
@@ -129,18 +136,18 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
// A folder created just now gets its version stamp here.
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
prevRoot := ""
|
||||
if a.cfg != nil {
|
||||
prevRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.cfg = cfg
|
||||
a.needsSetup = false
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
if filepath.Clean(prevRoot) != filepath.Clean(dir) {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
}
|
||||
a.logDataRoot(st)
|
||||
// Nothing touching the data folder ran before setup (startup), so plugins
|
||||
// start now whichever folder was chosen.
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
@@ -1,62 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ListSnapshots returns all internal qcow2 restore points for a VM, newest first.
|
||||
func (a *App) ListSnapshots(name string) ([]reims.DiskSnapshot, error) {
|
||||
// ListSnapshots returns all driver-owned restore points for a VM, newest first.
|
||||
func (a *App) ListSnapshots(name string) ([]driver.DiskSnapshot, error) {
|
||||
return a.ListSnapshotsWithDriver("", name)
|
||||
}
|
||||
func (a *App) ListSnapshotsWithDriver(driverID, name string) ([]driver.DiskSnapshot, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if svc == nil {
|
||||
return nil, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return nil, nil
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
snaps, err := reims.ListDiskSnapshots(a.baseCtx(), active.QemuImgPath(), env, diskPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(snaps, func(i, j int) bool {
|
||||
return snaps[i].CreatedAt > snaps[j].CreatedAt
|
||||
})
|
||||
return snaps, nil
|
||||
return svc.ListSnapshots(a.baseCtx(), driver.VMRef{DriverID: driverID, Name: name})
|
||||
}
|
||||
|
||||
// CreateSnapshot creates a named offline restore point inside a stopped VM's qcow2 disk.
|
||||
func (a *App) CreateSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-c", snapName, "Created restore point")
|
||||
return a.CreateSnapshotWithDriver("", name, snapName)
|
||||
}
|
||||
func (a *App) CreateSnapshotWithDriver(driverID, name, snapName string) error {
|
||||
return a.runSnapshotOpWithDriver(driverID, name, "create", snapName, "Created restore point")
|
||||
}
|
||||
|
||||
// RestoreSnapshot rolls back a stopped VM's qcow2 disk to the named restore point.
|
||||
func (a *App) RestoreSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-a", snapName, "Restored restore point")
|
||||
return a.RestoreSnapshotWithDriver("", name, snapName)
|
||||
}
|
||||
func (a *App) RestoreSnapshotWithDriver(driverID, name, snapName string) error {
|
||||
return a.runSnapshotOpWithDriver(driverID, name, "restore", snapName, "Restored restore point")
|
||||
}
|
||||
|
||||
// DeleteSnapshot removes a named restore point from a stopped VM's qcow2 disk.
|
||||
func (a *App) DeleteSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-d", snapName, "Deleted restore point")
|
||||
return a.DeleteSnapshotWithDriver("", name, snapName)
|
||||
}
|
||||
func (a *App) DeleteSnapshotWithDriver(driverID, name, snapName string) error {
|
||||
return a.runSnapshotOpWithDriver(driverID, name, "delete", snapName, "Deleted restore point")
|
||||
}
|
||||
|
||||
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
func (a *App) runSnapshotOpWithDriver(driverID, name, operation, snapName, verb string) error {
|
||||
loc := a.locale()
|
||||
cleanSnap := strings.TrimSpace(snapName)
|
||||
if cleanSnap == "" {
|
||||
@@ -65,45 +52,22 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
if len([]rune(cleanSnap)) > 64 {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_TOO_LONG", "err.snapshot.name_too_long", nil, nil)
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(cleanSnap); err != nil {
|
||||
if _, err := driver.ValidateSnapshotName(cleanSnap); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_INVALID", "err.snapshot.name_invalid", nil, err)
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ref := driver.VMRef{DriverID: driverID, Name: name}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(driverID, name, line) })
|
||||
if err := svc.RunSnapshot(a.baseCtx(), ref, operation, cleanSnap, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
if a.isVMSuspended(d) {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_QCOW2_ONLY", "err.snapshot.qcow2_only", nil, nil)
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, cleanSnap, diskPath); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_QEMU_IMG", "err.snapshot.qemu_img_failed", i18n.Vars{"snap": cleanSnap}, err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("%s %q", verb, cleanSnap))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("%s %q", verb, cleanSnap))
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
+49
-17
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
)
|
||||
|
||||
const sshUserFileName = ".reims-go-ssh-user"
|
||||
@@ -14,9 +16,21 @@ const sshUserFileName = ".reims-go-ssh-user"
|
||||
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
|
||||
func sshHostAlias(vmName string) string {
|
||||
func sshHostAlias(vmName string) string { return sshHostAliasForDriver("", vmName) }
|
||||
|
||||
func sshHostAliasForDriver(driverID, vmName string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("reims-")
|
||||
if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID {
|
||||
for _, r := range strings.ToLower(id) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('-')
|
||||
}
|
||||
}
|
||||
b.WriteByte('-')
|
||||
}
|
||||
for _, r := range strings.ToLower(strings.TrimSpace(vmName)) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
b.WriteRune(r)
|
||||
@@ -27,9 +41,17 @@ func sshHostAlias(vmName string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func sshConfigKey(driverID, name string) string {
|
||||
if id := driver.CanonicalDriverID(driverID); id == "" || id == driver.BuiltinReimsMacOSDriverID {
|
||||
return name
|
||||
}
|
||||
return driver.NewVMRef(driverID, name).Key()
|
||||
}
|
||||
|
||||
// GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset).
|
||||
func (a *App) GetVMSSHUser(name string) string {
|
||||
d, err := a.GetVMDetail(name)
|
||||
func (a *App) GetVMSSHUser(name string) string { return a.GetVMSSHUserWithDriver("", name) }
|
||||
func (a *App) GetVMSSHUserWithDriver(driverID, name string) string {
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil || d.Directory == "" {
|
||||
return ""
|
||||
}
|
||||
@@ -41,12 +63,13 @@ func (a *App) GetVMSSHUser(name string) string {
|
||||
}
|
||||
|
||||
// SetVMSSHUser persists the preferred SSH login user for a VM.
|
||||
func (a *App) SetVMSSHUser(name, user string) error {
|
||||
func (a *App) SetVMSSHUser(name, user string) error { return a.SetVMSSHUserWithDriver("", name, user) }
|
||||
func (a *App) SetVMSSHUserWithDriver(driverID, name, user string) error {
|
||||
user = strings.TrimSpace(user)
|
||||
if user != "" && !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -64,7 +87,10 @@ func (a *App) SetVMSSHUser(name, user string) error {
|
||||
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
|
||||
// PowerShell) connected to the VM's forwarded SSH port.
|
||||
func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
return a.OpenSSHTerminalWithDriver("", name, user)
|
||||
}
|
||||
func (a *App) OpenSSHTerminalWithDriver(driverID, name, user string) error {
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -73,11 +99,11 @@ func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
user = a.GetVMSSHUserWithDriver(driverID, name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
_ = a.SetVMSSHUserWithDriver(driverID, name, user)
|
||||
}
|
||||
target := "127.0.0.1"
|
||||
if user != "" {
|
||||
@@ -95,14 +121,17 @@ func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("open SSH terminal: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
|
||||
return 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(name, user string) (string, error) {
|
||||
d, err := a.GetVMDetail(name)
|
||||
return a.WriteSSHConfigWithDriver("", name, user)
|
||||
}
|
||||
func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, error) {
|
||||
d, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -111,11 +140,11 @@ func (a *App) WriteSSHConfig(name, user string) (string, error) {
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
user = a.GetVMSSHUserWithDriver(driverID, name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return "", fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
_ = a.SetVMSSHUserWithDriver(driverID, name, user)
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
@@ -126,18 +155,21 @@ func (a *App) WriteSSHConfig(name, user string) (string, error) {
|
||||
return "", fmt.Errorf("create ~/.ssh: %w", err)
|
||||
}
|
||||
cfgPath := filepath.Join(sshDir, "config")
|
||||
alias := sshHostAlias(name)
|
||||
if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil {
|
||||
alias := sshHostAliasForDriver(driverID, name)
|
||||
if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, d.SSHPort, user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
|
||||
return alias, nil
|
||||
}
|
||||
|
||||
// OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and
|
||||
// launches VS Code (falling back to Cursor) in Remote-SSH mode.
|
||||
func (a *App) OpenVSCodeSSH(name, user string) error {
|
||||
alias, err := a.WriteSSHConfig(name, user)
|
||||
return a.OpenVSCodeSSHWithDriver("", name, user)
|
||||
}
|
||||
func (a *App) OpenVSCodeSSHWithDriver(driverID, name, user string) error {
|
||||
alias, err := a.WriteSSHConfigWithDriver(driverID, name, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -155,7 +187,7 @@ func (a *App) OpenVSCodeSSH(name, user string) error {
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("launch editor Remote-SSH: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
|
||||
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ import (
|
||||
)
|
||||
|
||||
func TestSSHHostAlias(t *testing.T) {
|
||||
if sshHostAliasForDriver("test.driver.linux", "dev") == sshHostAliasForDriver("", "dev") {
|
||||
t.Fatal("same-name drivers share an SSH alias")
|
||||
}
|
||||
if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
|
||||
+32
-66
@@ -1,13 +1,10 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
@@ -34,50 +31,28 @@ type VMStats struct {
|
||||
GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"`
|
||||
}
|
||||
|
||||
func resolveVMDiskPath(d reims.VMDetail) string {
|
||||
raw := strings.TrimSpace(d.Disk)
|
||||
// `reims-ctl show` formats disk like "disk.qcow2 (nvme, 128G)" or an absolute path.
|
||||
if idx := strings.Index(raw, " ("); idx > 0 {
|
||||
raw = strings.TrimSpace(raw[:idx])
|
||||
}
|
||||
if raw != "" {
|
||||
if filepath.IsAbs(raw) {
|
||||
return raw
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, raw)
|
||||
}
|
||||
}
|
||||
if d.Directory != "" {
|
||||
return filepath.Join(d.Directory, "disk.qcow2")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetVMStats samples QEMU CPU/memory usage (when running), disk actual vs
|
||||
// virtual capacity, and live Guest Tools status.
|
||||
func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
stats := VMStats{Name: name}
|
||||
c, err := a.client()
|
||||
// GetVMStats samples host-side process and disk telemetry through the owning driver.
|
||||
func (a *App) GetVMStats(name string) (VMStats, error) { return a.GetVMStatsWithDriver("", name) }
|
||||
func (a *App) GetVMStatsWithDriver(driverID, name string) (VMStats, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
return VMStats{Name: name}, err
|
||||
}
|
||||
ctx := context.Background()
|
||||
vms, _ := a.polledVMs(ctx)
|
||||
var pid int
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
stats.Running = vm.State == "running"
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
break
|
||||
ref := vm.Ref()
|
||||
stats := VMStats{Name: vm.Name, Running: vm.State == "running"}
|
||||
pid := 0
|
||||
if vm.PID != nil {
|
||||
pid = *vm.PID
|
||||
}
|
||||
if listed, ok := a.polledVMForDriver(ref.DriverID, vm.Name); ok {
|
||||
stats.Running = stats.Running || listed.State == "running"
|
||||
if listed.PID != nil {
|
||||
pid = *listed.PID
|
||||
}
|
||||
}
|
||||
stats.PID = pid
|
||||
|
||||
if diskPath := a.vmDiskPath(ctx, c, name); diskPath != "" {
|
||||
if du, err := host.InspectDiskUsage(diskPath); err == nil {
|
||||
if vm.DiskPath != "" {
|
||||
if du, err := host.InspectDiskUsage(vm.DiskPath); err == nil {
|
||||
stats.DiskActualBytes = du.ActualBytes
|
||||
stats.DiskVirtualBytes = du.VirtualBytes
|
||||
stats.DiskFormat = du.Format
|
||||
@@ -86,13 +61,12 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
stats.DiskBackingDepthWarn = du.BackingDepth >= host.BackingChainWarnDepth || du.BackingBroken
|
||||
}
|
||||
}
|
||||
|
||||
if stats.Running && pid > 0 {
|
||||
stats.WindowFullscreen = host.IsProcessWindowFullscreen(uint32(pid))
|
||||
if sample, err := host.SampleProcessStats(pid); err == nil {
|
||||
a.mu.Lock()
|
||||
prev := a.procSamples[name]
|
||||
a.procSamples[name] = sample
|
||||
prev := a.procSamples[ref.Key()]
|
||||
a.procSamples[ref.Key()] = sample
|
||||
a.mu.Unlock()
|
||||
stats.CPUPercent = host.ComputeCPUPercent(prev, sample, runtime.NumCPU())
|
||||
stats.MemoryRSSBytes = sample.WorkingSet
|
||||
@@ -105,28 +79,20 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
}
|
||||
} else {
|
||||
a.mu.Lock()
|
||||
delete(a.procSamples, name)
|
||||
delete(a.procSamples, ref.Key())
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if srv != nil {
|
||||
st := srv.Status(name, 15*time.Second)
|
||||
stats.GuestToolsConnected = st.Connected
|
||||
stats.GuestToolsMountMode = st.MountMode
|
||||
stats.GuestToolsAgentVersion = st.AgentVersion
|
||||
stats.GuestToolsSleepGuard = st.SleepActive
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if srv != nil {
|
||||
st := srv.Status(vm.Name, 15*time.Second)
|
||||
stats.GuestToolsConnected = st.Connected
|
||||
stats.GuestToolsMountMode = st.MountMode
|
||||
stats.GuestToolsAgentVersion = st.AgentVersion
|
||||
stats.GuestToolsSleepGuard = st.SleepActive
|
||||
}
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// ToggleBorderless switches borderless fullscreen startup via `reims-ctl set --borderless`.
|
||||
func (a *App) ToggleBorderless(name string, enabled bool) error {
|
||||
v := enabled
|
||||
return a.ApplyVMSettings(reims.SetOpts{
|
||||
Name: name,
|
||||
Borderless: &v,
|
||||
})
|
||||
}
|
||||
+101
-114
@@ -1,204 +1,188 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func enrichVMListStates(vms []reims.VMListItem) {
|
||||
for i := range vms {
|
||||
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
|
||||
vms[i].State = "suspended"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) populateSuspendDetail(d *reims.VMDetail) {
|
||||
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
|
||||
d.State = "suspended"
|
||||
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
|
||||
d.SuspendInfo = info
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) isVMSuspended(d reims.VMDetail) bool {
|
||||
return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory))
|
||||
}
|
||||
|
||||
// SuspendVM saves a VM's running state and closes its QEMU process.
|
||||
func (a *App) SuspendVM(name string) error {
|
||||
return a.SuspendVMWithDriver("", name)
|
||||
}
|
||||
|
||||
func (a *App) SuspendVMWithDriver(driverID, name string) error {
|
||||
a.networkMu.Lock()
|
||||
defer a.networkMu.Unlock()
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc, gt := a.lifecycleSvc, a.guestTools
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
end, err := a.beginSuspendTransition(name, "suspending")
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
end, err := a.beginSuspendTransition(key, ref.Name, "suspending")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer end()
|
||||
|
||||
a.mu.Lock()
|
||||
mgr, gt := a.pluginMgr, a.guestTools
|
||||
a.mu.Unlock()
|
||||
event := plugin.VMEventPayload{VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, event)
|
||||
}
|
||||
lastPct := -1
|
||||
info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) {
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
res, err := svc.Suspend(ctx, ref, func(p driver.SuspendProgress) {
|
||||
if pct, ok := suspendProgressPercent(p); ok {
|
||||
if pct >= lastPct+25 || p.Status == "completed" {
|
||||
lastPct = pct
|
||||
a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
||||
}
|
||||
}
|
||||
})
|
||||
}, w, w)
|
||||
if err != nil {
|
||||
a.emitLog(name, "Suspend error: "+err.Error())
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Suspend error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcherKey(key)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(name)
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, event)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(info.VMStateSize)/float64(1<<30)))
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", ref.Name, float64(res.VMStateSize)/float64(1<<30)))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResumeVM restores a suspended VM with its original media and devices.
|
||||
func (a *App) ResumeVM(name string) error {
|
||||
a.networkMu.Lock()
|
||||
defer a.networkMu.Unlock()
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockVM(a.baseCtx(), prep.Client, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return a.resumeLocked(prep, d)
|
||||
return a.ResumeVMWithDriver("", name)
|
||||
}
|
||||
|
||||
func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error {
|
||||
if err := a.restoreVMNetworkChannels(prep.Client, d); err != nil {
|
||||
func (a *App) ResumeVMWithDriver(driverID, name string) error {
|
||||
a.networkMu.Lock()
|
||||
defer a.networkMu.Unlock()
|
||||
if err := a.beginVMStart(); err != nil {
|
||||
return err
|
||||
}
|
||||
name := d.Name
|
||||
end, err := a.beginSuspendTransition(name, "resuming")
|
||||
defer a.vmStarts.Done()
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
end, err := a.beginSuspendTransition(key, ref.Name, "resuming")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer end()
|
||||
|
||||
a.mu.Lock()
|
||||
root, tmpDir, mgr := a.cfg.DataRoot, a.cfg.TempDir(), a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
var qmpAddr string
|
||||
if d.State == "stopped" && reims.HasSuspendState(d.Directory) && rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(d.Directory, tmpDir, name)
|
||||
if qmp.HasWin10RebootUnixArgs(d.ExtraArgs, sockPath) {
|
||||
a.cancelRebootWatcher(name)
|
||||
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove stale reboot socket: %w", err)
|
||||
}
|
||||
qmpAddr = "unix:" + sockPath
|
||||
var extraEnv []string
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcherKey(key)
|
||||
if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input") {
|
||||
extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory)...)
|
||||
}
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
||||
prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...)
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
||||
host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) {
|
||||
prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("client-window-close") {
|
||||
prep.Client.Env = append(prep.Client.Env, vmCloseRequestEnv(name)...)
|
||||
}
|
||||
|
||||
startAt := time.Now()
|
||||
out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
if err := prep.ResumeSnapshot(a.baseCtx(), d, rep, out, out); err != nil {
|
||||
a.emitLog(name, "Resume error: "+err.Error())
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
result, err := svc.Resume(ctx, ref, extraEnv, w, w)
|
||||
if err != nil {
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Resume error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
|
||||
VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, QMPAddr: qmpAddr,
|
||||
})
|
||||
} else if qmpAddr != "" {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
for _, action := range result.PostStart {
|
||||
if action.Kind != "qmp.watch_cold_reboot" {
|
||||
continue
|
||||
}
|
||||
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
|
||||
a.watchWin10ColdReboot(ref.Name, addr)
|
||||
}
|
||||
}
|
||||
a.startVMMonitor(ref.Name, vm, startAt)
|
||||
}
|
||||
a.startVMMonitor(name, d, startAt)
|
||||
a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds()))
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Resumed %s in %.1fs", ref.Name, time.Since(startAt).Seconds()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// DiscardSuspend deletes a stopped VM's saved execution state.
|
||||
func (a *App) DiscardSuspend(name string) error {
|
||||
c, err := a.client()
|
||||
return a.DiscardSuspendWithDriver("", name)
|
||||
}
|
||||
|
||||
func (a *App) DiscardSuspendWithDriver(driverID, name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, release, err := vmstart.LockVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
ref := vm.Ref()
|
||||
if err := svc.DiscardSuspend(ctx, ref); err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if err := vmstart.DiscardSnapshot(a.locale(), d); err != nil {
|
||||
return err
|
||||
}
|
||||
a.emitLog(name, "Discarded suspend state for "+name)
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Discarded suspend state for "+ref.Name)
|
||||
a.wakePoll()
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) beginSuspendTransition(name, state string) (func(), error) {
|
||||
func (a *App) beginSuspendTransition(key, displayName, state string) (func(), error) {
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
if a.transitions[name] != "" {
|
||||
if a.transitions[key] != "" {
|
||||
a.mu.Unlock()
|
||||
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
|
||||
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": displayName}, nil)
|
||||
}
|
||||
a.transitions[name] = state
|
||||
a.transitions[key] = state
|
||||
a.mu.Unlock()
|
||||
a.emitStateChanged()
|
||||
return func() {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, name)
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitStateChanged()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func suspendProgressPercent(p qmp.MigrateProgress) (int, bool) {
|
||||
func suspendProgressPercent(p driver.SuspendProgress) (int, bool) {
|
||||
if p.Status == "completed" {
|
||||
return 100, true
|
||||
}
|
||||
@@ -226,3 +210,6 @@ func (a *App) emitStateChanged() {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep context import used cleanly for future cancellation hooks.
|
||||
var _ context.Context
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
@@ -31,12 +31,12 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
vms := []reims.VMListItem{
|
||||
vms := []driver.VMListItem{
|
||||
{Name: "mac-a", Dir: suspendedDir, State: "stopped"},
|
||||
{Name: "mac-b", Dir: stoppedDir, State: "stopped"},
|
||||
{Name: "mac-c", Dir: suspendedDir, State: "running"},
|
||||
}
|
||||
enrichVMListStates(vms)
|
||||
enrichMacOSVMListStates(vms)
|
||||
if vms[0].State != "suspended" {
|
||||
t.Fatalf("mac-a state = %q, want suspended", vms[0].State)
|
||||
}
|
||||
@@ -47,15 +47,11 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
|
||||
t.Fatalf("running VM must stay running, got %q", vms[2].State)
|
||||
}
|
||||
|
||||
a := &App{}
|
||||
det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"}
|
||||
a.populateSuspendDetail(&det)
|
||||
populateSuspendDetail(&det)
|
||||
if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 {
|
||||
t.Fatalf("populateSuspendDetail failed: %+v", det)
|
||||
}
|
||||
if !a.isVMSuspended(det) {
|
||||
t.Fatal("expected isVMSuspended=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) {
|
||||
@@ -68,14 +64,14 @@ func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) {
|
||||
func TestSuspendProgressPercentTracksRemainingAcrossSparseRAM(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
prog qmp.MigrateProgress
|
||||
prog driver.SuspendProgress
|
||||
pct int
|
||||
ok bool
|
||||
}{
|
||||
{"setup", qmp.MigrateProgress{Status: "setup"}, 0, false},
|
||||
{"active sparse", qmp.MigrateProgress{Status: "active", Transferred: 400, Remaining: 1000, Total: 2000}, 50, true},
|
||||
{"device stage caps below 100", qmp.MigrateProgress{Status: "device", Transferred: 1080, Remaining: 0, Total: 2000}, 99, true},
|
||||
{"completed always 100", qmp.MigrateProgress{Status: "completed", Transferred: 1080, Remaining: 0, Total: 2000}, 100, true},
|
||||
{"setup", driver.SuspendProgress{Status: "setup"}, 0, false},
|
||||
{"active sparse", driver.SuspendProgress{Status: "active", Transferred: 400, Remaining: 1000, Total: 2000}, 50, true},
|
||||
{"device stage caps below 100", driver.SuspendProgress{Status: "device", Transferred: 1080, Remaining: 0, Total: 2000}, 99, true},
|
||||
{"completed always 100", driver.SuspendProgress{Status: "completed", Transferred: 1080, Remaining: 0, Total: 2000}, 100, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
+12
-12
@@ -14,7 +14,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -86,7 +86,7 @@ func (m *taskManager) startWithInstaller(kind, subject, vm, installerKind, insta
|
||||
now := time.Now().UnixMilli()
|
||||
step := ""
|
||||
if installerPhase == TaskPhaseQueued {
|
||||
step = installer.WaitingNote
|
||||
step = host.WaitingNote
|
||||
}
|
||||
e := &taskEntry{
|
||||
task: Task{
|
||||
@@ -117,7 +117,7 @@ func (m *taskManager) setInstaller(id, kind, version, phase string) {
|
||||
e.task.InstallerVersion = version
|
||||
e.task.InstallerPhase = phase
|
||||
if phase == TaskPhaseQueued {
|
||||
e.task.Step = installer.WaitingNote
|
||||
e.task.Step = host.WaitingNote
|
||||
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
||||
e.rate = rateMeter{}
|
||||
}
|
||||
@@ -150,7 +150,7 @@ func (m *taskManager) clearInstallerPhase(id string) {
|
||||
}
|
||||
|
||||
// update applies an upstream progress report to the task.
|
||||
func (m *taskManager) update(id string, u installer.Update) {
|
||||
func (m *taskManager) update(id string, u host.Update) {
|
||||
m.mu.Lock()
|
||||
e, ok := m.tasks[id]
|
||||
if !ok || e.task.Status != TaskRunning {
|
||||
@@ -159,8 +159,8 @@ func (m *taskManager) update(id string, u installer.Update) {
|
||||
}
|
||||
force := false
|
||||
switch u.Kind {
|
||||
case installer.KindNote:
|
||||
if u.Message != installer.WaitingNote || e.task.InstallerKind == "" {
|
||||
case host.KindNote:
|
||||
if u.Message != host.WaitingNote || e.task.InstallerKind == "" {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func (m *taskManager) update(id string, u installer.Update) {
|
||||
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
||||
e.rate = rateMeter{}
|
||||
force = true
|
||||
case installer.KindStep:
|
||||
case host.KindStep:
|
||||
if e.task.InstallerPhase == TaskPhaseQueued {
|
||||
e.task.InstallerPhase = TaskPhaseDownloading
|
||||
force = true
|
||||
@@ -182,7 +182,7 @@ func (m *taskManager) update(id string, u installer.Update) {
|
||||
e.task.Step = u.Message
|
||||
e.task.Done, e.task.Total, e.task.Percent, e.task.Rate = 0, 0, -1, 0
|
||||
e.rate = rateMeter{}
|
||||
case installer.KindProgress:
|
||||
case host.KindProgress:
|
||||
if e.task.InstallerPhase == TaskPhaseQueued {
|
||||
e.task.InstallerPhase = TaskPhaseDownloading
|
||||
force = true
|
||||
@@ -358,7 +358,7 @@ func (a *App) ensureTaskEmitter() {
|
||||
|
||||
// ctlTaskWriter returns a writer for reims-ctl output that routes progress
|
||||
// lines into a task and everything else to the log. reims-ctl prints its
|
||||
// progress as "<step>: N% of <size>" (installer.ParseCtlLine), sometimes behind
|
||||
// progress as "<step>: N% of <size>" (host.ParseCtlLine), sometimes behind
|
||||
// a "<vm>: " prefix, which is dropped from the step. Each new step is logged
|
||||
// once, so the log keeps the milestones without one line per percent.
|
||||
// finish closes the task with the command's error.
|
||||
@@ -374,11 +374,11 @@ func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc
|
||||
lastLogAt := time.Now()
|
||||
trim := func(s string) string { return strings.TrimPrefix(s, vm+": ") }
|
||||
w = vmstart.LineWriter(func(line string) {
|
||||
u, ok := installer.ParseCtlLine(line)
|
||||
u, ok := host.ParseCtlLine(line)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if u.Kind == installer.KindProgress {
|
||||
if u.Kind == host.KindProgress {
|
||||
u.Step = trim(u.Step)
|
||||
if u.Step != lastStep {
|
||||
lastStep = u.Step
|
||||
@@ -399,7 +399,7 @@ func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc
|
||||
step := trim(u.Message)
|
||||
lastStep = step
|
||||
lastLogAt = time.Now()
|
||||
tasks.update(id, installer.Update{Kind: installer.KindStep, Message: step, Percent: -1})
|
||||
tasks.update(id, host.Update{Kind: host.KindStep, Message: step, Percent: -1})
|
||||
})
|
||||
return id, w, func(err error) { tasks.finish(id, "", err) }
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
func newTestTasks(t *testing.T) *[]Task {
|
||||
|
||||
@@ -14,16 +14,16 @@ import (
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// VMThumbnail is one frame of a VM's screen as a data URL.
|
||||
@@ -42,20 +42,32 @@ var thumbLocks = struct {
|
||||
locks map[string]*sync.Mutex
|
||||
}{locks: make(map[string]*sync.Mutex)}
|
||||
|
||||
func (a *App) thumbPath(name string) string {
|
||||
func (a *App) thumbPath(name string) string { return a.thumbPathForDriver("", name) }
|
||||
func (a *App) thumbPathForDriver(driverID, name string) string {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.XDGCacheDir()
|
||||
a.mu.Unlock()
|
||||
return filepath.Join(dir, "thumbs", name+".jpg")
|
||||
prefix := ""
|
||||
if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID {
|
||||
prefix = strings.Map(func(r rune) rune {
|
||||
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
return r
|
||||
}
|
||||
return '_'
|
||||
}, id) + "__"
|
||||
}
|
||||
return filepath.Join(dir, "thumbs", prefix+name+".jpg")
|
||||
}
|
||||
|
||||
func vmThumbLock(name string) *sync.Mutex {
|
||||
func vmThumbLock(name string) *sync.Mutex { return vmThumbLockForDriver("", name) }
|
||||
func vmThumbLockForDriver(driverID, name string) *sync.Mutex {
|
||||
key := vmKeyForDriver(driverID, name)
|
||||
thumbLocks.mu.Lock()
|
||||
defer thumbLocks.mu.Unlock()
|
||||
mu := thumbLocks.locks[name]
|
||||
mu := thumbLocks.locks[key]
|
||||
if mu == nil {
|
||||
mu = &sync.Mutex{}
|
||||
thumbLocks.locks[name] = mu
|
||||
thumbLocks.locks[key] = mu
|
||||
}
|
||||
return mu
|
||||
}
|
||||
@@ -63,11 +75,12 @@ func vmThumbLock(name string) *sync.Mutex {
|
||||
// releaseVMThumbnail waits for an in-flight capture before releasing its lock,
|
||||
// so an old request cannot install a new lock after the VM has been deleted.
|
||||
func releaseVMThumbnail(name string) {
|
||||
key := vmKey(name)
|
||||
mu := vmThumbLock(name)
|
||||
mu.Lock()
|
||||
thumbLocks.mu.Lock()
|
||||
if thumbLocks.locks[name] == mu {
|
||||
delete(thumbLocks.locks, name)
|
||||
if thumbLocks.locks[key] == mu {
|
||||
delete(thumbLocks.locks, key)
|
||||
}
|
||||
thumbLocks.mu.Unlock()
|
||||
mu.Unlock()
|
||||
@@ -76,11 +89,14 @@ func releaseVMThumbnail(name string) {
|
||||
// GetVMThumbnail returns the VM's screen: a fresh frame while it runs, else
|
||||
// the last one saved. An empty DataURL means there is no frame to show.
|
||||
func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
path := a.thumbPath(name)
|
||||
mu := vmThumbLock(name)
|
||||
return a.GetVMThumbnailWithDriver("", name)
|
||||
}
|
||||
func (a *App) GetVMThumbnailWithDriver(driverID, name string) (VMThumbnail, error) {
|
||||
path := a.thumbPathForDriver(driverID, name)
|
||||
mu := vmThumbLockForDriver(driverID, name)
|
||||
if mu.TryLock() {
|
||||
defer mu.Unlock()
|
||||
if t, ok := a.captureThumb(name, path); ok {
|
||||
if t, ok := a.captureThumbWithDriver(driverID, name, path); ok {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
@@ -89,8 +105,13 @@ func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
|
||||
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
|
||||
// restoring it first if minimized.
|
||||
func (a *App) FocusVMWindow(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
func (a *App) FocusVMWindow(name string) error { return a.FocusVMWindowWithDriver("", name) }
|
||||
func (a *App) FocusVMWindowWithDriver(driverID, name string) error {
|
||||
info, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
||||
if !ok || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
@@ -101,87 +122,55 @@ func (a *App) FocusVMWindow(name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode.
|
||||
// ToggleVMFullscreen switches the running VM's display through its owning driver.
|
||||
func (a *App) ToggleVMFullscreen(name string) (bool, error) {
|
||||
return a.ToggleVMFullscreenWithDriver("", name)
|
||||
}
|
||||
func (a *App) ToggleVMFullscreenWithDriver(driverID, name string) (bool, error) {
|
||||
a.mu.Lock()
|
||||
preference := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(preference)
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err)
|
||||
}
|
||||
fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return fullscreen, nil
|
||||
}
|
||||
|
||||
type fullscreenVMClient interface {
|
||||
Show(context.Context, string) (reims.VMDetail, error)
|
||||
List(context.Context) ([]reims.VMListItem, error)
|
||||
}
|
||||
|
||||
func findRunningVMPID(vms []reims.VMListItem, name string) (uint32, bool) {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return uint32(*vm.PID), true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) {
|
||||
vars := i18n.Vars{"name": name}
|
||||
beforeVMs, err := c.List(ctx)
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidBefore, ok := findRunningVMPID(beforeVMs, name)
|
||||
if !ok {
|
||||
if vm.State != "running" {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
if detail.State != "running" {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
if detail.Graphics == "vmware-svga" {
|
||||
if graphics, _ := vm.DriverData["graphics"].(string); graphics == "vmware-svga" {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil)
|
||||
}
|
||||
afterVMs, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
pidAfter, ok := findRunningVMPID(afterVMs, name)
|
||||
if !ok || pidAfter != pidBefore {
|
||||
listed, ok := a.polledVMForDriver(vm.DriverID, name)
|
||||
if !ok || listed.PID == nil || *listed.PID <= 0 {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
||||
}
|
||||
fullscreen, err := toggleWindow(pidAfter)
|
||||
fullscreen, err := host.ToggleProcessWindowFullscreen(uint32(*listed.PID))
|
||||
if errors.Is(err, host.ErrDisplayWindowNotFound) {
|
||||
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err)
|
||||
}
|
||||
if err != nil {
|
||||
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
||||
}
|
||||
a.emitVMLogForDriver(vm.DriverID, name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
||||
a.emitLifecycleStateChanged()
|
||||
return fullscreen, nil
|
||||
}
|
||||
|
||||
// CopyVMScreenshot captures a full-resolution frame from a running VM over QMP
|
||||
// and writes it as a PNG/DIB image to the Windows clipboard.
|
||||
func (a *App) CopyVMScreenshot(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
func (a *App) CopyVMScreenshot(name string) error { return a.CopyVMScreenshotWithDriver("", name) }
|
||||
func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error {
|
||||
info, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
mu := vmThumbLock(name)
|
||||
mu := vmThumbLockForDriver(driverID, name)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
@@ -191,7 +180,7 @@ func (a *App) CopyVMScreenshot(name string) error {
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
raw := filepath.Join(tmp, "screenshot-"+name)
|
||||
raw := filepath.Join(tmp, "screenshot-"+strings.TrimSuffix(filepath.Base(a.thumbPathForDriver(driverID, name)), ".jpg"))
|
||||
defer os.Remove(raw)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
@@ -211,18 +200,25 @@ func (a *App) CopyVMScreenshot(name string) error {
|
||||
if err := (&guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil {
|
||||
return fmt.Errorf("copy image to clipboard: %w", err)
|
||||
}
|
||||
a.emitLog(name, "Copied VM screenshot to clipboard")
|
||||
a.emitVMLogForDriver(driverID, name, "Copied VM screenshot to clipboard")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
return a.captureThumbWithDriver("", name, path)
|
||||
}
|
||||
func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, bool) {
|
||||
typing.mu.Lock()
|
||||
busy := typing.busy[name]
|
||||
busy := typing.busy[vmKeyForDriver(driverID, name)]
|
||||
typing.mu.Unlock()
|
||||
if busy {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
vm, ok := a.polledVM(name)
|
||||
info, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
@@ -238,7 +234,7 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
raw := filepath.Join(tmp, "screendump-"+name)
|
||||
raw := filepath.Join(tmp, "screendump-"+strings.TrimSuffix(filepath.Base(path), ".jpg"))
|
||||
defer os.Remove(raw)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
func TestReleaseVMThumbnailRemovesLock(t *testing.T) {
|
||||
|
||||
+25
-20
@@ -82,16 +82,17 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
return 0, errors.New("nothing to type")
|
||||
}
|
||||
|
||||
key := vmKey(name)
|
||||
typing.mu.Lock()
|
||||
if typing.busy[name] {
|
||||
if typing.busy[key] {
|
||||
typing.mu.Unlock()
|
||||
return 0, fmt.Errorf("%s is already being typed into", name)
|
||||
}
|
||||
typing.busy[name] = true
|
||||
typing.busy[key] = true
|
||||
typing.mu.Unlock()
|
||||
defer func() {
|
||||
typing.mu.Lock()
|
||||
delete(typing.busy, name)
|
||||
delete(typing.busy, key)
|
||||
typing.mu.Unlock()
|
||||
}()
|
||||
|
||||
@@ -132,12 +133,12 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
if err == nil {
|
||||
n := utf8.RuneCountInString(text)
|
||||
if !fromRemoteIME {
|
||||
a.emitLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
|
||||
a.emitVMLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
if !errors.Is(err, guesttools.ErrGuestToolsNotConnected) {
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
|
||||
a.emitVMLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,26 +149,26 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
if errors.As(err, &ue) {
|
||||
if fromRemoteIME {
|
||||
typing.mu.Lock()
|
||||
last := typing.lastHintAt[name]
|
||||
last := typing.lastHintAt[key]
|
||||
shouldLog := time.Since(last) > 15*time.Second
|
||||
if shouldLog {
|
||||
typing.lastHintAt[name] = time.Now()
|
||||
typing.lastHintAt[key] = time.Now()
|
||||
}
|
||||
typing.mu.Unlock()
|
||||
if shouldLog {
|
||||
a.emitLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
|
||||
a.emitVMLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).")
|
||||
}
|
||||
} else {
|
||||
a.emitLog(name, "Paste as keystrokes refused: "+ue.Error())
|
||||
a.emitVMLog(name, "Paste as keystrokes refused: "+ue.Error())
|
||||
}
|
||||
return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error())
|
||||
}
|
||||
if err != nil {
|
||||
a.emitLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
|
||||
a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err))
|
||||
return n, err
|
||||
}
|
||||
if !fromRemoteIME {
|
||||
a.emitLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
|
||||
a.emitVMLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -176,17 +177,21 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool)
|
||||
// or the reims-vgpu-window WM_CHAR bridge (/v1/host-text) onto a per-VM FIFO
|
||||
// worker so rapid IME bursts are delivered strictly in order without drops.
|
||||
func (a *App) injectRemoteText(vmName, vmDir, text string) {
|
||||
a.injectRemoteTextRef(vmKey(vmName), vmName, vmDir, text)
|
||||
}
|
||||
|
||||
func (a *App) injectRemoteTextRef(key, vmName, vmDir, text string) {
|
||||
if vmName == "" || text == "" {
|
||||
return
|
||||
}
|
||||
typing.mu.Lock()
|
||||
ch, ok := typing.remoteQueues[vmName]
|
||||
ch, ok := typing.remoteQueues[key]
|
||||
if !ok {
|
||||
ch = make(chan remoteTextItem, 32)
|
||||
typing.remoteQueues[vmName] = ch
|
||||
go a.runRemoteTextQueue(vmName, ch)
|
||||
typing.remoteQueues[key] = ch
|
||||
go a.runRemoteTextQueue(key, vmName, ch)
|
||||
}
|
||||
if typing.closing[vmName] {
|
||||
if typing.closing[key] {
|
||||
typing.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -201,7 +206,7 @@ func (a *App) injectRemoteText(vmName, vmDir, text string) {
|
||||
|
||||
func releaseVMTyping(vmName string) {
|
||||
typing.mu.Lock()
|
||||
names := []string{vmName}
|
||||
names := []string{vmKey(vmName)}
|
||||
if vmName == "" {
|
||||
names = make([]string, 0, len(typing.remoteQueues))
|
||||
for name := range typing.remoteQueues {
|
||||
@@ -220,12 +225,12 @@ func releaseVMTyping(vmName string) {
|
||||
typing.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) {
|
||||
func (a *App) runRemoteTextQueue(key, vmName string, ch <-chan remoteTextItem) {
|
||||
defer func() {
|
||||
typing.mu.Lock()
|
||||
delete(typing.remoteQueues, vmName)
|
||||
delete(typing.lastHintAt, vmName)
|
||||
delete(typing.closing, vmName)
|
||||
delete(typing.remoteQueues, key)
|
||||
delete(typing.lastHintAt, key)
|
||||
delete(typing.closing, key)
|
||||
typing.mu.Unlock()
|
||||
}()
|
||||
for item := range ch {
|
||||
|
||||
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user