Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
107a8d73e0 | ||
|
|
96ea9928e0 | ||
|
|
08409a1fa3 | ||
|
|
bff26d8fe1 | ||
|
|
c7419e7196 | ||
|
|
1e1649ed03 | ||
|
|
6388865cbb | ||
|
|
6f22f20fae | ||
|
|
e180b55a7b | ||
|
|
24da891365 | ||
|
|
e24422176a | ||
|
|
8ea7e3141e | ||
|
|
892d67644b | ||
|
|
875f4df333 | ||
|
|
6501fe2000 | ||
|
|
e0a25bb243 | ||
|
|
e25c7952ca |
No files matched your search
@@ -24,6 +24,7 @@ concurrency:
|
||||
jobs:
|
||||
plan:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
|
||||
@@ -3,8 +3,24 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- 'README.md'
|
||||
- 'README.*.md'
|
||||
- 'AGENTS.md'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
- '.github/PULL_REQUEST_TEMPLATE.md'
|
||||
- '.github/readme/**'
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- 'README.md'
|
||||
- 'README.*.md'
|
||||
- 'AGENTS.md'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
- '.github/PULL_REQUEST_TEMPLATE.md'
|
||||
- '.github/readme/**'
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.event.pull_request.number || github.ref }}
|
||||
@@ -16,6 +32,7 @@ env:
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 30
|
||||
outputs:
|
||||
rolling: ${{ steps.rolling.outputs.publish }}
|
||||
steps:
|
||||
@@ -28,8 +45,15 @@ jobs:
|
||||
PREVIOUS_SHA: ${{ github.event.before }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$publish = $true
|
||||
if ($env:PREVIOUS_SHA -notmatch '^0+$') {
|
||||
# Read the commit object so shallow checkouts retain its parent headers.
|
||||
$commitLines = @(git cat-file commit HEAD)
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not read the main commit' }
|
||||
$headerEnd = [Array]::IndexOf($commitLines, '')
|
||||
if ($headerEnd -lt 1) { throw 'Could not locate the main commit message' }
|
||||
$parents = @($commitLines[0..($headerEnd - 1)] -like 'parent *')
|
||||
$subject = $commitLines[$headerEnd + 1]
|
||||
$publish = $parents.Count -le 1 -and $subject -like '*#*' -and $subject -notlike '*docs*'
|
||||
if ($publish -and $env:PREVIOUS_SHA -notmatch '^0+$') {
|
||||
git fetch --depth=1 origin $env:PREVIOUS_SHA
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not fetch the previous main commit' }
|
||||
$changed = git diff --name-only $env:PREVIOUS_SHA HEAD -- . ':(exclude)docs/**' ':(exclude)README.md' ':(exclude,glob)README.*.md' ':(exclude)AGENTS.md' ':(exclude).github/ISSUE_TEMPLATE/**' ':(exclude).github/PULL_REQUEST_TEMPLATE.md' ':(exclude).github/readme/**'
|
||||
|
||||
@@ -17,6 +17,7 @@ env:
|
||||
jobs:
|
||||
dev-release:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -136,6 +137,8 @@ jobs:
|
||||
|
||||
- name: Build Windows x64 binary
|
||||
shell: pwsh
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ver = $env:DEV_VERSION
|
||||
|
||||
@@ -25,6 +25,7 @@ env:
|
||||
jobs:
|
||||
release:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -102,6 +103,8 @@ jobs:
|
||||
|
||||
- name: Build Windows x64 binary
|
||||
shell: pwsh
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
|
||||
@@ -4,6 +4,20 @@
|
||||
|
||||
Client releases are listed newest first. Release notes for portable runtimes (`runtime-*`) are available on [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases).
|
||||
|
||||
## v0.2.15 — 2026-12-05
|
||||
|
||||
[中文](#cn-v0.2.15) | [English](#en-v0.2.15)
|
||||
|
||||
<h3 id="cn-v0.2.15">问题修复</h3>
|
||||
|
||||
- 插件退出或长时间不再调用后,宿主替它抬起按住的输入时若释放失败会自动重试,不再让修饰键一直卡在客体里。释放期间插件新按下的键不会被误抬起,也不会从宿主记录中丢失。 — [@Nwflower](https://github.com/Nwflower)
|
||||
- 主运行时发布仓库无法访问时,自动从 `Nwflower/Reims-Go` 检查可用运行时。 — [@Nwflower](https://github.com/Nwflower)
|
||||
|
||||
<h3 id="en-v0.2.15">Bug Fixes</h3>
|
||||
|
||||
- When the host lifts input a plugin left held and that release fails, it now retries instead of leaving a modifier stuck in the guest. A key the plugin pressed while a release was in flight is no longer lifted by mistake or dropped from the host's record. — [@Nwflower](https://github.com/Nwflower)
|
||||
- Check `Nwflower/Reims-Go` for available runtimes when the primary runtime release repository is unavailable. — [@Nwflower](https://github.com/Nwflower)
|
||||
|
||||
## v0.2.14 — 2026-12-05
|
||||
|
||||
[中文](#cn-v0.2.14) | [English](#en-v0.2.14)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["reiasu2"],
|
||||
"zh": "虚拟机可在冷启动时自动选用当前目标显示器的推荐分辨率。",
|
||||
"en": "VMs can automatically use the target monitor's recommended resolution on cold start."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "chores",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "滚动开发版仅在合入主分支的提交标题包含 `#` 且不包含 `docs` 时自动构建。",
|
||||
"en": "Automatically build rolling Dev releases only when the commit title on the main branch contains `#` and does not contain `docs`."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["cosimawei"],
|
||||
"zh": "在插件市场点击安装或更新时直接使用市场推荐的最新版本。",
|
||||
"en": "Install or update directly to the latest version offered by the plugin market."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "移动硬盘换盘符后,即使旧版已保存新的数据目录,客户端启动或重新选择目录时仍会修复默认位置虚拟机的旧路径。([#181](https://github.com/Nwflower/Reims-Go/issues/181))",
|
||||
"en": "Repair stale paths for VMs in the default location when the client opens or reselects a data folder after an external drive changes letters, even if an older version already saved the new folder. ([#181](https://github.com/Nwflower/Reims-Go/issues/181))"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "虚拟机的 Vulkan 清单丢失或无法枚举显卡时,客户端会保存唯一匹配的新清单,找不到时改为自动选卡,再继续启动。",
|
||||
"en": "If a VM's Vulkan manifest is missing or cannot enumerate GPUs, the client saves the only matching replacement if one exists, otherwise selects Automatic, then continues startup."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 10,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "应用内更新改为优先下载已校验的 `.zip` 压缩包(更新流量减少约 62%),并优化物理桥接转发吞吐与离线安装镜像 PBZX 并发解压速度。",
|
||||
"en": "Download verified `.zip` release archives for in-app updates (~62% smaller update downloads), reduce per-packet allocations in the packet bridge, and parallelize PBZX chunk decompression for offline installer packages."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "removals",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "移除按虚拟机设置的修饰键重映射和「拦截宿主机全局热键」。升级后,原有设置停止生效,虚拟机恢复默认按键处理。",
|
||||
"en": "Remove per-VM modifier-key remapping and host global shortcut blocking. Existing settings stop taking effect after upgrading, and VMs return to default keyboard handling."
|
||||
}
|
||||
+2
-2
@@ -13,7 +13,7 @@
|
||||
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
|
||||
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
|
||||
|
||||
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。`main` 的滚动版复用同一提交的 CI 测试,手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
|
||||
GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。滚动开发版检查推送到 `main` 的最新提交消息的第一行,包含 `#` 且不包含 `docs`(忽略大小写)时才复用该提交的 CI 测试自动构建。自动构建跳过有多个父提交的合并提交及纯文档推送。手动构建会跑 CI 测试并冒烟。带版本标签的发布与每日 Alpha 先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。
|
||||
|
||||
桌面冒烟需要已安装 WebView2 Runtime 的 Windows 桌面会话。测试通过 Windows UI Automation 填入独立的数据目录、点击继续,检查配置和目录指针落盘,并等待运行时设置页渲染。每次运行使用独立的 WebView2 配置目录。失败时,测试入口打印保留的目录,应用日志在其中的 `app.log`。
|
||||
|
||||
@@ -25,7 +25,7 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限
|
||||
|
||||
## 覆盖和后续改进
|
||||
|
||||
- 前端测试直接加载生产模块验证任务排序、过期事件和键位映射。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
|
||||
- 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。
|
||||
- Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。
|
||||
- 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。
|
||||
- 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.2.14",
|
||||
"version": "0.2.15",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1 +1 @@
|
||||
282bb36bb366f28f2448bfe5025195e9
|
||||
e81d377cfdb873b5f163107395859d09
|
||||
@@ -0,0 +1,712 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const mod = await loadTestModule(`
|
||||
import './i18n/domains/settings.gen'
|
||||
import './i18n/domains/wizard.gen'
|
||||
export * from './i18n'
|
||||
export * from './lib/format'
|
||||
export * from './lib/displayResolution'
|
||||
`)
|
||||
|
||||
const host4K150 = {
|
||||
primary_display: { width: 3840, height: 2160, scale_pct: 150, work_width: 3840, work_height: 2088, primary: true },
|
||||
display_presets: [
|
||||
{ resolution: '3200x1800', label: '3200 × 1800', hidpi: true, recommended: true },
|
||||
{ resolution: '2880x1620', label: '2880 × 1620', hidpi: true },
|
||||
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
|
||||
],
|
||||
fullscreen_hidpi: true,
|
||||
recommended_gpu: { name: 'NVIDIA GeForce RTX 4070', kind: 'discrete' },
|
||||
gpus: [{ name: 'NVIDIA GeForce RTX 4070', kind: 'discrete' }],
|
||||
}
|
||||
|
||||
const host32K200 = {
|
||||
primary_display: { width: 3200, height: 2000, scale_pct: 200, work_width: 3200, work_height: 1904, primary: true },
|
||||
display_presets: [
|
||||
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: true, recommended: true },
|
||||
{ resolution: '2560x1600', label: '2560 × 1600', hidpi: true },
|
||||
{ resolution: '1920x1200', label: '1920 × 1200', hidpi: false },
|
||||
],
|
||||
fullscreen_hidpi: true,
|
||||
recommended_gpu: { name: 'Intel(R) Arc Graphics', kind: 'integrated' },
|
||||
gpus: [{ name: 'Intel(R) Arc Graphics', kind: 'integrated' }],
|
||||
}
|
||||
|
||||
test('resolveAutoDisplayPreset matches Go RecommendAutoResolution for 4K 16:9 and 3.2K 16:10', () => {
|
||||
// 4K 16:9 @ 150%
|
||||
const win4k = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
assert.equal(win4k.resolution, '3200x1800')
|
||||
assert.equal(win4k.hidpi, true)
|
||||
|
||||
const fs4kFixed = mod.resolveAutoDisplayPreset(host4K150, true, true)
|
||||
assert.equal(fs4kFixed.resolution, '5120x2880')
|
||||
assert.equal(fs4kFixed.hidpi, true)
|
||||
assert.equal(fs4kFixed.scaleBadge, '1.5×')
|
||||
|
||||
const fs4kNoFixed = mod.resolveAutoDisplayPreset(host4K150, true, false)
|
||||
assert.equal(fs4kNoFixed.resolution, '3840x2160')
|
||||
assert.equal(fs4kNoFixed.hidpi, true)
|
||||
assert.equal(fs4kNoFixed.native, true)
|
||||
|
||||
// 3.2K 16:10 @ 200% (scale >= 175 -> native fullscreen even with fixedModeSupported)
|
||||
const win32k = mod.resolveAutoDisplayPreset(host32K200, false, true)
|
||||
assert.equal(win32k.resolution, '2880x1800')
|
||||
assert.equal(win32k.hidpi, true)
|
||||
|
||||
const fs32kFixed = mod.resolveAutoDisplayPreset(host32K200, true, true)
|
||||
assert.equal(fs32kFixed.resolution, '3200x2000')
|
||||
assert.equal(fs32kFixed.hidpi, true)
|
||||
assert.equal(fs32kFixed.native, true)
|
||||
|
||||
const fs32kNoFixed = mod.resolveAutoDisplayPreset(host32K200, true, false)
|
||||
assert.equal(fs32kNoFixed.resolution, '3200x2000')
|
||||
assert.equal(fs32kNoFixed.hidpi, true)
|
||||
assert.equal(fs32kNoFixed.native, true)
|
||||
})
|
||||
|
||||
test('resolveAutoDisplayPreset falls back safely to 1920x1080 non-HiDPI when host display is empty or invalid (#6)', () => {
|
||||
const emptyHost = {}
|
||||
const winEmpty = mod.resolveAutoDisplayPreset(emptyHost, false, true)
|
||||
assert.equal(winEmpty.resolution, '1920x1080')
|
||||
assert.equal(winEmpty.hidpi, false)
|
||||
|
||||
for (const fixedModeSupported of [true, false]) {
|
||||
const fsEmpty = mod.resolveAutoDisplayPreset(emptyHost, true, fixedModeSupported)
|
||||
assert.equal(fsEmpty.resolution, '1920x1080')
|
||||
assert.equal(fsEmpty.label, '1920 × 1080')
|
||||
assert.equal(fsEmpty.hidpi, false)
|
||||
assert.equal(fsEmpty.native, true)
|
||||
assert.equal(fsEmpty.recommended, true)
|
||||
|
||||
const zeroHeightHost = {
|
||||
primary_display: { width: 3200, height: 0, scale_pct: 150, primary: true },
|
||||
fullscreen_hidpi: true,
|
||||
}
|
||||
const fsZeroHeight = mod.resolveAutoDisplayPreset(zeroHeightHost, true, fixedModeSupported)
|
||||
assert.equal(fsZeroHeight.resolution, '1920x1080')
|
||||
assert.equal(fsZeroHeight.label, '1920 × 1080')
|
||||
assert.equal(fsZeroHeight.hidpi, false)
|
||||
assert.equal(fsZeroHeight.native, true)
|
||||
}
|
||||
})
|
||||
|
||||
test('SettingsModal auto resolution never falls into custom or resBad across display and borderless switches', () => {
|
||||
// Auto mode with a resolution from 4K screen, now moved to 3.2K screen where 3200x1800 is not a preset
|
||||
const onLaptop = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: true, resolution: '3200x1800', borderless: false },
|
||||
displayProfile: host32K200,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(onLaptop.presetHit, false)
|
||||
assert.equal(onLaptop.customRes, false)
|
||||
assert.equal(onLaptop.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(onLaptop.resBad, false)
|
||||
assert.equal(onLaptop.autoPreset.resolution, '2880x1800')
|
||||
|
||||
// Even empty or invalid resolution string must not trigger resBad while auto_resolution is on
|
||||
const emptyResAuto = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: true, resolution: '', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.equal(emptyResAuto.customRes, false)
|
||||
assert.equal(emptyResAuto.resBad, false)
|
||||
assert.equal(emptyResAuto.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
|
||||
// Toggling borderless in auto mode keeps auto_resolution intact and refreshes autoPreset
|
||||
const borderlessPatch = mod.toggleSettingsBorderless({
|
||||
borderless: true,
|
||||
form: { auto_resolution: true, resolution: '3200x1800' },
|
||||
displayProfile: host4K150,
|
||||
targetDisplay: host4K150.primary_display,
|
||||
presets: onLaptop.presets,
|
||||
fsPresets: onLaptop.fsPresets,
|
||||
customRes: false,
|
||||
})
|
||||
assert.deepEqual(borderlessPatch, { borderless: true })
|
||||
|
||||
const afterBorderless = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: true, resolution: '3200x1800', borderless: true },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(afterBorderless.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(afterBorderless.autoPreset.resolution, '5120x2880')
|
||||
})
|
||||
|
||||
test('SettingsModal dirty count, save payload, reset, and custom blur snap-back behave consistently', () => {
|
||||
const baseFixed = { name: 'mac', auto_resolution: false, resolution: '3200x1800', borderless: false }
|
||||
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
|
||||
// Fixed -> Auto: keeps base.resolution so only auto_resolution is dirty (count = 1), save diff omits resolution
|
||||
const toAuto = mod.selectSettingsResolution({
|
||||
value: mod.AUTO_RESOLUTION_OPTION,
|
||||
form: { resolution: '2560x1440' },
|
||||
base: baseFixed,
|
||||
autoPreset,
|
||||
})
|
||||
assert.equal(toAuto.forceCustomRes, false)
|
||||
assert.deepEqual(toAuto.patch, { auto_resolution: true, resolution: '3200x1800' })
|
||||
assert.equal(mod.countChangedSettingsFields(['auto_resolution']), 1)
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], { ...baseFixed, auto_resolution: true, resolution: '2560x1440' }),
|
||||
{ name: 'mac', auto_resolution: true },
|
||||
)
|
||||
|
||||
// Auto -> Fixed different resolution: both fields dirty, UI count = 1, save diff sends both
|
||||
assert.equal(mod.countChangedSettingsFields(['auto_resolution', 'resolution']), 1)
|
||||
assert.equal(mod.countChangedSettingsFields(['auto_resolution', 'resolution', 'borderless']), 2)
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], { ...baseFixed, auto_resolution: false, resolution: '2560x1440' }),
|
||||
{ name: 'mac', auto_resolution: false, resolution: '2560x1440' },
|
||||
)
|
||||
|
||||
// Selecting custom disables auto_resolution and falls back to autoPreset when empty
|
||||
const toCustom = mod.selectSettingsResolution({
|
||||
value: mod.CUSTOM_RESOLUTION_OPTION,
|
||||
form: { resolution: '' },
|
||||
base: baseFixed,
|
||||
autoPreset,
|
||||
})
|
||||
assert.equal(toCustom.forceCustomRes, true)
|
||||
assert.deepEqual(toCustom.patch, { auto_resolution: false, resolution: '3200x1800' })
|
||||
|
||||
// Typing a known preset in custom input snaps back to preset card on blur
|
||||
const typedPreset = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: false, resolution: '3200x1800', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.equal(typedPreset.presetHit, true)
|
||||
assert.equal(typedPreset.customRes, true)
|
||||
assert.equal(
|
||||
mod.shouldExitCustomResOnBlur({ autoResolution: false, forceCustomRes: true, presetHit: typedPreset.presetHit }),
|
||||
true,
|
||||
)
|
||||
|
||||
// Typing an invalid custom resolution triggers resBad and does not snap back
|
||||
const typedInvalid = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: false, resolution: 'not-a-res', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.equal(typedInvalid.presetHit, false)
|
||||
assert.equal(typedInvalid.resBad, true)
|
||||
assert.equal(
|
||||
mod.shouldExitCustomResOnBlur({ autoResolution: false, forceCustomRes: true, presetHit: typedInvalid.presetHit }),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test('CreateWizard defaults to auto resolution and keeps preview resolution synced on borderless toggle', () => {
|
||||
const init = mod.initialWizardResolution(host4K150, true)
|
||||
assert.deepEqual(init, { auto_resolution: true, resolution: '3200x1800' })
|
||||
|
||||
const windowPresets = mod.windowDisplayPresets(host4K150, true)
|
||||
const fullscreenPresets = mod.fullscreenDisplayPresets(host4K150)
|
||||
|
||||
// Toggling borderless ON in auto mode updates preview resolution to fullscreen auto preset
|
||||
const fsOnFixed = mod.toggleWizardBorderless({
|
||||
borderless: true,
|
||||
opts: init,
|
||||
host: host4K150,
|
||||
fixedModeSupported: true,
|
||||
windowPresets,
|
||||
fullscreenPresets,
|
||||
})
|
||||
assert.deepEqual(fsOnFixed, { borderless: true, auto_resolution: true, resolution: '5120x2880' })
|
||||
|
||||
const fsOnNoFixed = mod.toggleWizardBorderless({
|
||||
borderless: true,
|
||||
opts: init,
|
||||
host: host4K150,
|
||||
fixedModeSupported: false,
|
||||
windowPresets,
|
||||
fullscreenPresets,
|
||||
})
|
||||
assert.deepEqual(fsOnNoFixed, { borderless: true, auto_resolution: true, resolution: '3840x2160' })
|
||||
|
||||
// Selecting a fixed preset turns auto_resolution off
|
||||
const fixedChoice = mod.selectWizardResolution('2560x1440', mod.resolveAutoDisplayPreset(host4K150, false, true))
|
||||
assert.deepEqual(fixedChoice, { auto_resolution: false, resolution: '2560x1440' })
|
||||
|
||||
// Selecting AUTO turns auto_resolution back on with current autoPreset
|
||||
const autoChoice = mod.selectWizardResolution(mod.AUTO_RESOLUTION_OPTION, mod.resolveAutoDisplayPreset(host4K150, true, true))
|
||||
assert.deepEqual(autoChoice, { auto_resolution: true, resolution: '5120x2880' })
|
||||
})
|
||||
|
||||
test('VM summary, formatResolutionLabel, and pendingChangeText format auto_resolution in zh-CN and en-US', () => {
|
||||
const trZh = (k, v) => mod.t('zh-CN', k, v)
|
||||
const trEn = (k, v) => mod.t('en-US', k, v)
|
||||
|
||||
assert.equal(mod.formatResolutionLabel('3200x1800', true, trZh), '自动(3200 × 1800)')
|
||||
assert.equal(mod.formatResolutionLabel('3200x1800', true, trEn), 'Auto (3200 × 1800)')
|
||||
assert.equal(mod.formatResolutionLabel('3200x1800', false, trZh), '3200 × 1800')
|
||||
assert.equal(mod.formatResolutionLabel('', true, trEn), 'Auto')
|
||||
|
||||
const autoDetail = {
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: 'auto',
|
||||
resolution: '3200x1800',
|
||||
auto_resolution: true,
|
||||
displays: 1,
|
||||
}
|
||||
assert.equal(mod.graphicsLabel('zh-CN', autoDetail, host4K150), 'RTX 4070 · 自动(3200 × 1800)')
|
||||
assert.equal(mod.graphicsLabel('en-US', autoDetail, host4K150), 'RTX 4070 · Auto (3200 × 1800)')
|
||||
|
||||
const fixedDetail = { ...autoDetail, auto_resolution: false }
|
||||
assert.equal(mod.graphicsLabel('en-US', fixedDetail, host4K150), 'RTX 4070 · 1800p')
|
||||
|
||||
const pendingOnZh = mod.pendingChangeText('zh-CN', { field: 'auto_resolution', from: 'false', to: 'true' }, host4K150)
|
||||
const pendingOffEn = mod.pendingChangeText('en-US', { field: 'auto_resolution', from: 'true', to: 'false' }, host4K150)
|
||||
assert.equal(pendingOnZh, '自动分辨率 关闭 → 开启')
|
||||
assert.equal(pendingOffEn, 'Auto resolution On → Off')
|
||||
assert.ok(!pendingOnZh.includes('auto_resolution'))
|
||||
assert.ok(!pendingOffEn.includes('auto_resolution'))
|
||||
})
|
||||
|
||||
test('vmware-svga disables and hides auto resolution across wizard, settings, and summary (#5)', () => {
|
||||
// Wizard initialization: svga defaults to auto_resolution: false, reims-vgpu defaults to true
|
||||
assert.deepEqual(mod.initialWizardResolution(host4K150, true, 'vmware-svga'), {
|
||||
auto_resolution: false,
|
||||
resolution: '3200x1800',
|
||||
})
|
||||
assert.deepEqual(mod.initialWizardResolution(host4K150, true, 'reims-vgpu'), {
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
})
|
||||
|
||||
// Switching graphics in wizard disables auto on svga, and restores auto on reims-vgpu only if user did not pick a fixed preset
|
||||
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
assert.deepEqual(
|
||||
mod.switchWizardGraphics({ graphics: 'vmware-svga', manualResolutionPicked: false, autoPreset }),
|
||||
{ graphics: 'vmware-svga', auto_resolution: false },
|
||||
)
|
||||
assert.deepEqual(
|
||||
mod.switchWizardGraphics({ graphics: 'reims-vgpu', manualResolutionPicked: false, autoPreset }),
|
||||
{ graphics: 'reims-vgpu', auto_resolution: true, resolution: '3200x1800' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
mod.switchWizardGraphics({ graphics: 'reims-vgpu', manualResolutionPicked: true, autoPreset }),
|
||||
{ graphics: 'reims-vgpu' },
|
||||
)
|
||||
|
||||
// SettingsModal switching to svga only patches graphics and exits custom input (R2 #11)
|
||||
assert.deepEqual(mod.switchSettingsGraphics('vmware-svga'), {
|
||||
patch: { graphics: 'vmware-svga' },
|
||||
forceCustomRes: false,
|
||||
})
|
||||
const svgaState = mod.deriveSettingsResolutionState({
|
||||
form: { graphics: 'vmware-svga', auto_resolution: true, resolution: 'not-a-res', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.notEqual(svgaState.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(svgaState.customRes, false)
|
||||
assert.equal(svgaState.resBad, false)
|
||||
|
||||
// R2 #2: SVGA never includes the AUTO resolution card in SettingsModal or CreateWizard options
|
||||
const activePresets = mod.windowDisplayPresets(host4K150, true)
|
||||
const settingsSvgaOpts = mod.buildResolutionOptions({
|
||||
graphics: 'vmware-svga',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
includeCustom: true,
|
||||
})
|
||||
const wizardSvgaOpts = mod.buildResolutionOptions({
|
||||
graphics: 'vmware-svga',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
})
|
||||
assert.equal(settingsSvgaOpts.some((o) => o.value === mod.AUTO_RESOLUTION_OPTION), false)
|
||||
assert.equal(wizardSvgaOpts.some((o) => o.value === mod.AUTO_RESOLUTION_OPTION), false)
|
||||
const settingsVgpuOpts = mod.buildResolutionOptions({
|
||||
graphics: 'reims-vgpu',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
includeCustom: true,
|
||||
})
|
||||
const wizardVgpuOpts = mod.buildResolutionOptions({
|
||||
graphics: 'reims-vgpu',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
})
|
||||
assert.equal(settingsVgpuOpts[0].value, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(wizardVgpuOpts[0].value, mod.AUTO_RESOLUTION_OPTION)
|
||||
|
||||
// Settings save diff never sends auto_resolution: true for vmware-svga
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['graphics', 'auto_resolution'], {
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
auto_resolution: true,
|
||||
resolution: '1920x1080',
|
||||
}),
|
||||
{ name: 'mac', graphics: 'vmware-svga', auto_resolution: false },
|
||||
)
|
||||
|
||||
// graphicsLabel never renders auto resolution label for vmware-svga
|
||||
const svgaDetail = {
|
||||
graphics: 'vmware-svga',
|
||||
gpu: 'auto',
|
||||
resolution: '3200x1800',
|
||||
auto_resolution: true,
|
||||
displays: 1,
|
||||
}
|
||||
assert.equal(mod.graphicsLabel('zh-CN', svgaDetail, host4K150), mod.t('zh-CN', 'softwareGraphics'))
|
||||
assert.equal(mod.graphicsLabel('en-US', svgaDetail, host4K150), mod.t('en-US', 'softwareGraphics'))
|
||||
})
|
||||
|
||||
test('installer wizard draft enables auto resolution by default while preserving user fixed drafts (#7)', () => {
|
||||
const installerDraftVgpu = mod.initialWizardResolution(host4K150, true, 'reims-vgpu')
|
||||
assert.deepEqual(installerDraftVgpu, { auto_resolution: true, resolution: '3200x1800' })
|
||||
|
||||
const installerDraftSvga = mod.initialWizardResolution(host4K150, true, 'vmware-svga')
|
||||
assert.deepEqual(installerDraftSvga, { auto_resolution: false, resolution: '3200x1800' })
|
||||
|
||||
// Returning from a failed create preserves explicit auto_resolution: false
|
||||
const failedFixedDraft = {
|
||||
name: 'macos-tahoe',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: false,
|
||||
resolution: '2560x1440',
|
||||
borderless: false,
|
||||
}
|
||||
const effectiveFixed = mod.resolveEffectiveWizardOpts(
|
||||
failedFixedDraft,
|
||||
mod.resolveAutoDisplayPreset(host32K200, false, true),
|
||||
)
|
||||
assert.equal(effectiveFixed.auto_resolution, false)
|
||||
assert.equal(effectiveFixed.resolution, '2560x1440')
|
||||
})
|
||||
|
||||
test('effective wizard opts track host screen changes in auto mode without mutating fixed mode (#8)', () => {
|
||||
const autoOptsFrom4K = {
|
||||
name: 'macos-tahoe',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
borderless: false,
|
||||
}
|
||||
// Host switches to 3.2K screen while wizard stays open or restores an auto draft
|
||||
const effectiveOn32K = mod.resolveEffectiveWizardOpts(
|
||||
autoOptsFrom4K,
|
||||
mod.resolveAutoDisplayPreset(host32K200, false, true),
|
||||
)
|
||||
assert.equal(effectiveOn32K.auto_resolution, true)
|
||||
assert.equal(effectiveOn32K.resolution, '2880x1800')
|
||||
|
||||
// Borderless auto mode on 4K updates to 5120x2880
|
||||
const effectiveBorderless = mod.resolveEffectiveWizardOpts(
|
||||
{ ...autoOptsFrom4K, borderless: true },
|
||||
mod.resolveAutoDisplayPreset(host4K150, true, true),
|
||||
)
|
||||
assert.equal(effectiveBorderless.resolution, '5120x2880')
|
||||
|
||||
// Fixed mode keeps user-selected resolution even when host changes
|
||||
const fixedOpts = { ...autoOptsFrom4K, auto_resolution: false, resolution: '2560x1440' }
|
||||
const effectiveFixed = mod.resolveEffectiveWizardOpts(
|
||||
fixedOpts,
|
||||
mod.resolveAutoDisplayPreset(host32K200, false, true),
|
||||
)
|
||||
assert.equal(effectiveFixed.auto_resolution, false)
|
||||
assert.equal(effectiveFixed.resolution, '2560x1440')
|
||||
})
|
||||
|
||||
test('custom resolution canonicalizes on blur and save diff to match Go validator (#9)', () => {
|
||||
assert.equal(mod.canonicalResolution('3200 × 1800'), '3200x1800')
|
||||
assert.equal(mod.canonicalResolution(' 3200X1800 '), '3200x1800')
|
||||
assert.equal(mod.canonicalResolution('2400 x 1500'), '2400x1500')
|
||||
assert.equal(mod.canonicalResolution(''), '')
|
||||
|
||||
const presets = mod.windowDisplayPresets(host4K150, true)
|
||||
|
||||
// Typing a known preset with × or uppercase X snaps back and writes canonical preset value
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: '3200 × 1800',
|
||||
autoResolution: false,
|
||||
forceCustomRes: true,
|
||||
activePresets: presets,
|
||||
}),
|
||||
{ exitCustom: true, nextResolution: '3200x1800' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: '3200X1800',
|
||||
autoResolution: false,
|
||||
forceCustomRes: true,
|
||||
activePresets: presets,
|
||||
}),
|
||||
{ exitCustom: true, nextResolution: '3200x1800' },
|
||||
)
|
||||
|
||||
// Typing a non-preset valid size canonicalizes without exiting custom input
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: ' 2400 × 1500 ',
|
||||
autoResolution: false,
|
||||
forceCustomRes: true,
|
||||
activePresets: presets,
|
||||
}),
|
||||
{ exitCustom: false, nextResolution: '2400x1500' },
|
||||
)
|
||||
|
||||
// Save diff always canonicalizes resolution even if saved before blur
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], {
|
||||
name: 'mac',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: false,
|
||||
resolution: '3200 × 1800',
|
||||
}),
|
||||
{ name: 'mac', auto_resolution: false, resolution: '3200x1800' },
|
||||
)
|
||||
})
|
||||
|
||||
test('background baseline refresh syncs untouched fields so saving memory never overwrites external auto_resolution (#11)', () => {
|
||||
const initialBase = {
|
||||
name: 'mac',
|
||||
memory: '8G',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
}
|
||||
// User only edits memory
|
||||
const touched = new Set(mod.expandTouchedSettingsFields(['memory']))
|
||||
const editedForm = { ...initialBase, memory: '16G' }
|
||||
|
||||
// External CLI disables auto_resolution and sets fixed 2560x1440; background poll refreshes base
|
||||
const refreshedBase = {
|
||||
...initialBase,
|
||||
auto_resolution: false,
|
||||
resolution: '2560x1440',
|
||||
}
|
||||
const syncedForm = mod.syncUntouchedSettingsForm(editedForm, refreshedBase, touched)
|
||||
assert.equal(syncedForm.memory, '16G')
|
||||
assert.equal(syncedForm.auto_resolution, false)
|
||||
assert.equal(syncedForm.resolution, '2560x1440')
|
||||
|
||||
// Only memory differs from refreshedBase, so save diff only sends memory
|
||||
const dirtyFields = ['memory', 'auto_resolution', 'resolution'].filter(
|
||||
(k) => syncedForm[k] !== refreshedBase[k],
|
||||
)
|
||||
assert.deepEqual(dirtyFields, ['memory'])
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyFields, syncedForm), {
|
||||
name: 'mac',
|
||||
memory: '16G',
|
||||
})
|
||||
|
||||
// Touching resolution pairs both resolution and auto_resolution so background refresh preserves user edits
|
||||
const resTouched = new Set(mod.expandTouchedSettingsFields(['resolution']))
|
||||
assert.ok(resTouched.has('resolution'))
|
||||
assert.ok(resTouched.has('auto_resolution'))
|
||||
const editedResForm = { ...initialBase, auto_resolution: false, resolution: '1920x1080' }
|
||||
const syncedWhileEditingRes = mod.syncUntouchedSettingsForm(editedResForm, refreshedBase, resTouched)
|
||||
assert.equal(syncedWhileEditingRes.auto_resolution, false)
|
||||
assert.equal(syncedWhileEditingRes.resolution, '1920x1080')
|
||||
})
|
||||
|
||||
test('R2 #7: switching VMs resets settings draft to target VM baseline without leaking previous VM edits', () => {
|
||||
const baseA = {
|
||||
name: 'vm-a',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
memory: '8G',
|
||||
}
|
||||
const baseB = {
|
||||
name: 'vm-b',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '2880x1800',
|
||||
memory: '16G',
|
||||
}
|
||||
const touchedA = new Set(mod.expandTouchedSettingsFields(['resolution', 'memory']))
|
||||
const editedA = { ...baseA, auto_resolution: false, resolution: '2560x1440', memory: '12G' }
|
||||
|
||||
const switched = mod.reconcileSettingsFormOnBaseChange({
|
||||
previousVMKey: 'builtin.driver.reims-macos:vm-a',
|
||||
nextVMKey: 'builtin.driver.reims-macos:vm-b',
|
||||
form: editedA,
|
||||
base: baseB,
|
||||
touchedFields: touchedA,
|
||||
})
|
||||
assert.equal(switched.resetDraft, true)
|
||||
assert.deepEqual(switched.form, baseB)
|
||||
|
||||
const dirtyB = Object.keys(baseB).filter((k) => switched.form[k] !== baseB[k])
|
||||
assert.deepEqual(dirtyB, [])
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('vm-b', dirtyB, switched.form, baseB), { name: 'vm-b' })
|
||||
})
|
||||
|
||||
test('R2 #5: internal digit spaces never match presets, keep custom input visible, and block save', () => {
|
||||
const hostWith1080 = {
|
||||
...host4K150,
|
||||
display_presets: [
|
||||
...host4K150.display_presets,
|
||||
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false },
|
||||
],
|
||||
}
|
||||
|
||||
assert.equal(mod.canonicalResolution('1 920x1080'), '1 920x1080')
|
||||
assert.equal(mod.normalizeResolution('1 920x1080'), '1 920x1080')
|
||||
assert.equal(mod.isValidResolution('1 920x1080'), false)
|
||||
|
||||
// Even when forceCustomRes is false (custom input opened automatically due to non-preset old value),
|
||||
// pasting "1 920x1080" must NOT match 1920x1080 preset, must keep input visible, and must set resBad = true.
|
||||
const badState = mod.deriveSettingsResolutionState({
|
||||
form: { graphics: 'reims-vgpu', auto_resolution: false, resolution: '1 920x1080', borderless: false },
|
||||
displayProfile: hostWith1080,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(badState.presetHit, false)
|
||||
assert.equal(badState.customRes, true)
|
||||
assert.equal(badState.resBad, true)
|
||||
|
||||
// Spaces around × or uppercase X still match preset and canonicalize to 3200x1800
|
||||
assert.equal(mod.isValidResolution('3200 × 1800'), true)
|
||||
assert.equal(mod.isValidResolution('3200X1800'), true)
|
||||
const goodState = mod.deriveSettingsResolutionState({
|
||||
form: { graphics: 'reims-vgpu', auto_resolution: false, resolution: '3200 × 1800', borderless: false },
|
||||
displayProfile: hostWith1080,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(goodState.presetHit, true)
|
||||
assert.equal(goodState.matchedPreset?.resolution, '3200x1800')
|
||||
assert.equal(goodState.resBad, false)
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: '3200 × 1800',
|
||||
autoResolution: false,
|
||||
forceCustomRes: false,
|
||||
activePresets: goodState.activePresets,
|
||||
}),
|
||||
{ exitCustom: true, nextResolution: '3200x1800' },
|
||||
)
|
||||
})
|
||||
|
||||
test('R2 #11: switching vGPU+auto to SVGA and resetting graphics leaves 0 changes; saving SVGA disables auto', () => {
|
||||
const base = {
|
||||
name: 'mac',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
}
|
||||
|
||||
// Temporarily switch to SVGA
|
||||
const svgaSwitch = mod.switchSettingsGraphics('vmware-svga')
|
||||
assert.deepEqual(svgaSwitch, { patch: { graphics: 'vmware-svga' }, forceCustomRes: false })
|
||||
const svgaForm = { ...base, ...svgaSwitch.patch }
|
||||
assert.equal(svgaForm.auto_resolution, true)
|
||||
|
||||
// Resetting graphics row back to reims-vgpu restores clean form with 0 changes
|
||||
const resetForm = { ...svgaForm, graphics: base.graphics }
|
||||
const dirtyAfterReset = ['graphics', 'auto_resolution', 'resolution'].filter((k) => resetForm[k] !== base[k])
|
||||
assert.deepEqual(dirtyAfterReset, [])
|
||||
assert.equal(mod.countChangedSettingsFields(dirtyAfterReset), 0)
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyAfterReset, resetForm, base), { name: 'mac' })
|
||||
|
||||
// Saving SVGA directly sends graphics: 'vmware-svga' and turns off auto_resolution when base had it on
|
||||
const dirtyOnSvga = ['graphics', 'auto_resolution', 'resolution'].filter((k) => svgaForm[k] !== base[k])
|
||||
assert.deepEqual(dirtyOnSvga, ['graphics'])
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyOnSvga, svgaForm, base), {
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
auto_resolution: false,
|
||||
})
|
||||
|
||||
// If base already had auto_resolution: false, saving SVGA only sends graphics
|
||||
const baseFixed = { ...base, auto_resolution: false }
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', ['graphics'], { ...baseFixed, graphics: 'vmware-svga' }, baseFixed), {
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
})
|
||||
})
|
||||
|
||||
test('R2 #3: CreateWizard preserves manual fixed resolution across SVGA create failure and return to vGPU', () => {
|
||||
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
// Step 1: User starts on vGPU and manually picks fixed 2560x1440
|
||||
let opts = {
|
||||
name: 'macos-tahoe',
|
||||
graphics: 'reims-vgpu',
|
||||
...mod.initialWizardResolution(host4K150, true, 'reims-vgpu'),
|
||||
borderless: false,
|
||||
}
|
||||
let manualResolutionPicked = true
|
||||
opts = { ...opts, ...mod.selectWizardResolution('2560x1440', autoPreset) }
|
||||
assert.equal(opts.auto_resolution, false)
|
||||
assert.equal(opts.resolution, '2560x1440')
|
||||
|
||||
// Step 2: User switches to SVGA and submits; create fails and saves draft with manualResolution: true
|
||||
opts = { ...opts, ...mod.switchWizardGraphics({ graphics: 'vmware-svga', manualResolutionPicked, autoPreset }) }
|
||||
const failedDraft = {
|
||||
opts: mod.resolveEffectiveWizardOpts(opts, autoPreset),
|
||||
step: 5,
|
||||
manualResolution: manualResolutionPicked,
|
||||
}
|
||||
assert.equal(failedDraft.opts.graphics, 'vmware-svga')
|
||||
assert.equal(failedDraft.opts.auto_resolution, false)
|
||||
assert.equal(failedDraft.opts.resolution, '2560x1440')
|
||||
|
||||
// Step 3: Reopen wizard from failed draft and switch back to vGPU
|
||||
const restoredManual = mod.initialWizardManualResolution(failedDraft)
|
||||
assert.equal(restoredManual, true)
|
||||
const backToVgpu = mod.switchWizardGraphics({
|
||||
graphics: 'reims-vgpu',
|
||||
manualResolutionPicked: restoredManual,
|
||||
autoPreset,
|
||||
})
|
||||
const restoredOpts = { ...failedDraft.opts, ...backToVgpu }
|
||||
assert.equal(restoredOpts.graphics, 'reims-vgpu')
|
||||
assert.equal(restoredOpts.auto_resolution, false)
|
||||
assert.equal(restoredOpts.resolution, '2560x1440')
|
||||
|
||||
// Fallback behavior when draft.manualResolution is omitted
|
||||
assert.equal(mod.initialWizardManualResolution(null), false)
|
||||
assert.equal(
|
||||
mod.initialWizardManualResolution({ opts: { graphics: 'vmware-svga', auto_resolution: false } }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
mod.initialWizardManualResolution({ opts: { graphics: 'reims-vgpu', auto_resolution: false } }),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('R3 #3 & #6: turning off auto includes fixed resolution; switching to SVGA omits hidden invalid resolution', () => {
|
||||
// R3 #3: switching from auto back to fixed card matching display-0 resolution still submits explicit resolution
|
||||
// so any per-display list (e.g. 3200x1800,2560x1440) is replaced uniformly.
|
||||
const baseAuto = { name: 'mac', graphics: 'reims-vgpu', auto_resolution: true, resolution: '3200x1800' }
|
||||
const formFixed = { ...baseAuto, auto_resolution: false, resolution: '3200x1800' }
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', ['auto_resolution'], formFixed, baseAuto), {
|
||||
name: 'mac',
|
||||
auto_resolution: false,
|
||||
resolution: '3200x1800',
|
||||
})
|
||||
|
||||
// R3 #6: typing invalid custom resolution then switching to SVGA does not submit hidden invalid resolution
|
||||
const baseVgpu = { name: 'mac', graphics: 'reims-vgpu', auto_resolution: false, resolution: '2560x1440' }
|
||||
const formSvgaWithHiddenInvalid = {
|
||||
...baseVgpu,
|
||||
graphics: 'vmware-svga',
|
||||
resolution: '1 920x1080',
|
||||
}
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['graphics', 'resolution'], formSvgaWithHiddenInvalid, baseVgpu),
|
||||
{
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -1,150 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets } = await loadTestModule(`export * from './lib/vmKeymap'`)
|
||||
const off = { preset: 'off', bindings: {}, capture_host_shortcuts: false }
|
||||
const custom = { preset: 'custom', bindings: { lwin: 'lcmd' }, capture_host_shortcuts: true }
|
||||
|
||||
test('switching presets preserves shortcut capture and carries bindings into custom', () => {
|
||||
const preset = { ...custom, preset: 'win_to_cmd' }
|
||||
assert.equal(keymapPresetUpdate(preset, 'win_to_cmd'), undefined)
|
||||
assert.deepEqual(keymapPresetUpdate(preset, 'custom'), custom)
|
||||
assert.deepEqual(keymapPresetUpdate(custom, 'off'), { ...off, capture_host_shortcuts: true })
|
||||
assert.deepEqual(keymapPresetUpdate(off, 'custom'), { ...off, preset: 'custom' })
|
||||
})
|
||||
|
||||
test('editing one binding preserves the other bindings, preset, and shortcut capture', () => {
|
||||
assert.deepEqual(keymapUpdate(custom, { bindings: { lalt: 'disabled' } }), {
|
||||
...custom,
|
||||
bindings: { lwin: 'lcmd', lalt: 'disabled' },
|
||||
})
|
||||
})
|
||||
|
||||
test('toggling shortcut capture preserves the preset and bindings', () => {
|
||||
const captureOff = { ...custom, capture_host_shortcuts: false }
|
||||
assert.deepEqual(keymapUpdate(captureOff, { capture_host_shortcuts: true }), custom)
|
||||
assert.deepEqual(keymapUpdate(custom, { capture_host_shortcuts: false }), captureOff)
|
||||
assert.deepEqual(keymapUpdate(off, { capture_host_shortcuts: true }), { ...off, capture_host_shortcuts: true })
|
||||
})
|
||||
|
||||
test('a pending write for one VM does not block or overwrite another VM', async () => {
|
||||
const saved = Promise.withResolvers()
|
||||
const writes = []
|
||||
let active = 'a'
|
||||
let state = {}
|
||||
const requests = createKeymapRequests({
|
||||
async GetVMKeymap(name) {
|
||||
assert.equal(name, 'b')
|
||||
return off
|
||||
},
|
||||
SetVMKeymap(name, request) {
|
||||
writes.push([name, request])
|
||||
return saved.promise
|
||||
},
|
||||
}, () => active, (patch) => Object.assign(state, patch))
|
||||
|
||||
const write = requests.write('a', custom)
|
||||
await requests.write('a', off)
|
||||
assert.deepEqual(writes, [['a', custom]])
|
||||
assert.equal(state.busy, true)
|
||||
|
||||
active = 'b'
|
||||
state = requests.initial('b')
|
||||
await requests.watch('b').refresh()
|
||||
saved.resolve(custom)
|
||||
await write
|
||||
assert.deepEqual(state, { keymap: off, busy: false, error: '' })
|
||||
assert.equal(requests.initial('a').busy, false)
|
||||
})
|
||||
|
||||
test('a failed keymap read recovers on the next refresh', async () => {
|
||||
let fail = true
|
||||
const state = {}
|
||||
const requests = createKeymapRequests({
|
||||
async GetVMKeymap() {
|
||||
if (fail) throw new Error('temporary')
|
||||
return off
|
||||
},
|
||||
}, () => 'vm', (patch) => Object.assign(state, patch))
|
||||
const watch = requests.watch('vm')
|
||||
await watch.refresh()
|
||||
assert.equal(state.error, 'temporary')
|
||||
fail = false
|
||||
await watch.refresh()
|
||||
assert.deepEqual(state, { keymap: off, error: '' })
|
||||
})
|
||||
|
||||
test('a read started before a write cannot restore the old keymap', async () => {
|
||||
const previousRead = Promise.withResolvers()
|
||||
const state = {}
|
||||
const requests = createKeymapRequests({
|
||||
GetVMKeymap: () => previousRead.promise,
|
||||
SetVMKeymap: async () => custom,
|
||||
}, () => 'vm', (patch) => Object.assign(state, patch))
|
||||
|
||||
const read = requests.watch('vm').refresh()
|
||||
await requests.write('vm', custom)
|
||||
previousRead.resolve(off)
|
||||
await read
|
||||
assert.deepEqual(state, { keymap: custom, busy: false, error: '' })
|
||||
})
|
||||
|
||||
test('visibleKeymapPresets hides win_to_cmd on modern runtimes unless already selected', () => {
|
||||
assert.deepEqual(visibleKeymapPresets('off', false), ['off', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('swap_alt_win', false), ['off', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('custom', false), ['off', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('win_to_cmd', false), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('off', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('swap_alt_win', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
|
||||
})
|
||||
|
||||
test('keymapStatusHint returns null when both preset and shortcut capture are off', () => {
|
||||
const base = {
|
||||
preset: 'off',
|
||||
bindings: {},
|
||||
capture_host_shortcuts: false,
|
||||
needs_guest_tools: false,
|
||||
guest_connected: true,
|
||||
guest_agent_version: 5,
|
||||
required_agent_version: 5,
|
||||
input_service_available: true,
|
||||
guest_keymap_active: true,
|
||||
hook_active: true,
|
||||
running: true,
|
||||
}
|
||||
assert.equal(keymapStatusHint(base), null)
|
||||
})
|
||||
|
||||
test('keymapStatusHint resolves priority when only capture_host_shortcuts is enabled', () => {
|
||||
const base = {
|
||||
preset: 'off',
|
||||
bindings: {},
|
||||
capture_host_shortcuts: true,
|
||||
needs_guest_tools: false,
|
||||
guest_connected: false,
|
||||
guest_agent_version: 0,
|
||||
required_agent_version: 4,
|
||||
input_service_available: true,
|
||||
guest_keymap_active: false,
|
||||
hook_active: true,
|
||||
running: true,
|
||||
}
|
||||
assert.deepEqual(keymapStatusHint(base), { key: 'keymapRunning' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, hook_active: false }), { key: 'keymapInactive' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, running: false }), { key: 'keymapStopped' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, input_service_available: false, running: false }), { key: 'keymapInputServiceRequired' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: false }), { key: 'keymapWaiting' })
|
||||
assert.deepEqual(
|
||||
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 3, required_agent_version: 4 }),
|
||||
{ key: 'keymapUpgrade', vars: { version: 4 } },
|
||||
)
|
||||
assert.deepEqual(
|
||||
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: false }),
|
||||
{ key: 'keymapPending' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: true }),
|
||||
{ key: 'keymapRunning' },
|
||||
)
|
||||
})
|
||||
@@ -30,11 +30,39 @@ function isEmptyBlock(block) {
|
||||
return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt))
|
||||
}
|
||||
|
||||
function isEmptyFunctionBody(expr) {
|
||||
function isSilentLiteralExpr(expr) {
|
||||
let current = expr
|
||||
while (ts.isParenthesizedExpression(current)) current = current.expression
|
||||
if (
|
||||
current.kind === ts.SyntaxKind.NullKeyword ||
|
||||
current.kind === ts.SyntaxKind.TrueKeyword ||
|
||||
current.kind === ts.SyntaxKind.FalseKeyword ||
|
||||
ts.isStringLiteralLike(current) ||
|
||||
ts.isNumericLiteral(current) ||
|
||||
ts.isVoidExpression(current)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (ts.isIdentifier(current) && current.text === 'undefined') return true
|
||||
if (ts.isArrayLiteralExpression(current) && current.elements.length === 0) return true
|
||||
if (ts.isObjectLiteralExpression(current) && current.properties.length === 0) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function isSilentFunctionBody(expr) {
|
||||
let current = expr
|
||||
while (ts.isParenthesizedExpression(current)) current = current.expression
|
||||
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) {
|
||||
return isEmptyBlock(current.body)
|
||||
if (isEmptyBlock(current.body)) return true
|
||||
if (!ts.isBlock(current.body) && isSilentLiteralExpr(current.body)) return true
|
||||
if (
|
||||
ts.isBlock(current.body) &&
|
||||
current.body.statements.length === 1 &&
|
||||
ts.isReturnStatement(current.body.statements[0]) &&
|
||||
(!current.body.statements[0].expression || isSilentLiteralExpr(current.body.statements[0].expression))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -70,9 +98,9 @@ export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
|
||||
record(node, 'empty-catch-clause')
|
||||
} else if (ts.isCallExpression(node)) {
|
||||
const method = getCalleeMethodName(node.expression)
|
||||
if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) {
|
||||
if (method === 'catch' && node.arguments.length >= 1 && isSilentFunctionBody(node.arguments[0])) {
|
||||
record(node.arguments[0], 'empty-promise-catch')
|
||||
} else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) {
|
||||
} else if (method === 'then' && node.arguments.length >= 2 && isSilentFunctionBody(node.arguments[1])) {
|
||||
record(node.arguments[1], 'empty-promise-then-reject')
|
||||
}
|
||||
}
|
||||
@@ -321,10 +349,15 @@ test('detector self-test: catches all empty JS/TS catch forms and allows handled
|
||||
'p.catch(async () => { ; })',
|
||||
'p.then(ok, () => {})',
|
||||
'p.then(ok, (err) => { // noop\n})',
|
||||
'p.catch(() => null)',
|
||||
'p.catch(() => "")',
|
||||
'p.catch(() => false)',
|
||||
'p.catch(() => [])',
|
||||
'p.catch(() => { return null })',
|
||||
].join('\n')
|
||||
|
||||
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts')
|
||||
assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`)
|
||||
assert.equal(badFindings.length, 16, `expected 16 findings, got ${JSON.stringify(badFindings)}`)
|
||||
|
||||
const good = [
|
||||
'const text = "try { a() } catch {} .catch(() => {})"',
|
||||
@@ -332,7 +365,7 @@ test('detector self-test: catches all empty JS/TS catch forms and allows handled
|
||||
'try { a() } catch (e) { console.warn(e) }',
|
||||
'try { a() } catch { return fallback }',
|
||||
'p.catch((e) => console.warn(e))',
|
||||
'p.catch(() => null)',
|
||||
'p.catch((e) => { console.warn(e); return null })',
|
||||
'p.then(ok, (e) => handle(e))',
|
||||
].join('\n')
|
||||
|
||||
|
||||
+97
-186
@@ -1,11 +1,8 @@
|
||||
import { Minus, Moon, Square, Sun, X } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { WizardDraft } from './components/CreateWizard'
|
||||
import { DeleteDialog } from './components/DeleteDialog'
|
||||
import { ElevationDialog } from './components/ElevationDialog'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { AppDialogs } from './components/AppDialogs'
|
||||
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule } from './components/UpdateCapsule'
|
||||
@@ -14,7 +11,8 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si
|
||||
import { CreatingVMView } from './components/CreatingVMView'
|
||||
import { VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
|
||||
import { initialWizardResolution } from './lib/displayResolution'
|
||||
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
||||
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
||||
import { LogLine, appendLog, createLogLine } from './lib/logs'
|
||||
@@ -23,7 +21,7 @@ import { creatingVMTasks, currentTask, finishedTaskTTL, isActiveInstallerTask, p
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
|
||||
import type { UIStateSnapshot } from './lib/uiSdk'
|
||||
import { hasVisibleDialog } from './lib/dialogState'
|
||||
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
|
||||
import { refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
|
||||
import { useAppearance } from './lib/useAppearance'
|
||||
import { useAppUpdate } from './lib/useAppUpdate'
|
||||
import { useFileDrop } from './lib/useFileDrop'
|
||||
@@ -34,18 +32,13 @@ import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCond
|
||||
import { publishPluginHostEvent } from './lib/pluginViewEvents'
|
||||
import { buildSafePluginAssetURL } from './lib/pluginAssets'
|
||||
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
import { ConfirmDialog, Modal } from './ui/dialog'
|
||||
import { Tip, TooltipProvider } from './ui/controls'
|
||||
import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast'
|
||||
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
|
||||
import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
|
||||
|
||||
// Opened on demand, so each is its own chunk and stays out of the startup
|
||||
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
|
||||
// the Engine / Installers / Settings pages.
|
||||
const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard })))
|
||||
const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })))
|
||||
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
|
||||
// bundle: first-run setup, and the Engine / Installers / Settings pages.
|
||||
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
|
||||
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
|
||||
const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage })))
|
||||
@@ -151,7 +144,7 @@ export const App: React.FC = () => {
|
||||
|
||||
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
|
||||
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
|
||||
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
|
||||
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch (e) { console.warn('[app] read sidebar state failed:', e); return true }
|
||||
})
|
||||
const toggleSidebar = () => setSidebarOpen((open) => {
|
||||
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) }
|
||||
@@ -371,7 +364,10 @@ export const App: React.FC = () => {
|
||||
let live = true
|
||||
api.GetVMDetail(selectedVM.name)
|
||||
.then((d) => { if (live) setDetail(d) })
|
||||
.catch(() => { if (live) setDetail(null) })
|
||||
.catch((e) => {
|
||||
console.warn('[app] GetVMDetail failed:', selectedVM.name, e)
|
||||
if (live) setDetail(null)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported])
|
||||
|
||||
@@ -596,9 +592,15 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
const folderDone = async () => {
|
||||
const s = await api.GetState().catch(() => null)
|
||||
if (s) setState(s)
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
try {
|
||||
const s = await api.GetState()
|
||||
setState(s)
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
} catch (e) {
|
||||
console.warn('[app] GetState after setup failed:', e)
|
||||
fail(tr('failGeneric'), e)
|
||||
setSetupStage('runtime')
|
||||
}
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
|
||||
// The data folder opened read-only (internal/dataroot): nothing in it may be
|
||||
@@ -956,6 +958,7 @@ export const App: React.FC = () => {
|
||||
defaultName = `macos-tahoe-${i}`
|
||||
}
|
||||
const isOffline = item.kind === 'offline' && !!item.version
|
||||
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
setWizardDraft({
|
||||
step: 1,
|
||||
opts: {
|
||||
@@ -970,9 +973,9 @@ export const App: React.FC = () => {
|
||||
disk_size: '128G',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
graphics,
|
||||
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
resolution: recommendedResolution(state.host),
|
||||
...initialWizardResolution(state.host, fixedModeSupported, graphics),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
@@ -1445,148 +1448,80 @@ export const App: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{showWizard && state && (
|
||||
<Suspense fallback={null}>
|
||||
<CreateWizard
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
captureSupported={state.runtime_capture_supported}
|
||||
tasks={Object.values(taskMap)}
|
||||
draft={wizardDraft}
|
||||
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
onSubmit={submitCreate}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{showSettings && state && detail && (
|
||||
<Suspense fallback={null}>
|
||||
<SettingsModal
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
driverID={selectedVM?.driver_id ?? ''}
|
||||
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
diskCacheSupported={diskCacheSupported}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onCopy={copy}
|
||||
onDiskChanged={refresh}
|
||||
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
|
||||
affinityVersion={affinityVersion}
|
||||
onHostChanged={refresh}
|
||||
onToast={toasts.push}
|
||||
onClose={() => setShowSettings(false)}
|
||||
onSaved={() => {
|
||||
setShowSettings(false)
|
||||
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{affinityTarget && state && (
|
||||
<Suspense fallback={null}>
|
||||
<AffinityDialog
|
||||
locale={locale}
|
||||
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)}
|
||||
onApplied={(st) => {
|
||||
setAffinityTarget(null)
|
||||
setAffinityVersion((v) => v + 1)
|
||||
const count = st.effective_cpus?.length ?? 0
|
||||
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
|
||||
toasts.push({
|
||||
kind: 'ok',
|
||||
title: st.running
|
||||
? tr('toastAffinityApplied', { count, mask })
|
||||
: tr('toastAffinitySaved'),
|
||||
})
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{update.confirming && (
|
||||
<Modal
|
||||
title={tr('updateConfirmTitle', { v: update.info?.latest ?? '' })}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => update.cancelInstall()}
|
||||
>
|
||||
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
|
||||
{state?.host.needs_cold_reboot_workaround && <p style={{ margin: 0 }}>{tr('updateConfirmWin10')}</p>}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => update.cancelInstall()}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" onClick={update.confirmInstall}>{tr('updateRestart')}</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{deleteTarget && (
|
||||
<DeleteDialog locale={locale} name={findVM(deleteTarget)?.name ?? deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
|
||||
)}
|
||||
|
||||
{closeDownloadsOpen && (
|
||||
<ConfirmDialog
|
||||
title={tr('closeDownloadsTitle')}
|
||||
description={tr('closeDownloadsDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('closeDownloadsConfirm')}
|
||||
onCancel={() => setCloseDownloadsOpen(false)}
|
||||
onConfirm={() => { setCloseDownloadsOpen(false); void api.QuitApp() }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{elevationQueue.length > 0 && (
|
||||
<ElevationDialog
|
||||
key={elevationQueue[0].id}
|
||||
locale={locale}
|
||||
request={elevationQueue[0]}
|
||||
onResolve={(approved) => {
|
||||
const active = elevationQueue[0]
|
||||
setElevationQueue((q) => q.filter((item) => item.id !== active.id))
|
||||
api.ResolveElevationRequest(active.id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{discardSuspendTarget && (() => {
|
||||
const targetVM = findVM(discardSuspendTarget)
|
||||
const targetName = targetVM?.name ?? discardSuspendTarget
|
||||
return (
|
||||
<ConfirmDialog
|
||||
title={tr('discardSuspendTitle', { name: displayNames[targetVM ? vmRefKey(targetVM) : targetName] || targetName })}
|
||||
description={tr('discardSuspendDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('discardSuspendConfirm')}
|
||||
onCancel={() => setDiscardSuspendTarget(null)}
|
||||
onConfirm={confirmDiscardSuspend}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{cloneSource && (
|
||||
<CloneDialog
|
||||
locale={locale}
|
||||
sourceName={cloneSource.name}
|
||||
defaultCloneName={`${cloneSource.name}-clone`}
|
||||
onCancel={() => setCloneSource(null)}
|
||||
onConfirm={confirmClone}
|
||||
/>
|
||||
)}
|
||||
<AppDialogs
|
||||
locale={locale}
|
||||
state={state}
|
||||
detail={detail}
|
||||
selectedVM={selectedVM}
|
||||
selectedIsMacOS={selectedIsMacOS}
|
||||
effectiveState={effectiveState}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
diskCacheSupported={diskCacheSupported}
|
||||
runningVMCount={runningVMCount}
|
||||
tasks={Object.values(taskMap)}
|
||||
displayNames={displayNames}
|
||||
showWizard={showWizard}
|
||||
wizardDraft={wizardDraft}
|
||||
onCloseWizard={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
onSubmitCreate={submitCreate}
|
||||
showSettings={showSettings}
|
||||
onCloseSettings={() => setShowSettings(false)}
|
||||
onSavedSettings={() => {
|
||||
setShowSettings(false)
|
||||
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') })
|
||||
refresh()
|
||||
}}
|
||||
affinityTarget={affinityTarget}
|
||||
affinityVersion={affinityVersion}
|
||||
onOpenAffinity={setAffinityTarget}
|
||||
onCloseAffinity={() => setAffinityTarget(null)}
|
||||
onAffinityApplied={(st) => {
|
||||
setAffinityTarget(null)
|
||||
setAffinityVersion((v) => v + 1)
|
||||
const count = st.effective_cpus?.length ?? 0
|
||||
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
|
||||
toasts.push({
|
||||
kind: 'ok',
|
||||
title: st.running
|
||||
? tr('toastAffinityApplied', { count, mask })
|
||||
: tr('toastAffinitySaved'),
|
||||
})
|
||||
refresh()
|
||||
}}
|
||||
updateConfirming={update.confirming}
|
||||
updateLatest={update.info?.latest ?? ''}
|
||||
onCancelInstallUpdate={() => update.cancelInstall()}
|
||||
onConfirmInstallUpdate={update.confirmInstall}
|
||||
deleteTarget={deleteTarget}
|
||||
onCancelDelete={() => setDeleteTarget(null)}
|
||||
onConfirmDelete={confirmDelete}
|
||||
closeDownloadsOpen={closeDownloadsOpen}
|
||||
onCancelCloseDownloads={() => setCloseDownloadsOpen(false)}
|
||||
elevationQueue={elevationQueue}
|
||||
onResolveElevation={(id, approved) => {
|
||||
setElevationQueue((q) => q.filter((item) => item.id !== id))
|
||||
api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e))
|
||||
}}
|
||||
discardSuspendTarget={discardSuspendTarget}
|
||||
onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)}
|
||||
onConfirmDiscardSuspend={confirmDiscardSuspend}
|
||||
cloneSource={cloneSource}
|
||||
onCancelClone={() => setCloneSource(null)}
|
||||
onConfirmClone={confirmClone}
|
||||
sendTextTarget={sendTextTarget}
|
||||
onCancelSendText={() => setSendTextTarget(null)}
|
||||
onConfirmSendText={(key, driverID, name, text) => {
|
||||
setSendTextTarget(null)
|
||||
typeInto(key, () => api.TypeText(driverID, name, text))
|
||||
}}
|
||||
pluginDialogs={pluginViewState.dialogs}
|
||||
findRouteView={findRouteView}
|
||||
renderPluginView={renderPluginView}
|
||||
findVM={findVM}
|
||||
onCopy={copy}
|
||||
onRefresh={refresh}
|
||||
onToast={toasts.push}
|
||||
/>
|
||||
|
||||
{onlineRecoveryTarget && (
|
||||
<OnlineRecoveryDialog
|
||||
@@ -1597,30 +1532,6 @@ export const App: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{sendTextTarget && (() => {
|
||||
const sendVM = findVM(sendTextTarget)
|
||||
const sendName = sendVM?.name ?? sendTextTarget
|
||||
return (
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendName}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
|
||||
onCancel={() => setSendTextTarget(null)}
|
||||
onConfirm={(text) => {
|
||||
const target = sendTextTarget
|
||||
setSendTextTarget(null)
|
||||
typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeText(sendVM?.driver_id ?? '', sendName, text))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{/* Every open dialog stays mounted so the ones underneath keep their state. */}
|
||||
{pluginViewState.dialogs.map((route) => {
|
||||
const view = findRouteView(route)
|
||||
return view && renderPluginView(route, view, true)
|
||||
})}
|
||||
|
||||
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
|
||||
</div>
|
||||
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
|
||||
|
||||
@@ -98,7 +98,10 @@ export const AboutPage: React.FC<Props> = ({
|
||||
let cancelled = false
|
||||
api.CanOpenQQGroup()
|
||||
.then((ok) => { if (!cancelled) setQQInstalled(!!ok) })
|
||||
.catch(() => { if (!cancelled) setQQInstalled(false) })
|
||||
.catch((e) => {
|
||||
console.warn('[about] CanOpenQQGroup failed:', e)
|
||||
if (!cancelled) setQQInstalled(false)
|
||||
})
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
cancelled = true
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import React, { Suspense, lazy } from 'react'
|
||||
import type { WizardDraft } from './CreateWizard'
|
||||
import { DeleteDialog } from './DeleteDialog'
|
||||
import { ElevationDialog } from './ElevationDialog'
|
||||
import { CloneDialog } from './CloneDialog'
|
||||
import { SendTextDialog } from './SendTextDialog'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { latestVMStats } from '../lib/vmStats'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import type { PluginViewRoute } from '../lib/pluginViewRouter'
|
||||
import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { ConfirmDialog, Modal } from '../ui/dialog'
|
||||
import type { ToastInput } from '../ui/toast'
|
||||
import { api, type ElevationPrompt } from '../wails'
|
||||
|
||||
const CreateWizard = lazy(() => import('./CreateWizard').then((m) => ({ default: m.CreateWizard })))
|
||||
const SettingsModal = lazy(() => import('./SettingsModal').then((m) => ({ default: m.SettingsModal })))
|
||||
const AffinityDialog = lazy(() => import('./AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
|
||||
|
||||
interface AppDialogsProps {
|
||||
locale: Locale
|
||||
state: AppState | null
|
||||
detail: VMDetail | null
|
||||
selectedVM: VMListItem | undefined
|
||||
selectedIsMacOS: boolean
|
||||
effectiveState: string
|
||||
fixedModeSupported: boolean
|
||||
diskCacheSupported: boolean
|
||||
runningVMCount: number
|
||||
tasks: Task[]
|
||||
displayNames: Record<string, string>
|
||||
|
||||
showWizard: boolean
|
||||
wizardDraft: WizardDraft | null
|
||||
onCloseWizard: () => void
|
||||
onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void
|
||||
|
||||
showSettings: boolean
|
||||
onCloseSettings: () => void
|
||||
onSavedSettings: () => void
|
||||
|
||||
affinityTarget: { name: string; driverID: string } | null
|
||||
affinityVersion: number
|
||||
onOpenAffinity: (target: { name: string; driverID: string }) => void
|
||||
onCloseAffinity: () => void
|
||||
onAffinityApplied: (st: { running?: boolean; effective_cpus?: number[]; live_mask_hex?: string; effective_mask_hex?: string }) => void
|
||||
|
||||
updateConfirming: boolean
|
||||
updateLatest: string
|
||||
onCancelInstallUpdate: () => void
|
||||
onConfirmInstallUpdate: () => void
|
||||
|
||||
deleteTarget: string | null
|
||||
onCancelDelete: () => void
|
||||
onConfirmDelete: (keepFiles: boolean) => void
|
||||
|
||||
closeDownloadsOpen: boolean
|
||||
onCancelCloseDownloads: () => void
|
||||
|
||||
elevationQueue: ElevationPrompt[]
|
||||
onResolveElevation: (id: string, approved: boolean) => void
|
||||
|
||||
discardSuspendTarget: string | null
|
||||
onCancelDiscardSuspend: () => void
|
||||
onConfirmDiscardSuspend: () => void
|
||||
|
||||
cloneSource: { name: string; driverID: string } | null
|
||||
onCancelClone: () => void
|
||||
onConfirmClone: (cloneName: string) => void
|
||||
|
||||
sendTextTarget: string | null
|
||||
onCancelSendText: () => void
|
||||
onConfirmSendText: (vmKey: string, driverID: string, vmName: string, text: string) => void
|
||||
|
||||
pluginDialogs: PluginViewRoute[]
|
||||
findRouteView: (route: PluginViewRoute) => ViewContribution | undefined
|
||||
renderPluginView: (route: PluginViewRoute, view: ViewContribution, asDialog: boolean) => React.ReactNode
|
||||
|
||||
findVM: (keyOrName: string) => VMListItem | undefined
|
||||
onCopy: (text: string) => void
|
||||
onRefresh: () => void
|
||||
onToast: (toast: ToastInput) => void
|
||||
}
|
||||
|
||||
export const AppDialogs: React.FC<AppDialogsProps> = (props) => {
|
||||
const {
|
||||
locale, state, detail, selectedVM, selectedIsMacOS, effectiveState,
|
||||
fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames,
|
||||
showWizard, wizardDraft, onCloseWizard, onSubmitCreate,
|
||||
showSettings, onCloseSettings, onSavedSettings,
|
||||
affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied,
|
||||
updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate,
|
||||
deleteTarget, onCancelDelete, onConfirmDelete,
|
||||
closeDownloadsOpen, onCancelCloseDownloads,
|
||||
elevationQueue, onResolveElevation,
|
||||
discardSuspendTarget, onCancelDiscardSuspend, onConfirmDiscardSuspend,
|
||||
cloneSource, onCancelClone, onConfirmClone,
|
||||
sendTextTarget, onCancelSendText, onConfirmSendText,
|
||||
pluginDialogs, findRouteView, renderPluginView,
|
||||
findVM, onCopy, onRefresh, onToast,
|
||||
} = props
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
|
||||
return (
|
||||
<>
|
||||
{showWizard && state && (
|
||||
<Suspense fallback={null}>
|
||||
<CreateWizard
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
captureSupported={state.runtime_capture_supported}
|
||||
tasks={tasks}
|
||||
draft={wizardDraft}
|
||||
onClose={onCloseWizard}
|
||||
onSubmit={onSubmitCreate}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{showSettings && state && detail && (
|
||||
<Suspense fallback={null}>
|
||||
<SettingsModal
|
||||
key={`${selectedVM?.driver_id ?? ''}:${detail.name}`}
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
driverID={selectedVM?.driver_id ?? ''}
|
||||
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
diskCacheSupported={diskCacheSupported}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onCopy={onCopy}
|
||||
onDiskChanged={onRefresh}
|
||||
onOpenAffinity={() => onOpenAffinity({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
|
||||
affinityVersion={affinityVersion}
|
||||
onHostChanged={onRefresh}
|
||||
onToast={onToast}
|
||||
onClose={onCloseSettings}
|
||||
onSaved={onSavedSettings}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{affinityTarget && state && (
|
||||
<Suspense fallback={null}>
|
||||
<AffinityDialog
|
||||
locale={locale}
|
||||
vmName={affinityTarget.name}
|
||||
driverID={affinityTarget.driverID}
|
||||
vcpus={detail?.name === affinityTarget.name ? detail.cpus : 4}
|
||||
host={state.host}
|
||||
globalAutoPin={state.config.auto_pin_pcores}
|
||||
onClose={onCloseAffinity}
|
||||
onApplied={onAffinityApplied}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{updateConfirming && (
|
||||
<Modal
|
||||
title={tr('updateConfirmTitle', { v: updateLatest })}
|
||||
closeLabel={tr('close')}
|
||||
onClose={onCancelInstallUpdate}
|
||||
>
|
||||
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
|
||||
{state?.host.needs_cold_reboot_workaround && <p style={{ margin: 0 }}>{tr('updateConfirmWin10')}</p>}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={onCancelInstallUpdate}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" onClick={onConfirmInstallUpdate}>{tr('updateRestart')}</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{deleteTarget && (
|
||||
<DeleteDialog
|
||||
locale={locale}
|
||||
name={findVM(deleteTarget)?.name ?? deleteTarget}
|
||||
onCancel={onCancelDelete}
|
||||
onConfirm={onConfirmDelete}
|
||||
/>
|
||||
)}
|
||||
|
||||
{closeDownloadsOpen && (
|
||||
<ConfirmDialog
|
||||
title={tr('closeDownloadsTitle')}
|
||||
description={tr('closeDownloadsDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('closeDownloadsConfirm')}
|
||||
onCancel={onCancelCloseDownloads}
|
||||
onConfirm={() => { onCancelCloseDownloads(); void api.QuitApp() }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{elevationQueue.length > 0 && (
|
||||
<ElevationDialog
|
||||
key={elevationQueue[0].id}
|
||||
locale={locale}
|
||||
request={elevationQueue[0]}
|
||||
onResolve={(approved) => onResolveElevation(elevationQueue[0].id, approved)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{discardSuspendTarget && (() => {
|
||||
const targetVM = findVM(discardSuspendTarget)
|
||||
const targetName = targetVM?.name ?? discardSuspendTarget
|
||||
return (
|
||||
<ConfirmDialog
|
||||
title={tr('discardSuspendTitle', { name: displayNames[targetVM ? vmRefKey(targetVM) : targetName] || targetName })}
|
||||
description={tr('discardSuspendDesc')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('discardSuspendConfirm')}
|
||||
onCancel={onCancelDiscardSuspend}
|
||||
onConfirm={onConfirmDiscardSuspend}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{cloneSource && (
|
||||
<CloneDialog
|
||||
locale={locale}
|
||||
sourceName={cloneSource.name}
|
||||
defaultCloneName={`${cloneSource.name}-clone`}
|
||||
onCancel={onCancelClone}
|
||||
onConfirm={onConfirmClone}
|
||||
/>
|
||||
)}
|
||||
|
||||
{sendTextTarget && (() => {
|
||||
const sendVM = findVM(sendTextTarget)
|
||||
const sendName = sendVM?.name ?? sendTextTarget
|
||||
return (
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendName}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
|
||||
onCancel={onCancelSendText}
|
||||
onConfirm={(text) => onConfirmSendText(sendVM ? vmRefKey(sendVM) : sendTextTarget, sendVM?.driver_id ?? '', sendName, text)}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{/* Every open dialog stays mounted so the ones underneath keep their state. */}
|
||||
{pluginDialogs.map((route) => {
|
||||
const view = findRouteView(route)
|
||||
return view && renderPluginView(route, view, true)
|
||||
})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useState } from 'react'
|
||||
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
|
||||
import { useNetworkPlan } from '../lib/useNetworkPlan'
|
||||
import { NpcapDependency } from './NpcapDependency'
|
||||
import { NetworkErrorNotice } from './NetworkErrorNotice'
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
defaultGuestLang,
|
||||
findGPU,
|
||||
formatMemory,
|
||||
formatResolutionLabel,
|
||||
gpuCompatHint,
|
||||
gpuLabel,
|
||||
gpuOptionValue,
|
||||
@@ -21,22 +22,32 @@ import {
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
canKeepDisplayPreset,
|
||||
fullscreenDisplayPresets,
|
||||
FullscreenDisplayPreset,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
resolveAutoDisplayPreset,
|
||||
windowDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import {
|
||||
AUTO_RESOLUTION_OPTION,
|
||||
buildResolutionOptions,
|
||||
initialWizardManualResolution,
|
||||
initialWizardResolution,
|
||||
resolveEffectiveWizardOpts,
|
||||
selectWizardResolution,
|
||||
supportsAutoResolution,
|
||||
switchWizardGraphics,
|
||||
toggleWizardBorderless,
|
||||
} from '../lib/displayResolution'
|
||||
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
|
||||
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api } from '../wails'
|
||||
|
||||
@@ -47,6 +58,7 @@ const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
export interface WizardDraft {
|
||||
opts: CreateOpts
|
||||
step: number
|
||||
manualResolution?: boolean
|
||||
}
|
||||
|
||||
interface Props {
|
||||
@@ -106,6 +118,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
const activeDriver = drivers.find((d) => d.id === driverID)
|
||||
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
|
||||
|
||||
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
dir: '',
|
||||
@@ -120,11 +133,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
disk: '',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga',
|
||||
graphics: defaultGraphics,
|
||||
// Default to "auto" rather than a DriverStore FileRepository ICD path so
|
||||
// Windows GPU driver updates never break existing VM configs.
|
||||
gpu: 'auto',
|
||||
resolution: recommendedResolution(host),
|
||||
...initialWizardResolution(host, fixedModeSupported, defaultGraphics),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
...(captureSupported ? { capture: false } : {}),
|
||||
@@ -136,6 +149,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
guest_lang: defaultGuestLang(locale),
|
||||
start: true,
|
||||
})
|
||||
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
|
||||
initialWizardManualResolution(draft),
|
||||
)
|
||||
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
|
||||
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
|
||||
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
|
||||
@@ -157,9 +173,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
}, [step, networkMode, locale])
|
||||
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
|
||||
const fullscreenPresets = fullscreenDisplayPresets(host)
|
||||
const activePresets: FullscreenDisplayPreset[] = opts.borderless ? fullscreenPresets : windowPresets
|
||||
const autoPreset = resolveAutoDisplayPreset(host, !!opts.borderless, fixedModeSupported)
|
||||
const effectiveOpts = useMemo(
|
||||
() => resolveEffectiveWizardOpts(opts, autoPreset),
|
||||
[opts, autoPreset.resolution],
|
||||
)
|
||||
const changeGraphics = (graphics: CreateOpts['graphics']) => {
|
||||
set(switchWizardGraphics({ graphics, manualResolutionPicked, autoPreset }))
|
||||
}
|
||||
const resArt = (r: string) => {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
|
||||
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
|
||||
}
|
||||
|
||||
const buildPayload = (): CreateOpts => {
|
||||
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
|
||||
const p: CreateOpts = { ...effectiveOpts, offline: effectiveOpts.source_mode === 'offline' }
|
||||
if (!captureSupported) {
|
||||
delete p.capture
|
||||
}
|
||||
@@ -233,7 +262,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
}, [step, reviewed, opts, validationRefresh, captureSupported])
|
||||
}, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
|
||||
|
||||
const pickDir = async () => {
|
||||
const dir = await api.PickDirectory(tr('vmDir'))
|
||||
@@ -247,7 +276,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
|
||||
const handleCreate = () => {
|
||||
if (dependencyBusy || networkBlocked) return
|
||||
onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
|
||||
onSubmit(buildPayload(), { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked })
|
||||
}
|
||||
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
|
||||
|
||||
@@ -545,7 +574,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<Segmented
|
||||
label={tr('graphicsBackend')}
|
||||
value={opts.graphics}
|
||||
onChange={(graphics) => set({ graphics })}
|
||||
onChange={changeGraphics}
|
||||
options={[
|
||||
{ value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') },
|
||||
{ value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') },
|
||||
@@ -566,7 +595,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<button
|
||||
type="button"
|
||||
className="link-btn"
|
||||
onClick={() => set({ graphics: 'vmware-svga' })}
|
||||
onClick={() => changeGraphics('vmware-svga')}
|
||||
>
|
||||
{tr('gpuSwitchSvga')}
|
||||
</button>
|
||||
@@ -602,23 +631,47 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-res"
|
||||
block={
|
||||
<OptionCards
|
||||
label={tr('resolution')}
|
||||
value={opts.resolution}
|
||||
onChange={(resolution) => set({ resolution })}
|
||||
options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({
|
||||
value: p.resolution,
|
||||
label: p.label,
|
||||
detail: [
|
||||
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
|
||||
p.scaleBadge ?? '',
|
||||
p.native ? tr('resNativeBadge') : '',
|
||||
p.scaleToFit ? tr('resScaleToFitWindow') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean).join(' · ') || undefined,
|
||||
}))}
|
||||
value={supportsAutoResolution(opts.graphics) && opts.auto_resolution ? AUTO_RESOLUTION_OPTION : opts.resolution}
|
||||
onChange={(v) => {
|
||||
setManualResolutionPicked(v !== AUTO_RESOLUTION_OPTION)
|
||||
set(selectWizardResolution(v, autoPreset))
|
||||
}}
|
||||
options={buildResolutionOptions({
|
||||
graphics: opts.graphics,
|
||||
autoPreset,
|
||||
activePresets,
|
||||
}).map((item) => {
|
||||
const p = item.preset!
|
||||
if (item.kind === 'auto') {
|
||||
return {
|
||||
value: item.value,
|
||||
title: tr('resAuto'),
|
||||
sub: tr('resAutoSub', { res: p.label }),
|
||||
art: resArt(p.resolution),
|
||||
badges: [
|
||||
p.hidpi ? tr('hidpiPresetBadge') : '',
|
||||
p.scaleBadge ?? '',
|
||||
tr('recommendedBadge'),
|
||||
].filter(Boolean),
|
||||
}
|
||||
}
|
||||
return {
|
||||
value: item.value,
|
||||
title: p.label,
|
||||
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
|
||||
art: resArt(p.resolution),
|
||||
badges: [
|
||||
p.hidpi ? tr('hidpiPresetBadge') : '',
|
||||
p.scaleBadge ?? '',
|
||||
p.native ? tr('resNativeBadge') : '',
|
||||
p.scaleToFit ? tr('resScaleToFitWindow') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean),
|
||||
}
|
||||
})}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -686,12 +739,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<Switch
|
||||
label={tr('fullscreenLaunch')}
|
||||
checked={!!opts.borderless}
|
||||
onChange={(borderless) => {
|
||||
const list = borderless ? fullscreenPresets : windowPresets
|
||||
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
|
||||
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
|
||||
set(keep ? { borderless } : { borderless, resolution: fallback })
|
||||
}}
|
||||
onChange={(borderless) => set(toggleWizardBorderless({
|
||||
borderless,
|
||||
opts,
|
||||
host,
|
||||
fixedModeSupported,
|
||||
windowPresets,
|
||||
fullscreenPresets,
|
||||
}))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -707,7 +762,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<Review
|
||||
locale={locale}
|
||||
host={host}
|
||||
opts={opts}
|
||||
opts={effectiveOpts}
|
||||
captureSupported={captureSupported}
|
||||
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
|
||||
issues={issues}
|
||||
@@ -801,7 +856,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, i
|
||||
? tr('summaryInstallerSource', { file: fileName(opts.installer) })
|
||||
: tr('summaryDiskSource', { file: fileName(opts.disk) })
|
||||
|
||||
const res = (opts.resolution ?? '').replace(/x/i, ' × ')
|
||||
const res = formatResolutionLabel(opts.resolution ?? '', !!opts.auto_resolution, tr)
|
||||
const graphicsRows: Row[] = opts.graphics === 'reims-vgpu'
|
||||
? [
|
||||
{ label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` },
|
||||
|
||||
@@ -34,20 +34,6 @@ function formatCompactCount(n: number): string {
|
||||
return String(n)
|
||||
}
|
||||
|
||||
function formatByteSize(bytes?: number): string {
|
||||
if (!bytes || bytes <= 0) return ''
|
||||
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
if (bytes >= 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`
|
||||
return `${bytes} B`
|
||||
}
|
||||
|
||||
function formatShortDate(iso?: string): string {
|
||||
if (!iso) return ''
|
||||
const ms = Date.parse(iso)
|
||||
if (Number.isNaN(ms)) return ''
|
||||
return new Date(ms).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function parseTimestamp(iso?: string): number {
|
||||
if (!iso) return 0
|
||||
const ms = Date.parse(iso)
|
||||
@@ -62,20 +48,6 @@ function compositeScore(item: MarketCatalogItem, nowMs: number): number {
|
||||
return recency + downloads
|
||||
}
|
||||
|
||||
function entryReleases(item: MarketCatalogItem) {
|
||||
const e = item.entry
|
||||
if (e.releases && e.releases.length > 0) return e.releases
|
||||
return [{
|
||||
version: e.version,
|
||||
channel: e.channel || 'stable',
|
||||
download_url: e.download_url,
|
||||
sha256: e.sha256,
|
||||
size_bytes: e.size_bytes,
|
||||
published_at: e.updated_at,
|
||||
changelog: e.changelog,
|
||||
}]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
safeMode?: boolean
|
||||
@@ -102,7 +74,6 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
const [query, setQuery] = useState('')
|
||||
const [kind, setKind] = useState('')
|
||||
const [sortBy, setSortBy] = useState<MarketSortMode>('composite')
|
||||
const [versionPick, setVersionPick] = useState<{ item: MarketCatalogItem; selected: string } | null>(null)
|
||||
const [result, setResult] = useState<MarketBrowseResult | null>(null)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
@@ -277,22 +248,13 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
advancePrompt()
|
||||
}
|
||||
|
||||
const openVersionPicker = (item: MarketCatalogItem) => {
|
||||
const list = entryReleases(item)
|
||||
const defaultVer = list.find((r) => r.version === item.entry.version)?.version ?? list[0]?.version ?? item.entry.version
|
||||
setVersionPick({ item, selected: defaultVer })
|
||||
}
|
||||
|
||||
const install = async (item: MarketCatalogItem, version?: string) => {
|
||||
const install = async (item: MarketCatalogItem) => {
|
||||
const id = item.entry.id
|
||||
if (installingRef.current.has(id)) return
|
||||
installingRef.current.add(id)
|
||||
const rel = entryReleases(item).find((r) => r.version === version)
|
||||
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: rel?.size_bytes ?? item.entry.size_bytes ?? 0 } }))
|
||||
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
|
||||
try {
|
||||
const info = version
|
||||
? await api.InstallMarketPluginVersion(id, version)
|
||||
: await api.InstallMarketPlugin(id, true)
|
||||
const info = await api.InstallMarketPluginVersion(id, item.entry.version)
|
||||
await onChanged({})
|
||||
if (info && !info.enabled) {
|
||||
if (promptTargetIDRef.current) {
|
||||
@@ -372,7 +334,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
return (
|
||||
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
|
||||
<span>
|
||||
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => openVersionPicker(item)}>
|
||||
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
||||
{tr('pluginMarketUpdateShort')}
|
||||
</Button>
|
||||
</span>
|
||||
@@ -380,7 +342,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => openVersionPicker(item)}>
|
||||
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
||||
{tr('pluginMarketInstall')}
|
||||
</Button>
|
||||
)
|
||||
@@ -536,73 +498,6 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
</>
|
||||
)}
|
||||
|
||||
{versionPick && (
|
||||
<Modal
|
||||
title={tr('pluginMarketPickVersionTitle')}
|
||||
subtitle={locText(versionPick.item.entry.name, locale, versionPick.item.entry.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setVersionPick(null)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<div className="market-version-list" role="radiogroup" aria-label={tr('pluginMarketPickVersionTitle')}>
|
||||
{entryReleases(versionPick.item).map((rel) => {
|
||||
const selected = versionPick.selected === rel.version
|
||||
const isCurrent = versionPick.item.installed && versionPick.item.installed_version === rel.version
|
||||
const notes = locText(rel.changelog, locale, '')
|
||||
const date = formatShortDate(rel.published_at)
|
||||
const size = formatByteSize(rel.size_bytes)
|
||||
return (
|
||||
<label
|
||||
key={rel.version}
|
||||
className={`market-version-opt${selected ? ' is-selected' : ''}`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="market-version"
|
||||
checked={selected}
|
||||
onChange={() => setVersionPick({ ...versionPick, selected: rel.version })}
|
||||
/>
|
||||
<div className="market-version-main">
|
||||
<div className="market-version-head">
|
||||
<span className="market-card-version">v{rel.version}</span>
|
||||
{rel.channel === 'alpha' && (
|
||||
<span className="market-alpha-badge">{tr('pluginMarketAlphaTag')}</span>
|
||||
)}
|
||||
{isCurrent && (
|
||||
<span className="market-version-current">{tr('pluginMarketCurrentVersion')}</span>
|
||||
)}
|
||||
<span className="market-version-meta">
|
||||
{[date, size].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
</div>
|
||||
{notes && <p className="market-version-notes">{notes}</p>}
|
||||
</div>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setVersionPick(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={!versionPick.selected || !!safeMode}
|
||||
icon={<Download size={13} aria-hidden="true" />}
|
||||
onClick={() => {
|
||||
const target = versionPick
|
||||
setVersionPick(null)
|
||||
void install(target.item, target.selected)
|
||||
}}
|
||||
>
|
||||
{tr('pluginMarketPickVersionInstall')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{prompt && (
|
||||
<Modal
|
||||
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
|
||||
|
||||
@@ -13,18 +13,26 @@ import {
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
canKeepDisplayPreset,
|
||||
fullscreenDisplayPresets,
|
||||
FullscreenDisplayPreset,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
windowDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import {
|
||||
buildResolutionOptions,
|
||||
buildSettingsSaveDiff,
|
||||
countChangedSettingsFields,
|
||||
deriveSettingsResolutionState,
|
||||
expandTouchedSettingsFields,
|
||||
normalizeResolution,
|
||||
reconcileSettingsFormOnBaseChange,
|
||||
resolveCustomResBlur,
|
||||
selectSettingsResolution,
|
||||
switchSettingsGraphics,
|
||||
toggleSettingsBorderless,
|
||||
} from '../lib/displayResolution'
|
||||
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types'
|
||||
@@ -37,7 +45,6 @@ import { formatAffinitySummary } from './AffinityDialog'
|
||||
import { VMNetworkSettings } from './VMNetworkSettings'
|
||||
import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk'
|
||||
import { DiskCacheRow } from './vmSettings/diskCache'
|
||||
import { KeymapSection, useKeymap } from './vmSettings/keymap'
|
||||
import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins'
|
||||
import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing'
|
||||
import { SMBIOSDialog, SMBIOSSection, useSMBIOS } from './vmSettings/smbios'
|
||||
@@ -70,6 +77,7 @@ const FIELD_CAT: Record<Field, Cat> = {
|
||||
graphics: 'display',
|
||||
gpu: 'display',
|
||||
resolution: 'display',
|
||||
auto_resolution: 'display',
|
||||
displays: 'display',
|
||||
borderless: 'display',
|
||||
disk_controller: 'storage',
|
||||
@@ -88,18 +96,16 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[]
|
||||
|
||||
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
|
||||
const CUSTOM = '__custom'
|
||||
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()
|
||||
|
||||
/** 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) {
|
||||
case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string)
|
||||
case 'gpu': return normPath(a as string) === normPath(b as string)
|
||||
case 'resolution': return normRes(a as string) === normRes(b as string)
|
||||
case 'resolution': return normalizeResolution(a as string) === normalizeResolution(b as string)
|
||||
case 'log_level':
|
||||
case 'extra_args':
|
||||
case 'audio_backend':
|
||||
@@ -122,6 +128,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
|
||||
disk_controller: detail.disk_controller,
|
||||
disk_cache: (detail.disk_cache as DiskCache) || 'default',
|
||||
resolution: detail.resolution,
|
||||
auto_resolution: !!detail.auto_resolution,
|
||||
borderless: detail.borderless,
|
||||
...(detail.capture_supported ? { capture: detail.capture } : {}),
|
||||
gpu: icd ?? (detail.gpu || 'auto'),
|
||||
@@ -175,7 +182,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
const drives = useDriveShares(detail.name)
|
||||
const folders = useSharedFolders(detail.name, locale)
|
||||
const smbios = useSMBIOS(detail, running)
|
||||
const keymap = useKeymap(detail.name, running, cat === 'input')
|
||||
const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr)
|
||||
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged })
|
||||
const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general')
|
||||
@@ -187,24 +193,47 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
const tzBusy = timezone.tzBusy
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
|
||||
const fsPresets = fullscreenDisplayPresets(displayProfile)
|
||||
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
|
||||
const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution))
|
||||
const [forceCustomRes, setCustomRes] = useState(false)
|
||||
const customRes = forceCustomRes || !presetHit
|
||||
const { presets, fsPresets, activePresets, autoPreset, customRes, resValue, resBad } = deriveSettingsResolutionState({
|
||||
form,
|
||||
displayProfile,
|
||||
fixedModeSupported,
|
||||
forceCustomRes,
|
||||
})
|
||||
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
|
||||
|
||||
// The detail the panel opened with can be a stale one (reopened right after
|
||||
// a save, before the refreshed detail arrives): follow newer details until
|
||||
// the person changes something.
|
||||
const edited = useRef(false)
|
||||
// a save, before the refreshed detail arrives) or refreshed in the background:
|
||||
// sync untouched fields from the latest baseline while preserving user edits.
|
||||
const vmIdentity = `${driverID}:${detail.name}`
|
||||
const vmIdentityRef = useRef(vmIdentity)
|
||||
const touchedFieldsRef = useRef<Set<Field>>(new Set())
|
||||
useEffect(() => {
|
||||
if (edited.current) return
|
||||
setForm(base)
|
||||
setCustomRes(false)
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}, [base])
|
||||
const prevKey = vmIdentityRef.current
|
||||
vmIdentityRef.current = vmIdentity
|
||||
if (prevKey !== vmIdentity) {
|
||||
touchedFieldsRef.current.clear()
|
||||
setIssues([])
|
||||
setErr('')
|
||||
setCustomRes(false)
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
} else {
|
||||
const touched = touchedFieldsRef.current
|
||||
if (!touched.has('resolution') && !touched.has('auto_resolution')) {
|
||||
setCustomRes(false)
|
||||
}
|
||||
if (!touched.has('log_level')) {
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}
|
||||
}
|
||||
setForm((cur) => reconcileSettingsFormOnBaseChange({
|
||||
previousVMKey: prevKey,
|
||||
nextVMKey: vmIdentity,
|
||||
form: cur,
|
||||
base,
|
||||
touchedFields: touchedFieldsRef.current,
|
||||
}).form)
|
||||
}, [base, vmIdentity])
|
||||
|
||||
useEffect(() => {
|
||||
setForm((f) => {
|
||||
@@ -216,25 +245,34 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
}, [detail.capture_supported, detail.capture])
|
||||
|
||||
const set = (patch: Partial<SetOpts>) => {
|
||||
edited.current = true
|
||||
const touched = expandTouchedSettingsFields(Object.keys(patch)) as Field[]
|
||||
for (const f of touched) touchedFieldsRef.current.add(f)
|
||||
setForm((f) => ({ ...f, ...patch }))
|
||||
const touched = Object.keys(patch)
|
||||
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
|
||||
setIssues((list) => list.filter((i) => !touched.includes(i.field as Field)))
|
||||
}
|
||||
const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f]))
|
||||
const reset = (f: Field) => () => {
|
||||
set({ [f]: base[f] } as Partial<SetOpts>)
|
||||
if (f === 'resolution' || f === 'borderless') setCustomRes(false)
|
||||
const toClear = expandTouchedSettingsFields([f]) as Field[]
|
||||
for (const field of toClear) touchedFieldsRef.current.delete(field)
|
||||
setForm((cur) => {
|
||||
const next = { ...cur }
|
||||
for (const field of toClear) {
|
||||
;(next as unknown as Record<string, unknown>)[field] = (base as unknown as Record<string, unknown>)[field]
|
||||
}
|
||||
return next
|
||||
})
|
||||
setIssues((list) => list.filter((i) => !toClear.includes(i.field as Field)))
|
||||
if (f === 'resolution' || f === 'auto_resolution' || f === 'borderless') setCustomRes(false)
|
||||
if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}
|
||||
const changed = FIELDS.filter(dirty)
|
||||
const changedIn = (c: Cat) => changed.filter((f) => FIELD_CAT[f] === c).length
|
||||
const changedCount = countChangedSettingsFields(changed)
|
||||
const changedIn = (c: Cat) => countChangedSettingsFields(changed.filter((f) => FIELD_CAT[f] === c))
|
||||
const issueOf = (f: Field) => issues.find((i) => i.field === f)?.message
|
||||
const issueIn = (c: Cat) => issues.some((i) => FIELD_CAT[i.field as Field] === c) || (c === 'display' && resBad)
|
||||
const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT))
|
||||
|
||||
// Inline checks the backend would also reject, so the row says it first.
|
||||
const resBad = customRes && !RES_RE.test(form.resolution ?? '')
|
||||
const sshOn = (form.ssh_port ?? 0) > 0
|
||||
const localBlock = resBad
|
||||
const nestedVirtAvailable = host.whpx === 'ready' && host.whpx_caps?.nested_vmx && !host.needs_cold_reboot_workaround
|
||||
@@ -283,8 +321,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
setIssues([])
|
||||
setBusy(true)
|
||||
try {
|
||||
const diff: SetOpts = { name: detail.name }
|
||||
for (const f of changed) (diff as unknown as Record<string, unknown>)[f] = form[f]
|
||||
const diff = buildSettingsSaveDiff(detail.name, changed, form, base)
|
||||
const iss = await api.ValidateSet(diff)
|
||||
if (iss && iss.length > 0) {
|
||||
setIssues(iss)
|
||||
@@ -302,7 +339,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
}
|
||||
|
||||
const resetAll = () => {
|
||||
edited.current = false
|
||||
touchedFieldsRef.current.clear()
|
||||
setForm(base)
|
||||
setIssues([])
|
||||
setCustomRes(false)
|
||||
@@ -499,19 +536,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
const vgpu = form.graphics !== 'vmware-svga'
|
||||
const targetDisp = activeTargetDisplay
|
||||
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr, presets)
|
||||
const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
|
||||
const changeGraphics = (graphics: string) => {
|
||||
const next = switchSettingsGraphics(graphics)
|
||||
if (next.forceCustomRes !== undefined) setCustomRes(next.forceCustomRes)
|
||||
set(next.patch)
|
||||
}
|
||||
const toggleBorderless = (borderless: boolean) => {
|
||||
const targetPresets = borderless ? fsPresets : presets
|
||||
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
|
||||
const nextRes = borderless
|
||||
? (targetDisp && targetDisp.width > 0 && targetDisp.height > 0
|
||||
? `${targetDisp.width}x${targetDisp.height}`
|
||||
: targetPresets[0]?.resolution ?? form.resolution)
|
||||
: recommendedResolution(displayProfile)
|
||||
set({ borderless, resolution: nextRes })
|
||||
return
|
||||
}
|
||||
set({ borderless })
|
||||
set(toggleSettingsBorderless({
|
||||
borderless,
|
||||
form,
|
||||
displayProfile,
|
||||
targetDisplay: targetDisp,
|
||||
presets,
|
||||
fsPresets,
|
||||
customRes,
|
||||
}))
|
||||
}
|
||||
const resArt = (r: string) => {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
|
||||
@@ -530,7 +569,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<Segmented
|
||||
label={tr('graphicsBackend')}
|
||||
value={form.graphics}
|
||||
onChange={(graphics) => set({ graphics })}
|
||||
onChange={changeGraphics}
|
||||
options={[
|
||||
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') },
|
||||
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') },
|
||||
@@ -553,7 +592,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<button
|
||||
type="button"
|
||||
className="link-btn"
|
||||
onClick={() => set({ graphics: 'vmware-svga' })}
|
||||
onClick={() => changeGraphics('vmware-svga')}
|
||||
>
|
||||
{tr('gpuSwitchSvga')}
|
||||
</button>
|
||||
@@ -577,7 +616,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
/>
|
||||
<SetRow
|
||||
{...rowProps('resolution')}
|
||||
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
|
||||
dirty={dirty('resolution') || dirty('auto_resolution')}
|
||||
onReset={reset('resolution')}
|
||||
disabled={!vgpu}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
error={issueOf('resolution') ?? issueOf('auto_resolution') ?? (resBad ? tr('resInvalid') : undefined)}
|
||||
title={tr('resolution')}
|
||||
desc={hostDisplayDesc(host, tr, activeTargetDisplay, (d) =>
|
||||
tr('targetDisplayHint', {
|
||||
@@ -593,13 +636,41 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
label={tr('resolution')}
|
||||
value={resValue}
|
||||
onChange={(v) => {
|
||||
if (v === CUSTOM) { setCustomRes(true); return }
|
||||
setCustomRes(false)
|
||||
set({ resolution: v })
|
||||
const next = selectSettingsResolution({ value: v, form, base, autoPreset })
|
||||
setCustomRes(next.forceCustomRes)
|
||||
set(next.patch)
|
||||
}}
|
||||
options={[
|
||||
...activePresets.map((p) => ({
|
||||
value: p.resolution,
|
||||
options={buildResolutionOptions({
|
||||
graphics: form.graphics,
|
||||
autoPreset,
|
||||
activePresets,
|
||||
includeCustom: true,
|
||||
}).map((item) => {
|
||||
if (item.kind === 'auto') {
|
||||
const p = item.preset!
|
||||
return {
|
||||
value: item.value,
|
||||
title: tr('resAuto'),
|
||||
sub: tr('resAutoSub', { res: p.label }),
|
||||
art: resArt(p.resolution),
|
||||
badges: [
|
||||
p.hidpi ? tr('hidpiPresetBadge') : '',
|
||||
p.scaleBadge ?? '',
|
||||
tr('recommendedBadge'),
|
||||
].filter(Boolean),
|
||||
}
|
||||
}
|
||||
if (item.kind === 'custom') {
|
||||
return {
|
||||
value: item.value,
|
||||
title: tr('resCustom'),
|
||||
sub: tr('resCustomSub'),
|
||||
art: <span className="screen-art custom" aria-hidden="true" />,
|
||||
}
|
||||
}
|
||||
const p = item.preset!
|
||||
return {
|
||||
value: item.value,
|
||||
title: p.label,
|
||||
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
|
||||
art: resArt(p.resolution),
|
||||
@@ -610,9 +681,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
p.scaleToFit ? tr('resScaleToFitWindow') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean),
|
||||
})),
|
||||
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
|
||||
]}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
{customRes && (
|
||||
<input
|
||||
@@ -622,6 +692,20 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
autoFocus
|
||||
value={form.resolution ?? ''}
|
||||
onChange={(e) => set({ resolution: e.target.value })}
|
||||
onBlur={() => {
|
||||
const blurred = resolveCustomResBlur({
|
||||
resolution: form.resolution,
|
||||
autoResolution: form.auto_resolution,
|
||||
forceCustomRes,
|
||||
activePresets,
|
||||
})
|
||||
if (blurred.nextResolution !== undefined && blurred.nextResolution !== form.resolution) {
|
||||
set({ resolution: blurred.nextResolution })
|
||||
}
|
||||
if (blurred.exitCustom) {
|
||||
setCustomRes(false)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!form.borderless && hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
|
||||
@@ -760,7 +844,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
/>
|
||||
</SetGroup>
|
||||
)}
|
||||
<KeymapSection locale={locale} vm={detail.name} state={keymap} captureSupported={detail.capture_supported} />
|
||||
<VMPluginGroup locale={locale} group="keyboard" state={plugins} />
|
||||
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
|
||||
<SetRow
|
||||
@@ -904,10 +987,10 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
|
||||
<div className="dialog-foot">
|
||||
<span className="foot-status" aria-live="polite">
|
||||
{changed.length > 0
|
||||
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</>
|
||||
{changedCount > 0
|
||||
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changedCount })}</>
|
||||
: <span className="muted">{tr('noChanges')}</span>}
|
||||
{changed.length > 0 && (
|
||||
{changedCount > 0 && (
|
||||
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -80,8 +80,13 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
|
||||
}, [selected])
|
||||
|
||||
const browse = async () => {
|
||||
const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '')
|
||||
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
|
||||
try {
|
||||
const dir = await api.PickDirectory(tr('setupTitle'))
|
||||
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
|
||||
} catch (e) {
|
||||
console.warn('[setup] PickDirectory failed:', e)
|
||||
onError(tr('failGeneric'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const next = async () => {
|
||||
|
||||
@@ -32,7 +32,12 @@ export const SnapshotSection: React.FC<Props> = ({ locale, driverID, name, state
|
||||
|
||||
const loadSnapshots = () => {
|
||||
if (!shown) { setSnapshots([]); return }
|
||||
api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
api.ListSnapshots(driverID, name)
|
||||
.then((list) => setSnapshots(list ?? []))
|
||||
.catch((e) => {
|
||||
console.warn('[snapshots] ListSnapshots failed:', driverID, name, e)
|
||||
setSnapshots([])
|
||||
})
|
||||
}
|
||||
useEffect(() => {
|
||||
setCreatingSnap(false)
|
||||
|
||||
@@ -29,7 +29,12 @@ export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError
|
||||
useEffect(() => {
|
||||
if (!enabled) { setSshUser(''); return }
|
||||
let live = true
|
||||
api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
api.GetVMSSHUser(driverID, name)
|
||||
.then((u) => { if (live) setSshUser(u ?? '') })
|
||||
.catch((e) => {
|
||||
console.warn('[ssh] GetVMSSHUser failed:', driverID, name, e)
|
||||
if (live) setSshUser('')
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [driverID, name, enabled])
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ChevronRight, Copy } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { formatResolutionLabel } from '../../lib/format'
|
||||
import { Locale, VMDetail, VMInfo } from '../../types'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
|
||||
@@ -16,6 +17,9 @@ interface Props {
|
||||
/** The raw values upstream tools use for the VM, folded by default. */
|
||||
export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmInfo, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const resolutionValue = detail
|
||||
? (detail.graphics !== 'vmware-svga' && detail.auto_resolution ? formatResolutionLabel(detail.resolution, true, tr) : detail.resolution)
|
||||
: ''
|
||||
const copyTechSummary = () => {
|
||||
if (!detail) {
|
||||
if (!vmInfo) return
|
||||
@@ -32,7 +36,7 @@ export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmIn
|
||||
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
|
||||
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
|
||||
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
|
||||
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
|
||||
`${tr('resolution')}: ${detail.displays} × ${resolutionValue}`,
|
||||
`${tr('fieldController')}: ${detail.disk_controller}`,
|
||||
`${tr('fieldDisk')}: ${detail.disk}`,
|
||||
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
|
||||
@@ -71,7 +75,7 @@ export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmIn
|
||||
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
|
||||
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
|
||||
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
|
||||
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
|
||||
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {resolutionValue}</dd>
|
||||
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
|
||||
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
|
||||
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets, type KeymapState } from '../../lib/vmKeymap'
|
||||
import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types'
|
||||
import { PopupSelect, Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
const PRESET_LABEL: Record<VMKeymapPreset, I18nKey> = {
|
||||
off: 'keymapPresetOff',
|
||||
win_to_cmd: 'keymapPresetWinToCmd',
|
||||
swap_alt_win: 'keymapPresetSwapAltWin',
|
||||
custom: 'keymapPresetCustom',
|
||||
}
|
||||
|
||||
/** The VM's modifier key mapping, refreshed while shown. */
|
||||
export function useKeymap(vm: string, running: boolean, shown: boolean) {
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState<KeymapState>({ keymap: null, error: '', busy: false })
|
||||
const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current,
|
||||
(patch) => setKeymapState((state) => ({ ...state, ...patch }))))
|
||||
|
||||
useEffect(() => {
|
||||
setKeymapState(keymapRequests.initial(vm))
|
||||
}, [vm, keymapRequests])
|
||||
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const { refresh, stop } = keymapRequests.watch(vm)
|
||||
void refresh()
|
||||
const timer = window.setInterval(refresh, 3000)
|
||||
return () => { stop(); window.clearInterval(timer) }
|
||||
}, [shown, vm, running, keymapRequests])
|
||||
|
||||
return { keymap, keymapErr, keymapBusy, write: keymapRequests.write }
|
||||
}
|
||||
|
||||
export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType<typeof useKeymap>; captureSupported: boolean }> = ({ locale, vm, state, captureSupported }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { keymap, keymapErr, keymapBusy, write } = state
|
||||
const statusHint = keymap ? keymapStatusHint(keymap) : null
|
||||
const presetOptions = keymap
|
||||
? visibleKeymapPresets(keymap.preset, captureSupported).map((value) => ({ value, label: tr(PRESET_LABEL[value]) }))
|
||||
: []
|
||||
return (
|
||||
<SetGroup title={tr('keymapGroupTitle')} note={tr('keymapGroupNote')}>
|
||||
{keymapErr && <div className="notice notice-error" role="alert">{keymapErr}</div>}
|
||||
{keymap && <>
|
||||
<SetRow title={tr('keymapPresetTitle')} desc={tr('keymapPresetDesc')} disabled={keymapBusy}
|
||||
control={<Segmented<VMKeymapPreset> label={tr('keymapPresetTitle')} value={keymap.preset}
|
||||
options={presetOptions}
|
||||
onChange={(preset) => {
|
||||
const request = keymapPresetUpdate(keymap, preset)
|
||||
if (request) void write(vm, request)
|
||||
}} />}
|
||||
/>
|
||||
<SetRow title={tr('keymapCaptureHostShortcutsTitle')} desc={tr('keymapCaptureHostShortcutsDesc')} disabled={keymapBusy}
|
||||
control={<Switch label={tr('keymapCaptureHostShortcutsTitle')} checked={keymap.capture_host_shortcuts}
|
||||
onChange={(capture_host_shortcuts) => { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />}
|
||||
/>
|
||||
{statusHint && (
|
||||
<SetValue title={tr('keymapStatusTitle')} value={tr(statusHint.key, statusHint.vars)} />
|
||||
)}
|
||||
{keymap.preset === 'custom' && ([
|
||||
['lwin', 'keymapHostLwin'],
|
||||
['rwin', 'keymapHostRwin'],
|
||||
['lalt', 'keymapHostLalt'],
|
||||
['ralt', 'keymapHostRalt'],
|
||||
['lctrl', 'keymapHostLctrl'],
|
||||
['rctrl', 'keymapHostRctrl'],
|
||||
['capslock', 'keymapHostCapslock'],
|
||||
] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => (
|
||||
<SetRow key={modifier} title={tr(label)} disabled={keymapBusy}
|
||||
control={<PopupSelect<VMKeymapGuestModifier> label={tr(label)} value={keymap.bindings[modifier] ?? 'default'}
|
||||
options={[
|
||||
{ value: 'default', label: tr('keymapGuestDefault') },
|
||||
{ value: 'lcmd', label: tr('keymapGuestLcmd') },
|
||||
{ value: 'rcmd', label: tr('keymapGuestRcmd') },
|
||||
{ value: 'lopt', label: tr('keymapGuestLopt') },
|
||||
{ value: 'ropt', label: tr('keymapGuestRopt') },
|
||||
{ value: 'lctrl', label: tr('keymapGuestLctrl') },
|
||||
{ value: 'rctrl', label: tr('keymapGuestRctrl') },
|
||||
{ value: 'esc', label: tr('keymapGuestEsc') },
|
||||
{ value: 'disabled', label: tr('keymapGuestDisabled') },
|
||||
]}
|
||||
onChange={(target) => { void write(vm, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />}
|
||||
/>
|
||||
))}
|
||||
</>}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
export const coreZh: Record<string, string> = {
|
||||
"affinityMenu": "处理器相关性…",
|
||||
"appearance": "外观",
|
||||
"autoResolution": "自动分辨率",
|
||||
"backToEdit": "返回修改",
|
||||
"borderless": "无边框全屏",
|
||||
"cancel": "取消",
|
||||
@@ -138,6 +139,8 @@ export const coreZh: Record<string, string> = {
|
||||
"quitFailed": "已取消退出",
|
||||
"quitInProgress": "正在退出…",
|
||||
"refresh": "刷新",
|
||||
"resAuto": "自动",
|
||||
"resAutoValue": "自动({res})",
|
||||
"resLooksLike": "看起来像 {w} × {h}",
|
||||
"resizeLogPanel": "拖动调整日志高度",
|
||||
"resolution": "分辨率",
|
||||
@@ -215,6 +218,7 @@ export const coreZh: Record<string, string> = {
|
||||
export const coreEn: Record<string, string> = {
|
||||
"affinityMenu": "Processor Affinity…",
|
||||
"appearance": "Appearance",
|
||||
"autoResolution": "Auto resolution",
|
||||
"backToEdit": "Edit and retry",
|
||||
"borderless": "Borderless full screen",
|
||||
"cancel": "Cancel",
|
||||
@@ -350,6 +354,8 @@ export const coreEn: Record<string, string> = {
|
||||
"quitFailed": "Quit canceled",
|
||||
"quitInProgress": "Quitting…",
|
||||
"refresh": "Refresh",
|
||||
"resAuto": "Auto",
|
||||
"resAutoValue": "Auto ({res})",
|
||||
"resLooksLike": "Looks like {w} × {h}",
|
||||
"resizeLogPanel": "Drag to resize log panel",
|
||||
"resolution": "Resolution",
|
||||
|
||||
@@ -48,7 +48,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginLinkDevBtn": "链接插件开发目录",
|
||||
"pluginLinkDevTitle": "链接本地开发插件目录",
|
||||
"pluginMarketAlphaTag": "Alpha",
|
||||
"pluginMarketCurrentVersion": "当前已安装",
|
||||
"pluginMarketDownloading": "下载中",
|
||||
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
|
||||
"pluginMarketFeedEnd": "共 {count} 个插件",
|
||||
@@ -64,8 +63,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginMarketKindTheme": "主题",
|
||||
"pluginMarketKindTool": "工具",
|
||||
"pluginMarketLoading": "正在读取插件市场",
|
||||
"pluginMarketPickVersionInstall": "安装此版本",
|
||||
"pluginMarketPickVersionTitle": "选择安装版本",
|
||||
"pluginMarketRefresh": "刷新索引",
|
||||
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
|
||||
"pluginMarketSortComposite": "综合排序",
|
||||
@@ -173,7 +170,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginLinkDevBtn": "Link plugin dev folder",
|
||||
"pluginLinkDevTitle": "Link local dev plugin folder",
|
||||
"pluginMarketAlphaTag": "Alpha",
|
||||
"pluginMarketCurrentVersion": "Installed",
|
||||
"pluginMarketDownloading": "Downloading",
|
||||
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.",
|
||||
"pluginMarketFeedEnd": "{count} plugins",
|
||||
@@ -189,8 +185,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginMarketKindTheme": "Themes",
|
||||
"pluginMarketKindTool": "Tools",
|
||||
"pluginMarketLoading": "Loading the plugin market",
|
||||
"pluginMarketPickVersionInstall": "Install version",
|
||||
"pluginMarketPickVersionTitle": "Select version",
|
||||
"pluginMarketRefresh": "Refresh index",
|
||||
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
|
||||
"pluginMarketSortComposite": "Recommended",
|
||||
|
||||
@@ -368,40 +368,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"kernelIrqchipLabel": "中断加速",
|
||||
"kernelIrqchipOff": "关闭",
|
||||
"kernelIrqchipOn": "开启",
|
||||
"keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option",
|
||||
"keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键",
|
||||
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效;更改立即生效,无需点击保存。Ctrl+Alt+Win 保留用于释放键盘捕获",
|
||||
"keymapGroupTitle": "修饰键映射",
|
||||
"keymapGuestDefault": "默认",
|
||||
"keymapGuestDisabled": "禁用",
|
||||
"keymapGuestEsc": "Esc",
|
||||
"keymapGuestLcmd": "左 ⌘ Command",
|
||||
"keymapGuestLctrl": "左 ⌃ Control",
|
||||
"keymapGuestLopt": "左 ⌥ Option",
|
||||
"keymapGuestRcmd": "右 ⌘ Command",
|
||||
"keymapGuestRctrl": "右 ⌃ Control",
|
||||
"keymapGuestRopt": "右 ⌥ Option",
|
||||
"keymapHostCapslock": "Caps Lock",
|
||||
"keymapHostLalt": "左 Alt",
|
||||
"keymapHostLctrl": "左 Ctrl",
|
||||
"keymapHostLwin": "左 Win",
|
||||
"keymapHostRalt": "右 Alt",
|
||||
"keymapHostRctrl": "右 Ctrl",
|
||||
"keymapHostRwin": "右 Win",
|
||||
"keymapInactive": "修饰键映射未启用",
|
||||
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
|
||||
"keymapPending": "等待 Guest Tools 启用修饰键映射",
|
||||
"keymapPresetCustom": "自定义",
|
||||
"keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可",
|
||||
"keymapPresetOff": "关闭",
|
||||
"keymapPresetSwapAltWin": "Alt ↔ Win",
|
||||
"keymapPresetTitle": "映射预设",
|
||||
"keymapPresetWinToCmd": "Win → ⌘",
|
||||
"keymapRunning": "虚拟机获得焦点时生效",
|
||||
"keymapStatusTitle": "生效状态",
|
||||
"keymapStopped": "虚拟机启动后生效",
|
||||
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
|
||||
"keymapWaiting": "等待 Guest Tools 连接",
|
||||
"language": "语言",
|
||||
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
|
||||
"logLevel": "日志级别",
|
||||
@@ -454,6 +420,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"qemuASLR": "自动为 QEMU 启用 ASLR",
|
||||
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
|
||||
"recommendedBadge": "推荐",
|
||||
"resAutoSub": "当前屏 {res}",
|
||||
"resCustom": "自定义",
|
||||
"resCustomSub": "宽 × 高",
|
||||
"resInvalid": "格式为 宽x高,例如 2560x1600",
|
||||
@@ -917,40 +884,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"kernelIrqchipLabel": "Interrupt acceleration",
|
||||
"kernelIrqchipOff": "Off",
|
||||
"kernelIrqchipOn": "On",
|
||||
"keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS",
|
||||
"keymapCaptureHostShortcutsTitle": "Block host global hotkeys",
|
||||
"keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard capture",
|
||||
"keymapGroupTitle": "Modifier keys",
|
||||
"keymapGuestDefault": "Default",
|
||||
"keymapGuestDisabled": "Disabled",
|
||||
"keymapGuestEsc": "Esc",
|
||||
"keymapGuestLcmd": "Left ⌘ Command",
|
||||
"keymapGuestLctrl": "Left ⌃ Control",
|
||||
"keymapGuestLopt": "Left ⌥ Option",
|
||||
"keymapGuestRcmd": "Right ⌘ Command",
|
||||
"keymapGuestRctrl": "Right ⌃ Control",
|
||||
"keymapGuestRopt": "Right ⌥ Option",
|
||||
"keymapHostCapslock": "Caps Lock",
|
||||
"keymapHostLalt": "Left Alt",
|
||||
"keymapHostLctrl": "Left Ctrl",
|
||||
"keymapHostLwin": "Left Win",
|
||||
"keymapHostRalt": "Right Alt",
|
||||
"keymapHostRctrl": "Right Ctrl",
|
||||
"keymapHostRwin": "Right Win",
|
||||
"keymapInactive": "Modifier mapping is inactive",
|
||||
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
|
||||
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
|
||||
"keymapPresetCustom": "Custom",
|
||||
"keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed",
|
||||
"keymapPresetOff": "Off",
|
||||
"keymapPresetSwapAltWin": "Alt ↔ Win",
|
||||
"keymapPresetTitle": "Preset",
|
||||
"keymapPresetWinToCmd": "Win → ⌘",
|
||||
"keymapRunning": "Active while this VM is focused",
|
||||
"keymapStatusTitle": "Status",
|
||||
"keymapStopped": "Applies when this VM is running",
|
||||
"keymapUpgrade": "Update Guest Tools to version {version}",
|
||||
"keymapWaiting": "Waiting for Guest Tools to connect",
|
||||
"language": "Language",
|
||||
"languageSub": "Simplified Chinese and English built in; add more via plugins",
|
||||
"logLevel": "Log level",
|
||||
@@ -1003,6 +936,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"qemuASLR": "Automatically enable ASLR for QEMU",
|
||||
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
|
||||
"recommendedBadge": "Recommended",
|
||||
"resAutoSub": "Follows display · {res}",
|
||||
"resCustom": "Custom",
|
||||
"resCustomSub": "Width × height",
|
||||
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
|
||||
|
||||
@@ -79,6 +79,7 @@ export type I18nKey =
|
||||
| "audioDisabledReason"
|
||||
| "audioTroubleshootNote"
|
||||
| "autoPinPCores"
|
||||
| "autoResolution"
|
||||
| "back"
|
||||
| "backToEdit"
|
||||
| "borderless"
|
||||
@@ -608,40 +609,6 @@ export type I18nKey =
|
||||
| "kernelIrqchipLabel"
|
||||
| "kernelIrqchipOff"
|
||||
| "kernelIrqchipOn"
|
||||
| "keymapCaptureHostShortcutsDesc"
|
||||
| "keymapCaptureHostShortcutsTitle"
|
||||
| "keymapGroupNote"
|
||||
| "keymapGroupTitle"
|
||||
| "keymapGuestDefault"
|
||||
| "keymapGuestDisabled"
|
||||
| "keymapGuestEsc"
|
||||
| "keymapGuestLcmd"
|
||||
| "keymapGuestLctrl"
|
||||
| "keymapGuestLopt"
|
||||
| "keymapGuestRcmd"
|
||||
| "keymapGuestRctrl"
|
||||
| "keymapGuestRopt"
|
||||
| "keymapHostCapslock"
|
||||
| "keymapHostLalt"
|
||||
| "keymapHostLctrl"
|
||||
| "keymapHostLwin"
|
||||
| "keymapHostRalt"
|
||||
| "keymapHostRctrl"
|
||||
| "keymapHostRwin"
|
||||
| "keymapInactive"
|
||||
| "keymapInputServiceRequired"
|
||||
| "keymapPending"
|
||||
| "keymapPresetCustom"
|
||||
| "keymapPresetDesc"
|
||||
| "keymapPresetOff"
|
||||
| "keymapPresetSwapAltWin"
|
||||
| "keymapPresetTitle"
|
||||
| "keymapPresetWinToCmd"
|
||||
| "keymapRunning"
|
||||
| "keymapStatusTitle"
|
||||
| "keymapStopped"
|
||||
| "keymapUpgrade"
|
||||
| "keymapWaiting"
|
||||
| "language"
|
||||
| "languageSub"
|
||||
| "localeAuto"
|
||||
@@ -798,7 +765,6 @@ export type I18nKey =
|
||||
| "pluginLinkDevBtn"
|
||||
| "pluginLinkDevTitle"
|
||||
| "pluginMarketAlphaTag"
|
||||
| "pluginMarketCurrentVersion"
|
||||
| "pluginMarketDownloading"
|
||||
| "pluginMarketEmpty"
|
||||
| "pluginMarketFeedEnd"
|
||||
@@ -814,8 +780,6 @@ export type I18nKey =
|
||||
| "pluginMarketKindTheme"
|
||||
| "pluginMarketKindTool"
|
||||
| "pluginMarketLoading"
|
||||
| "pluginMarketPickVersionInstall"
|
||||
| "pluginMarketPickVersionTitle"
|
||||
| "pluginMarketRefresh"
|
||||
| "pluginMarketSearchPlaceholder"
|
||||
| "pluginMarketSortComposite"
|
||||
@@ -881,6 +845,9 @@ export type I18nKey =
|
||||
| "quitInProgress"
|
||||
| "recommendedBadge"
|
||||
| "refresh"
|
||||
| "resAuto"
|
||||
| "resAutoSub"
|
||||
| "resAutoValue"
|
||||
| "resCustom"
|
||||
| "resCustomSub"
|
||||
| "resInvalid"
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import {
|
||||
canKeepDisplayPreset,
|
||||
FullscreenDisplayPreset,
|
||||
fullscreenDisplayPresets,
|
||||
recommendedResolution,
|
||||
resolveAutoDisplayPreset,
|
||||
windowDisplayPresets,
|
||||
} from './format'
|
||||
import { CreateOpts, DisplayInfo, HostReport, SetOpts } from '../types'
|
||||
|
||||
export const AUTO_RESOLUTION_OPTION = '__auto'
|
||||
export const CUSTOM_RESOLUTION_OPTION = '__custom'
|
||||
const CANONICAL_RESOLUTION_RE = /^\d{3,5}x\d{3,5}$/
|
||||
|
||||
export function canonicalResolution(raw: string | undefined): string {
|
||||
const trimmed = (raw ?? '').trim()
|
||||
const m = /^(\d+)\s*[x×X]\s*(\d+)$/.exec(trimmed)
|
||||
return m ? `${m[1]}x${m[2]}` : trimmed
|
||||
}
|
||||
|
||||
export const normalizeResolution = (raw: string | undefined) => canonicalResolution(raw).toLowerCase()
|
||||
|
||||
export function isValidResolution(raw: string | undefined): boolean {
|
||||
return CANONICAL_RESOLUTION_RE.test(canonicalResolution(raw))
|
||||
}
|
||||
|
||||
interface ResolutionOptionItem {
|
||||
value: string
|
||||
kind: 'auto' | 'preset' | 'custom'
|
||||
preset?: FullscreenDisplayPreset
|
||||
}
|
||||
|
||||
export function buildResolutionOptions(params: {
|
||||
graphics?: string
|
||||
autoPreset: FullscreenDisplayPreset
|
||||
activePresets: FullscreenDisplayPreset[]
|
||||
includeCustom?: boolean
|
||||
}): ResolutionOptionItem[] {
|
||||
const items: ResolutionOptionItem[] = []
|
||||
if (supportsAutoResolution(params.graphics)) {
|
||||
items.push({ value: AUTO_RESOLUTION_OPTION, kind: 'auto', preset: params.autoPreset })
|
||||
}
|
||||
for (const preset of params.activePresets) {
|
||||
items.push({ value: preset.resolution, kind: 'preset', preset })
|
||||
}
|
||||
if (params.includeCustom) {
|
||||
items.push({ value: CUSTOM_RESOLUTION_OPTION, kind: 'custom' })
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export function supportsAutoResolution(graphics: string | undefined): boolean {
|
||||
return graphics !== 'vmware-svga'
|
||||
}
|
||||
|
||||
export function deriveSettingsResolutionState(params: {
|
||||
form: Pick<SetOpts, 'graphics' | 'resolution' | 'auto_resolution' | 'borderless'>
|
||||
displayProfile: HostReport
|
||||
fixedModeSupported: boolean
|
||||
forceCustomRes: boolean
|
||||
}) {
|
||||
const { form, displayProfile, fixedModeSupported, forceCustomRes } = params
|
||||
const vgpu = supportsAutoResolution(form.graphics)
|
||||
const autoOn = vgpu && !!form.auto_resolution
|
||||
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
|
||||
const fsPresets = fullscreenDisplayPresets(displayProfile)
|
||||
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
|
||||
const autoPreset = resolveAutoDisplayPreset(displayProfile, !!form.borderless, fixedModeSupported)
|
||||
const matchedPreset = activePresets.find((p) => normalizeResolution(p.resolution) === normalizeResolution(form.resolution))
|
||||
const presetHit = !!matchedPreset
|
||||
const customRes = vgpu && !autoOn && (forceCustomRes || !presetHit)
|
||||
const resValue = autoOn
|
||||
? AUTO_RESOLUTION_OPTION
|
||||
: (customRes ? CUSTOM_RESOLUTION_OPTION : matchedPreset?.resolution)
|
||||
const resBad = vgpu && !autoOn && customRes && !isValidResolution(form.resolution)
|
||||
return { presets, fsPresets, activePresets, autoPreset, matchedPreset, presetHit, customRes, resValue, resBad }
|
||||
}
|
||||
|
||||
export function selectSettingsResolution(params: {
|
||||
value: string
|
||||
form: Pick<SetOpts, 'resolution'>
|
||||
base: Pick<SetOpts, 'resolution'>
|
||||
autoPreset: FullscreenDisplayPreset
|
||||
}): { patch: Partial<SetOpts>; forceCustomRes: boolean } {
|
||||
const { value, form, base, autoPreset } = params
|
||||
if (value === AUTO_RESOLUTION_OPTION) {
|
||||
return {
|
||||
patch: { auto_resolution: true, resolution: base.resolution },
|
||||
forceCustomRes: false,
|
||||
}
|
||||
}
|
||||
if (value === CUSTOM_RESOLUTION_OPTION) {
|
||||
return {
|
||||
patch: { auto_resolution: false, resolution: form.resolution || autoPreset.resolution },
|
||||
forceCustomRes: true,
|
||||
}
|
||||
}
|
||||
return {
|
||||
patch: { auto_resolution: false, resolution: value },
|
||||
forceCustomRes: false,
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldExitCustomResOnBlur(params: {
|
||||
autoResolution?: boolean
|
||||
forceCustomRes: boolean
|
||||
presetHit: boolean
|
||||
}): boolean {
|
||||
return !params.autoResolution && params.forceCustomRes && params.presetHit
|
||||
}
|
||||
|
||||
export function resolveCustomResBlur(params: {
|
||||
resolution?: string
|
||||
autoResolution?: boolean
|
||||
forceCustomRes: boolean
|
||||
activePresets: FullscreenDisplayPreset[]
|
||||
}): { exitCustom: boolean; nextResolution?: string } {
|
||||
const { resolution, autoResolution, forceCustomRes, activePresets } = params
|
||||
if (autoResolution) return { exitCustom: false }
|
||||
const matched = activePresets.find((p) => normalizeResolution(p.resolution) === normalizeResolution(resolution))
|
||||
if (matched) {
|
||||
return {
|
||||
exitCustom: forceCustomRes || true,
|
||||
nextResolution: matched.resolution,
|
||||
}
|
||||
}
|
||||
if (isValidResolution(resolution)) {
|
||||
const canonical = canonicalResolution(resolution)
|
||||
if (canonical && canonical !== resolution) {
|
||||
return { exitCustom: false, nextResolution: canonical }
|
||||
}
|
||||
}
|
||||
return { exitCustom: false }
|
||||
}
|
||||
|
||||
export function switchSettingsGraphics(graphics: string): { patch: Partial<SetOpts>; forceCustomRes?: boolean } {
|
||||
if (!supportsAutoResolution(graphics)) {
|
||||
return { patch: { graphics }, forceCustomRes: false }
|
||||
}
|
||||
return { patch: { graphics } }
|
||||
}
|
||||
|
||||
export function expandTouchedSettingsFields(fields: Iterable<string>): string[] {
|
||||
const out = new Set<string>()
|
||||
for (const field of fields) {
|
||||
out.add(field)
|
||||
if (field === 'resolution' || field === 'auto_resolution') {
|
||||
out.add('resolution')
|
||||
out.add('auto_resolution')
|
||||
}
|
||||
}
|
||||
return Array.from(out)
|
||||
}
|
||||
|
||||
export function syncUntouchedSettingsForm<T extends object>(
|
||||
form: T,
|
||||
base: T,
|
||||
touchedFields: ReadonlySet<string>,
|
||||
): T {
|
||||
let changed = false
|
||||
const next = { ...form } as Record<string, unknown>
|
||||
const baseRec = base as Record<string, unknown>
|
||||
for (const key of Object.keys(baseRec)) {
|
||||
if (touchedFields.has(key)) continue
|
||||
if (next[key] !== baseRec[key]) {
|
||||
next[key] = baseRec[key]
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? (next as T) : form
|
||||
}
|
||||
|
||||
export function reconcileSettingsFormOnBaseChange<T extends object>(params: {
|
||||
previousVMKey: string
|
||||
nextVMKey: string
|
||||
form: T
|
||||
base: T
|
||||
touchedFields: ReadonlySet<string>
|
||||
}): { form: T; resetDraft: boolean } {
|
||||
const { previousVMKey, nextVMKey, form, base, touchedFields } = params
|
||||
if (previousVMKey !== nextVMKey) {
|
||||
return { form: base, resetDraft: true }
|
||||
}
|
||||
return { form: syncUntouchedSettingsForm(form, base, touchedFields), resetDraft: false }
|
||||
}
|
||||
|
||||
export function toggleSettingsBorderless(params: {
|
||||
borderless: boolean
|
||||
form: Pick<SetOpts, 'resolution' | 'auto_resolution'>
|
||||
displayProfile: HostReport
|
||||
targetDisplay?: DisplayInfo
|
||||
presets: FullscreenDisplayPreset[]
|
||||
fsPresets: FullscreenDisplayPreset[]
|
||||
customRes: boolean
|
||||
}): Partial<SetOpts> {
|
||||
const { borderless, form, displayProfile, targetDisplay, presets, fsPresets, customRes } = params
|
||||
if (form.auto_resolution) {
|
||||
return { borderless }
|
||||
}
|
||||
const targetPresets = borderless ? fsPresets : presets
|
||||
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
|
||||
const nextRes = borderless
|
||||
? (targetDisplay && targetDisplay.width > 0 && targetDisplay.height > 0
|
||||
? `${targetDisplay.width}x${targetDisplay.height}`
|
||||
: targetPresets[0]?.resolution ?? form.resolution)
|
||||
: recommendedResolution(displayProfile)
|
||||
return { borderless, resolution: nextRes }
|
||||
}
|
||||
return { borderless }
|
||||
}
|
||||
|
||||
export function countChangedSettingsFields(changedFields: readonly string[]): number {
|
||||
const hasBothRes = changedFields.includes('resolution') && changedFields.includes('auto_resolution')
|
||||
return changedFields.length - (hasBothRes ? 1 : 0)
|
||||
}
|
||||
|
||||
export function buildSettingsSaveDiff(
|
||||
name: string,
|
||||
changedFields: readonly string[],
|
||||
form: SetOpts,
|
||||
base?: Pick<SetOpts, 'auto_resolution'>,
|
||||
): SetOpts {
|
||||
const diff: SetOpts = { name }
|
||||
const vgpu = supportsAutoResolution(form.graphics)
|
||||
const effectiveAuto = vgpu && !!form.auto_resolution
|
||||
for (const field of changedFields) {
|
||||
if (field === 'resolution') {
|
||||
if (!vgpu || effectiveAuto) continue
|
||||
diff.resolution = canonicalResolution(form.resolution)
|
||||
continue
|
||||
}
|
||||
if (field === 'auto_resolution') {
|
||||
diff.auto_resolution = effectiveAuto
|
||||
continue
|
||||
}
|
||||
;(diff as unknown as Record<string, unknown>)[field] = (form as unknown as Record<string, unknown>)[field]
|
||||
}
|
||||
if (!vgpu && changedFields.includes('graphics') && base?.auto_resolution) {
|
||||
diff.auto_resolution = false
|
||||
}
|
||||
if (vgpu && !effectiveAuto && diff.auto_resolution === false && !diff.resolution) {
|
||||
const resolved = canonicalResolution(form.resolution)
|
||||
if (resolved) diff.resolution = resolved
|
||||
}
|
||||
return diff
|
||||
}
|
||||
|
||||
export function initialWizardManualResolution(
|
||||
draft?: { opts: Pick<CreateOpts, 'graphics' | 'auto_resolution'>; manualResolution?: boolean } | null,
|
||||
): boolean {
|
||||
if (!draft) return false
|
||||
if (typeof draft.manualResolution === 'boolean') return draft.manualResolution
|
||||
return supportsAutoResolution(draft.opts.graphics) && draft.opts.auto_resolution === false
|
||||
}
|
||||
|
||||
export function initialWizardResolution(
|
||||
host: HostReport,
|
||||
fixedModeSupported: boolean,
|
||||
graphics: string = 'reims-vgpu',
|
||||
): Pick<CreateOpts, 'auto_resolution' | 'resolution'> {
|
||||
return {
|
||||
auto_resolution: supportsAutoResolution(graphics),
|
||||
resolution: resolveAutoDisplayPreset(host, false, fixedModeSupported).resolution,
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveEffectiveWizardOpts(
|
||||
opts: CreateOpts,
|
||||
autoPreset: FullscreenDisplayPreset,
|
||||
): CreateOpts {
|
||||
if (!supportsAutoResolution(opts.graphics)) {
|
||||
return opts.auto_resolution ? { ...opts, auto_resolution: false } : opts
|
||||
}
|
||||
if (opts.auto_resolution) {
|
||||
return { ...opts, resolution: autoPreset.resolution }
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
export function switchWizardGraphics(params: {
|
||||
graphics: CreateOpts['graphics']
|
||||
manualResolutionPicked: boolean
|
||||
autoPreset: FullscreenDisplayPreset
|
||||
}): Partial<CreateOpts> {
|
||||
const { graphics, manualResolutionPicked, autoPreset } = params
|
||||
if (!supportsAutoResolution(graphics)) {
|
||||
return { graphics, auto_resolution: false }
|
||||
}
|
||||
if (!manualResolutionPicked) {
|
||||
return { graphics, auto_resolution: true, resolution: autoPreset.resolution }
|
||||
}
|
||||
return { graphics }
|
||||
}
|
||||
|
||||
export function selectWizardResolution(
|
||||
value: string,
|
||||
autoPreset: FullscreenDisplayPreset,
|
||||
): Pick<CreateOpts, 'auto_resolution' | 'resolution'> {
|
||||
if (value === AUTO_RESOLUTION_OPTION) {
|
||||
return { auto_resolution: true, resolution: autoPreset.resolution }
|
||||
}
|
||||
return { auto_resolution: false, resolution: value }
|
||||
}
|
||||
|
||||
export function toggleWizardBorderless(params: {
|
||||
borderless: boolean
|
||||
opts: Pick<CreateOpts, 'graphics' | 'auto_resolution' | 'resolution'>
|
||||
host: HostReport
|
||||
fixedModeSupported: boolean
|
||||
windowPresets: FullscreenDisplayPreset[]
|
||||
fullscreenPresets: FullscreenDisplayPreset[]
|
||||
}): Partial<CreateOpts> {
|
||||
const { borderless, opts, host, fixedModeSupported, windowPresets, fullscreenPresets } = params
|
||||
if (supportsAutoResolution(opts.graphics) && opts.auto_resolution) {
|
||||
return {
|
||||
borderless,
|
||||
auto_resolution: true,
|
||||
resolution: resolveAutoDisplayPreset(host, borderless, fixedModeSupported).resolution,
|
||||
}
|
||||
}
|
||||
const list = borderless ? fullscreenPresets : windowPresets
|
||||
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
|
||||
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
|
||||
return keep ? { borderless } : { borderless, resolution: fallback }
|
||||
}
|
||||
@@ -155,10 +155,18 @@ export function gpuLabel(locale: Locale, icd: string | undefined, host: HostRepo
|
||||
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
|
||||
export function formatResolutionLabel(res: string, auto: boolean, tr: Tr): string {
|
||||
const displayRes = (res ?? '').trim().replace(/\s*[x×]\s*/i, ' × ')
|
||||
if (!auto) return displayRes
|
||||
return displayRes ? tr('resAutoValue', { res: displayRes }) : tr('resAuto')
|
||||
}
|
||||
|
||||
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
|
||||
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
|
||||
const gpu = gpuLabel(locale, d.gpu, host)
|
||||
const res = resolutionLabel(d.resolution)
|
||||
const tr: Tr = (k, v) => t(locale, k, v)
|
||||
const isAuto = d.graphics !== 'vmware-svga' && !!d.auto_resolution
|
||||
const res = isAuto ? formatResolutionLabel(d.resolution, true, tr) : resolutionLabel(d.resolution)
|
||||
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
|
||||
return res ? `${gpu} · ${screens}` : gpu
|
||||
}
|
||||
@@ -427,6 +435,38 @@ export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPre
|
||||
return out
|
||||
}
|
||||
|
||||
export function resolveAutoDisplayPreset(
|
||||
host: HostReport,
|
||||
borderless: boolean,
|
||||
fixedModeSupported: boolean,
|
||||
): FullscreenDisplayPreset {
|
||||
if (!borderless) {
|
||||
const presets = recommendedDisplayPresets(host)
|
||||
return presets.find((p) => p.recommended) ?? presets[0]
|
||||
}
|
||||
const d = host.primary_display
|
||||
if (!d || d.width <= 0 || d.height <= 0) {
|
||||
return {
|
||||
resolution: '1920x1080',
|
||||
label: '1920 × 1080',
|
||||
hidpi: false,
|
||||
native: true,
|
||||
recommended: true,
|
||||
}
|
||||
}
|
||||
const fsPresets = fullscreenDisplayPresets(host)
|
||||
if (fixedModeSupported) {
|
||||
return fsPresets.find((p) => p.recommended) ?? fsPresets[0]
|
||||
}
|
||||
return {
|
||||
resolution: `${d.width}x${d.height}`,
|
||||
label: `${d.width} × ${d.height}`,
|
||||
hidpi: !!host.fullscreen_hidpi,
|
||||
native: true,
|
||||
recommended: true,
|
||||
}
|
||||
}
|
||||
|
||||
export function recommendedResolution(host: HostReport): string {
|
||||
if (host.recommended_resolution) return host.recommended_resolution
|
||||
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
|
||||
@@ -492,6 +532,7 @@ export function pendingChangeText(locale: Locale, p: { field: string; from: stri
|
||||
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
|
||||
memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) },
|
||||
resolution: { label: 'resolution', fmt: resolutionLabel },
|
||||
auto_resolution: { label: 'autoResolution', fmt: bool },
|
||||
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
|
||||
displays: { label: 'displays', fmt: (v) => v },
|
||||
borderless: { label: 'borderless', fmt: bool },
|
||||
|
||||
@@ -159,8 +159,9 @@ export async function mountInteractiveThemeScript(
|
||||
addDisposer(localDispose)
|
||||
try {
|
||||
setup((fn) => localDisposers.push(fn))
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// Feature-isolated error: tear down only this feature.
|
||||
console.warn('[uiSdk] feature setup failed:', _name, e)
|
||||
localDispose()
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import type { VMKeymapPreset, VMKeymapStatus, VMKeymapUpdate } from '../types'
|
||||
import { createVMSettingRequests } from './vmSettingRequests'
|
||||
|
||||
type KeymapAPI = {
|
||||
GetVMKeymap(name: string): Promise<VMKeymapStatus>
|
||||
SetVMKeymap(name: string, request: VMKeymapUpdate): Promise<VMKeymapStatus>
|
||||
}
|
||||
|
||||
export type KeymapState = { keymap: VMKeymapStatus | null; error: string; busy: boolean }
|
||||
|
||||
type KeymapStatusKey =
|
||||
| 'keymapInputServiceRequired'
|
||||
| 'keymapStopped'
|
||||
| 'keymapWaiting'
|
||||
| 'keymapUpgrade'
|
||||
| 'keymapPending'
|
||||
| 'keymapRunning'
|
||||
| 'keymapInactive'
|
||||
|
||||
type KeymapStatusHint = { key: KeymapStatusKey; vars?: { version: number } }
|
||||
|
||||
const ALL_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'win_to_cmd', 'swap_alt_win', 'custom']
|
||||
const MODERN_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'swap_alt_win', 'custom']
|
||||
|
||||
export function visibleKeymapPresets(preset: VMKeymapPreset, captureSupported: boolean): readonly VMKeymapPreset[] {
|
||||
if (!captureSupported && preset !== 'win_to_cmd') return MODERN_KEYMAP_PRESETS
|
||||
return ALL_KEYMAP_PRESETS
|
||||
}
|
||||
|
||||
export function keymapStatusHint(keymap: VMKeymapStatus): KeymapStatusHint | null {
|
||||
if (keymap.preset === 'off' && !keymap.capture_host_shortcuts) return null
|
||||
if (!keymap.input_service_available) return { key: 'keymapInputServiceRequired' }
|
||||
if (!keymap.running) return { key: 'keymapStopped' }
|
||||
if (keymap.needs_guest_tools && !keymap.guest_connected) return { key: 'keymapWaiting' }
|
||||
if (keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version) {
|
||||
return { key: 'keymapUpgrade', vars: { version: keymap.required_agent_version } }
|
||||
}
|
||||
if (keymap.needs_guest_tools && !keymap.guest_keymap_active) return { key: 'keymapPending' }
|
||||
return { key: keymap.hook_active ? 'keymapRunning' : 'keymapInactive' }
|
||||
}
|
||||
|
||||
type KeymapRequest = Required<VMKeymapUpdate>
|
||||
|
||||
export function keymapUpdate(current: VMKeymapStatus, changes: Partial<KeymapRequest>): KeymapRequest {
|
||||
const preset = changes.preset ?? current.preset
|
||||
const bindings = preset === current.preset || (preset === 'custom' && current.preset !== 'off')
|
||||
? current.bindings
|
||||
: {}
|
||||
return {
|
||||
preset,
|
||||
bindings: changes.bindings ? { ...bindings, ...changes.bindings } : bindings,
|
||||
capture_host_shortcuts: changes.capture_host_shortcuts ?? current.capture_host_shortcuts,
|
||||
}
|
||||
}
|
||||
|
||||
export function keymapPresetUpdate(current: VMKeymapStatus, preset: VMKeymapPreset): KeymapRequest | undefined {
|
||||
if (preset === current.preset) return undefined
|
||||
return keymapUpdate(current, { preset })
|
||||
}
|
||||
|
||||
export function createKeymapRequests(api: KeymapAPI, activeVM: () => string, update: (patch: Partial<KeymapState>) => void) {
|
||||
const requests = createVMSettingRequests<VMKeymapStatus>(activeVM, ({ value, ...patch }) => {
|
||||
update(value === undefined ? patch : { ...patch, keymap: value })
|
||||
})
|
||||
|
||||
return {
|
||||
initial(name: string): KeymapState {
|
||||
return { keymap: null, error: '', busy: requests.isWriting(name) }
|
||||
},
|
||||
watch(name: string) {
|
||||
return requests.watch(name, () => api.GetVMKeymap(name))
|
||||
},
|
||||
write(name: string, request: VMKeymapUpdate) {
|
||||
return requests.write(name, () => api.SetVMKeymap(name, request))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1878,26 +1878,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
border-radius: 4px; font-size: 10px; font-weight: 600; flex-shrink: 0;
|
||||
color: var(--amber); background: color-mix(in srgb, var(--amber) 14%, transparent);
|
||||
}
|
||||
.market-version-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.market-version-opt {
|
||||
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border);
|
||||
background: var(--surface-1); cursor: pointer;
|
||||
}
|
||||
.market-version-opt.is-selected {
|
||||
border-color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 6%, var(--surface-1));
|
||||
}
|
||||
.market-version-opt input[type='radio'] { margin-top: 3px; flex-shrink: 0; }
|
||||
.market-version-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; }
|
||||
.market-version-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: var(--fs-13); }
|
||||
.market-version-current {
|
||||
display: inline-flex; align-items: center; padding: 0 5px; height: 16px;
|
||||
border-radius: 4px; font-size: 10px; font-weight: 600;
|
||||
color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, transparent);
|
||||
}
|
||||
.market-version-meta { margin-left: auto; font-size: var(--fs-12); color: var(--text-3); font-variant-numeric: tabular-nums; }
|
||||
.market-version-notes { margin: 0; font-size: var(--fs-12); color: var(--text-2); line-height: 1.45; }
|
||||
.plugin-title-link { color: inherit; text-decoration: none; }
|
||||
.plugin-title-link:hover { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
|
||||
.market-card-action { flex-shrink: 0; }
|
||||
|
||||
@@ -215,24 +215,3 @@ export interface LogEntry {
|
||||
source: string
|
||||
line: string
|
||||
}
|
||||
export type VMKeymapPreset = 'off' | 'win_to_cmd' | 'swap_alt_win' | 'custom'
|
||||
export type VMKeymapHostModifier = 'lwin' | 'rwin' | 'lalt' | 'ralt' | 'lctrl' | 'rctrl' | 'capslock'
|
||||
export type VMKeymapGuestModifier = 'default' | 'lcmd' | 'rcmd' | 'lopt' | 'ropt' | 'lctrl' | 'rctrl' | 'esc' | 'disabled'
|
||||
|
||||
export interface VMKeymapUpdate {
|
||||
preset: VMKeymapPreset
|
||||
bindings: Partial<Record<VMKeymapHostModifier, VMKeymapGuestModifier>>
|
||||
capture_host_shortcuts?: boolean
|
||||
}
|
||||
|
||||
export interface VMKeymapStatus extends VMKeymapUpdate {
|
||||
capture_host_shortcuts: boolean
|
||||
needs_guest_tools: boolean
|
||||
guest_connected: boolean
|
||||
guest_agent_version?: number
|
||||
required_agent_version: number
|
||||
input_service_available: boolean
|
||||
guest_keymap_active: boolean
|
||||
hook_active: boolean
|
||||
running: boolean
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import type {
|
||||
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
|
||||
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
|
||||
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
|
||||
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan,
|
||||
} from './types'
|
||||
|
||||
type AnyFn = (...args: never[]) => unknown
|
||||
@@ -157,9 +157,7 @@ export const api = {
|
||||
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
|
||||
GetVMInfo: boundGo.GetVMInfo as (driverID: string, name: string) => Promise<VMInfo>,
|
||||
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
|
||||
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
|
||||
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
|
||||
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
|
||||
|
||||
Vendored
-4
@@ -122,8 +122,6 @@ export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promis
|
||||
|
||||
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
|
||||
|
||||
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
|
||||
|
||||
export function GetVMMacOS(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<app.VMNetworkPlan>;
|
||||
@@ -278,8 +276,6 @@ export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise<app.VM
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
|
||||
|
||||
export function SetVMNote(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
@@ -222,10 +222,6 @@ export function GetVMInfo(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMInfo'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMKeymap(arg1) {
|
||||
return window['go']['app']['App']['GetVMKeymap'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMMacOS(arg1) {
|
||||
return window['go']['app']['App']['GetVMMacOS'](arg1);
|
||||
}
|
||||
@@ -534,10 +530,6 @@ export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMKeymap(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMKeymap'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMNote(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMNote'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
@@ -592,54 +592,6 @@ export namespace app {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class VMKeymapStatus {
|
||||
preset: string;
|
||||
bindings: Record<string, string>;
|
||||
capture_host_shortcuts: boolean;
|
||||
needs_guest_tools: boolean;
|
||||
guest_connected: boolean;
|
||||
guest_agent_version?: number;
|
||||
required_agent_version: number;
|
||||
guest_keymap_active: boolean;
|
||||
input_service_available: boolean;
|
||||
hook_active: boolean;
|
||||
running: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMKeymapStatus(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.preset = source["preset"];
|
||||
this.bindings = source["bindings"];
|
||||
this.capture_host_shortcuts = source["capture_host_shortcuts"];
|
||||
this.needs_guest_tools = source["needs_guest_tools"];
|
||||
this.guest_connected = source["guest_connected"];
|
||||
this.guest_agent_version = source["guest_agent_version"];
|
||||
this.required_agent_version = source["required_agent_version"];
|
||||
this.guest_keymap_active = source["guest_keymap_active"];
|
||||
this.input_service_available = source["input_service_available"];
|
||||
this.hook_active = source["hook_active"];
|
||||
this.running = source["running"];
|
||||
}
|
||||
}
|
||||
export class VMKeymapUpdate {
|
||||
preset: string;
|
||||
bindings: Record<string, string>;
|
||||
capture_host_shortcuts?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMKeymapUpdate(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.preset = source["preset"];
|
||||
this.bindings = source["bindings"];
|
||||
this.capture_host_shortcuts = source["capture_host_shortcuts"];
|
||||
}
|
||||
}
|
||||
export class VMNetworkPlan {
|
||||
npcap_installed: boolean;
|
||||
running_vms: string[];
|
||||
@@ -1244,6 +1196,8 @@ export namespace host {
|
||||
scale_pct: number;
|
||||
refresh_hz?: number;
|
||||
primary: boolean;
|
||||
left?: number;
|
||||
top?: number;
|
||||
work_width?: number;
|
||||
work_height?: number;
|
||||
|
||||
@@ -1260,6 +1214,8 @@ export namespace host {
|
||||
this.scale_pct = source["scale_pct"];
|
||||
this.refresh_hz = source["refresh_hz"];
|
||||
this.primary = source["primary"];
|
||||
this.left = source["left"];
|
||||
this.top = source["top"];
|
||||
this.work_width = source["work_width"];
|
||||
this.work_height = source["work_height"];
|
||||
}
|
||||
@@ -3023,6 +2979,7 @@ export namespace reims {
|
||||
graphics?: string;
|
||||
gpu?: string;
|
||||
resolution?: string;
|
||||
auto_resolution?: boolean;
|
||||
displays?: number;
|
||||
borderless?: boolean;
|
||||
capture?: boolean;
|
||||
@@ -3057,6 +3014,7 @@ export namespace reims {
|
||||
this.graphics = source["graphics"];
|
||||
this.gpu = source["gpu"];
|
||||
this.resolution = source["resolution"];
|
||||
this.auto_resolution = source["auto_resolution"];
|
||||
this.displays = source["displays"];
|
||||
this.borderless = source["borderless"];
|
||||
this.capture = source["capture"];
|
||||
@@ -3079,6 +3037,7 @@ export namespace reims {
|
||||
disk_controller?: string;
|
||||
disk_cache?: string;
|
||||
resolution?: string;
|
||||
auto_resolution?: boolean;
|
||||
borderless?: boolean;
|
||||
capture?: boolean;
|
||||
gpu?: string;
|
||||
@@ -3108,6 +3067,7 @@ export namespace reims {
|
||||
this.disk_controller = source["disk_controller"];
|
||||
this.disk_cache = source["disk_cache"];
|
||||
this.resolution = source["resolution"];
|
||||
this.auto_resolution = source["auto_resolution"];
|
||||
this.borderless = source["borderless"];
|
||||
this.capture = source["capture"];
|
||||
this.gpu = source["gpu"];
|
||||
@@ -3186,6 +3146,7 @@ export namespace reims {
|
||||
display: string;
|
||||
displays: number;
|
||||
resolution: string;
|
||||
auto_resolution: boolean;
|
||||
gpu: string;
|
||||
has_opencore: boolean;
|
||||
has_installer: boolean;
|
||||
@@ -3240,6 +3201,7 @@ export namespace reims {
|
||||
this.display = source["display"];
|
||||
this.displays = source["displays"];
|
||||
this.resolution = source["resolution"];
|
||||
this.auto_resolution = source["auto_resolution"];
|
||||
this.gpu = source["gpu"];
|
||||
this.has_opencore = source["has_opencore"];
|
||||
this.has_installer = source["has_installer"];
|
||||
|
||||
+1
-10
@@ -150,9 +150,6 @@ type App struct {
|
||||
|
||||
displayPlacements sync.Map
|
||||
|
||||
keymapMu sync.Mutex
|
||||
keymapPIDs map[string]int
|
||||
fallbackInputSvc *host.InputService
|
||||
inputShuttingDown bool
|
||||
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
@@ -313,12 +310,8 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
a.stopPluginControlServer()
|
||||
a.mu.Lock()
|
||||
a.inputShuttingDown = true
|
||||
fallback := a.fallbackInputSvc
|
||||
a.mu.Unlock()
|
||||
a.fullscreenHotkey.Close()
|
||||
if fallback != nil {
|
||||
fallback.Close()
|
||||
}
|
||||
a.shutdownPlugins()
|
||||
a.mu.Lock()
|
||||
for name, entry := range a.rebootWatchers {
|
||||
@@ -549,10 +542,8 @@ func (a *App) startTray() {
|
||||
}
|
||||
items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state})
|
||||
}
|
||||
effLoc := i18n.EffectiveLocale(loc)
|
||||
return tray.Snapshot{
|
||||
Locale: effLoc,
|
||||
LocaleZh: effLoc == i18n.ZhCN,
|
||||
Locale: i18n.EffectiveLocale(loc),
|
||||
CanSuspend: canSuspend,
|
||||
VMs: items,
|
||||
}
|
||||
|
||||
@@ -18,15 +18,10 @@ func TestPolledVMsReusesFreshPoll(t *testing.T) {
|
||||
a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}}
|
||||
a.lastVMsAt = time.Now()
|
||||
|
||||
vm, ok := a.polledVM("m0")
|
||||
if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 {
|
||||
t.Fatalf("polledVM = %+v, %v", vm, ok)
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil || len(vms) != 1 || vms[0].Name != "m0" {
|
||||
t.Fatalf("polledVMs = %+v, %v", vms, err)
|
||||
}
|
||||
if _, ok := a.polledVM("missing"); ok {
|
||||
t.Fatal("unknown VM should not be found")
|
||||
}
|
||||
|
||||
vms, _ := a.polledVMs(context.Background())
|
||||
vms[0].State = "stopped"
|
||||
if a.lastVMs[0].State != "running" {
|
||||
t.Fatal("polledVMs must return a copy, not the cached slice")
|
||||
|
||||
@@ -6,9 +6,13 @@ package app
|
||||
// running; Guest Tools reconnects once the new window is up.
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -121,8 +125,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// downloadAppUpdate fetches info's executable into dir and checks it against
|
||||
// GitHub's assets[].digest SHA-256. It returns the file and its hash.
|
||||
// downloadAppUpdate fetches info's release asset (.zip or .exe) into dir,
|
||||
// checks it against GitHub's assets[].digest SHA-256, extracts the executable
|
||||
// when a .zip archive was downloaded, and returns the executable path and its
|
||||
// SHA-256 hash.
|
||||
func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
|
||||
want := strings.ToLower(strings.TrimSpace(info.AssetSHA256))
|
||||
if len(want) != 64 {
|
||||
@@ -136,9 +142,64 @@ func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string,
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if strings.HasSuffix(strings.ToLower(path), ".zip") {
|
||||
exePath, exeSum, err := extractAppUpdateZip(path, dir)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return exePath, exeSum, nil
|
||||
}
|
||||
return path, want, nil
|
||||
}
|
||||
|
||||
// extractAppUpdateZip extracts the single Windows executable from a verified
|
||||
// release .zip into dir and returns its path and SHA-256 digest.
|
||||
func extractAppUpdateZip(zipPath, dir string) (string, string, error) {
|
||||
zr, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("open update archive: %w", err)
|
||||
}
|
||||
defer zr.Close()
|
||||
|
||||
const maxUpdateExeBytes = 256 << 20 // 256 MiB safety cap against zip bombs
|
||||
for _, f := range zr.File {
|
||||
if f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
base := filepath.Base(f.Name)
|
||||
if base == "." || base == ".." || strings.ContainsAny(f.Name, `/\`) {
|
||||
continue
|
||||
}
|
||||
lower := strings.ToLower(base)
|
||||
if !strings.HasSuffix(lower, ".exe") || strings.Contains(lower, "-cli-") {
|
||||
continue
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("read %s from update archive: %w", base, err)
|
||||
}
|
||||
dest := filepath.Join(dir, base)
|
||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
_ = rc.Close()
|
||||
return "", "", fmt.Errorf("create extracted update %s: %w", base, err)
|
||||
}
|
||||
h := sha256.New()
|
||||
n, copyErr := io.Copy(io.MultiWriter(out, h), io.LimitReader(rc, maxUpdateExeBytes+1))
|
||||
closeErr := errors.Join(rc.Close(), out.Close())
|
||||
if copyErr != nil || closeErr != nil {
|
||||
_ = os.Remove(dest)
|
||||
return "", "", fmt.Errorf("extract %s from update archive: %w", base, errors.Join(copyErr, closeErr))
|
||||
}
|
||||
if n > maxUpdateExeBytes {
|
||||
_ = os.Remove(dest)
|
||||
return "", "", fmt.Errorf("extracted update %s exceeds %d byte limit", base, maxUpdateExeBytes)
|
||||
}
|
||||
return dest, hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
return "", "", errors.New("update archive does not contain a Windows executable")
|
||||
}
|
||||
|
||||
// InstallAppUpdate swaps the downloaded update in for the running executable,
|
||||
// starts it, and quits this window. The new window waits for this process to
|
||||
// exit before it opens. Running VMs are not touched.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
@@ -56,6 +58,61 @@ func TestDownloadAppUpdateVerifiesAgainstAssetDigest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadAppUpdateExtractsZipAndVerifiesDigest(t *testing.T) {
|
||||
exePayload := []byte("MZ-reims-go-zip-update-binary")
|
||||
exeHash := sha256.Sum256(exePayload)
|
||||
wantExeSum := hex.EncodeToString(exeHash[:])
|
||||
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
w, err := zw.Create("reims-go-v9.9.9-windows-amd64.exe")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write(exePayload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zipBytes := buf.Bytes()
|
||||
zipHash := sha256.Sum256(zipBytes)
|
||||
wantZipSum := hex.EncodeToString(zipHash[:])
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/app.zip" {
|
||||
_, _ = w.Write(zipBytes)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
info := version.UpdateInfo{
|
||||
Latest: "v9.9.9",
|
||||
HasUpdate: true,
|
||||
AssetName: "reims-go-v9.9.9-windows-amd64.zip",
|
||||
AssetSize: int64(len(zipBytes)),
|
||||
DownloadURL: srv.URL + "/app.zip",
|
||||
AssetSHA256: wantZipSum,
|
||||
}
|
||||
gotPath, gotSum, err := downloadAppUpdate(context.Background(), info, dir, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("downloadAppUpdate(zip): %v", err)
|
||||
}
|
||||
if filepath.Base(gotPath) != "reims-go-v9.9.9-windows-amd64.exe" {
|
||||
t.Fatalf("extracted path = %s, want reims-go-v9.9.9-windows-amd64.exe", gotPath)
|
||||
}
|
||||
if gotSum != wantExeSum {
|
||||
t.Fatalf("extracted exe sum = %s, want %s", gotSum, wantExeSum)
|
||||
}
|
||||
gotBody, err := os.ReadFile(gotPath)
|
||||
if err != nil || !bytes.Equal(gotBody, exePayload) {
|
||||
t.Fatalf("extracted exe content mismatch: %q, err=%v", gotBody, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallAppUpdateGuards(t *testing.T) {
|
||||
cfg := config.Default()
|
||||
cfg.Locale = i18n.EnUS
|
||||
|
||||
@@ -15,6 +15,12 @@ import (
|
||||
// plugin's next call.
|
||||
var heldInputIdleTimeout = 2 * time.Minute
|
||||
|
||||
// heldReleaseRetryTimeout is how long the host waits before trying a fallback
|
||||
// release again. A release can fail while the VM is still running, for example
|
||||
// while its console is busy, and a plugin that already exited will never make
|
||||
// the next call that would otherwise retry it.
|
||||
var heldReleaseRetryTimeout = 30 * time.Second
|
||||
|
||||
// heldReleaseTimeout bounds one fallback release, which runs while the plugin
|
||||
// that held the input may already be gone.
|
||||
const heldReleaseTimeout = 5 * time.Second
|
||||
@@ -29,6 +35,10 @@ type heldInputs struct {
|
||||
buttons map[string]bool
|
||||
touched time.Time
|
||||
timer *time.Timer
|
||||
// generation counts every change to this record. A release that finishes
|
||||
// after the plugin pressed something new compares it with the generation it
|
||||
// snapshotted, so it never deletes a press it did not lift.
|
||||
generation uint64
|
||||
}
|
||||
|
||||
// noteHeldKey records or forgets one key transition. code must already be a
|
||||
@@ -77,19 +87,25 @@ func (a *App) heldLocked(pluginID, vmKey string) *heldInputs {
|
||||
return held
|
||||
}
|
||||
|
||||
// touchHeldLocked drops a record that holds nothing and rearms the idle timer
|
||||
// of one that still does. The caller holds computerUseHeldMu.
|
||||
// touchHeldLocked marks the record as changed, drops it when it holds nothing
|
||||
// and rearms its idle timer otherwise. The caller holds computerUseHeldMu.
|
||||
func (a *App) touchHeldLocked(pluginID, vmKey string, held *heldInputs) {
|
||||
held.generation++
|
||||
held.touched = time.Now()
|
||||
if held.timer != nil {
|
||||
held.timer.Stop()
|
||||
held.timer = nil
|
||||
}
|
||||
if len(held.keys)+len(held.buttons) == 0 {
|
||||
a.pruneHeldLocked(pluginID, vmKey)
|
||||
return
|
||||
}
|
||||
held.timer = time.AfterFunc(heldInputIdleTimeout, func() {
|
||||
a.armHeldTimerLocked(pluginID, vmKey, held, heldInputIdleTimeout)
|
||||
}
|
||||
|
||||
// armHeldTimerLocked replaces the record's timer with one that fires after d.
|
||||
// The caller holds computerUseHeldMu.
|
||||
func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d time.Duration) {
|
||||
if held.timer != nil {
|
||||
held.timer.Stop()
|
||||
}
|
||||
held.timer = time.AfterFunc(d, func() {
|
||||
a.releaseHeldForVM(pluginID, vmKey)
|
||||
})
|
||||
}
|
||||
@@ -113,17 +129,18 @@ func (a *App) pruneHeldLocked(pluginID, vmKey string) {
|
||||
}
|
||||
}
|
||||
|
||||
// heldState returns what one plugin holds in one VM, sorted.
|
||||
func (a *App) heldState(pluginID, vmKey string) (keys, buttons []string) {
|
||||
// heldSnapshot returns what one plugin holds in one VM, sorted, with the
|
||||
// generation it was read at.
|
||||
func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return nil, nil
|
||||
return nil, nil, 0
|
||||
}
|
||||
held := byVM[vmKey]
|
||||
if held == nil {
|
||||
return nil, nil
|
||||
return nil, nil, 0
|
||||
}
|
||||
for code := range held.keys {
|
||||
keys = append(keys, code)
|
||||
@@ -133,7 +150,18 @@ func (a *App) heldState(pluginID, vmKey string) (keys, buttons []string) {
|
||||
}
|
||||
sort.Strings(keys)
|
||||
sort.Strings(buttons)
|
||||
return keys, buttons
|
||||
return keys, buttons, held.generation
|
||||
}
|
||||
|
||||
// heldGeneration returns the record's current generation, or 0 when there is
|
||||
// no record.
|
||||
func (a *App) heldGeneration(pluginID, vmKey string) uint64 {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
if held := a.computerUseHeld[pluginID][vmKey]; held != nil {
|
||||
return held.generation
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// heldVMs lists the VMs one plugin currently holds input in.
|
||||
@@ -147,16 +175,13 @@ func (a *App) heldVMs(pluginID string) map[string]bool {
|
||||
return out
|
||||
}
|
||||
|
||||
// dropHeld forgets the named keys and buttons of one plugin and VM. It is
|
||||
// called only after the release reached the guest.
|
||||
// dropHeld forgets the named keys and buttons of one plugin and VM. It is used
|
||||
// when the caller itself named what it lifted, so there is no snapshot to
|
||||
// compare with.
|
||||
func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
byVM := a.computerUseHeld[pluginID]
|
||||
if byVM == nil {
|
||||
return
|
||||
}
|
||||
held := byVM[vmKey]
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return
|
||||
}
|
||||
@@ -169,6 +194,42 @@ func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
|
||||
a.touchHeldLocked(pluginID, vmKey, held)
|
||||
}
|
||||
|
||||
// dropHeldIfGeneration forgets the named keys and buttons only when the record
|
||||
// has not changed since generation was read. A record that changed in the
|
||||
// meantime may hold a press this release did not lift, so it keeps everything
|
||||
// and its timer releases it later.
|
||||
func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil {
|
||||
return false
|
||||
}
|
||||
if held.generation != generation {
|
||||
return false
|
||||
}
|
||||
for _, code := range keys {
|
||||
delete(held.keys, code)
|
||||
}
|
||||
for _, button := range buttons {
|
||||
delete(held.buttons, button)
|
||||
}
|
||||
a.touchHeldLocked(pluginID, vmKey, held)
|
||||
return true
|
||||
}
|
||||
|
||||
// rearmHeld schedules another fallback release for a record whose release
|
||||
// failed while the VM is still running.
|
||||
func (a *App) rearmHeld(pluginID, vmKey string) {
|
||||
a.computerUseHeldMu.Lock()
|
||||
defer a.computerUseHeldMu.Unlock()
|
||||
held := a.computerUseHeld[pluginID][vmKey]
|
||||
if held == nil || len(held.keys)+len(held.buttons) == 0 {
|
||||
return
|
||||
}
|
||||
a.armHeldTimerLocked(pluginID, vmKey, held, heldReleaseRetryTimeout)
|
||||
}
|
||||
|
||||
// forgetHeld drops the record of one plugin and VM without touching the
|
||||
// guest. It is for a VM that is not running: nothing in a powered-off guest
|
||||
// can still be held, and a release sent later could lift a key the user is
|
||||
@@ -209,10 +270,10 @@ func (a *App) heldConsoleRoute(vmKey string) (consoleRoute, bool) {
|
||||
// releaseHeldForVM lifts everything one plugin still holds in one VM. It is the
|
||||
// fallback for a plugin that can no longer release: its process exited, its
|
||||
// scope was disposed, or it stopped calling. A VM that is not running has
|
||||
// nothing held, so its record is dropped instead of retried; a release that
|
||||
// fails on a running VM keeps its record for the next attempt.
|
||||
// nothing held, so its record is dropped instead of retried. A release that
|
||||
// fails while the VM is running keeps its record and is retried.
|
||||
func (a *App) releaseHeldForVM(pluginID, vmKey string) {
|
||||
keys, buttons := a.heldState(pluginID, vmKey)
|
||||
keys, buttons, generation := a.heldSnapshot(pluginID, vmKey)
|
||||
if len(keys)+len(buttons) == 0 {
|
||||
a.forgetHeld(pluginID, vmKey)
|
||||
return
|
||||
@@ -222,6 +283,12 @@ func (a *App) releaseHeldForVM(pluginID, vmKey string) {
|
||||
a.forgetHeld(pluginID, vmKey)
|
||||
return
|
||||
}
|
||||
// The plugin may have pressed something since the snapshot; lifting now
|
||||
// would undo that press, so wait for the record to settle instead.
|
||||
if a.heldGeneration(pluginID, vmKey) != generation {
|
||||
a.rearmHeld(pluginID, vmKey)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), heldReleaseTimeout)
|
||||
defer cancel()
|
||||
if err := a.consoleRelease(ctx, route, keys, buttons); err != nil {
|
||||
@@ -231,9 +298,14 @@ func (a *App) releaseHeldForVM(pluginID, vmKey string) {
|
||||
return
|
||||
}
|
||||
a.emitLog("plugin", "Could not release input held by "+pluginID+" in "+vmKey+": "+err.Error())
|
||||
a.rearmHeld(pluginID, vmKey)
|
||||
return
|
||||
}
|
||||
a.dropHeld(pluginID, vmKey, keys, buttons)
|
||||
if !a.dropHeldIfGeneration(pluginID, vmKey, keys, buttons, generation) {
|
||||
// Something was pressed while the release was in flight. The record
|
||||
// keeps it, and its timer lifts it if the plugin goes quiet again.
|
||||
a.rearmHeld(pluginID, vmKey)
|
||||
}
|
||||
}
|
||||
|
||||
// releaseHeldForPlugin lifts everything one plugin holds in any VM.
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"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/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
@@ -17,9 +18,10 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts, connectedDisplays func() []host.DisplayInfo) (err error) {
|
||||
defer func() {
|
||||
var coded *i18n.CodedError
|
||||
if errors.As(err, &coded) && strings.HasPrefix(coded.Code, "E_NETWORK_") {
|
||||
@@ -54,6 +56,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
}
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
autoResolution := opts.AutoResolution != nil && *opts.AutoResolution && vmstart.SupportsAutoResolution(opts.Graphics)
|
||||
|
||||
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
|
||||
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly.
|
||||
@@ -171,6 +174,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
opts.DiskMode = "copy"
|
||||
}
|
||||
|
||||
if autoResolution {
|
||||
opts.Resolution, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(connectedDisplays()), opts.Borderless != nil && *opts.Borderless, c.DisplayFixedMode)
|
||||
}
|
||||
err = c.Create(ctx, opts, w, w)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
@@ -195,6 +201,12 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
finishTask(err)
|
||||
return fmt.Errorf("record VM driver ownership: %w", err)
|
||||
}
|
||||
if autoResolution {
|
||||
if _, err := vmstart.SaveVMAutoResolution(createdDir, true); err != nil {
|
||||
finishTask(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
@@ -27,7 +28,9 @@ func (a *App) openDataRoot() dataroot.Status {
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() && explicitLaunch {
|
||||
// Older clients could save the new data folder while leaving its registry stale.
|
||||
// A registry explicitly shared outside the data folder still requires an explicit launch.
|
||||
if st.Writable() && (explicitLaunch || strings.TrimSpace(os.Getenv("REIMS_CTL_CONFIG_DIR")) == "") {
|
||||
a.relocateRegisteredVMs(dir, prevRoot)
|
||||
}
|
||||
return st
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
@@ -181,22 +182,7 @@ func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) {
|
||||
if err := config.Save(filepath.Join(newRoot, "reims-go.json"), oldCfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
if err := os.MkdirAll(newVMDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(newVMDir, "vm.toml"), []byte("disk = \"disk.qcow2\"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldVMDir := filepath.Join((&config.Config{DataRoot: oldRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
regDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGConfigDir(), "reims-ctl")
|
||||
if err := os.MkdirAll(regDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vmsToml := "[[vm]]\nname = 'macos-tahoe'\ndir = '" + strings.ReplaceAll(oldVMDir, "'", "''") + "'\n"
|
||||
if err := os.WriteFile(filepath.Join(regDir, "vms.toml"), []byte(vmsToml), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, newVMDir := writeMovedVMRegistry(t, oldRoot, newRoot)
|
||||
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: oldRoot, Locale: "zh-CN"},
|
||||
@@ -206,15 +192,67 @@ func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) {
|
||||
if err := a.setDataRoot(newRoot, noopASLR); err != nil {
|
||||
t.Fatalf("setDataRoot: %v", err)
|
||||
}
|
||||
assertRegisteredVMDir(t, newRoot, newVMDir)
|
||||
}
|
||||
|
||||
vms, err := reims.ListRegisteredVMs(newRoot)
|
||||
func TestOpenDataRoot_RepairsPreviouslySelectedVMRegistry(t *testing.T) {
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
|
||||
t.Setenv("REIMS_GO_DATA_ROOT", "")
|
||||
base := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(base, "location.json"))
|
||||
oldRoot := filepath.Join(base, "old-drive")
|
||||
newRoot := filepath.Join(base, "new-drive")
|
||||
oldVMDir, newVMDir := writeMovedVMRegistry(t, oldRoot, newRoot)
|
||||
|
||||
// An older release saved the new data root but left the old VM registration.
|
||||
cfg := &config.Config{DataRoot: newRoot}
|
||||
if err := config.Save("", cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := config.SaveLocation(newRoot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assertRegisteredVMDir(t, newRoot, oldVMDir)
|
||||
a, _ := New(nil, cli.WindowArgs{})
|
||||
if st := a.openDataRoot(); !st.Writable() {
|
||||
t.Fatalf("openDataRoot: %+v", st)
|
||||
}
|
||||
assertRegisteredVMDir(t, newRoot, newVMDir)
|
||||
}
|
||||
|
||||
func writeMovedVMRegistry(t *testing.T, oldRoot, newRoot string) (oldVMDir, newVMDir string) {
|
||||
t.Helper()
|
||||
newVMDir = filepath.Join(datamigrate.VMRoot(newRoot), "macos-tahoe")
|
||||
if err := os.MkdirAll(newVMDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(newVMDir, "vm.toml"), []byte("name = \"macos-tahoe\"\ndisk = \"disk.qcow2\"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldVMDir = filepath.Join(datamigrate.VMRoot(oldRoot), "macos-tahoe")
|
||||
regDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGConfigDir(), "reims-ctl")
|
||||
if err := os.MkdirAll(regDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vmsToml := "[[vm]]\nname = 'macos-tahoe'\ndir = '" + strings.ReplaceAll(oldVMDir, "'", "''") + "'\n"
|
||||
if err := os.WriteFile(filepath.Join(regDir, "vms.toml"), []byte(vmsToml), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return oldVMDir, newVMDir
|
||||
}
|
||||
|
||||
func assertRegisteredVMDir(t *testing.T, root, want string) {
|
||||
t.Helper()
|
||||
vms, err := reims.ListRegisteredVMs(root)
|
||||
if err != nil {
|
||||
t.Fatalf("ListRegisteredVMs: %v", err)
|
||||
}
|
||||
if len(vms) != 1 {
|
||||
t.Fatalf("got %d vms, want 1", len(vms))
|
||||
}
|
||||
if !strings.EqualFold(filepath.Clean(vms[0].Directory), filepath.Clean(newVMDir)) {
|
||||
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, newVMDir)
|
||||
if vms[0].Directory != want {
|
||||
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, want)
|
||||
}
|
||||
}
|
||||
@@ -94,21 +94,16 @@ func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatu
|
||||
placement.Lock()
|
||||
defer placement.Unlock()
|
||||
|
||||
displays := a.displayHost.displays()
|
||||
cfg := vmstart.VMDisplayConfig{TargetDisplay: vmstart.NormalizeTargetDisplay(targetDisplay)}
|
||||
status := buildVMDisplayStatus(vm, cfg, displays)
|
||||
if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, vmstart.ReadVMDisplay(vm.Directory).TargetDisplay) {
|
||||
return VMDisplayStatus{}, fmt.Errorf("%w: %q is not connected", host.ErrDisplayNotFound, cfg.TargetDisplay)
|
||||
}
|
||||
if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil {
|
||||
status, err := saveVMTargetDisplay(vm, targetDisplay, a.displayHost.displays())
|
||||
if err != nil {
|
||||
return VMDisplayStatus{}, err
|
||||
}
|
||||
defer a.emitStateChanged()
|
||||
if !status.Running || len(displays) == 0 {
|
||||
if !status.Running || len(status.Displays) == 0 {
|
||||
return status, nil
|
||||
}
|
||||
if status.FallbackToPrimary {
|
||||
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(cfg.TargetDisplay))
|
||||
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(status.TargetDisplay))
|
||||
}
|
||||
if driver.IsHosted(vm.Capabilities) {
|
||||
// The driver owns a hosted VM's display; only the choice is saved.
|
||||
@@ -158,6 +153,27 @@ func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatu
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func saveVMTargetDisplay(vm driver.VMInfo, targetDisplay string, displays []host.DisplayInfo) (VMDisplayStatus, error) {
|
||||
if vm.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
release, err := lockMacOSDisplaySettings(vm.Directory)
|
||||
if err != nil {
|
||||
return VMDisplayStatus{}, err
|
||||
}
|
||||
defer release()
|
||||
}
|
||||
cfg := vmstart.ReadVMDisplay(vm.Directory)
|
||||
previousTarget := cfg.TargetDisplay
|
||||
cfg.TargetDisplay = vmstart.NormalizeTargetDisplay(targetDisplay)
|
||||
status := buildVMDisplayStatus(vm, cfg, displays)
|
||||
if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, previousTarget) {
|
||||
return VMDisplayStatus{}, fmt.Errorf("%w: %q is not connected", host.ErrDisplayNotFound, cfg.TargetDisplay)
|
||||
}
|
||||
if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil {
|
||||
return VMDisplayStatus{}, err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func displayFallbackLog(target string) string {
|
||||
return fmt.Sprintf("Display %q is disconnected. Using the primary display.", target)
|
||||
}
|
||||
|
||||
@@ -131,6 +131,26 @@ func TestGetAndSetVMDisplay(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetVMDisplayPreservesAutoResolution(t *testing.T) {
|
||||
const driverID = driver.BuiltinReimsMacOSDriverID
|
||||
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
|
||||
a := newDisplayTestApp(t, &appSecondDriver{id: driverID, vms: []driver.VMInfo{vm}})
|
||||
a.displayHost.displays = func() []host.DisplayInfo {
|
||||
return []host.DisplayInfo{{Name: "DISPLAY1", Primary: true}, {Name: "DISPLAY2"}}
|
||||
}
|
||||
if _, err := vmstart.SaveVMAutoResolution(vm.Directory, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, target := range []string{"DISPLAY2", ""} {
|
||||
if _, err := a.SetVMDisplay(driverID, vm.Name, target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := vmstart.ReadVMDisplay(vm.Directory); got != (vmstart.VMDisplayConfig{TargetDisplay: target, AutoResolution: true}) {
|
||||
t.Fatalf("selection %q saved %+v", target, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetVMDisplayReadOnly(t *testing.T) {
|
||||
const driverID = driver.BuiltinReimsMacOSDriverID
|
||||
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
|
||||
|
||||
+20
-102
@@ -14,6 +14,7 @@ import (
|
||||
"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/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
@@ -119,6 +120,23 @@ func (a *App) guestToolsImagePath(name string) string {
|
||||
return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img")
|
||||
}
|
||||
|
||||
func buildToolsHFSImage(outPath string, cfg guesttools.VMConfig) error {
|
||||
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
src := guesttools.ToolsDiskFiles(cfg)
|
||||
files := make([]installer.HFSFile, len(src))
|
||||
for i, f := range src {
|
||||
files[i] = installer.HFSFile{
|
||||
Name: f.Name,
|
||||
Mode: f.Mode,
|
||||
Size: f.Size,
|
||||
Open: f.Open,
|
||||
}
|
||||
}
|
||||
return installer.BuildHFSPlusDiskImage(outPath, guesttools.ToolsVolumeName, files)
|
||||
}
|
||||
|
||||
// buildGuestToolsImage runs in the macOS driver after all start hooks pass.
|
||||
func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
|
||||
_, port, _, err := a.startGuestToolsServer()
|
||||
@@ -132,7 +150,7 @@ func (a *App) buildGuestToolsImage(vmName, vmDir string) error {
|
||||
return err
|
||||
}
|
||||
cfg, _ = a.validatedShareConfig(cfg)
|
||||
return guesttools.BuildToolsDiskImage(a.guestToolsImagePath(vmName), cfg)
|
||||
return buildToolsHFSImage(a.guestToolsImagePath(vmName), cfg)
|
||||
}
|
||||
|
||||
// startGuestToolsServer starts the shared localhost HTTP bridge once. Only the
|
||||
@@ -161,7 +179,6 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
|
||||
})
|
||||
a.guestTools = srv
|
||||
srv.SetHostDNSConfig(a.hostDNSConfigLocked())
|
||||
srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() })
|
||||
created = true
|
||||
}
|
||||
a.syncClipboardStagingLocked()
|
||||
@@ -214,51 +231,6 @@ func (a *App) guestToolsEnabled() bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// inputBridgeEnv returns REIMS_GO_INPUT_URL and REIMS_GO_INPUT_TOKEN env vars
|
||||
// for the VM's QEMU/reims-vgpu-window child process so direct WM_CHAR / IME
|
||||
// commits can forward to reims-go's local text router.
|
||||
func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string {
|
||||
if vmDir == "" {
|
||||
return nil
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil || port <= 0 {
|
||||
return nil
|
||||
}
|
||||
cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch)
|
||||
if err != nil || cfg.Token == "" {
|
||||
return nil
|
||||
}
|
||||
srv.SetKeymapCarrier(name, false)
|
||||
a.syncKeymapRules()
|
||||
return []string{
|
||||
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
|
||||
"REIMS_GO_INPUT_TOKEN=" + cfg.Token,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) dropBridgeEnv(name, vmDir string, epoch uint64) []string {
|
||||
if vmDir == "" {
|
||||
return nil
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil || port <= 0 {
|
||||
return nil
|
||||
}
|
||||
cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch)
|
||||
if err != nil || cfg.Token == "" {
|
||||
return nil
|
||||
}
|
||||
token := srv.HostDropToken(cfg.DriverID, name)
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{
|
||||
fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port),
|
||||
"REIMS_GO_DROP_TOKEN=" + token,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) registerExistingGuestTools(ctx context.Context) {
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
@@ -271,7 +243,6 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
|
||||
// guest agent that is already running reconnects after reims-go restarts or
|
||||
// the Guest Tools plugin is switched back on.
|
||||
func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) {
|
||||
defer a.syncKeymapRules()
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return
|
||||
@@ -387,59 +358,6 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) {
|
||||
}
|
||||
}
|
||||
|
||||
// syncGuestTools ensures the host HTTP bridge is running and refreshes the
|
||||
// REIMSTOOLS HFS+ image before VM start when Guest Tools is configured or attached.
|
||||
func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, epoch uint64) {
|
||||
if cur.Directory == "" {
|
||||
return
|
||||
}
|
||||
attached := reims.HasGuestToolsArgs(cur.ExtraArgs)
|
||||
unlock := a.lockGuestToolsVM(name)
|
||||
_, configured, err := guesttools.ReadVMConfigStrict(cur.Directory)
|
||||
unlock()
|
||||
if err != nil {
|
||||
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
if !attached && !configured {
|
||||
return
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error())
|
||||
return
|
||||
}
|
||||
cfg, err := a.loadAndRegisterGuestTools(srv, port, cur.Directory, name, epoch, cur.NetworkMode)
|
||||
if err != nil {
|
||||
a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged := reims.StripGuestToolsNetworkArgs(cur.ExtraArgs)
|
||||
if cur.NetworkMode == "bridge" && a.npcapPluginEnabled() {
|
||||
tokens, argsErr := reims.GuestToolsNetworkUnixArgs(cur.Directory, cfg.ManagementOutSock, cfg.ManagementInSock)
|
||||
if argsErr != nil {
|
||||
a.emitVMLog(name, networkmsg.Localize(argsErr, a.locale()).Error())
|
||||
return
|
||||
}
|
||||
merged = strings.TrimSpace(merged + " " + strings.Join(tokens, " "))
|
||||
} else {
|
||||
srv.StopManagementNetwork(name)
|
||||
}
|
||||
if attached {
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error())
|
||||
return
|
||||
}
|
||||
merged = reims.MergeGuestToolsArgs(merged, imgPath)
|
||||
}
|
||||
if merged != cur.ExtraArgs {
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err == nil {
|
||||
cur.ExtraArgs = merged
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AttachGuestTools prepares the per-VM Bearer token, ensures the shared folder
|
||||
// and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk,
|
||||
// and attaches it to the VM via `reims-ctl set --extra-args`.
|
||||
@@ -468,7 +386,7 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
}
|
||||
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
if err := buildToolsHFSImage(imgPath, cfg); err != nil {
|
||||
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
|
||||
}
|
||||
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
|
||||
|
||||
@@ -196,14 +196,14 @@ func TestHeldLedgerTracksAndForgets(t *testing.T) {
|
||||
app.noteHeldButton("p", vmKey, "left", true)
|
||||
app.noteHeldKey("p", vmKey, "a", true)
|
||||
|
||||
keys, buttons := app.heldState("p", vmKey)
|
||||
keys, buttons, _ := app.heldSnapshot("p", vmKey)
|
||||
if len(keys) != 2 || len(buttons) != 1 {
|
||||
t.Fatalf("held = %v %v", keys, buttons)
|
||||
}
|
||||
|
||||
// Releasing one key keeps the rest.
|
||||
app.dropHeld("p", vmKey, []string{"a"}, nil)
|
||||
if keys, _ := app.heldState("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" {
|
||||
if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" {
|
||||
t.Fatalf("keys after drop = %v", keys)
|
||||
}
|
||||
|
||||
@@ -221,6 +221,58 @@ func TestHeldLedgerTracksAndForgets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHeldLedgerKeepsAPressMadeDuringARelease checks that a release which
|
||||
// finished after the plugin pressed something new does not delete that press
|
||||
// from the record: the fallback would then no longer know to lift it.
|
||||
func TestHeldLedgerKeepsAPressMadeDuringARelease(t *testing.T) {
|
||||
app := &App{}
|
||||
const vmKey = "driver:vm"
|
||||
app.noteHeldKey("p", vmKey, "meta_l", true)
|
||||
keys, buttons, generation := app.heldSnapshot("p", vmKey)
|
||||
|
||||
// The plugin presses another key while the release is in flight.
|
||||
app.noteHeldKey("p", vmKey, "shift", true)
|
||||
|
||||
if app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) {
|
||||
t.Fatal("a stale release deleted a press it did not lift")
|
||||
}
|
||||
if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 2 {
|
||||
t.Fatalf("keys = %v, want both presses kept", keys)
|
||||
}
|
||||
|
||||
// A release whose snapshot is still current does clear the record.
|
||||
keys, buttons, generation = app.heldSnapshot("p", vmKey)
|
||||
if !app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) {
|
||||
t.Fatal("a current release was refused")
|
||||
}
|
||||
if vms := app.heldVMs("p"); len(vms) != 0 {
|
||||
t.Fatalf("ledger still holds %v", vms)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHeldLedgerRetriesAfterTheIdleTimeout checks that a record whose fallback
|
||||
// release could not run keeps a timer: a plugin that already exited never
|
||||
// makes the call that would otherwise retry it.
|
||||
func TestHeldLedgerRetriesAfterTheIdleTimeout(t *testing.T) {
|
||||
previousIdle, previousRetry := heldInputIdleTimeout, heldReleaseRetryTimeout
|
||||
heldInputIdleTimeout = time.Hour
|
||||
heldReleaseRetryTimeout = 20 * time.Millisecond
|
||||
t.Cleanup(func() { heldInputIdleTimeout, heldReleaseRetryTimeout = previousIdle, previousRetry })
|
||||
|
||||
app := &App{}
|
||||
app.noteHeldKey("p", "driver:vm", "meta_l", true)
|
||||
app.rearmHeld("p", "driver:vm")
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
// The VM is not running here, so the retry drops the record instead of
|
||||
// leaving a key pressed forever.
|
||||
if vms := app.heldVMs("p"); len(vms) != 0 {
|
||||
t.Fatalf("the retry left %v behind", vms)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHeldLedgerReleasesAfterTheIdleTimeout checks that a plugin which stops
|
||||
// calling mid-hold does not leave the guest stuck: the record carries its own
|
||||
// timer, and a VM that is not running has nothing left to lift.
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"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/vmstart"
|
||||
)
|
||||
|
||||
const KeymapRequiredAgentVersion = guesttools.KeymapAgentVersion
|
||||
|
||||
type VMKeymapUpdate struct {
|
||||
Preset string `json:"preset"`
|
||||
Bindings map[string]string `json:"bindings"`
|
||||
CaptureHostShortcuts *bool `json:"capture_host_shortcuts,omitempty"`
|
||||
}
|
||||
|
||||
type VMKeymapStatus struct {
|
||||
Preset string `json:"preset"`
|
||||
Bindings map[string]string `json:"bindings"`
|
||||
CaptureHostShortcuts bool `json:"capture_host_shortcuts"`
|
||||
NeedsGuestTools bool `json:"needs_guest_tools"`
|
||||
GuestConnected bool `json:"guest_connected"`
|
||||
GuestAgentVersion int `json:"guest_agent_version,omitempty"`
|
||||
RequiredAgentVersion int `json:"required_agent_version"`
|
||||
GuestKeymapActive bool `json:"guest_keymap_active"`
|
||||
InputServiceAvailable bool `json:"input_service_available"`
|
||||
HookActive bool `json:"hook_active"`
|
||||
Running bool `json:"running"`
|
||||
}
|
||||
|
||||
func (a *App) GetVMKeymap(name string) (VMKeymapStatus, error) {
|
||||
if vm, ok := a.polledVM(name); ok && vm.Dir != "" {
|
||||
return a.keymapStatus(name, vm.State == "running", vmstart.ReadVMKeymap(vm.Dir)), nil
|
||||
}
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return VMKeymapStatus{}, err
|
||||
}
|
||||
return a.keymapStatus(name, detail.State == "running", vmstart.ReadVMKeymap(detail.Directory)), nil
|
||||
}
|
||||
|
||||
func (a *App) SetVMKeymap(name string, req VMKeymapUpdate) (VMKeymapStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return VMKeymapStatus{}, err
|
||||
}
|
||||
a.keymapMu.Lock()
|
||||
capture := vmstart.ReadVMKeymap(detail.Directory).CaptureHostShortcuts
|
||||
if req.CaptureHostShortcuts != nil {
|
||||
capture = *req.CaptureHostShortcuts
|
||||
}
|
||||
cfg := vmstart.VMKeymapConfig{
|
||||
Preset: vmstart.KeymapPreset(req.Preset),
|
||||
Bindings: make(map[vmstart.HostModifier]vmstart.GuestModifier, len(req.Bindings)),
|
||||
CaptureHostShortcuts: capture,
|
||||
}
|
||||
for k, v := range req.Bindings {
|
||||
cfg.Bindings[vmstart.HostModifier(k)] = vmstart.GuestModifier(v)
|
||||
}
|
||||
cfg, err = vmstart.SaveVMKeymap(detail.Directory, cfg)
|
||||
if err != nil {
|
||||
a.keymapMu.Unlock()
|
||||
return VMKeymapStatus{}, err
|
||||
}
|
||||
a.syncKeymapRulesLocked()
|
||||
a.keymapMu.Unlock()
|
||||
return a.keymapStatus(name, detail.State == "running", cfg), nil
|
||||
}
|
||||
|
||||
func (a *App) keymapStatus(name string, running bool, cfg vmstart.VMKeymapConfig) VMKeymapStatus {
|
||||
status := VMKeymapStatus{
|
||||
Preset: string(cfg.Preset),
|
||||
Bindings: keymapBindingStrings(vmstart.ResolveKeymapBindings(cfg)),
|
||||
CaptureHostShortcuts: cfg.CaptureHostShortcuts,
|
||||
NeedsGuestTools: vmstart.NeedsGuestCarrier(vmstart.EffectiveKeymapBindings(cfg)),
|
||||
RequiredAgentVersion: KeymapRequiredAgentVersion,
|
||||
Running: running,
|
||||
}
|
||||
a.mu.Lock()
|
||||
srv := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if srv != nil && running {
|
||||
guest := srv.Status(name, guesttools.KeymapStatusMaxAge)
|
||||
status.GuestConnected = guest.Connected
|
||||
status.GuestAgentVersion = guest.AgentVersion
|
||||
status.GuestKeymapActive = guest.KeymapActive
|
||||
}
|
||||
svc := a.getInputService()
|
||||
status.InputServiceAvailable = svc != nil
|
||||
if svc != nil && running {
|
||||
status.HookActive = svc.IsKeymapActiveForVM(name)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func keymapBindingStrings(bindings map[vmstart.HostModifier]vmstart.GuestModifier) map[string]string {
|
||||
out := make(map[string]string, len(bindings))
|
||||
for k, v := range bindings {
|
||||
out[string(k)] = string(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *App) syncKeymapRules() {
|
||||
a.keymapMu.Lock()
|
||||
defer a.keymapMu.Unlock()
|
||||
a.syncKeymapRulesLocked()
|
||||
}
|
||||
|
||||
func (a *App) syncKeymapRulesLocked() {
|
||||
a.mu.Lock()
|
||||
vms := append([]driver.VMListItem(nil), a.lastVMs...)
|
||||
srv := a.guestTools
|
||||
a.mu.Unlock()
|
||||
svc := a.getInputService()
|
||||
var rules []host.KeymapRule
|
||||
var targets []host.IMETarget
|
||||
pids := make(map[string]int)
|
||||
for _, vm := range vms {
|
||||
if vm.RunningPID() == 0 {
|
||||
if srv != nil {
|
||||
srv.SetKeymapCarrier(vm.Name, false)
|
||||
}
|
||||
continue
|
||||
}
|
||||
dir := vm.Dir
|
||||
if dir == "" {
|
||||
if detail, err := a.GetVMDetail(vm.Name); err == nil {
|
||||
dir = detail.Directory
|
||||
}
|
||||
}
|
||||
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: dir, PID: uint32(*vm.PID)})
|
||||
pids[vm.Name] = *vm.PID
|
||||
cfg := vmstart.ReadVMKeymap(dir)
|
||||
effective := vmstart.EffectiveKeymapBindings(cfg)
|
||||
rule := host.KeymapRule{VMName: vm.Name, Bindings: keymapBindingStrings(effective)}
|
||||
if srv != nil {
|
||||
if oldPID := a.keymapPIDs[vm.Name]; oldPID != 0 && oldPID != *vm.PID {
|
||||
srv.SetKeymapCarrier(vm.Name, false)
|
||||
}
|
||||
srv.SetKeymapCarrier(vm.Name, svc != nil && vmstart.NeedsGuestCarrier(effective))
|
||||
rule.CarrierReady = srv.Status(vm.Name, guesttools.KeymapStatusMaxAge).KeymapActive
|
||||
}
|
||||
if len(effective) != 0 {
|
||||
rules = append(rules, rule)
|
||||
}
|
||||
}
|
||||
a.keymapPIDs = pids
|
||||
if svc != nil {
|
||||
svc.SetTargetsAndKeymapRules(targets, rules)
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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/vmstart"
|
||||
)
|
||||
|
||||
func boolPtr(v bool) *bool { return &v }
|
||||
|
||||
func TestVMKeymapCaptureStatus(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
id := driver.BuiltinReimsMacOSDriverID
|
||||
drv := &appSecondDriver{id: id, vms: []driver.VMInfo{{Name: "mac", DriverID: id, Directory: dir, State: "running"}}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{ID: "test." + id, Version: "1.0.0"},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, id, drv)
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
a := &App{cfg: &config.Config{DataRoot: dir}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)}
|
||||
t.Cleanup(func() { a.getInputService().Close() })
|
||||
for _, enabled := range []bool{true, false} {
|
||||
got, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(enabled)})
|
||||
if err != nil || got.Preset != "off" || !got.Running || got.CaptureHostShortcuts != enabled || got.NeedsGuestTools != enabled || len(got.Bindings) != 0 {
|
||||
t.Fatalf("SetVMKeymap capture=%v: %+v, %v", enabled, got, err)
|
||||
}
|
||||
got, err = a.GetVMKeymap("mac")
|
||||
if err != nil || got.Preset != "off" || !got.Running || got.CaptureHostShortcuts != enabled || got.NeedsGuestTools != enabled || len(got.Bindings) != 0 {
|
||||
t.Fatalf("GetVMKeymap capture=%v: %+v, %v", enabled, got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy Wails payloads omitting capture_host_shortcuts must preserve existing setting.
|
||||
if _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(true)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, raw := range []string{`{"preset":"win_to_cmd","bindings":{}}`, `{"preset":"off","bindings":{}}`} {
|
||||
var legacy VMKeymapUpdate
|
||||
if err := json.Unmarshal([]byte(raw), &legacy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if legacy.CaptureHostShortcuts != nil {
|
||||
t.Fatalf("legacy payload %s unexpectedly set pointer", raw)
|
||||
}
|
||||
got, err := a.SetVMKeymap("mac", legacy)
|
||||
if err != nil || !got.CaptureHostShortcuts || !got.NeedsGuestTools {
|
||||
t.Fatalf("legacy update %s lost capture flag: %+v, %v", raw, got, err)
|
||||
}
|
||||
}
|
||||
got, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(false)})
|
||||
if err != nil || got.CaptureHostShortcuts || got.NeedsGuestTools {
|
||||
t.Fatalf("explicit false did not disable capture: %+v, %v", got, err)
|
||||
}
|
||||
|
||||
// Concurrent explicit enable + legacy update (omitting capture_host_shortcuts)
|
||||
// must serialize read-merge-save and never clobber capture back to false.
|
||||
const iterations = 16
|
||||
for i := 0; i < iterations; i++ {
|
||||
if _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(false)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := make(chan struct{})
|
||||
done := make(chan error, 2)
|
||||
go func() {
|
||||
<-start
|
||||
_, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(true)})
|
||||
done <- err
|
||||
}()
|
||||
go func() {
|
||||
<-start
|
||||
_, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "win_to_cmd"})
|
||||
done <- err
|
||||
}()
|
||||
close(start)
|
||||
for j := 0; j < 2; j++ {
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
final, err := a.GetVMKeymap("mac")
|
||||
if err != nil || !final.CaptureHostShortcuts {
|
||||
t.Fatalf("iter %d: concurrent legacy update clobbered capture flag: %+v, %v", i, final, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeymapStatusWithoutPluginManager(t *testing.T) {
|
||||
a := &App{}
|
||||
t.Cleanup(func() { a.getInputService().Close() })
|
||||
a.syncKeymapRules()
|
||||
cfg := vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd}
|
||||
got := a.keymapStatus("mac", true, cfg)
|
||||
if got.Preset != "win_to_cmd" || got.Bindings["lwin"] != "lcmd" ||
|
||||
!got.NeedsGuestTools || !got.InputServiceAvailable || !got.Running || got.RequiredAgentVersion != KeymapRequiredAgentVersion ||
|
||||
got.GuestConnected || got.GuestKeymapActive || got.HookActive {
|
||||
t.Fatalf("unexpected status: %+v", got)
|
||||
}
|
||||
got = a.keymapStatus("mac", false, vmstart.DefaultVMKeymapConfig())
|
||||
if got.Preset != "off" || got.Running || got.NeedsGuestTools || got.Bindings == nil || len(got.Bindings) != 0 {
|
||||
t.Fatalf("unexpected defaults: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeymapStatusWithoutInputService(t *testing.T) {
|
||||
a := &App{inputShuttingDown: true}
|
||||
status := a.keymapStatus("mac", true, vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd})
|
||||
if status.InputServiceAvailable || status.HookActive || !status.NeedsGuestTools {
|
||||
t.Fatalf("unexpected status: %+v", status)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -11,6 +13,23 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
)
|
||||
|
||||
func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
s := reims.StripGuestToolsArgs(extraArgs)
|
||||
s = reims.StripPacketBridgeArgs(s)
|
||||
s = reims.StripGuestToolsNetworkArgs(s)
|
||||
s = reims.StripOfflineHelperArgs(s)
|
||||
s = qmp.StripLegacyWin10RebootArgs(s)
|
||||
s = reims.StripIncomingDeferArgs(s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
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: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
|
||||
}
|
||||
|
||||
func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
// Simulate an existing pre-plugin VM whose vm.toml already contains:
|
||||
// user arg + REIMSTOOLS + REIMSHELP + Win10 managed QMP args, with NO ledger file yet.
|
||||
@@ -45,7 +64,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
}
|
||||
|
||||
base := stripLegacyManagedExtraArgs(legacy)
|
||||
res := plugin.ReconcileStartIntents(base, ledger, active, intents)
|
||||
res := plugin.ReconcileStartIntentsForDriver(base, ledger, active, "", intents)
|
||||
|
||||
if !strings.Contains(res.ExtraArgs, "-cpu host") {
|
||||
t.Fatalf("user arg lost: %s", res.ExtraArgs)
|
||||
@@ -62,7 +81,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
|
||||
{PluginID: guest.ID, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}},
|
||||
}
|
||||
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
|
||||
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents)
|
||||
res2 := plugin.ReconcileStartIntentsForDriver(base2, ledger, active, "", nextIntents)
|
||||
if res2.ExtraArgs != "-cpu host" {
|
||||
t.Fatalf("expected only user arg after clearing managed keys, got: %q", res2.ExtraArgs)
|
||||
}
|
||||
@@ -94,7 +113,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
}}
|
||||
}
|
||||
|
||||
unmigrated := plugin.ReconcileStartIntents(extra, newLedger(), active, intents)
|
||||
unmigrated := plugin.ReconcileStartIntentsForDriver(extra, newLedger(), active, "", intents)
|
||||
if strings.Contains(unmigrated.ExtraArgs, "kernel-irqchip") {
|
||||
t.Fatalf("test premise: an unmigrated ledger should drop the fragment, got %q", unmigrated.ExtraArgs)
|
||||
}
|
||||
@@ -103,7 +122,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) {
|
||||
if !guest.MigrateLedger(ledger) {
|
||||
t.Fatal("MigrateLedger reported no change for a retired owner")
|
||||
}
|
||||
res := plugin.ReconcileStartIntents(extra, ledger, active, intents)
|
||||
res := plugin.ReconcileStartIntentsForDriver(extra, ledger, active, "", intents)
|
||||
if got := strings.Count(res.ExtraArgs, "kernel-irqchip=off"); got != 1 {
|
||||
t.Fatalf("want kernel-irqchip=off carried exactly once, got %d in %q", got, res.ExtraArgs)
|
||||
}
|
||||
|
||||
@@ -75,7 +75,12 @@ func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) {
|
||||
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: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil
|
||||
return driver.VMInfo{
|
||||
Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID,
|
||||
State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory,
|
||||
DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory,
|
||||
Network: detail.Network, SSHPort: detail.SSHPort,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) {
|
||||
@@ -101,16 +106,7 @@ func (a *App) StartVM(driverID, name string) error {
|
||||
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)
|
||||
}
|
||||
vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error {
|
||||
return a.startMacOSVM(vm.Name)
|
||||
})
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
@@ -128,7 +124,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
|
||||
Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error)
|
||||
}, vm driver.VMInfo) error {
|
||||
if svc == nil {
|
||||
return a.startMacOSVM(vm.Name)
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
@@ -179,10 +175,7 @@ func (a *App) stopVM(ctx context.Context, driverID, name string, force bool) err
|
||||
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.stopMacOSVM(ctx, name, force)
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(ctx, driverID, name)
|
||||
if err != nil {
|
||||
@@ -222,10 +215,7 @@ func (a *App) EjectInstaller(driverID, name string) error {
|
||||
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.ejectMacOSInstaller(name)
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
@@ -247,7 +237,14 @@ func (a *App) ReadVMLogs(driverID, name string, serial bool) (string, error) {
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return a.readMacOSVMLogs(name, serial)
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return "", fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.ReadLogs(context.Background(), name, serial)
|
||||
}
|
||||
return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial)
|
||||
}
|
||||
@@ -261,27 +258,15 @@ func (a *App) RestartVM(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 svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(a.baseCtx(), ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.withComputerUseVM(a.baseCtx(), vm.Directory, func(ctx context.Context) error {
|
||||
if err := a.stopVM(ctx, ref.DriverID, ref.Name, false); err != nil {
|
||||
return err
|
||||
@@ -289,7 +274,7 @@ func (a *App) RestartVM(driverID, name string) error {
|
||||
return a.startResolvedVMLocked(ctx, svc, vm)
|
||||
})
|
||||
}
|
||||
_, err := a.restartMacOSVM(a.baseCtx(), ref.Name)
|
||||
_, err = a.restartMacOSVM(a.baseCtx(), ref.Name)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -298,10 +283,7 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
|
||||
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.deleteMacOSVM(name, keepFiles)
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -15,12 +12,10 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"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/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
@@ -67,101 +62,6 @@ func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareLegacyColdStart(t *testing.T) {
|
||||
log := func(line string) { t.Log(line) }
|
||||
t.Run("recoverable snapshot", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
state := reims.SuspendStatePath(dir) + ".tmp"
|
||||
meta := reims.SuspendMetaPath(dir) + ".tmp"
|
||||
for _, path := range []string{state, meta} {
|
||||
if err := os.WriteFile(path, []byte("snapshot data"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log)
|
||||
var coded *i18n.CodedError
|
||||
if !errors.As(err, &coded) || coded.Code != "E_VM_SUSPENDED" || coded.Key != "err.suspend.action_blocked" {
|
||||
t.Fatalf("legacy cold start = %v, want E_VM_SUSPENDED", err)
|
||||
}
|
||||
if !reims.HasSuspendState(dir) {
|
||||
t.Fatal("recoverable snapshot was removed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inspection error", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
staged := reims.SuspendStatePath(dir) + ".tmp"
|
||||
if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(reims.SuspendMetaPath(dir)+".tmp", 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log)
|
||||
if !errors.Is(err, reims.ErrSuspendArtifactsUncertain) {
|
||||
t.Fatalf("legacy cold start = %v, want inspection error", err)
|
||||
}
|
||||
if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" {
|
||||
t.Fatalf("staged state = %q, %v", data, err)
|
||||
}
|
||||
})
|
||||
|
||||
for _, tt := range []struct {
|
||||
name, dir string
|
||||
}{
|
||||
{"postmigrate", "."},
|
||||
{"postmigrate on short socket for long VM directory", strings.Repeat("v", 100)},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
const name, tmpDir = "mac", "tmp"
|
||||
if err := os.MkdirAll(tt.dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
staged := reims.SuspendStatePath(tt.dir) + ".tmp"
|
||||
if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
socket := qmp.SocketPathForVM(tt.dir, name, tmpDir)
|
||||
if err := os.MkdirAll(filepath.Dir(socket), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
if tt.dir != "." {
|
||||
if _, err := os.Lstat(qmp.SocketPath(tt.dir)); !os.IsNotExist(err) {
|
||||
t.Fatalf("unexpected VM directory socket: %v", err)
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
_, _ = fmt.Fprintln(conn, `{"QMP":{}}`)
|
||||
sc := bufio.NewScanner(conn)
|
||||
if sc.Scan() {
|
||||
_, _ = fmt.Fprintln(conn, `{"return":{}}`)
|
||||
}
|
||||
if sc.Scan() {
|
||||
_, _ = fmt.Fprintln(conn, `{"return":{"running":false,"status":"postmigrate"}}`)
|
||||
}
|
||||
}()
|
||||
err = prepareLegacyColdStart(t.Context(), i18n.EnUS, name, tmpDir, reims.VMDetail{Directory: tt.dir, State: "stopped"}, log)
|
||||
if err == nil || !strings.Contains(err.Error(), "QEMU is still active (QMP status: postmigrate)") {
|
||||
t.Fatalf("legacy cold start = %v, want active QEMU error", err)
|
||||
}
|
||||
if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" {
|
||||
t.Fatalf("staged state = %q, %v", data, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type appSecondDriver struct {
|
||||
id string
|
||||
vms []driver.VMInfo
|
||||
|
||||
@@ -23,13 +23,6 @@ func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) {
|
||||
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: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
|
||||
}
|
||||
|
||||
func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
@@ -44,6 +37,7 @@ func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, erro
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
populateNestedVirtDetail(&d)
|
||||
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
|
||||
return d, nil
|
||||
}
|
||||
|
||||
@@ -78,6 +72,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
populateNestedVirtDetail(&d)
|
||||
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
|
||||
return d, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -4,23 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"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/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
"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"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
@@ -178,353 +166,6 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
||||
}()
|
||||
}
|
||||
|
||||
// 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.StripPacketBridgeArgs(s)
|
||||
s = reims.StripGuestToolsNetworkArgs(s)
|
||||
s = reims.StripOfflineHelperArgs(s)
|
||||
s = qmp.StripLegacyWin10RebootArgs(s)
|
||||
s = reims.StripIncomingDeferArgs(s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func (a *App) startMacOSVM(name string) error {
|
||||
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()
|
||||
locale := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
a.emitVMLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
}
|
||||
curDetail, release, err := startprep.LockVM(context.Background(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
unlock := sync.OnceFunc(release)
|
||||
defer unlock()
|
||||
if err := prepareLegacyColdStart(context.Background(), c.Locale, name, tmpDir, curDetail, func(line string) {
|
||||
a.emitVMLog(name, line)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
releaseNet, err := a.prepareManagedVMNetwork(context.Background(), name, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if releaseNet != nil {
|
||||
defer releaseNet()
|
||||
}
|
||||
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,
|
||||
VMSettingsKey: driver.NewVMRef(builtin.IDDriverReimsMacOS, name).Key(),
|
||||
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{}}
|
||||
}
|
||||
// Reassign macOS-owned fragments from legacy builtin.core records to
|
||||
// builtin.guest.macos before reconciling.
|
||||
guest.MigrateLedger(ledger)
|
||||
// Strip pre-ledger or out-of-band managed fragments so upgrading existing
|
||||
// VMs never duplicates QEMU device IDs.
|
||||
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
|
||||
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
|
||||
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep)
|
||||
reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested))
|
||||
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 {
|
||||
if err := a.reconcileLegacyBridgeArgs(context.Background(), c, &curDetail); err != nil {
|
||||
return err
|
||||
}
|
||||
a.syncGuestTools(c, name, &curDetail, a.vmDeleteEpoch(name))
|
||||
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
||||
if env := a.inputBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name)); len(env) > 0 {
|
||||
c.Env = append(c.Env, env...)
|
||||
}
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("window-file-drop") {
|
||||
c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...)
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
ledger, err := plugin.LoadArgLedger(curDetail.Directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
|
||||
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep)
|
||||
reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested})
|
||||
for _, warning := range reconciled.Warnings {
|
||||
a.emitVMLog(name, warning)
|
||||
}
|
||||
if reconciled.Changed {
|
||||
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil {
|
||||
return err
|
||||
}
|
||||
curDetail.ExtraArgs = reconciled.ExtraArgs
|
||||
}
|
||||
}
|
||||
|
||||
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
||||
vmstart.UsesFixedGuestMode(curDetail.Directory, rep.Displays, curDetail.Borderless, curDetail.Resolution) {
|
||||
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()
|
||||
a.emitStateChanged()
|
||||
|
||||
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+"...")
|
||||
err = c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
||||
a.emitVMLog(name, msg)
|
||||
})
|
||||
unlock()
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, vmKey(name))
|
||||
a.mu.Unlock()
|
||||
a.emitVMLog(name, "Start error: "+err.Error())
|
||||
a.emitStateChanged()
|
||||
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()
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// 备用启动同样记录参数归属,停用扩展时可精确移除桥接片段。
|
||||
func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlClient, detail *reims.VMDetail) error {
|
||||
ledger, err := plugin.LoadArgLedger(detail.Directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
intent := plugin.StartIntent{PluginID: builtin.IDNpcapBridge, ClearKeys: []string{"bridge-network", "npcap-bridge"}}
|
||||
if detail.NetworkMode == "bridge" {
|
||||
record, err := reims.ReadNetworkRecord(detail.Directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if record.Corrupt {
|
||||
return networkmsg.Error("record_invalid", nil)
|
||||
}
|
||||
if record.Pending {
|
||||
return networkmsg.Error("packet_pending", nil)
|
||||
}
|
||||
mac, err := resolveVMNetworkMAC(ctx, c, *detail)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sockPath := record.SocketPath
|
||||
if sockPath == "" {
|
||||
sockPath = reims.VMUnixSocketPath(detail.Directory, a.tempDir(), detail.Name, "bridge.sock")
|
||||
}
|
||||
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
intent.Args = []plugin.ArgFragment{{PluginID: builtin.IDNpcapBridge, Key: "bridge-network", Tokens: tokens, Builtin: true, Priority: 78}}
|
||||
}
|
||||
// 先剥除旧版未登记的主通道;管理网卡和用户参数保持各自归属。
|
||||
extra := reims.StripPacketBridgeArgs(detail.ExtraArgs)
|
||||
result := plugin.ReconcileStartIntents(extra, ledger, nil, []plugin.StartIntent{intent})
|
||||
for _, warning := range result.Warnings {
|
||||
a.emitVMLog(detail.Name, warning)
|
||||
}
|
||||
if result.ExtraArgs != detail.ExtraArgs {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: detail.Name, ExtraArgs: &result.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
||||
return networkmsg.Error("config_save", err)
|
||||
}
|
||||
}
|
||||
if err := plugin.SaveArgLedger(detail.Directory, ledger); err != nil {
|
||||
return err
|
||||
}
|
||||
detail.ExtraArgs = result.ExtraArgs
|
||||
return nil
|
||||
}
|
||||
|
||||
// prepareLegacyColdStart guards the older start path against a stopped VM that
|
||||
// still holds suspend artifacts. It drops provably orphaned files, then refuses
|
||||
// the start while a recoverable snapshot remains: this path cannot resume one,
|
||||
// and cold-starting over it would discard the guest's saved state. Resume or
|
||||
// discard the snapshot from the UI first.
|
||||
func prepareLegacyColdStart(ctx context.Context, locale i18n.Locale, name, tmpDir string, cur reims.VMDetail, log func(string)) error {
|
||||
if cur.State != "stopped" {
|
||||
return nil
|
||||
}
|
||||
suspended, err := reims.InspectSuspendState(cur.Directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !suspended {
|
||||
err := startprep.CleanStaleSuspendBeforeStart(ctx, cur.Directory, name, tmpDir, log, log)
|
||||
if !errors.Is(err, reims.ErrSuspendStatePresent) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return i18n.NewCodedError(locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
|
||||
func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error {
|
||||
return a.stopMacOSVMLocked(operationCtx, name, force, c)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
|
||||
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().DispatchBeforeStop(ctx, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
a.emitStateChanged()
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
||||
var err error
|
||||
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.stopPacketBridge(name)
|
||||
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()
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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(ctx context.Context, name string) (stopped bool, err error) {
|
||||
@@ -555,11 +196,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
vm, resolveErr := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if resolveErr != nil {
|
||||
return true, resolveErr
|
||||
}
|
||||
return true, a.startResolvedVMLocked(ctx, nil, vm)
|
||||
return true, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
@@ -568,99 +205,6 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
|
||||
return true, a.startResolvedVMLocked(ctx, svc, vm)
|
||||
}
|
||||
|
||||
func (a *App) ejectMacOSInstaller(name string) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
|
||||
return c.Eject(ctx, name, w, w)
|
||||
}); err != nil {
|
||||
a.emitVMLog(name, "Eject error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
a.emitVMLog(name, "Installer ejected.")
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
removed := false
|
||||
err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
|
||||
return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed)
|
||||
})
|
||||
if removed {
|
||||
releaseVMTyping(name)
|
||||
releaseVMThumbnail(name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error {
|
||||
name := detail.Name
|
||||
if detail.State != "running" {
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
a.stopPacketBridge(name)
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error {
|
||||
return c.Delete(ctx, name, keepFiles, w, w)
|
||||
}, func() (bool, error) {
|
||||
vms, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if strings.EqualFold(vm.Name, name) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
if deleteErr != nil {
|
||||
a.emitVMLog(name, "Delete error: "+deleteErr.Error())
|
||||
}
|
||||
if !deleted {
|
||||
return deleteErr
|
||||
}
|
||||
*removed = true
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
a.stopPacketBridge(name)
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, vmKey(name))
|
||||
delete(a.transitions, vmKey(name))
|
||||
delete(a.diskPaths, vmKey(name))
|
||||
delete(a.procSamples, vmKey(name))
|
||||
delMgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if delMgr != nil {
|
||||
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitStateChanged()
|
||||
return deleteErr
|
||||
}
|
||||
|
||||
// OpenVMFolder shows the VM's directory in File Explorer.
|
||||
func (a *App) OpenVMFolder(name string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
@@ -672,11 +216,3 @@ func (a *App) OpenVMFolder(name string) error {
|
||||
}
|
||||
return host.OpenFolder(d.Directory)
|
||||
}
|
||||
|
||||
func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.ReadLogs(context.Background(), name, serial)
|
||||
}
|
||||
+89
-110
@@ -6,13 +6,17 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/macosdriver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
@@ -79,7 +83,7 @@ func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.createVMFlow(opts)
|
||||
return a.createVMFlow(opts, host.ConnectedDisplays)
|
||||
}
|
||||
|
||||
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
||||
@@ -132,126 +136,99 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
|
||||
if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
var outcome macosdriver.SettingsOutcome
|
||||
ctx := macosdriver.WithSettingsOutcome(context.Background(), &outcome)
|
||||
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 {
|
||||
if strings.TrimSpace(opts.DiskCache) != "" {
|
||||
cfg := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
|
||||
}
|
||||
if !active.Manifest.HasCapability("win32-native-aio") {
|
||||
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime"))
|
||||
}
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
locked, 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 opts.NestedVirt != nil {
|
||||
if err := vmstart.SaveVMNestedVirt(locked.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
|
||||
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 svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
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 dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) {
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
|
||||
}
|
||||
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
|
||||
from := cur.DiskCache
|
||||
if from == "" {
|
||||
from = "default"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
|
||||
}
|
||||
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.NestedVirt != nil && *opts.NestedVirt != cur.NestedVirt {
|
||||
diffs = append(diffs, PendingChange{Field: "nested_virt", From: fmt.Sprintf("%v", cur.NestedVirt), To: fmt.Sprintf("%v", *opts.NestedVirt)})
|
||||
}
|
||||
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()
|
||||
raw, merr := json.Marshal(opts)
|
||||
if merr != nil {
|
||||
return fmt.Errorf("encode VM settings: %w", merr)
|
||||
}
|
||||
var changes map[string]any
|
||||
if uerr := json.Unmarshal(raw, &changes); uerr != nil {
|
||||
return fmt.Errorf("decode VM settings: %w", uerr)
|
||||
}
|
||||
if err := svc.Set(ctx, driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, opts.Name), changes, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
if diffs := pendingVMSettingsChanges(outcome, opts); len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
key := vmKey(opts.Name)
|
||||
a.pendingChanges[key] = mergePendingChanges(a.pendingChanges[key], diffs)
|
||||
if len(a.pendingChanges[key]) == 0 {
|
||||
delete(a.pendingChanges, key)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func pendingVMSettingsChanges(outcome macosdriver.SettingsOutcome, opts reims.SetOpts) []PendingChange {
|
||||
if !outcome.Valid || !outcome.Running {
|
||||
return nil
|
||||
}
|
||||
before, after := outcome.Before, outcome.After
|
||||
candidates := []struct {
|
||||
touched bool
|
||||
change PendingChange
|
||||
}{
|
||||
{opts.CPUs > 0, PendingChange{Field: "cpus", From: strconv.Itoa(before.CPUs), To: strconv.Itoa(after.CPUs)}},
|
||||
{opts.Memory != "", PendingChange{Field: "memory", From: before.Memory, To: after.Memory}},
|
||||
{opts.AutoResolution != nil, PendingChange{Field: "auto_resolution", From: strconv.FormatBool(before.AutoResolution), To: strconv.FormatBool(after.AutoResolution)}},
|
||||
{opts.Resolution != "", PendingChange{Field: "resolution", From: before.Resolution, To: after.Resolution}},
|
||||
{opts.GPU != "", PendingChange{Field: "gpu", From: before.GPU, To: after.GPU}},
|
||||
{opts.Displays > 0, PendingChange{Field: "displays", From: strconv.Itoa(before.Displays), To: strconv.Itoa(after.Displays)}},
|
||||
{strings.TrimSpace(opts.DiskController) != "", PendingChange{Field: "disk_controller", From: before.DiskController, To: after.DiskController}},
|
||||
{strings.TrimSpace(opts.DiskCache) != "", PendingChange{Field: "disk_cache", From: before.DiskCache, To: after.DiskCache}},
|
||||
{opts.Borderless != nil, PendingChange{Field: "borderless", From: strconv.FormatBool(before.Borderless), To: strconv.FormatBool(after.Borderless)}},
|
||||
{opts.NestedVirt != nil, PendingChange{Field: "nested_virt", From: strconv.FormatBool(before.NestedVirt), To: strconv.FormatBool(after.NestedVirt)}},
|
||||
{opts.Audio != nil, PendingChange{Field: "audio", From: strconv.FormatBool(before.Audio), To: strconv.FormatBool(after.Audio)}},
|
||||
{opts.AudioBackend != "", PendingChange{Field: "audio_backend", From: before.AudioBackend, To: after.AudioBackend}},
|
||||
{strings.TrimSpace(opts.GuestLang) != "", PendingChange{Field: "guest_lang", From: before.GuestLang, To: after.GuestLang}},
|
||||
}
|
||||
out := make([]PendingChange, 0, len(candidates))
|
||||
for _, item := range candidates {
|
||||
if item.touched || !noPendingChange(item.change) {
|
||||
out = append(out, item.change)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mergePendingChanges(existing, incoming []PendingChange) []PendingChange {
|
||||
merged := make([]PendingChange, 0, len(existing)+len(incoming))
|
||||
for _, changes := range [2][]PendingChange{existing, incoming} {
|
||||
for _, change := range changes {
|
||||
index := slices.IndexFunc(merged, func(pending PendingChange) bool { return pending.Field == change.Field })
|
||||
if index < 0 {
|
||||
merged = append(merged, change)
|
||||
} else {
|
||||
merged[index].To = change.To
|
||||
}
|
||||
}
|
||||
}
|
||||
return slices.DeleteFunc(merged, noPendingChange)
|
||||
}
|
||||
|
||||
func noPendingChange(change PendingChange) bool {
|
||||
if change.Field == "memory" || change.Field == "resolution" || change.Field == "disk_controller" || change.Field == "disk_cache" {
|
||||
return strings.EqualFold(change.From, change.To)
|
||||
}
|
||||
return change.From == change.To
|
||||
}
|
||||
|
||||
func lockMacOSDisplaySettings(vmDir string) (func(), error) {
|
||||
return reims.LockVMOperation(vmDir)
|
||||
}
|
||||
|
||||
type VMNetworkSettings struct {
|
||||
Adapters []NetworkAdapter `json:"adapters"`
|
||||
UplinkGUID string `json:"uplink_guid"`
|
||||
@@ -325,7 +302,9 @@ func clearManagedNetworkLedger(vmDir string) {
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
_ = plugin.SaveArgLedger(vmDir, ledger)
|
||||
if err := plugin.SaveArgLedger(vmDir, ledger); err != nil {
|
||||
log.Printf("[app] save plugin arg ledger failed (%s): %v", vmDir, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
const (
|
||||
displayFixtureVM = "test-vm"
|
||||
displayFixtureClone = "test-clone"
|
||||
)
|
||||
|
||||
type displayCtlFixture struct {
|
||||
Dir, State, Resolution string
|
||||
Memory string
|
||||
BeforeLockResolution string
|
||||
Shows int
|
||||
Graphics string
|
||||
CloneDir string
|
||||
Borderless bool
|
||||
FailSet bool
|
||||
NestedVirtBeforeSet bool
|
||||
FailShowAfterSet bool
|
||||
ReplaceDisplayAfterSet bool
|
||||
Commands []string
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if path := os.Getenv("REIMS_TEST_DISPLAY_CTL"); path != "" {
|
||||
switch filepath.Base(os.Args[0]) {
|
||||
case "reims-ctl", "reims-ctl.exe":
|
||||
if err := runDisplayCtl(path, os.Args[1:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
case "qemu-img", "qemu-img.exe":
|
||||
if os.Args[1] == "info" {
|
||||
fmt.Println(`{"format":"qcow2"}`)
|
||||
return
|
||||
}
|
||||
if os.Args[1] == "create" {
|
||||
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("overlay"), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if os.Args[1] == "convert" {
|
||||
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("converted disk"), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "unexpected qemu-img call", os.Args[1:])
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func runDisplayCtl(path string, args []string) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var vm displayCtlFixture
|
||||
if err := json.Unmarshal(raw, &vm); err != nil {
|
||||
return err
|
||||
}
|
||||
switch args[0] {
|
||||
case "show":
|
||||
if args[1] == displayFixtureClone && vm.CloneDir != "" {
|
||||
fmt.Printf("state stopped\ndirectory %s\ndisplay one opening at %s\n", vm.CloneDir, vm.Resolution)
|
||||
return nil
|
||||
}
|
||||
if vm.State == "" || args[1] != displayFixtureVM || vm.FailShowAfterSet && len(vm.Commands) > 0 {
|
||||
return fmt.Errorf("VM %q not found", args[1])
|
||||
}
|
||||
if vm.BeforeLockResolution != "" {
|
||||
vm.Shows++
|
||||
if vm.Shows == 2 {
|
||||
unlock, err := reims.LockVMOperation(vm.Dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlock()
|
||||
vm.Resolution = vm.BeforeLockResolution
|
||||
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Printf("state %s\ndirectory %s\ndisk system.qcow2\ngraphics %s\nmemory %s\n", vm.State, vm.Dir, vm.Graphics, vm.Memory)
|
||||
if vm.Borderless {
|
||||
fmt.Printf("display one borderless at %s\n", vm.Resolution)
|
||||
} else {
|
||||
fmt.Printf("display one opening at %s\n", vm.Resolution)
|
||||
}
|
||||
return nil
|
||||
case "list":
|
||||
if vm.State == "" {
|
||||
fmt.Println("[]")
|
||||
return nil
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode([]reims.VMListItem{{Name: displayFixtureVM, State: vm.State, Dir: vm.Dir}})
|
||||
case "create":
|
||||
if args[1] == displayFixtureClone {
|
||||
vm.CloneDir = filepath.Join(filepath.Dir(vm.Dir), displayFixtureClone)
|
||||
if err := os.MkdirAll(vm.CloneDir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
vm.State = "stopped"
|
||||
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "set", "start":
|
||||
if args[0] == "set" && len(args) > 1 && args[1] == "--help" {
|
||||
return nil
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected command %v", args)
|
||||
}
|
||||
failSet := args[0] == "set" && vm.FailSet
|
||||
if failSet {
|
||||
nested, err := vmstart.ReadVMNestedVirt(vm.Dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vm.NestedVirtBeforeSet = nested.Enabled
|
||||
}
|
||||
for i := 2; !failSet && i+1 < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--resolution":
|
||||
vm.Resolution = args[i+1]
|
||||
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
|
||||
return err
|
||||
}
|
||||
case "--borderless":
|
||||
vm.Borderless = args[i+1] == "true"
|
||||
case "--graphics":
|
||||
vm.Graphics = args[i+1]
|
||||
case "--memory":
|
||||
vm.Memory = args[i+1]
|
||||
}
|
||||
}
|
||||
if args[0] == "set" && vm.ReplaceDisplayAfterSet {
|
||||
vm.Resolution = "1024x768"
|
||||
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
command := strings.Join(args, " ")
|
||||
if args[0] == "start" {
|
||||
command += " fixed=" + os.Getenv("REIMS_VGPU_WINDOW_FIXED_MODE")
|
||||
}
|
||||
vm.Commands = append(vm.Commands, command)
|
||||
raw, err = json.Marshal(vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if args[0] == "start" {
|
||||
return fmt.Errorf("stop before launching QEMU")
|
||||
}
|
||||
if failSet {
|
||||
return fmt.Errorf("fixture refused set")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDisplayCtlResolution(dir, resolution string) error {
|
||||
config := fmt.Sprintf("disk = 'system.qcow2'\n[display]\nresolution = %q\n", resolution)
|
||||
return os.WriteFile(filepath.Join(dir, "vm.toml"), []byte(config), 0o600)
|
||||
}
|
||||
|
||||
func newDisplayCtlApp(t *testing.T, vm displayCtlFixture, useDriver bool) (*App, func() displayCtlFixture) {
|
||||
t.Helper()
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "test-rt"}
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
active := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
|
||||
control := active.ControlPath()
|
||||
if err := os.MkdirAll(filepath.Dir(control), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(active.Dir, "manifest.json"), []byte(`{"schema_version":2,"commit":"test-rt","kind":"reims-vgpu","runtime_api":"1.0.0","capabilities":["display-fixed-mode","vm-suspend"]}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exe, err := os.ReadFile(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(control, exe, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(active.QemuImgPath()), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(control, active.QemuImgPath()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixturePath := filepath.Join(cfg.DataRoot, "display-fixture.json")
|
||||
t.Setenv("REIMS_TEST_DISPLAY_CTL", fixturePath)
|
||||
t.Setenv("REIMS_VGPU_WINDOW_FIXED_MODE", "")
|
||||
t.Setenv("GORACE", "atexit_sleep_ms=0")
|
||||
registryDir := filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", registryDir)
|
||||
if err := os.MkdirAll(registryDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm.Dir = filepath.Join(cfg.DataRoot, displayFixtureVM)
|
||||
if vm.State != "" {
|
||||
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(vm.Dir, "system.qcow2"), []byte("source disk fixture"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := fmt.Sprintf("[[vm]]\nname = %q\ndir = '%s'\n", displayFixtureVM, vm.Dir)
|
||||
if err := os.WriteFile(filepath.Join(registryDir, "vms.toml"), []byte(registry), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(vm)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(fixturePath, raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := &App{}
|
||||
if useDriver {
|
||||
a = newDisplayTestApp(t, macosdriver.NewReimsMacOSDriver(func() config.Config { return cfg }))
|
||||
}
|
||||
a.cfg = &cfg
|
||||
a.transitions = map[string]string{}
|
||||
a.pendingChanges = map[string][]PendingChange{}
|
||||
return a, func() displayCtlFixture {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(fixturePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var current displayCtlFixture
|
||||
if err := json.Unmarshal(raw, ¤t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return current
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionWhileRunning(t *testing.T) {
|
||||
for _, state := range []string{"running", "paused"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
initial := "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: state, Resolution: initial}, true)
|
||||
on := true
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm := fixture()
|
||||
want := []PendingChange{
|
||||
{Field: "auto_resolution", From: "false", To: "true"},
|
||||
}
|
||||
if vm.Resolution != initial || len(vm.Commands) != 0 || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
|
||||
t.Fatalf("enable auto: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
|
||||
}
|
||||
if raw, found := reims.ReadConfiguredResolution(vm.Dir); !found || raw != initial {
|
||||
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
|
||||
}
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: initial}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm = fixture()
|
||||
if vm.Resolution != initial || vmstart.ReadVMDisplay(vm.Dir).AutoResolution || len(a.pendingChanges) != 0 {
|
||||
t.Fatalf("manual resolution: VM %+v, want initial resolution and no pending changes, got %+v", vm, a.pendingChanges)
|
||||
}
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want = []PendingChange{{Field: "resolution", From: initial, To: "1280x800"}}
|
||||
if vm = fixture(); vm.Resolution != "1280x800" || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
|
||||
t.Fatalf("changed fixed resolution: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionDoesNotReadBackSettings(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
failShow, replace bool
|
||||
}{
|
||||
{name: "show fails", failShow: true},
|
||||
{name: "display changed externally", replace: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
|
||||
State: "running", Resolution: initial, FailShowAfterSet: tc.failShow, ReplaceDisplayAfterSet: tc.replace,
|
||||
}, true)
|
||||
on := true
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, CPUs: 1, AutoResolution: &on}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []PendingChange{
|
||||
{Field: "cpus", From: "0", To: "1"},
|
||||
{Field: "auto_resolution", From: "false", To: "true"},
|
||||
}
|
||||
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
|
||||
t.Fatalf("pending changes = %+v, want %+v", got, want)
|
||||
}
|
||||
if got := fixture().Commands; !slices.Equal(got, []string{"set test-vm --cpus 1"}) {
|
||||
t.Fatalf("commands = %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionUsesLockedSettingsForPendingChanges(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
|
||||
State: "running", Resolution: "1234x876", BeforeLockResolution: "2560x1600", Memory: "2G",
|
||||
}, true)
|
||||
if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Memory: "3G"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm := fixture()
|
||||
if vm.Resolution != "2560x1600" || vm.Memory != "3G" || vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
|
||||
t.Fatalf("saved VM = %+v, display = %+v", vm, vmstart.ReadVMDisplay(vm.Dir))
|
||||
}
|
||||
want := []PendingChange{{Field: "memory", From: "2G", To: "3G"}}
|
||||
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
|
||||
t.Fatalf("pending changes = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergePendingChangesKeepsRunningValues(t *testing.T) {
|
||||
existing := []PendingChange{
|
||||
{Field: "memory", From: "8G", To: "12G"},
|
||||
{Field: "resolution", From: "1920x1080", To: "2560x1440"},
|
||||
{Field: "gpu", From: "gpu-a", To: "gpu-b"},
|
||||
{Field: "cpus", From: "4", To: "6"},
|
||||
}
|
||||
incoming := []PendingChange{
|
||||
{Field: "memory", From: "12G", To: "8g"},
|
||||
{Field: "resolution", From: "2560x1440", To: "1920X1080"},
|
||||
{Field: "gpu", From: "gpu-b", To: "GPU-A"},
|
||||
{Field: "cpus", From: "6", To: "8"},
|
||||
}
|
||||
want := []PendingChange{
|
||||
{Field: "gpu", From: "gpu-a", To: "GPU-A"},
|
||||
{Field: "cpus", From: "4", To: "8"},
|
||||
}
|
||||
if got := mergePendingChanges(existing, incoming); !slices.Equal(got, want) {
|
||||
t.Fatalf("merge = %+v, want %+v", got, want)
|
||||
}
|
||||
// When show reports live running value (4 -> 4) while user explicitly sets cpus back to 4,
|
||||
// pendingVMSettingsChanges still emits cpus so mergePendingChanges removes stale 4 -> 8
|
||||
// without disturbing unrelated pending entries.
|
||||
liveOutcome := macosdriver.SettingsOutcome{
|
||||
Valid: true,
|
||||
Running: true,
|
||||
Before: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
|
||||
After: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
|
||||
}
|
||||
diffs := pendingVMSettingsChanges(liveOutcome, reims.SetOpts{Name: displayFixtureVM, CPUs: 4})
|
||||
got := mergePendingChanges([]PendingChange{
|
||||
{Field: "cpus", From: "4", To: "8"},
|
||||
{Field: "memory", From: "8G", To: "12G"},
|
||||
}, diffs)
|
||||
wantAfterRevert := []PendingChange{{Field: "memory", From: "8G", To: "12G"}}
|
||||
if !slices.Equal(got, wantAfterRevert) {
|
||||
t.Fatalf("merge after live-value revert = %+v, want %+v", got, wantAfterRevert)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionTransaction(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
failSidecar, failSet bool
|
||||
}{
|
||||
{name: "saved"},
|
||||
{name: "sidecar write fails", failSidecar: true},
|
||||
{name: "set fails", failSet: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, FailSet: tc.failSet}, true)
|
||||
dir := fixture().Dir
|
||||
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
|
||||
if tc.failSidecar {
|
||||
if err := os.Mkdir(filepath.Join(dir, ".reims-go-display.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
on := true
|
||||
err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on, NestedVirt: &on})
|
||||
if tc.failSidecar {
|
||||
if err == nil || len(fixture().Commands) != 0 {
|
||||
t.Fatalf("save = %v, commands = %v, want sidecar error before set", err, fixture().Commands)
|
||||
}
|
||||
return
|
||||
}
|
||||
vm := fixture()
|
||||
target, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
|
||||
if !slices.Equal(vm.Commands, []string{"set test-vm --resolution " + target}) {
|
||||
t.Fatalf("commands = %v", vm.Commands)
|
||||
}
|
||||
if nested, readErr := vmstart.ReadVMNestedVirt(dir); readErr != nil || nested.Enabled != !tc.failSet {
|
||||
t.Fatalf("nested virtualization = %+v, %v, want enabled = %t", nested, readErr, !tc.failSet)
|
||||
}
|
||||
if tc.failSet {
|
||||
if err == nil || !vm.NestedVirtBeforeSet || vm.Resolution != initial || vmstart.ReadVMDisplay(dir) != prev {
|
||||
t.Fatalf("save = %v, VM = %+v, display = %+v, want original settings", err, vm, vmstart.ReadVMDisplay(dir))
|
||||
}
|
||||
return
|
||||
}
|
||||
prev.AutoResolution = true
|
||||
if err != nil || vm.Resolution != target || vmstart.ReadVMDisplay(dir) != prev {
|
||||
t.Fatalf("save = %v, VM = %+v, display = %+v, want %s and %+v", err, vm, vmstart.ReadVMDisplay(dir), target, prev)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionWithSVGA(t *testing.T) {
|
||||
for _, graphics := range []string{"vmware-svga", "reims-vgpu"} {
|
||||
t.Run(graphics, func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, Graphics: graphics}, true)
|
||||
dir := fixture().Dir
|
||||
prev := vmstart.VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true}
|
||||
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := a.GetVMDetail(displayFixtureVM)
|
||||
if err != nil || detail.AutoResolution != (graphics == "reims-vgpu") {
|
||||
t.Fatalf("details = %+v, %v", detail, err)
|
||||
}
|
||||
on := true
|
||||
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
|
||||
var want []string
|
||||
if graphics != "vmware-svga" {
|
||||
opts.Graphics = "vmware-svga"
|
||||
want = []string{"set test-vm --graphics vmware-svga"}
|
||||
}
|
||||
if err := a.ApplyVMSettings(opts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prev.AutoResolution = false
|
||||
if vm := fixture(); vm.Graphics != "vmware-svga" || vm.Resolution != initial ||
|
||||
!slices.Equal(vm.Commands, want) || vmstart.ReadVMDisplay(dir) != prev {
|
||||
t.Fatalf("VM = %+v, display = %+v, want commands %v and display %+v", vm, vmstart.ReadVMDisplay(dir), want, prev)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionRollsBackDisplayOnLaterFailure(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
state, blockedFile string
|
||||
}{
|
||||
{"running", ".reims-go-nested-virt.json"},
|
||||
{"stopped", ".reims-go-nested-virt.json"},
|
||||
{"running", ".reims-go-guest-lang"},
|
||||
{"stopped", ".reims-go-guest-lang"},
|
||||
} {
|
||||
t.Run(tc.state+"/"+tc.blockedFile, func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: tc.state, Resolution: initial}, true)
|
||||
dir := fixture().Dir
|
||||
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
|
||||
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, tc.blockedFile), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
on := true
|
||||
opts := reims.SetOpts{Name: displayFixtureVM, Memory: "4G", AutoResolution: &on, NestedVirt: &on}
|
||||
if tc.blockedFile == ".reims-go-guest-lang" {
|
||||
opts.GuestLang = "zh-Hans:0"
|
||||
}
|
||||
if err := a.ApplyVMSettings(opts); err == nil || !strings.Contains(err.Error(), tc.blockedFile) {
|
||||
t.Fatalf("save = %v, want error writing %s", err, tc.blockedFile)
|
||||
}
|
||||
if commands := fixture().Commands; len(commands) != 0 {
|
||||
t.Fatalf("commands = %v, want no reims-ctl set call before local failures", commands)
|
||||
}
|
||||
if got := vmstart.ReadVMDisplay(dir); got != prev || len(a.pendingChanges) != 0 {
|
||||
t.Fatalf("display = %+v, want %+v; pending = %+v", got, prev, a.pendingChanges)
|
||||
}
|
||||
if raw, found := reims.ReadConfiguredResolution(dir); !found || raw != initial {
|
||||
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
|
||||
}
|
||||
if opts.GuestLang != "" {
|
||||
if nested, err := vmstart.ReadVMNestedVirt(dir); err != nil || nested.Enabled {
|
||||
t.Fatalf("nested virtualization = %+v, %v, want disabled", nested, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionSyncsExistingConfiguration(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, graphics string
|
||||
borderless bool
|
||||
}{
|
||||
{name: "windowed multi-display"},
|
||||
{name: "borderless multi-display", borderless: true},
|
||||
{name: "from SVGA", graphics: "vmware-svga"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
res, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), tc.borderless, true)
|
||||
raw := res
|
||||
want := "set test-vm --resolution " + res
|
||||
on := true
|
||||
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
|
||||
if tc.graphics == "vmware-svga" {
|
||||
opts.Graphics = "reims-vgpu"
|
||||
want = "set test-vm --graphics reims-vgpu --resolution " + res
|
||||
} else {
|
||||
raw += ",2560x1440"
|
||||
}
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
|
||||
State: "stopped", Resolution: res, Graphics: tc.graphics, Borderless: tc.borderless,
|
||||
}, true)
|
||||
dir := fixture().Dir
|
||||
if err := writeDisplayCtlResolution(dir, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.ApplyVMSettings(opts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := fixture().Commands; !slices.Equal(got, []string{want}) {
|
||||
t.Fatalf("commands = %v, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateVMWithAutoResolution(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name, graphics, resolution string
|
||||
wantAuto bool
|
||||
}{
|
||||
{name: "no draft", wantAuto: true},
|
||||
{name: "stale draft", resolution: "1234x876", wantAuto: true},
|
||||
{name: "SVGA", graphics: "vmware-svga", resolution: "1234x876"},
|
||||
{name: "SVGA without resolution", graphics: "vmware-svga"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
|
||||
if useDriver {
|
||||
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
|
||||
req := driver.CreateRequest{Name: displayFixtureVM, Options: map[string]any{"auto_resolution": true, "resolution": tc.resolution, "graphics": tc.graphics}}
|
||||
if err := d.Create(t.Context(), req, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
on := true
|
||||
if err := a.CreateVM(reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", AutoResolution: &on, Resolution: tc.resolution, Graphics: tc.graphics}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
vm := fixture()
|
||||
want := tc.resolution
|
||||
if tc.wantAuto {
|
||||
want, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
|
||||
}
|
||||
if vm.Resolution != want || vmstart.ReadVMDisplay(vm.Dir).AutoResolution != tc.wantAuto {
|
||||
t.Fatalf("created VM = %+v, want resolution %s and automatic mode %t", vm, want, tc.wantAuto)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateVMWithAutoResolutionRefreshesAfterDiskConversion(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
|
||||
source := filepath.Join(a.cfg.DataRoot, "source.raw")
|
||||
if err := os.WriteFile(source, []byte("raw disk"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connectedDisplays := func() []host.DisplayInfo {
|
||||
converted, err := filepath.Glob(filepath.Join(a.cfg.TempDir(), "import-*.qcow2"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(converted) == 0 {
|
||||
return []host.DisplayInfo{{Primary: true, Width: 3840, Height: 2160, ScalePct: 150}}
|
||||
}
|
||||
return []host.DisplayInfo{{Primary: true, Width: 3200, Height: 2000, ScalePct: 200}}
|
||||
}
|
||||
on := true
|
||||
opts := reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", Disk: source, AutoResolution: &on, Borderless: &on}
|
||||
if err := a.createVMFlow(opts, connectedDisplays); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if vm := fixture(); vm.Resolution != "3200x2000" || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
|
||||
t.Fatalf("created VM = %+v, want automatic 3200x2000", vm)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClonePreservesAutoResolution(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: "2880x1800"}, false)
|
||||
source := fixture().Dir
|
||||
if _, err := vmstart.SaveVMDisplay(source, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2", AutoResolution: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
|
||||
if err := d.CloneCoW(t.Context(), displayFixtureVM, displayFixtureClone, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := vmstart.ReadVMDisplay(fixture().CloneDir); got != (vmstart.VMDisplayConfig{AutoResolution: true}) {
|
||||
t.Fatalf("cloned display preference = %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -1,143 +1,14 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
type reviewNetworkControl struct {
|
||||
extra string
|
||||
writes int
|
||||
setErr error
|
||||
}
|
||||
|
||||
func (*reviewNetworkControl) List(context.Context) ([]reims.VMListItem, error) { return nil, nil }
|
||||
func (*reviewNetworkControl) Show(context.Context, string) (reims.VMDetail, error) {
|
||||
return reims.VMDetail{}, nil
|
||||
}
|
||||
func (*reviewNetworkControl) CommandText(context.Context, string) (string, error) {
|
||||
return "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac=02:00:00:00:00:01", nil
|
||||
}
|
||||
func (c *reviewNetworkControl) Set(_ context.Context, opts reims.SetOpts, _, _ io.Writer) error {
|
||||
if c.setErr != nil {
|
||||
return c.setErr
|
||||
}
|
||||
if opts.ExtraArgs != nil {
|
||||
c.extra = *opts.ExtraArgs
|
||||
c.writes++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestLegacyBridgeArgsHaveRemovableOwner(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
|
||||
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
control := &reviewNetworkControl{}
|
||||
a := &App{}
|
||||
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(control.extra, "id=reimsbridge0") {
|
||||
t.Fatal("隔离客户端未收到桥接参数")
|
||||
}
|
||||
ledger, err := plugin.LoadArgLedger(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ledger.Owners[builtin.IDNpcapBridge]) != 1 {
|
||||
t.Fatalf("桥接参数已写入,但 Npcap 账本条目数为 %d", len(ledger.Owners[builtin.IDNpcapBridge]))
|
||||
}
|
||||
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if control.writes != 1 {
|
||||
t.Fatalf("重复准备写入了 %d 次参数", control.writes)
|
||||
}
|
||||
if strings.Count(detail.ExtraArgs, "id=reimsbridge0,") != 1 {
|
||||
t.Fatal("重复准备产生重复桥接设备")
|
||||
}
|
||||
clean := plugin.ReconcileStartIntents(detail.ExtraArgs, ledger, map[string]bool{}, nil)
|
||||
if clean.ExtraArgs != "-cpu host" {
|
||||
t.Fatalf("停用后残留桥接参数:%s", clean.ExtraArgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyBridgeArgsStopOnInvalidRecordOrWriteFailure(t *testing.T) {
|
||||
for _, mode := range []string{"corrupt", "pending", "set failure"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
|
||||
record := reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}
|
||||
code := "E_NETWORK_CONFIG_SAVE"
|
||||
control := &reviewNetworkControl{setErr: errors.New("模拟配置写入失败")}
|
||||
if mode == "corrupt" {
|
||||
record.Version = 99
|
||||
code = "E_NETWORK_RECORD_INVALID"
|
||||
}
|
||||
if mode == "pending" {
|
||||
record.Pending = true
|
||||
code = "E_NETWORK_PACKET_PENDING"
|
||||
}
|
||||
if err := reims.SaveNetworkRecord(dir, record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := (&App{}).reconcileLegacyBridgeArgs(context.Background(), control, &detail)
|
||||
var coded *i18n.CodedError
|
||||
if !errors.As(err, &coded) || coded.Code != code {
|
||||
t.Fatalf("错误 = %v,预期 %s", err, code)
|
||||
}
|
||||
ledger, err := plugin.LoadArgLedger(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners) != 0 {
|
||||
t.Fatal("准备失败却更新了参数或归属")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyBridgeArgsClearOwnerWhenLeavingBridge(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"}
|
||||
if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := &App{}
|
||||
control := &reviewNetworkControl{}
|
||||
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail.NetworkMode = "nat"
|
||||
if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ledger, err := plugin.LoadArgLedger(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.ExtraArgs != "-cpu host" || len(ledger.Owners[builtin.IDNpcapBridge]) != 0 {
|
||||
t.Fatal("离开桥接后仍残留参数或归属")
|
||||
}
|
||||
}
|
||||
|
||||
func networkLockCount(a *App) int {
|
||||
count := 0
|
||||
a.vmNetworkLocks.Range(func(_, _ any) bool { count++; return true })
|
||||
|
||||
+88
-124
@@ -70,18 +70,19 @@ func (a *App) initPlugins() {
|
||||
return
|
||||
}
|
||||
var mgr *plugin.Manager
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: host.RedactText,
|
||||
LocaleFn: a.locale,
|
||||
var drvRouter *driver.Router
|
||||
mgr, drvRouter, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
|
||||
DataRoot: dataRoot,
|
||||
DataRootFn: func() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
},
|
||||
SafeMode: safeMode,
|
||||
LocaleFn: a.locale,
|
||||
Logger: func(source, line string) {
|
||||
a.emitLog(source, line)
|
||||
},
|
||||
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
|
||||
return driver.NewSidecarDriver(contrib, sup)
|
||||
},
|
||||
HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
a.mu.Lock()
|
||||
current := a.pluginMgr
|
||||
@@ -96,23 +97,86 @@ func (a *App) initPlugins() {
|
||||
// longer release it, so the host lifts what it left down.
|
||||
a.releaseHeldForPlugin(pluginID)
|
||||
},
|
||||
VMInventory: guest.VMInventory(),
|
||||
Callbacks: builtin.HostCallbacks{
|
||||
GetConfig: a.runtimeConfig,
|
||||
Log: func(source, line string) {
|
||||
a.emitLog(source, line)
|
||||
},
|
||||
EnsureGuestTools: func() (*guesttools.Server, int, error) {
|
||||
srv, port, created, err := a.startGuestToolsServer()
|
||||
if err == nil && created {
|
||||
// A fresh server knows no VM tokens: at startup and when the
|
||||
// plugin is switched back on, re-register configured VMs.
|
||||
go a.registerVMsWithBridge(context.Background(), srv, port)
|
||||
}
|
||||
return srv, port, err
|
||||
},
|
||||
StopGuestTools: func() {
|
||||
a.mu.Lock()
|
||||
gt := a.guestTools
|
||||
a.guestTools = nil
|
||||
a.mu.Unlock()
|
||||
if gt != nil {
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = gt.Close(shutCtx)
|
||||
cancel()
|
||||
}
|
||||
},
|
||||
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
|
||||
epoch := a.vmDeleteEpoch(name)
|
||||
// The start hook can receive a directory read before the VM was deleted.
|
||||
if epoch != 0 {
|
||||
vms, err := a.listVMsInternal(context.Background())
|
||||
if err != nil {
|
||||
return guesttools.VMConfig{}, err
|
||||
}
|
||||
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
|
||||
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
|
||||
}) {
|
||||
return guesttools.VMConfig{}, os.ErrNotExist
|
||||
}
|
||||
}
|
||||
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
|
||||
},
|
||||
OnIMEText: func(target host.IMETarget, text string) {
|
||||
go a.injectRemoteText(target.VMName, target.VMDir, text)
|
||||
},
|
||||
StartColdReboot: func(vmName, qmpAddr string) {
|
||||
a.watchWin10ColdReboot(vmName, qmpAddr)
|
||||
},
|
||||
CancelColdReboot: func(vmName string) {
|
||||
a.cancelRebootWatcher(vmName)
|
||||
},
|
||||
GuestToolsImg: func(vmName string) string {
|
||||
return a.guestToolsImagePath(vmName)
|
||||
},
|
||||
BuildGuestToolsImage: a.buildGuestToolsImage,
|
||||
OpenAppWindow: a.openAppWindow,
|
||||
PrepareVMNetwork: a.prepareManagedVMNetwork,
|
||||
RestorePacketBridges: func(ctx context.Context) func() {
|
||||
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
|
||||
if a.dataRootUsable() {
|
||||
a.registerExistingPacketBridges(ctx)
|
||||
}
|
||||
})
|
||||
},
|
||||
StopPacketBridges: a.closePacketBridges,
|
||||
OnInstallGuidesChanged: func() {
|
||||
a.emitStateChanged()
|
||||
},
|
||||
SyncInstallGuides: func() {
|
||||
a.wakePoll()
|
||||
},
|
||||
},
|
||||
RegisterGuest: guest.Register,
|
||||
})
|
||||
if err != nil {
|
||||
a.emitLog("plugin", "Plugin state warning: "+err.Error())
|
||||
if mgr == nil {
|
||||
return
|
||||
}
|
||||
a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
kindReg := rt.NewKindRegistry()
|
||||
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
}, guest.VMInventory())
|
||||
|
||||
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
|
||||
|
||||
// Drivers push the state of the VMs they host; the router merges the table
|
||||
// into what the drivers return. A spawned VM's exit wakes the poll at once.
|
||||
@@ -133,92 +197,6 @@ func (a *App) initPlugins() {
|
||||
a.emitLog("plugin:"+pluginID, title+": "+body)
|
||||
})
|
||||
|
||||
cb := builtin.HostCallbacks{
|
||||
GetConfig: a.runtimeConfig,
|
||||
Log: func(source, line string) {
|
||||
a.emitLog(source, line)
|
||||
},
|
||||
EnsureGuestTools: func() (*guesttools.Server, int, error) {
|
||||
srv, port, created, err := a.startGuestToolsServer()
|
||||
if err == nil && created {
|
||||
// A fresh server knows no VM tokens: at startup and when the
|
||||
// plugin is switched back on, re-register configured VMs.
|
||||
go a.registerVMsWithBridge(context.Background(), srv, port)
|
||||
}
|
||||
return srv, port, err
|
||||
},
|
||||
StopGuestTools: func() {
|
||||
a.mu.Lock()
|
||||
gt := a.guestTools
|
||||
a.guestTools = nil
|
||||
a.mu.Unlock()
|
||||
if gt != nil {
|
||||
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = gt.Close(shutCtx)
|
||||
cancel()
|
||||
}
|
||||
},
|
||||
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
|
||||
epoch := a.vmDeleteEpoch(name)
|
||||
// The start hook can receive a directory read before the VM was deleted.
|
||||
if epoch != 0 {
|
||||
vms, err := a.listVMsInternal(context.Background())
|
||||
if err != nil {
|
||||
return guesttools.VMConfig{}, err
|
||||
}
|
||||
if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool {
|
||||
return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir)
|
||||
}) {
|
||||
return guesttools.VMConfig{}, os.ErrNotExist
|
||||
}
|
||||
}
|
||||
return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch)
|
||||
},
|
||||
OnIMEText: func(target host.IMETarget, text string) {
|
||||
go a.injectRemoteText(target.VMName, target.VMDir, text)
|
||||
},
|
||||
StartColdReboot: func(vmName, qmpAddr string) {
|
||||
a.watchWin10ColdReboot(vmName, qmpAddr)
|
||||
},
|
||||
CancelColdReboot: func(vmName string) {
|
||||
a.cancelRebootWatcher(vmName)
|
||||
},
|
||||
GuestToolsImg: func(vmName string) string {
|
||||
return a.guestToolsImagePath(vmName)
|
||||
},
|
||||
BuildGuestToolsImage: a.buildGuestToolsImage,
|
||||
OpenAppWindow: a.openAppWindow,
|
||||
PrepareVMNetwork: a.prepareManagedVMNetwork,
|
||||
RestorePacketBridges: func(ctx context.Context) func() {
|
||||
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
|
||||
if a.dataRootUsable() {
|
||||
a.registerExistingPacketBridges(ctx)
|
||||
}
|
||||
})
|
||||
},
|
||||
StopPacketBridges: a.closePacketBridges,
|
||||
OnInstallGuidesChanged: func() {
|
||||
a.emitStateChanged()
|
||||
},
|
||||
SyncInstallGuides: func() {
|
||||
a.wakePoll()
|
||||
},
|
||||
GetSetting: func(pluginID, vmName, key string) (any, bool) {
|
||||
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
|
||||
return v, ok
|
||||
},
|
||||
}
|
||||
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
a.emitLog("plugin", "Builtin extension register error: "+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())
|
||||
}
|
||||
|
||||
// Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes.
|
||||
mgr.Registry().OnChange(func() {
|
||||
active := map[string]bool{}
|
||||
@@ -228,27 +206,19 @@ func (a *App) initPlugins() {
|
||||
stateTable.PruneDrivers(active)
|
||||
a.syncRuntimeKinds(kindReg, mgr.Registry())
|
||||
a.syncInputFilters()
|
||||
a.syncKeymapRules()
|
||||
a.syncClipboardPolicies()
|
||||
a.syncLocales()
|
||||
a.wakePoll()
|
||||
a.emitStateChanged()
|
||||
})
|
||||
|
||||
a.keymapMu.Lock()
|
||||
a.mu.Lock()
|
||||
fallback := a.fallbackInputSvc
|
||||
a.fallbackInputSvc = nil
|
||||
a.pluginMgr = mgr
|
||||
a.driverRouter = drvRouter
|
||||
a.vmStateTable = stateTable
|
||||
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
|
||||
a.runtimeKinds = kindReg
|
||||
a.mu.Unlock()
|
||||
if fallback != nil {
|
||||
fallback.Close()
|
||||
}
|
||||
a.keymapMu.Unlock()
|
||||
|
||||
fetch.SetDefaultDownloader(a.activeDownloader)
|
||||
|
||||
@@ -258,7 +228,6 @@ func (a *App) initPlugins() {
|
||||
}
|
||||
mgr.MarkBootComplete()
|
||||
a.syncInputFilters()
|
||||
a.syncKeymapRules()
|
||||
a.syncClipboardPolicies()
|
||||
a.syncLocales()
|
||||
a.startPluginControlServer()
|
||||
@@ -407,15 +376,10 @@ func (a *App) getInputService() *host.InputService {
|
||||
return nil
|
||||
}
|
||||
mgr := a.pluginMgr
|
||||
if mgr == nil {
|
||||
if a.fallbackInputSvc == nil {
|
||||
a.fallbackInputSvc = host.NewInputService(nil)
|
||||
}
|
||||
svc := a.fallbackInputSvc
|
||||
a.mu.Unlock()
|
||||
return svc
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
|
||||
if !ok {
|
||||
return nil
|
||||
|
||||
@@ -109,9 +109,6 @@ func (a *App) ResumeVM(driverID, name string) error {
|
||||
unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input")
|
||||
windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop")
|
||||
extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop)
|
||||
if unicodeInput && len(extraEnv) > 0 {
|
||||
a.syncKeymapRules()
|
||||
}
|
||||
}
|
||||
|
||||
startAt := time.Now()
|
||||
@@ -199,7 +196,6 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn
|
||||
}
|
||||
var env []string
|
||||
if unicodeInput {
|
||||
srv.SetKeymapCarrier(ref.Name, false)
|
||||
env = append(env,
|
||||
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
|
||||
"REIMS_GO_INPUT_TOKEN="+cfg.Token,
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -281,8 +282,10 @@ func (a *App) captureThumb(driverID, name, path string) (VMThumbnail, bool) {
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil {
|
||||
_ = atomicfile.Write(path, jpg, 0o644)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
log.Printf("[thumb] create cache dir failed (%s): %v", filepath.Dir(path), err)
|
||||
} else if err := atomicfile.Write(path, jpg, 0o644); err != nil {
|
||||
log.Printf("[thumb] write cache failed (%s): %v", path, err)
|
||||
}
|
||||
return VMThumbnail{
|
||||
DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg),
|
||||
|
||||
+9
-15
@@ -117,7 +117,15 @@ func (p *vmPoller) tick(ctx context.Context) {
|
||||
if ib != nil {
|
||||
ib.SetTargets(imeTargets(vms))
|
||||
}
|
||||
a.syncKeymapRules()
|
||||
if svc := a.getInputService(); svc != nil {
|
||||
var targets []host.IMETarget
|
||||
for _, vm := range vms {
|
||||
if pid := vm.RunningPID(); pid > 0 {
|
||||
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)})
|
||||
}
|
||||
}
|
||||
svc.SetTargets(targets)
|
||||
}
|
||||
a.syncFullscreenHotkeyTargets()
|
||||
if tm != nil {
|
||||
tm.UpdateTooltip(trayTooltip(loc, vms))
|
||||
@@ -410,20 +418,6 @@ func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) {
|
||||
return a.listVMsInternal(ctx)
|
||||
}
|
||||
|
||||
// polledVM looks name up in polledVMs.
|
||||
func (a *App) polledVM(name string) (driver.VMListItem, bool) {
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
return driver.VMListItem{}, false
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
return vm, true
|
||||
}
|
||||
}
|
||||
return driver.VMListItem{}, false
|
||||
}
|
||||
|
||||
func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) {
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package archtest
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestNoSilentRecover forbids bare `recover()` and `_ = recover()` statements
|
||||
// in production code so panics are never silently swallowed without logging or
|
||||
// surfacing an error.
|
||||
func TestNoSilentRecover(t *testing.T) {
|
||||
for _, s := range sources(t) {
|
||||
if s.isTest() {
|
||||
continue
|
||||
}
|
||||
ast.Inspect(s.file, func(n ast.Node) bool {
|
||||
switch stmt := n.(type) {
|
||||
case *ast.ExprStmt:
|
||||
if isRecoverCall(stmt.X) {
|
||||
pos := fileSet.Position(stmt.Pos())
|
||||
t.Errorf("%s:%d: bare recover() silently swallows panics; bind and log/report it", s.rel, pos.Line)
|
||||
}
|
||||
case *ast.AssignStmt:
|
||||
if len(stmt.Rhs) == 1 && isRecoverCall(stmt.Rhs[0]) && allBlankIdents(stmt.Lhs) {
|
||||
pos := fileSet.Position(stmt.Pos())
|
||||
t.Errorf("%s:%d: `_ = recover()` silently swallows panics; bind and log/report it", s.rel, pos.Line)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func isRecoverCall(expr ast.Expr) bool {
|
||||
call, ok := expr.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
ident, ok := call.Fun.(*ast.Ident)
|
||||
return ok && ident.Name == "recover"
|
||||
}
|
||||
|
||||
func allBlankIdents(exprs []ast.Expr) bool {
|
||||
if len(exprs) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, e := range exprs {
|
||||
id, ok := e.(*ast.Ident)
|
||||
if !ok || id.Name != "_" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// TestNoSilentFatalPersistenceDiscards guards against `_ = <call>` on critical
|
||||
// persistence/rollback primitives where dropping an error silently corrupts
|
||||
// on-disk state.
|
||||
func TestNoSilentFatalPersistenceDiscards(t *testing.T) {
|
||||
guarded := map[string]bool{
|
||||
"atomicfile.Write": true,
|
||||
"atomicfile.WriteJSON": true,
|
||||
"plugin.SaveArgLedger": true,
|
||||
}
|
||||
for _, s := range sources(t) {
|
||||
if s.isTest() {
|
||||
continue
|
||||
}
|
||||
ast.Inspect(s.file, func(n ast.Node) bool {
|
||||
assign, ok := n.(*ast.AssignStmt)
|
||||
if !ok || assign.Tok != token.ASSIGN || len(assign.Rhs) != 1 || !allBlankIdents(assign.Lhs) {
|
||||
return true
|
||||
}
|
||||
call, ok := assign.Rhs[0].(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
pkg, ok := sel.X.(*ast.Ident)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
key := pkg.Name + "." + sel.Sel.Name
|
||||
if guarded[key] {
|
||||
pos := fileSet.Position(assign.Pos())
|
||||
t.Errorf("%s:%d: discarding error from %s with `_ =` is forbidden; handle or log the error", s.rel, pos.Line, key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,6 @@ var macosImporters = map[string]macosImporter{
|
||||
"internal/app": {test: true, why: "GUI composition root tests may exercise native macOS flows"},
|
||||
"internal/datamigrate": {src: true, test: true, why: "data layout v3 invokes and verifies the macOS-owned state and ledger migration"},
|
||||
"internal/plugin/builtin": {src: true, why: "host Guest Tools bridge still uses reims argument helpers; guest registration moved to internal/macos/guest"},
|
||||
"internal/guesttools": {src: true, test: true, why: "mixed: host transport and clipboard next to the macOS guest agent image"},
|
||||
}
|
||||
|
||||
// macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go
|
||||
|
||||
+16
-36
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"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/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -22,49 +21,30 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
if err := guest.MigrateFiles(cfg.DataRoot); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: cfg.DataRoot,
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: host.RedactText,
|
||||
logf := func(source, line string) {
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
||||
}
|
||||
mgr, router, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
|
||||
DataRoot: cfg.DataRoot,
|
||||
SafeMode: safeMode,
|
||||
LocaleFn: func() i18n.Locale {
|
||||
return i18n.EffectiveLocale(cfg.Locale)
|
||||
},
|
||||
Logger: func(source, line string) {
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
||||
},
|
||||
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
|
||||
return driver.NewSidecarDriver(contrib, sup)
|
||||
Logger: logf,
|
||||
VMInventory: guest.VMInventory(),
|
||||
Callbacks: builtin.HostCallbacks{
|
||||
GetConfig: func() config.Config { return *cfg },
|
||||
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
|
||||
return nil, checkDirectMacOSNetwork(ctx, cfg, name)
|
||||
},
|
||||
Log: logf,
|
||||
},
|
||||
RegisterGuest: guest.Register,
|
||||
StrictRegister: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cb := builtin.HostCallbacks{
|
||||
GetConfig: func() config.Config { return *cfg },
|
||||
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
|
||||
return nil, checkDirectMacOSNetwork(ctx, cfg, name)
|
||||
},
|
||||
Log: func(source, line string) {
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
||||
},
|
||||
GetSetting: func(pluginID, vmName, key string) (any, bool) {
|
||||
value, ok := mgr.GetSettings(pluginID, vmName, false)[key]
|
||||
return value, ok
|
||||
},
|
||||
}
|
||||
router := driver.NewRouter(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory())
|
||||
mgr.Registry().SetInUseChecker(router.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(router.PluginBusyChecker())
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
mgr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
mgr.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
_ = mgr.LoadExternal()
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
mgr.MarkBootComplete()
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// startHandoffTimeout bounds how long `vm start` waits for the window to
|
||||
@@ -52,7 +53,7 @@ func startVM(ctx context.Context, cfg *config.Config, driverID, name string, via
|
||||
if err := requireDirectNetwork(vm); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
|
||||
_, err = svc.Start(vmstart.WithPrimaryDisplayOnly(ctx), vm.Ref(), os.Stdout, os.Stderr)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -99,7 +99,9 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time
|
||||
}
|
||||
if err := s.Run(dataRoot); err != nil {
|
||||
if res.To > res.From {
|
||||
_ = writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()})
|
||||
if serr := writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()}); serr != nil {
|
||||
return res, fmt.Errorf("data migration %q (to v%d): %w (also failed to persist partial stamp v%d: %v)", s.Name, s.To, err, res.To, serr)
|
||||
}
|
||||
}
|
||||
return res, fmt.Errorf("data migration %q (to v%d): %w", s.Name, s.To, err)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -141,6 +142,28 @@ func statePath(destPath string) string {
|
||||
return filepath.Join(filepath.Dir(destPath), "."+filepath.Base(destPath)+".reims-dl.json")
|
||||
}
|
||||
|
||||
// DiscardPartial removes the checkpoint before deleting the payload it tracks.
|
||||
func DiscardPartial(destPath string) error {
|
||||
for _, path := range []string{statePath(destPath), destPath} {
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("discard download partial: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrepareHTTPResume removes a parallel partial before a sequential client
|
||||
// treats the file's length as a contiguous download offset.
|
||||
func PrepareHTTPResume(destPath string) error {
|
||||
if _, err := os.Stat(statePath(destPath)); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("check download checkpoint: %w", err)
|
||||
}
|
||||
return DiscardPartial(destPath)
|
||||
}
|
||||
|
||||
func loadResumeState(destPath, rawURL string, destOffset, totalSize int64, chunkCount int) []bool {
|
||||
raw, err := os.ReadFile(statePath(destPath))
|
||||
if err != nil {
|
||||
@@ -166,9 +189,12 @@ func saveResumeState(destPath, rawURL string, destOffset, totalSize int64, done
|
||||
}
|
||||
raw, err := json.Marshal(st)
|
||||
if err != nil {
|
||||
log.Printf("[downloader] marshal resume state failed (%s): %v", destPath, err)
|
||||
return
|
||||
}
|
||||
_ = atomicfile.Write(statePath(destPath), raw, 0o644)
|
||||
if err := atomicfile.Write(statePath(destPath), raw, 0o644); err != nil {
|
||||
log.Printf("[downloader] save resume state failed (%s): %v", destPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Download fetches req.URL into req.DestPath (at req.DestOffset) using concurrent
|
||||
|
||||
+35
-9
@@ -8,8 +8,10 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -146,7 +148,8 @@ func resumeWithOptions(ctx context.Context, client *http.Client, url, final stri
|
||||
}
|
||||
part := final + ".part"
|
||||
|
||||
// Try the active downloader plugin first unless bypassed for security-sensitive paths.
|
||||
// Try the active downloader first unless this transfer requires the
|
||||
// caller's HTTP client (for example, plugin market downloads).
|
||||
if !opts.BypassDownloader {
|
||||
if prov := activeDownloader(); prov != nil {
|
||||
err := prov.Download(ctx, downloader.Request{
|
||||
@@ -158,23 +161,46 @@ func resumeWithOptions(ctx context.Context, client *http.Client, url, final stri
|
||||
}, func(p downloader.Progress) {
|
||||
onProgress(p.Done, p.Total)
|
||||
})
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if err == nil {
|
||||
if got, herr := FileSHA256(part); herr == nil && strings.EqualFold(got, want) {
|
||||
if rerr := os.Rename(part, final); rerr != nil {
|
||||
return "", rerr
|
||||
got, hashErr := FileSHA256(part)
|
||||
switch {
|
||||
case hashErr != nil:
|
||||
err = hashErr
|
||||
case !strings.EqualFold(got, want):
|
||||
err = fmt.Errorf("SHA256 mismatch (got %s, want %s)", got, want)
|
||||
default:
|
||||
if err := os.Rename(part, final); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return final, nil
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
// A parallel partial can contain holes. Discard its checkpoint
|
||||
// together with the file before the HTTP client starts over.
|
||||
providerErr := fmt.Errorf("download %s (%s): %w", name, prov.ID(), err)
|
||||
if err := downloader.DiscardPartial(part); err != nil {
|
||||
return "", errors.Join(providerErr, err)
|
||||
}
|
||||
// Clean up any partial multi-range file before single-stream fallback so
|
||||
// sequential append doesn't concatenate onto sparse holes.
|
||||
_ = os.Remove(part)
|
||||
log.Printf("[fetch] downloader %s failed for %s; retrying with the HTTP client", prov.ID(), name)
|
||||
path, err := resumeHTTP(ctx, client, url, final, size, want, onProgress, opts)
|
||||
if err != nil {
|
||||
return "", errors.Join(providerErr, err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
}
|
||||
return resumeHTTP(ctx, client, url, final, size, want, onProgress, opts)
|
||||
}
|
||||
|
||||
func resumeHTTP(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
|
||||
name := filepath.Base(final)
|
||||
part := final + ".part"
|
||||
if err := downloader.PrepareHTTPResume(part); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for attempt := 0; ; attempt++ {
|
||||
var have int64
|
||||
if st, err := os.Stat(part); err == nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -101,15 +102,88 @@ var timeZero = time.Time{}
|
||||
|
||||
type spyDownloader struct {
|
||||
called atomic.Int32
|
||||
run func(context.Context, downloader.Request) error
|
||||
}
|
||||
|
||||
func (s *spyDownloader) ID() string { return "test.spy" }
|
||||
|
||||
func (s *spyDownloader) Download(_ context.Context, _ downloader.Request, _ func(downloader.Progress)) error {
|
||||
func (s *spyDownloader) Download(ctx context.Context, req downloader.Request, _ func(downloader.Progress)) error {
|
||||
s.called.Add(1)
|
||||
if s.run != nil {
|
||||
return s.run(ctx, req)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestResumePreservesCanceledDownloadAndDiscardsFailedCheckpoint(t *testing.T) {
|
||||
body := []byte("verified download")
|
||||
srv := rangeServer(t, "app.exe", body, "")
|
||||
final := filepath.Join(t.TempDir(), "app.exe")
|
||||
part := final + ".part"
|
||||
checkpoint := filepath.Join(filepath.Dir(part), ".app.exe.part.reims-dl.json")
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
pluginErr := errors.New("plugin transfer failed")
|
||||
provider := &spyDownloader{run: func(_ context.Context, req downloader.Request) error {
|
||||
if req.DestPath != part || !req.Resume {
|
||||
t.Fatalf("wrong resumable destination: %+v", req)
|
||||
}
|
||||
if err := os.WriteFile(part, make([]byte, len(body)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(checkpoint, []byte("checkpoint"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel()
|
||||
return pluginErr
|
||||
}}
|
||||
SetDefaultDownloader(func() downloader.Provider { return provider })
|
||||
t.Cleanup(func() { SetDefaultDownloader(nil) })
|
||||
|
||||
if _, err := Resume(ctx, srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("canceled resume = %v, want context.Canceled", err)
|
||||
}
|
||||
for _, path := range []string{part, checkpoint} {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("canceled resume lost %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
provider.run = func(context.Context, downloader.Request) error { return pluginErr }
|
||||
path, err := Resume(t.Context(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil)
|
||||
if err != nil || path != final {
|
||||
t.Fatalf("HTTP fallback = %q, %v", path, err)
|
||||
}
|
||||
for _, path := range []string{part, checkpoint} {
|
||||
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("HTTP fallback kept %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeClearsParallelCheckpointWhenPluginIsDisabled(t *testing.T) {
|
||||
body := []byte("verified download")
|
||||
srv := rangeServer(t, "app.exe", body, "")
|
||||
final := filepath.Join(t.TempDir(), "app.exe")
|
||||
part := final + ".part"
|
||||
checkpoint := filepath.Join(filepath.Dir(part), ".app.exe.part.reims-dl.json")
|
||||
if err := os.WriteFile(part, make([]byte, len(body)/2), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(checkpoint, []byte("checkpoint"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
path, err := Resume(t.Context(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil)
|
||||
if err != nil || path != final {
|
||||
t.Fatalf("HTTP resume = %q, %v", path, err)
|
||||
}
|
||||
if _, err := os.Stat(checkpoint); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("HTTP resume kept %s: %v", checkpoint, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeDirectBypassesDownloaderAndEnforcesMaxBytesAndStall(t *testing.T) {
|
||||
spy := &spyDownloader{}
|
||||
SetDefaultDownloader(func() downloader.Provider { return spy })
|
||||
|
||||
@@ -4,7 +4,7 @@ import "testing"
|
||||
|
||||
func TestGuestAgentFileSyncControlLoop(t *testing.T) {
|
||||
agent := string(GuestAgentScript())
|
||||
state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\nkeymap_active=")
|
||||
state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\n\n")
|
||||
cleanup := scriptSection(t, agent, "\ncleanup() {", "\n\n")
|
||||
worker := scriptSection(t, agent, "\nreap_file_sync() {", "\ntext_input_loop &")
|
||||
config := scriptSection(t, agent, "\napply_host_config() {", "\nreport_status() {")
|
||||
@@ -16,7 +16,6 @@ func TestGuestAgentFileSyncControlLoop(t *testing.T) {
|
||||
})
|
||||
t.Run("cleanup_running_worker", func(t *testing.T) {
|
||||
runShareShell(t, fixture+`
|
||||
report_status() { [ "$1" = 1 ]; }
|
||||
sync_files() {
|
||||
: > "$TMP_DIR/sync-download.part"
|
||||
sleep 30 >/dev/null 2>&1 &
|
||||
@@ -36,7 +35,7 @@ child_pid=$(cat child.pid)
|
||||
command kill "$child_pid" 2>/dev/null || true
|
||||
[ "$elapsed" -lt 5 ] || fail "cleanup blocked for ${elapsed}s waiting on foreground child"
|
||||
check "$(cat reaped)" "$worker_pid" "cleanup reaped the worker"
|
||||
check "$(cat parent-cleanup)" disable "parent cleanup disabled the keymap once"
|
||||
check "$(cat parent-cleanup)" stopped "parent cleanup stopped the window reporter once"
|
||||
[ ! -f "$FILE_SYNC_DONE" ] && [ ! -f "$TMP_DIR/sync-download.part" ] ||
|
||||
fail "cleanup left files from the terminated worker"
|
||||
[ ! -f "$INJECT_LOCK" ] || fail "cleanup left the injection lock"
|
||||
@@ -58,7 +57,6 @@ REIMS_TOKEN=token
|
||||
REIMS_VM=guest
|
||||
DROP_MOUNT=./drop_mount
|
||||
mount_mode=webdav
|
||||
keymap_active=false
|
||||
sleep_active=false
|
||||
timezone_helper_ready=false
|
||||
timezone_error=
|
||||
@@ -125,7 +123,6 @@ CAFFEINATE_PID=""
|
||||
TEXT_INPUT_PID=""
|
||||
DROP_EVENTS_PID=""
|
||||
CLIPBOARD_PID=""
|
||||
keymap_applied=true
|
||||
tick=0
|
||||
: > "$INJECT_LOCK"
|
||||
: > parent-cleanup
|
||||
@@ -142,9 +139,8 @@ await_file() {
|
||||
sleep 0.05
|
||||
done
|
||||
}
|
||||
stop_window_reporter() { :; }
|
||||
stop_window_reporter() { printf 'stopped\n' >> parent-cleanup; }
|
||||
sync_window_reporter() { :; }
|
||||
apply_hidutil_carrier() { printf '%s\n' "$1" >> parent-cleanup; }
|
||||
|
||||
# Model a completed child that still answers kill -0 until wait.
|
||||
kill() {
|
||||
@@ -177,7 +173,6 @@ ensure_webdav_mount() {
|
||||
}
|
||||
ensure_drop_webdav_mount() { :; }
|
||||
curl() { printf '%s\n' '{"shared_folders_count":2}'; }
|
||||
sync_keymap_carrier() { printf '%s keymap\n' "$tick" >> config; }
|
||||
sync_drive_mounts() { printf '%s drives\n' "$tick" >> config; }
|
||||
sync_folder_mounts() { printf '%s folders=%s\n' "$tick" "$1" >> config; }
|
||||
sync_timezone() { :; }
|
||||
@@ -199,8 +194,8 @@ sleep() {
|
||||
check "$FILE_SYNC_PID" "$first_pid" "only one worker ran while the first was blocked"
|
||||
check "$(cat started)" 0 "fallback runs before the gate opens"
|
||||
check "$(cat status)" "$(printf '0\n5\n10')" "status ticks while the worker is blocked"
|
||||
check "$(cat config)" "$(printf '%s\n' '0 keymap' '0 drives' '0 folders=2' \
|
||||
'5 keymap' '5 drives' '5 folders=2' '10 keymap' '10 drives' '10 folders=2')" "host config order"
|
||||
check "$(cat config)" "$(printf '%s\n' '0 drives' '0 folders=2' \
|
||||
'5 drives' '5 folders=2' '10 drives' '10 folders=2')" "host config order"
|
||||
: > release-0
|
||||
await_file "$FILE_SYNC_DONE"
|
||||
[ ! -s parent-cleanup ] && [ -f "$INJECT_LOCK" ] || fail "worker ran parent cleanup"
|
||||
|
||||
@@ -256,8 +256,9 @@ func (s *Server) handleDropEvents(w http.ResponseWriter, r *http.Request) {
|
||||
cur.dropQueue[0] = nil
|
||||
cur.dropQueue = cur.dropQueue[1:]
|
||||
cur.dropActive[item.DropID] = item
|
||||
cur.markSeen(time.Now())
|
||||
cur.lastDropPoll = time.Now()
|
||||
now := time.Now()
|
||||
cur.lastSeen = now
|
||||
cur.lastDropPoll = now
|
||||
s.mu.Unlock()
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -2,6 +2,7 @@ package guesttools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -20,13 +21,24 @@ func TestToolsDiskImageIncludesDropResolveJS(t *testing.T) {
|
||||
if !strings.Contains(resolver, "com.apple.finder") || strings.Contains(resolver, "'Finder'") {
|
||||
t.Fatal("drop resolver must identify Finder by bundle ID")
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "tools.img")
|
||||
if err := BuildToolsDiskImage(path, VMConfig{VMName: "mac"}); err != nil {
|
||||
t.Fatal(err)
|
||||
var foundResolver bool
|
||||
for _, f := range ToolsDiskFiles(VMConfig{VMName: "mac"}) {
|
||||
if f.Name != "drop-resolve.js" {
|
||||
continue
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := io.ReadAll(rc)
|
||||
_ = rc.Close()
|
||||
if err != nil || !bytes.Contains(data, []byte(resolver)) {
|
||||
t.Fatalf("missing resolver in tools disk files: %v", err)
|
||||
}
|
||||
foundResolver = true
|
||||
}
|
||||
image, err := os.ReadFile(path)
|
||||
if err != nil || !bytes.Contains(image, []byte(resolver)) {
|
||||
t.Fatalf("missing resolver in image: %v", err)
|
||||
if !foundResolver {
|
||||
t.Fatal("missing drop-resolve.js in tools disk files")
|
||||
}
|
||||
install := string(GuestInstallScript())
|
||||
agent := string(GuestAgentScript())
|
||||
|
||||
@@ -130,7 +130,6 @@ FOLDER_MODE_DIR="$APP_DIR/folder_modes"
|
||||
FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders"
|
||||
TMP_DIR="$PWD/tmp"
|
||||
REIMS_HOST_URL=http://stub:19847
|
||||
sync_keymap_carrier() { :; }
|
||||
REIMS_TOKEN=token
|
||||
REIMS_VM=mac
|
||||
CAFFEINATE_PID=""
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
)
|
||||
|
||||
const SharedFolderAgentVersion = 9
|
||||
const KeymapAgentVersion = 10
|
||||
const TimezoneAgentVersion = 11
|
||||
const HostDNSAgentVersion = 12
|
||||
const WindowDropAgentVersion = 13
|
||||
@@ -28,7 +27,7 @@ const SharedFolderWebDAVAgentVersion = 20
|
||||
const DropNetworkVolumesAgentVersion = 21
|
||||
const StableWindowReporterAgentVersion = 22
|
||||
|
||||
const CurrentAgentVersion = StableWindowReporterAgentVersion
|
||||
const CurrentAgentVersion = 23
|
||||
|
||||
type SharedFolderConfig struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
type memClipboard struct {
|
||||
@@ -285,25 +284,26 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
|
||||
t.Fatalf("long-poll timed out instead of waking on change")
|
||||
}
|
||||
|
||||
// 5. Config & Status endpoints (prevent-sleep + mount mode).
|
||||
// 5. A version 22 agent can keep using prevent-sleep and WebDAV after a host upgrade.
|
||||
srv.SetPreventSleep("macos-tahoe", true)
|
||||
r = doReq("GET", "/v1/config", "", nil)
|
||||
var cfgResp struct {
|
||||
PreventSleep bool `json:"prevent_sleep"`
|
||||
WebDAVPath string `json:"webdav_path"`
|
||||
PreventSleep bool `json:"prevent_sleep"`
|
||||
WebDAVPath string `json:"webdav_path"`
|
||||
KeymapEnabled bool `json:"keymap_carrier_enabled"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&cfgResp)
|
||||
r.Body.Close()
|
||||
if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" {
|
||||
if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" || cfgResp.KeymapEnabled {
|
||||
t.Fatalf("unexpected /v1/config: %+v", cfgResp)
|
||||
}
|
||||
r = doReq("POST", "/v1/status", "application/json", strings.NewReader(`{"mount_mode":"webdav","sleep_active":true,"agent_version":2}`))
|
||||
r = doReq("POST", "/v1/status", "application/json", strings.NewReader(`{"mount_mode":"webdav","sleep_active":true,"agent_version":22,"keymap_active":true}`))
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 200 {
|
||||
t.Fatalf("/v1/status POST: status=%d", r.StatusCode)
|
||||
}
|
||||
st := srv.Status("macos-tahoe", 5*time.Second)
|
||||
if !st.Connected || st.MountMode != "webdav" || !st.SleepActive || st.AgentVersion != 2 {
|
||||
if !st.Connected || st.MountMode != "webdav" || !st.SleepActive || st.AgentVersion != 22 {
|
||||
t.Fatalf("unexpected status: %+v", st)
|
||||
}
|
||||
|
||||
@@ -617,16 +617,23 @@ func TestServerWebDAVAuthAndOperations(t *testing.T) {
|
||||
|
||||
func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
imgPath := filepath.Join(tmp, "reims-tools.img")
|
||||
cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847, PreventSleep: true, GuestTimezone: "Etc/GMT+8"}
|
||||
if err := BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
t.Fatalf("BuildToolsDiskImage: %v", err)
|
||||
diskFiles := map[string][]byte{}
|
||||
for _, tf := range ToolsDiskFiles(cfg) {
|
||||
rc, err := tf.Open()
|
||||
if err != nil {
|
||||
t.Fatalf("open %s: %v", tf.Name, err)
|
||||
}
|
||||
data, err := io.ReadAll(rc)
|
||||
_ = rc.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", tf.Name, err)
|
||||
}
|
||||
if int64(len(data)) != tf.Size {
|
||||
t.Fatalf("%s size mismatch: got %d, declared %d", tf.Name, len(data), tf.Size)
|
||||
}
|
||||
diskFiles[tf.Name] = data
|
||||
}
|
||||
f, err := os.Open(imgPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
for _, file := range []struct{ name, content string }{
|
||||
{"config", "REIMS_VM='macos-tahoe'\n"},
|
||||
{"guest-tools.sh", fmt.Sprintf(`\"agent_version\":%d,`, CurrentAgentVersion)},
|
||||
@@ -636,13 +643,12 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
|
||||
{"set-timezone.sh", guestTimezoneHelper},
|
||||
{"Apply-Timezone.command", guestApplyTimezone},
|
||||
} {
|
||||
offset, sz, err := installer.FindFileInHFSPlusImage(f, file.name)
|
||||
if err != nil || sz == 0 {
|
||||
t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", file.name, err, sz)
|
||||
data, ok := diskFiles[file.name]
|
||||
if !ok || len(data) == 0 {
|
||||
t.Fatalf("missing %s in REIMSTOOLS files", file.name)
|
||||
}
|
||||
data := make([]byte, sz)
|
||||
if _, err := f.ReadAt(data, offset); err != nil || !strings.Contains(string(data), file.content) {
|
||||
t.Errorf("unexpected %s contents: %v", file.name, err)
|
||||
if !strings.Contains(string(data), file.content) {
|
||||
t.Errorf("unexpected %s contents", file.name)
|
||||
}
|
||||
if file.name == "config" && strings.Contains(string(data), "REIMS_TIMEZONE=") {
|
||||
t.Error("tools image config contains a build-time timezone")
|
||||
@@ -654,13 +660,9 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
|
||||
"Disable-Host-DNS.command": guestDisableHostDNS,
|
||||
"active-window-reporter.js": guestWindowReporter,
|
||||
} {
|
||||
offset, size, err := installer.FindFileInHFSPlusImage(f, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, size)
|
||||
if _, err := f.ReadAt(got, offset); err != nil {
|
||||
t.Fatal(err)
|
||||
got, ok := diskFiles[name]
|
||||
if !ok {
|
||||
t.Fatalf("missing %s in REIMSTOOLS files", name)
|
||||
}
|
||||
if !bytes.Equal(got, bytes.ReplaceAll(script, []byte("\r\n"), []byte("\n"))) {
|
||||
t.Fatalf("unexpected content in %s on REIMSTOOLS", name)
|
||||
|
||||
+18
-108
@@ -5,12 +5,8 @@ import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
)
|
||||
|
||||
func shellSingleQuote(s string) string {
|
||||
@@ -43,13 +39,19 @@ var guestApplyHostDNS []byte
|
||||
//go:embed Disable-Host-DNS.command
|
||||
var guestDisableHostDNS []byte
|
||||
|
||||
// BuildToolsDiskImage creates a read-only HFS+ disk image ("REIMSTOOLS")
|
||||
// containing the per-VM Bearer token config, the POSIX guest agent script, and
|
||||
// installation, pmset, DNS, and timezone scripts.
|
||||
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
|
||||
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
// ToolsDiskFile describes one file to place into the read-only REIMSTOOLS
|
||||
// disk image without coupling guesttools to a specific disk-image format.
|
||||
type ToolsDiskFile struct {
|
||||
Name string
|
||||
Mode uint16
|
||||
Size int64
|
||||
Open func() (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// ToolsDiskFiles returns the files to package into the read-only REIMSTOOLS
|
||||
// image: per-VM Bearer token config, POSIX guest agent, and install/pmset/DNS/
|
||||
// timezone scripts.
|
||||
func ToolsDiskFiles(cfg VMConfig) []ToolsDiskFile {
|
||||
confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL='http://10.0.2.2:%d'\nREIMS_HOST_PORT='%d'\nREIMS_TOKEN=%s\nREIMS_VM=%s\n",
|
||||
cfg.Port, cfg.Port, shellSingleQuote(cfg.Token), shellSingleQuote(cfg.VMName)))
|
||||
agentBytes := GuestAgentScript()
|
||||
@@ -58,7 +60,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
|
||||
uninstallBytes := GuestUninstallScript()
|
||||
pmsetBytes := GuestPmsetScript()
|
||||
|
||||
files := []installer.HFSFile{
|
||||
files := []ToolsDiskFile{
|
||||
{
|
||||
Name: "config",
|
||||
Mode: 0o100600,
|
||||
@@ -119,14 +121,14 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
|
||||
} {
|
||||
// The Windows checkout may have CRLF line endings.
|
||||
data := bytes.ReplaceAll(script.data, []byte("\r\n"), []byte("\n"))
|
||||
files = append(files, installer.HFSFile{
|
||||
files = append(files, ToolsDiskFile{
|
||||
Name: script.name,
|
||||
Mode: 0o100755,
|
||||
Size: int64(len(data)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil },
|
||||
})
|
||||
}
|
||||
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
|
||||
return files
|
||||
}
|
||||
|
||||
// GuestAgentScript returns the stock-macOS POSIX shell daemon handling
|
||||
@@ -172,9 +174,7 @@ WINDOW_REPORTER_PID=""
|
||||
window_report_generation=""
|
||||
FILE_SYNC_PID=""
|
||||
FILE_SYNC_DONE="$TMP_DIR/file-sync.done"
|
||||
keymap_active="false"
|
||||
keymap_applied="false"
|
||||
` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + `
|
||||
` + guestTimezoneAgent + guestTimezoneConfig + `
|
||||
|
||||
stop_window_reporter() {
|
||||
if [ -n "${WINDOW_REPORTER_PID:-}" ]; then
|
||||
@@ -186,10 +186,6 @@ stop_window_reporter() {
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [ "$keymap_applied" = "true" ]; then
|
||||
apply_hidutil_carrier disable
|
||||
report_status 1
|
||||
fi
|
||||
if [ -n "${FILE_SYNC_PID:-}" ]; then
|
||||
if [ ! -f "$FILE_SYNC_DONE" ]; then
|
||||
pkill -P "$FILE_SYNC_PID" 2>/dev/null || true
|
||||
@@ -643,7 +639,6 @@ apply_host_config() {
|
||||
fi
|
||||
printf '%s %s\n' "$upload_files" "$archive_bytes" > "$TMP_DIR/clip_file_config.tmp" &&
|
||||
mv -f "$TMP_DIR/clip_file_config.tmp" "$TMP_DIR/clip_file_config"
|
||||
sync_keymap_carrier "$cfg_json"
|
||||
sync_drive_mounts "$cfg_json"
|
||||
folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p')
|
||||
sync_folder_mounts "${folders_count:-0}"
|
||||
@@ -696,7 +691,7 @@ report_status() {
|
||||
if curl -fsS -m "${1:-3}" -X POST \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,\"keymap_active\":$keymap_active,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale,\"drop_mount_denied\":$drop_mount_denied}" \
|
||||
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale,\"drop_mount_denied\":$drop_mount_denied}" \
|
||||
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1; then
|
||||
reported_drop_mount_denied="$drop_mount_denied"
|
||||
fi
|
||||
@@ -1740,8 +1735,6 @@ fi
|
||||
` + guestURLencode + folderMountHelpers + shareUnmountScript + `
|
||||
uid=$(id -u)
|
||||
launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
|
||||
` + guestKeymapCarrier + `
|
||||
apply_hidutil_carrier disable
|
||||
if ! unmount_reims_shares; then
|
||||
echo "Reims Guest Tools shares are busy. Close files using the shares and retry uninstalling." >&2
|
||||
exit 1
|
||||
@@ -1827,89 +1820,6 @@ urlencode() {
|
||||
}
|
||||
`
|
||||
|
||||
const guestKeymapCarrier = `
|
||||
apply_hidutil_carrier() {
|
||||
keymap_active="false"
|
||||
mappings=$(/usr/bin/hidutil property --get UserKeyMapping 2>/dev/null) || return 0
|
||||
[ -n "$mappings" ] || return 0
|
||||
plan=$(printf '%s\n' "$mappings" | LC_ALL=C awk -v mode="$1" '
|
||||
function number(value, i, n, digit) {
|
||||
if (value ~ /^[0-9]+$/) return value + 0
|
||||
if (value !~ /^0[xX][0-9a-fA-F]+$/) { invalid = 1; return 0 }
|
||||
for (i = 3; i <= length(value); i++) {
|
||||
digit = index("0123456789abcdef", tolower(substr(value, i, 1))) - 1
|
||||
n = 16 * n + digit
|
||||
}
|
||||
return n
|
||||
}
|
||||
function append(src, dst) {
|
||||
if (entries != "") entries = entries ","
|
||||
entries = entries sprintf("{\"HIDKeyboardModifierMappingSrc\":%.0f,\"HIDKeyboardModifierMappingDst\":%.0f}", src, dst)
|
||||
}
|
||||
BEGIN {
|
||||
carrier["30064771183"] = 30064771298
|
||||
carrier["30064771184"] = 30064771299
|
||||
carrier["30064771185"] = 30064771303
|
||||
carrier["30064771187"] = 30064771302
|
||||
RS = "}"
|
||||
}
|
||||
{
|
||||
n = split($0, fields, /[[:space:]=;{}(),]+/)
|
||||
have_src = have_dst = 0
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (fields[i] == "HIDKeyboardModifierMappingSrc") {
|
||||
src = number(fields[++i])
|
||||
have_src++
|
||||
} else if (fields[i] == "HIDKeyboardModifierMappingDst") {
|
||||
dst = number(fields[++i])
|
||||
have_dst++
|
||||
} else if (fields[i] != "" && fields[i] != "null" && fields[i] != "UserKeyMapping") {
|
||||
invalid = 1
|
||||
}
|
||||
}
|
||||
if (!have_src && !have_dst) next
|
||||
if (have_src != 1 || have_dst != 1) { invalid = 1; next }
|
||||
id = sprintf("%.0f", src)
|
||||
if (id in carrier) {
|
||||
found++
|
||||
if (!seen[id]++ && dst == carrier[id]) correct++
|
||||
} else {
|
||||
append(src, dst)
|
||||
}
|
||||
}
|
||||
END {
|
||||
if (invalid) exit 1
|
||||
if ((mode == "disable" && !found) || (mode == "enable" && found == 4 && correct == 4)) {
|
||||
print "unchanged"
|
||||
exit
|
||||
}
|
||||
if (mode == "enable") {
|
||||
for (src in carrier) append(src, carrier[src])
|
||||
}
|
||||
printf "{\"UserKeyMapping\":[%s]}\n", entries
|
||||
}
|
||||
') || return 0
|
||||
if [ "$plan" != "unchanged" ]; then
|
||||
/usr/bin/hidutil property --set "$plan" >/dev/null 2>&1 || return 0
|
||||
fi
|
||||
if [ "$1" = "enable" ]; then
|
||||
keymap_active="true"
|
||||
else
|
||||
keymap_carrier_clean="1"
|
||||
fi
|
||||
keymap_applied="$keymap_active"
|
||||
}
|
||||
|
||||
sync_keymap_carrier() {
|
||||
if printf '%s' "$1" | grep -q '"keymap_carrier_enabled"[[:space:]]*:[[:space:]]*true'; then
|
||||
keymap_carrier_clean="0"
|
||||
apply_hidutil_carrier enable
|
||||
elif [ "${keymap_carrier_clean:-0}" != "1" ]; then
|
||||
apply_hidutil_carrier disable
|
||||
fi
|
||||
}
|
||||
`
|
||||
|
||||
const folderMountHelpers = `
|
||||
is_drive_mounted() {
|
||||
mount 2>/dev/null | grep -F "on $1 (" >/dev/null 2>&1
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGuestAgentKeymapScript(t *testing.T) {
|
||||
sh, err := exec.LookPath("sh")
|
||||
if err != nil {
|
||||
sh = "C:/Program Files/Git/bin/sh.exe"
|
||||
if _, err := os.Stat(sh); err != nil {
|
||||
t.Skip("POSIX sh is unavailable")
|
||||
}
|
||||
}
|
||||
agent := string(GuestAgentScript())
|
||||
start := strings.Index(agent, "apply_hidutil_carrier() {")
|
||||
end := strings.Index(agent, "load_conf() {")
|
||||
if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":`+strconv.Itoa(CurrentAgentVersion)+`,\"keymap_active\":$keymap_active`) {
|
||||
t.Fatal("missing guest keymap script or current agent version in status")
|
||||
}
|
||||
for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lockShellFixture(t)
|
||||
dir := t.TempDir()
|
||||
fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil")
|
||||
fixture += "\nprintf '%s\\n' \"$1\" > state\nsync_keymap_carrier '{}'\n"
|
||||
fixture += "[ \"$keymap_carrier_clean\" = 1 ]\nrm state\nsync_keymap_carrier '{}'\n[ ! -f state ]\n"
|
||||
cmd := exec.Command(sh, "-c", fixture, "fixture", input)
|
||||
cmd.Dir = dir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("shell fixture: %v\n%s", err, out)
|
||||
}
|
||||
gets, err := os.ReadFile(filepath.Join(dir, "get.log"))
|
||||
if err != nil || strings.TrimSpace(string(gets)) != "get" {
|
||||
t.Fatalf("expected exactly one hidutil read: %q, %v", gets, err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(dir, "set.log"))
|
||||
if strings.Contains(input, "30064771184") {
|
||||
if err != nil || strings.TrimSpace(string(got)) != `{"UserKeyMapping":[]}` {
|
||||
t.Fatalf("disable output = %q, %v", got, err)
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
t.Fatalf("empty input should require no write: %q, %v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, teardown := range []string{"disable", "exit", "uninstall"} {
|
||||
t.Run(teardown, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lockShellFixture(t)
|
||||
dir := t.TempDir()
|
||||
fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") + keymapShellExercise
|
||||
if teardown == "uninstall" {
|
||||
uninstall := string(GuestUninstallScript())
|
||||
start := strings.Index(uninstall, "apply_hidutil_carrier() {")
|
||||
end := strings.Index(uninstall, "if ! unmount_reims_shares;")
|
||||
if start < 0 || end <= start {
|
||||
t.Fatal("missing uninstall carrier cleanup")
|
||||
}
|
||||
fixture += strings.ReplaceAll(uninstall[start:end], "/usr/bin/hidutil", "hidutil")
|
||||
fixture += "\ntrap - EXIT\n"
|
||||
}
|
||||
script := filepath.Join(dir, "keymap.sh")
|
||||
if err := os.WriteFile(script, []byte(fixture), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(sh, script, teardown)
|
||||
cmd.Dir = dir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("shell fixture: %v\n%s", err, out)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, "set.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("expected one enable and one removal, got %s", data)
|
||||
}
|
||||
for i, line := range lines {
|
||||
var result struct {
|
||||
Mappings []struct {
|
||||
Src uint64 `json:"HIDKeyboardModifierMappingSrc"`
|
||||
Dst uint64 `json:"HIDKeyboardModifierMappingDst"`
|
||||
} `json:"UserKeyMapping"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[uint64]uint64{0x700000039: 0x7000000E0}
|
||||
if i == 0 {
|
||||
want[0x70000006F] = 0x7000000E2
|
||||
want[0x700000070] = 0x7000000E3
|
||||
want[0x700000071] = 0x7000000E7
|
||||
want[0x700000073] = 0x7000000E6
|
||||
}
|
||||
for _, pair := range result.Mappings {
|
||||
if want[pair.Src] != pair.Dst || pair.Dst == 0 {
|
||||
t.Fatalf("unexpected pair %+v", pair)
|
||||
}
|
||||
delete(want, pair.Src)
|
||||
}
|
||||
if len(want) != 0 {
|
||||
t.Fatalf("missing mappings: %v", want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const keymapShellFixture = `set -eu
|
||||
PATH="/usr/bin:/bin:$PATH"
|
||||
CAFFEINATE_PID=
|
||||
TEXT_INPUT_PID=
|
||||
CLIPBOARD_PID=
|
||||
INJECT_LOCK=./injecting
|
||||
keymap_active=false
|
||||
keymap_applied=false
|
||||
report_status() { [ "$1" = "1" ] && [ "$keymap_active" = "false" ]; }
|
||||
hidutil() {
|
||||
case "$2" in
|
||||
--get) printf "get\n" >> get.log; cat state ;;
|
||||
--set)
|
||||
printf '%s\n' "$3" >> set.log
|
||||
printf '%s\n' "$3" | sed 's/{"UserKeyMapping":\[/(/; s/\]}$/)/; s/"HIDKeyboardModifierMappingSrc":/HIDKeyboardModifierMappingSrc = /g; s/,"HIDKeyboardModifierMappingDst":/; HIDKeyboardModifierMappingDst = /g' > state
|
||||
;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
printf '%s\n' '({' 'HIDKeyboardModifierMappingSrc = 0x700000039;' 'HIDKeyboardModifierMappingDst = 0x7000000E0;' '})' > state
|
||||
`
|
||||
|
||||
const keymapShellExercise = `
|
||||
sync_keymap_carrier '{"keymap_carrier_enabled": true}'
|
||||
[ "$keymap_active" = "true" ]
|
||||
sync_keymap_carrier '{"keymap_carrier_enabled":true}'
|
||||
[ "$keymap_active" = "true" ]
|
||||
if [ "$1" = "disable" ]; then
|
||||
sync_keymap_carrier '{"keymap_carrier_enabled":false}'
|
||||
[ "$keymap_active" = "false" ]
|
||||
fi
|
||||
`
|
||||
|
||||
func TestKeymapCarrierStatusHandshake(t *testing.T) {
|
||||
srv := NewTransportServer(nil)
|
||||
srv.RegisterVM(VMConfig{VMName: "mac", Token: "token"})
|
||||
srv.SetKeymapCarrier("mac", true)
|
||||
var statuses []bool
|
||||
srv.SetStatusChangeHandler(func(name string) {
|
||||
statuses = append(statuses, srv.Status(name, time.Minute).KeymapActive)
|
||||
})
|
||||
config := httptest.NewRequest("GET", "/v1/config", nil)
|
||||
config.Header.Set("Authorization", "Bearer token")
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleConfig(w, config)
|
||||
if !strings.Contains(w.Body.String(), `"keymap_carrier_enabled":true`) {
|
||||
t.Fatalf("guest config = %s", w.Body)
|
||||
}
|
||||
for _, body := range []string{
|
||||
`{"agent_version":9,"keymap_active":true}`,
|
||||
`{"agent_version":10,"keymap_active":true}`,
|
||||
`{"agent_version":10,"keymap_active":true}`,
|
||||
`{"agent_version":10,"keymap_active":false}`,
|
||||
} {
|
||||
req := httptest.NewRequest("POST", "/v1/status", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer token")
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleStatus(w, req)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("status = %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
if len(statuses) != 3 || statuses[0] || !statuses[1] || statuses[2] {
|
||||
t.Fatalf("callbacks = %v", statuses)
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestKeymapConfirmationFollowsGuestConnection(t *testing.T) {
|
||||
for _, agentVersion := range []int{14, CurrentAgentVersion} {
|
||||
t.Run(fmt.Sprintf("agent_%d", agentVersion), func(t *testing.T) {
|
||||
srv := NewTransportServer(nil)
|
||||
cfg := VMConfig{VMName: "mac", Token: "token", SharedDir: t.TempDir()}
|
||||
srv.RegisterVM(cfg)
|
||||
srv.SetKeymapCarrier(cfg.VMName, true)
|
||||
|
||||
request := func(handler http.HandlerFunc, method, path, body string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
w := httptest.NewRecorder()
|
||||
handler(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("%s %s: status %d: %s", method, path, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
report := func(active bool) {
|
||||
t.Helper()
|
||||
body := fmt.Sprintf(`{"mount_mode":"sync","agent_version":%d,"keymap_active":%t}`, agentVersion, active)
|
||||
request(srv.handleStatus, http.MethodPost, "/v1/status", body)
|
||||
}
|
||||
check := func(connected, active bool) {
|
||||
t.Helper()
|
||||
got := srv.Status(cfg.VMName, KeymapStatusMaxAge)
|
||||
if got.Connected != connected || got.KeymapActive != active {
|
||||
t.Fatalf("guest connected/keymap active = %t/%t, want %t/%t", got.Connected, got.KeymapActive, connected, active)
|
||||
}
|
||||
}
|
||||
|
||||
report(true)
|
||||
check(true, true)
|
||||
|
||||
// The guest can still be handling files after its last status report expires.
|
||||
srv.mu.Lock()
|
||||
vm := srv.vms[normalizeVMRegistryKey(cfg.VMName)]
|
||||
vm.lastStatus = time.Now().Add(-2 * KeymapStatusMaxAge)
|
||||
vm.lastSeen = time.Now().Add(-KeymapStatusMaxAge / 2)
|
||||
srv.mu.Unlock()
|
||||
request(srv.handleListFiles, http.MethodGet, "/v1/files", "")
|
||||
check(true, true)
|
||||
|
||||
// A resumed connection without a fresh report cannot restore the mapping.
|
||||
srv.mu.Lock()
|
||||
vm.lastSeen = time.Now().Add(-2 * KeymapStatusMaxAge)
|
||||
srv.mu.Unlock()
|
||||
check(false, false)
|
||||
request(srv.handleConfig, http.MethodGet, "/v1/config", "")
|
||||
check(true, false)
|
||||
report(true)
|
||||
check(true, true)
|
||||
report(false)
|
||||
check(true, false)
|
||||
|
||||
report(true)
|
||||
srv.SetKeymapCarrier(cfg.VMName, false)
|
||||
srv.SetKeymapCarrier(cfg.VMName, true)
|
||||
check(true, false)
|
||||
report(true)
|
||||
cfg.Token = "replacement"
|
||||
srv.RegisterVM(cfg)
|
||||
request(srv.handleConfig, http.MethodGet, "/v1/config", "")
|
||||
check(true, false)
|
||||
report(true)
|
||||
check(true, true)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,6 @@ const (
|
||||
|
||||
const bridgeProtocolVersion = 4
|
||||
|
||||
// KeymapStatusMaxAge is the maximum idle time of a confirmed keymap session.
|
||||
const KeymapStatusMaxAge = 30 * time.Second
|
||||
|
||||
// ErrGuestToolsNotConnected is returned when a guest-assisted operation
|
||||
// requires a live Guest Tools agent inside macOS.
|
||||
var ErrGuestToolsNotConnected = errors.New("guest tools not connected")
|
||||
@@ -124,7 +121,6 @@ type VMConfig struct {
|
||||
|
||||
// GuestStatus summarizes live Guest Tools connection and capability state.
|
||||
type GuestStatus struct {
|
||||
KeymapActive bool `json:"keymap_active"`
|
||||
Connected bool `json:"connected"`
|
||||
MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync"
|
||||
DropMountDenied bool `json:"drop_mount_denied"`
|
||||
@@ -259,8 +255,6 @@ type registeredVM struct {
|
||||
verifyDriveRoot func(*os.Root, string, string) error
|
||||
resolvedFolders map[string]ResolvedSharedFolder
|
||||
verifyFolderRoot func(*os.Root, ResolvedSharedFolder) error
|
||||
keymapCarrierEnabled bool
|
||||
keymapActive bool // Carrier confirmed by a status report since the last disconnect.
|
||||
lastStatus time.Time
|
||||
mountMode string
|
||||
dropMountDenied bool
|
||||
@@ -325,7 +319,6 @@ type Server struct {
|
||||
onDropAck func(vmKey, vmName string, ack DropEventAck)
|
||||
onHostDrop func(vmKey, vmName string, req HostDropRequest) (HostDropResult, error)
|
||||
onHostText func(vmKey, vmName, text string)
|
||||
onStatusChange func(vmName string)
|
||||
hostDNSConfig HostDNSConfig
|
||||
hostDNS hostDNS
|
||||
}
|
||||
@@ -584,7 +577,6 @@ func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
} else if cur.token != cfg.Token {
|
||||
cur.dropShares.revokeClipboard()
|
||||
s.clearVMClipFilesLocked(key)
|
||||
cur.keymapActive = false
|
||||
cur.windowReportGen = 0
|
||||
cur.windowReport = windowReport{}
|
||||
cur.clipboardDelivery = guestClipboardDelivery{}
|
||||
@@ -883,7 +875,6 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus {
|
||||
HostDNSActive: dnsReported && vm.hostDNSActive,
|
||||
HostDNSReported: dnsReported,
|
||||
HostDNSConfigStale: dnsReported && vm.hostDNSConfigStale,
|
||||
KeymapActive: connected && vm.keymapActive,
|
||||
Connected: connected,
|
||||
MountMode: vm.mountMode,
|
||||
DropMountDenied: freshStatus && vm.dropMountDenied,
|
||||
@@ -897,35 +888,11 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) SetKeymapCarrier(vmName string, enabled bool) {
|
||||
vmName = normalizeVMRegistryKey(vmName)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if vm := s.vms[vmName]; vm != nil && vm.keymapCarrierEnabled != enabled {
|
||||
vm.keymapCarrierEnabled = enabled
|
||||
vm.keymapActive = false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) SetStatusChangeHandler(fn func(vmName string)) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.onStatusChange = fn
|
||||
}
|
||||
|
||||
func (vm *registeredVM) markSeen(now time.Time) {
|
||||
// After a disconnected session, require the agent to confirm the mapping again.
|
||||
if now.Sub(vm.lastSeen) > KeymapStatusMaxAge {
|
||||
vm.keymapActive = false
|
||||
}
|
||||
vm.lastSeen = now
|
||||
}
|
||||
|
||||
func (s *Server) touchLastSeen(vmName string) {
|
||||
vmName = normalizeVMRegistryKey(vmName)
|
||||
s.mu.Lock()
|
||||
if vm := s.vms[vmName]; vm != nil {
|
||||
vm.markSeen(time.Now())
|
||||
vm.lastSeen = time.Now()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
@@ -956,31 +923,30 @@ func (s *Server) authenticateToken(tok string) *registeredVM {
|
||||
defer s.mu.Unlock()
|
||||
for _, vm := range s.vms {
|
||||
if len(vm.token) == len(tok) && subtle.ConstantTimeCompare([]byte(vm.token), []byte(tok)) == 1 {
|
||||
vm.markSeen(time.Now())
|
||||
vm.lastSeen = time.Now()
|
||||
// A snapshot of the plain fields only: copying *vm would copy
|
||||
// injectMu and alias the text queues. Handlers that need the
|
||||
// queues look the live VM up again by name under s.mu.
|
||||
cp := registeredVM{
|
||||
key: vm.key,
|
||||
name: vm.name,
|
||||
token: vm.token,
|
||||
regGen: vm.regGen,
|
||||
dropDAVHandler: vm.dropDAVHandler,
|
||||
sharedDir: vm.sharedDir,
|
||||
sharedRoot: vm.sharedRoot,
|
||||
preventSleep: vm.preventSleep,
|
||||
hostDNSEnabled: vm.hostDNSEnabled,
|
||||
guestTimezone: vm.guestTimezone,
|
||||
driveSharingEnabled: vm.driveSharingEnabled,
|
||||
sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots),
|
||||
driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs),
|
||||
resolvedFolders: maps.Clone(vm.resolvedFolders),
|
||||
keymapCarrierEnabled: vm.keymapCarrierEnabled,
|
||||
mountMode: vm.mountMode,
|
||||
sleepActive: vm.sleepActive,
|
||||
agentVersion: vm.agentVersion,
|
||||
lastSeen: vm.lastSeen,
|
||||
windowReportGen: vm.windowReportGen,
|
||||
key: vm.key,
|
||||
name: vm.name,
|
||||
token: vm.token,
|
||||
regGen: vm.regGen,
|
||||
dropDAVHandler: vm.dropDAVHandler,
|
||||
sharedDir: vm.sharedDir,
|
||||
sharedRoot: vm.sharedRoot,
|
||||
preventSleep: vm.preventSleep,
|
||||
hostDNSEnabled: vm.hostDNSEnabled,
|
||||
guestTimezone: vm.guestTimezone,
|
||||
driveSharingEnabled: vm.driveSharingEnabled,
|
||||
sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots),
|
||||
driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs),
|
||||
resolvedFolders: maps.Clone(vm.resolvedFolders),
|
||||
mountMode: vm.mountMode,
|
||||
sleepActive: vm.sleepActive,
|
||||
agentVersion: vm.agentVersion,
|
||||
lastSeen: vm.lastSeen,
|
||||
windowReportGen: vm.windowReportGen,
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
@@ -1013,7 +979,7 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "keymap-carrier", "drop-events", "drop-webdav", "drop-paste"}
|
||||
caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "drop-events", "drop-webdav", "drop-paste"}
|
||||
if policy := s.EffectiveClipboardPolicy(vm.key); policy.Enabled {
|
||||
if policy.allowsHostToGuestFiles() {
|
||||
caps = append(caps, "clipboard-files")
|
||||
@@ -1046,7 +1012,6 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"vm": vm.name,
|
||||
"keymap_carrier_enabled": vm.keymapCarrierEnabled,
|
||||
"window_report_generation": vm.windowReportGen,
|
||||
"prevent_sleep": vm.preventSleep,
|
||||
"webdav_drop_path": "/dav-drop/" + vm.name + "/",
|
||||
@@ -1076,7 +1041,6 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
KeymapActive bool `json:"keymap_active"`
|
||||
MountMode string `json:"mount_mode"`
|
||||
DropMountDenied bool `json:"drop_mount_denied"`
|
||||
SleepActive bool `json:"sleep_active"`
|
||||
@@ -1099,15 +1063,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
req.TimezoneApplied = ""
|
||||
}
|
||||
s.mu.Lock()
|
||||
var notify func(string)
|
||||
if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token {
|
||||
now := time.Now()
|
||||
cur.markSeen(now)
|
||||
active := cur.keymapCarrierEnabled && req.KeymapActive && req.AgentVersion >= KeymapAgentVersion
|
||||
if cur.keymapActive != active || now.Sub(cur.lastStatus) > KeymapStatusMaxAge {
|
||||
notify = s.onStatusChange
|
||||
}
|
||||
cur.keymapActive = active
|
||||
cur.lastSeen = now
|
||||
cur.lastStatus = now
|
||||
if mode != "" {
|
||||
cur.mountMode = mode
|
||||
@@ -1126,9 +1084,6 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
s.mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if notify != nil {
|
||||
notify(vm.name)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) readClipboardState(wantImage, wantFiles bool) (ClipPayload, uint32, error) {
|
||||
@@ -1574,7 +1529,7 @@ func (s *Server) handleTextInput(w http.ResponseWriter, r *http.Request) {
|
||||
item := cur.textQueue[0]
|
||||
cur.textQueue = cur.textQueue[1:]
|
||||
cur.textActive[item.id] = item
|
||||
cur.markSeen(time.Now())
|
||||
cur.lastSeen = time.Now()
|
||||
cur.lastTextPoll = time.Now()
|
||||
s.mu.Unlock()
|
||||
|
||||
|
||||
@@ -71,7 +71,6 @@ printf '#!/bin/sh\nexit 0\n' > "$TIMEZONE_HELPER"
|
||||
chmod +x "$TIMEZONE_HELPER"
|
||||
mount_mode=sync
|
||||
sleep_active=false
|
||||
keymap_active=false
|
||||
current_timezone() { printf Asia/Shanghai; }
|
||||
curl() {
|
||||
while [ "$1" != "-d" ]; do shift; done
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import "runtime"
|
||||
|
||||
// ProbeAudio returns a non-Windows stub audio report for dev/test hosts.
|
||||
func ProbeAudio() AudioInfo {
|
||||
def := "pipewire"
|
||||
if runtime.GOOS == "darwin" {
|
||||
def = "coreaudio"
|
||||
}
|
||||
return AudioInfo{
|
||||
OutputCount: 1,
|
||||
InputCount: 1,
|
||||
DefaultBackend: def,
|
||||
}
|
||||
}
|
||||
|
||||
// FreeDiskBytesAt returns (0, false) on non-Windows stubs.
|
||||
func FreeDiskBytesAt(_ string) (uint64, bool) {
|
||||
return 0, false
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
type VMCloseChoice uint8
|
||||
|
||||
const (
|
||||
VMCloseCancel VMCloseChoice = iota
|
||||
VMCloseShutdown
|
||||
VMCloseSuspend
|
||||
)
|
||||
|
||||
func ConfirmVMClose(context.Context, uintptr, string, i18n.Locale, string, bool) (VMCloseChoice, error) {
|
||||
return VMCloseCancel, errors.ErrUnsupported
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import "os/exec"
|
||||
|
||||
// HideConsole does nothing: only Windows opens console windows.
|
||||
func HideConsole(*exec.Cmd) {}
|
||||
@@ -1,11 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import "errors"
|
||||
|
||||
func probeDefenderRealtime() bool { return false }
|
||||
|
||||
func OpenWindowsSecurityExclusions() error {
|
||||
return errors.New("Windows Security is only available on Windows")
|
||||
}
|
||||
@@ -15,6 +15,8 @@ type DisplayInfo struct {
|
||||
ScalePct int `json:"scale_pct"` // Windows DPI scaling percentage, e.g. 100, 125, 150, 200
|
||||
RefreshHz int `json:"refresh_hz,omitempty"`
|
||||
Primary bool `json:"primary"`
|
||||
Left int `json:"left,omitempty"`
|
||||
Top int `json:"top,omitempty"`
|
||||
// WorkWidth and WorkHeight are the work area (the screen less the taskbar) in
|
||||
// pixels; 0 where unknown.
|
||||
WorkWidth int `json:"work_width,omitempty"`
|
||||
@@ -207,6 +209,28 @@ func RecommendDisplayPresets(primary *DisplayInfo) ([]DisplayPreset, string) {
|
||||
return out, out[rec].Resolution
|
||||
}
|
||||
|
||||
func RecommendAutoResolution(target *DisplayInfo, borderless, fixedModeSupported bool) (resolution string, hidpi bool) {
|
||||
if !borderless {
|
||||
presets, recommended := RecommendDisplayPresets(target)
|
||||
for _, preset := range presets {
|
||||
if preset.Resolution == recommended {
|
||||
return recommended, preset.HiDPI
|
||||
}
|
||||
}
|
||||
}
|
||||
if target == nil || target.Width <= 0 || target.Height <= 0 {
|
||||
return "1920x1080", false
|
||||
}
|
||||
if fixedModeSupported && target.Width >= 3200 && target.ScalePct >= 125 && target.ScalePct < 175 {
|
||||
width := max(16, (target.Width*4/3)/16*16)
|
||||
height := max(2, (target.Height*4/3)/2*2)
|
||||
if width <= 5120 && height <= 3200 && (width != target.Width || height != target.Height) {
|
||||
return fmt.Sprintf("%dx%d", width, height), true
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%dx%d", target.Width, target.Height), FullscreenStartsHiDPI(target)
|
||||
}
|
||||
|
||||
// ParseResolution parses "WxH" or "W×H" (ignoring surrounding spaces).
|
||||
func ParseResolution(raw string) (w, h int, ok bool) {
|
||||
var x rune
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
func MoveProcessWindowToDisplay(pid uint32, displayName string, borderless bool) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func MoveProcessTreeWindowToDisplay(pids []uint32, displayName string, borderless bool) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
func probeDisplays() []DisplayInfo {
|
||||
return nil
|
||||
}
|
||||
@@ -139,6 +139,38 @@ func TestRecommendDisplayPresets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecommendAutoResolution(t *testing.T) {
|
||||
uhd := &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150}
|
||||
laptop := &DisplayInfo{Width: 3200, Height: 2000, ScalePct: 200}
|
||||
wideLaptop := &DisplayInfo{Width: 3200, Height: 1800, ScalePct: 200}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
target *DisplayInfo
|
||||
borderless, fixed bool
|
||||
resolution string
|
||||
hidpi bool
|
||||
}{
|
||||
{"window 4K", uhd, false, true, "3200x1800", true},
|
||||
{"window 16:10", laptop, false, true, "2880x1800", true},
|
||||
{"window 16:9", wideLaptop, false, true, "2880x1620", true},
|
||||
{"window no screen", nil, false, true, "1920x1080", false},
|
||||
{"fullscreen supersampled", uhd, true, true, "5120x2880", true},
|
||||
{"fullscreen without fixed mode", uhd, true, false, "3840x2160", true},
|
||||
{"fullscreen 16:10 at 200%", laptop, true, true, "3200x2000", true},
|
||||
{"fullscreen no screen", nil, true, true, "1920x1080", false},
|
||||
{"fullscreen invalid size", &DisplayInfo{Width: 3200}, true, true, "1920x1080", false},
|
||||
{"fullscreen unknown scale", &DisplayInfo{Width: 3200, Height: 1800}, true, true, "3200x1800", false},
|
||||
{"fullscreen above size cap", &DisplayInfo{Width: 5120, Height: 2880, ScalePct: 150}, true, true, "5120x2880", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
res, hidpi := RecommendAutoResolution(tc.target, tc.borderless, tc.fixed)
|
||||
if res != tc.resolution || hidpi != tc.hidpi {
|
||||
t.Fatalf("recommendation = %s, HiDPI %t, want %s, HiDPI %t", res, hidpi, tc.resolution, tc.hidpi)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldUseFixedGuestMode(t *testing.T) {
|
||||
uhd := &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, WorkWidth: 3840, WorkHeight: 2088, Primary: true}
|
||||
qhd := &DisplayInfo{Width: 2560, Height: 1440, ScalePct: 125, WorkWidth: 2560, WorkHeight: 1380, Primary: true}
|
||||
|
||||
@@ -184,6 +184,8 @@ func readDisplayInfo(monitor displayMonitor) DisplayInfo {
|
||||
ScalePct: scalePct,
|
||||
RefreshHz: refresh,
|
||||
Primary: mi.Flags&monitorInfoPrimary != 0,
|
||||
Left: int(mi.Monitor.Left),
|
||||
Top: int(mi.Monitor.Top),
|
||||
WorkWidth: workW,
|
||||
WorkHeight: workH,
|
||||
}
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Drive is a disk a data folder could go on.
|
||||
type Drive struct {
|
||||
Root string `json:"root"`
|
||||
FreeGB float64 `json:"free_gb"`
|
||||
System bool `json:"system"`
|
||||
External bool `json:"external"`
|
||||
VolumeGUID string `json:"volume_guid,omitempty"`
|
||||
}
|
||||
|
||||
// ListDrives returns the home directory's volume on dev/preview hosts.
|
||||
func ListDrives() []Drive {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
free, _ := FreeGB(home)
|
||||
return []Drive{{Root: home, FreeGB: free, System: true}}
|
||||
}
|
||||
|
||||
// FreeGB is the free space on the volume holding path.
|
||||
func FreeGB(path string) (float64, bool) {
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(path, &st); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return float64(st.Bavail) * float64(st.Bsize) / (1 << 30), true
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// RunElevatedAction is only available on Windows.
|
||||
func RunElevatedAction(_ context.Context, action, _ string) (ElevationResult, error) {
|
||||
if _, ok := LookupElevationAction(action); !ok {
|
||||
return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action)
|
||||
}
|
||||
return ElevationResult{Action: action}, fmt.Errorf("elevated actions are a Windows feature (current OS: %s)", runtime.GOOS)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/i18n"
|
||||
|
||||
func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string {
|
||||
return ""
|
||||
}
|
||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user