Compare commits

...
13 Commits
Author SHA1 Message Date
NwflowerandClaude Opus 5.5 8397d15bc5 release: v0.2.2
Release Reims-Go / release (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:53:10 -07:00
NwflowerandClaude Opus 5.5 c62bf17d91 docs(roadmap): separate implemented, released and accepted; plan by user tasks
Drop version labels from milestones, add a status line per milestone, and
order follow-up work as user tasks U1-U5 with an entry bar for new features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:52:44 -07:00
NwflowerandClaude Opus 5.5 b2237997f2 feat(input): send Chinese, emoji and host-IME text into the VM
- "Send text to VM..." dialog: arbitrary Unicode goes through Guest Tools
  (clipboard paste in the guest, agent v3 /v1/text-input long poll); without
  Guest Tools only US-keyboard ASCII is typed via QMP.
- Host IME / dictation: a low-level keyboard hook (internal/host/ime_*) catches
  VK_PACKET input aimed at a running VM window, coalesces bursts and forwards
  them in order through a per-VM queue (type_flow.go).
- reims-vgpu-window bridge: new runtime patch reims-vgpu-win32-unicode-input
  enables SDL text input and posts committed text to /v1/host-text; StartVM
  passes REIMS_GO_INPUT_URL/TOKEN to the window process. This also adds the
  patch file that patches/series.txt already listed.
- Guest Tools auth returns a field snapshot instead of copying the VM entry
  (it now holds a mutex and text queues).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:52:34 -07:00
NwflowerandClaude Opus 5.5 331d0748a4 refactor(vmstart): share VM start preparation between GUI and CLI
New internal/vmstart holds the steps both front ends need: commit-memory
precheck, offline helper disk, recovery boot picker, guest-language replay,
WHPX nested-virt compatibility, and P-core pinning after start. app.go's
StartVM and the CLI's "vm start" / "vm create --start" (cmd/reims-go/start.go)
call it, replacing memcheck.go and the copies in install/opencore flows.
"vm start" now refuses a VM that is already running instead of rewriting its
OpenCore image. Guest Tools bridging and the Win10 cold-reboot watcher still
need a long-lived process and stay GUI-only (architecture.md 3.5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:51:23 -07:00
NwflowerandClaude Opus 5.5 437aceb580 refactor(frontend): call the generated Wails bindings directly
types.ts now derives from wailsjs/go/models.ts and only adds string unions and
nil-able slices; wails.ts re-exports the generated App calls and events instead
of a hand-written mirror, so a Go signature change shows up as a type error.
Unused strings are dropped. The create wizard keeps one size across steps and
lets "start after creating" be toggled on the review page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:50:41 -07:00
NwflowerandClaude Opus 5.5 d2cdb3a09a chore: drop an unused pbzx field and refresh doc pointers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:49:52 -07:00
NwflowerandClaude Opus 5.5 e195858a0e perf(qmp): take VM thumbnails as PPM instead of PNG
QEMU encodes screendumps on its main loop; on a 2880x1620 reims-vgpu console
PNG took ~820 ms against ~35 ms for PPM, stalling the guest on every refresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:49:52 -07:00
NwflowerandClaude Opus 5.5 24acc9d6ed fix(driver): read a running VM's state without the PID suffix
reims-ctl show prints "running (pid 22032)" (older builds "running, pid N"),
so every "== running" check missed running VMs: settings-applied-on-next-start
notices, guest-language disk protection and the graphics-switch guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:49:52 -07:00
NwflowerandClaude Opus 5.5 ce2a0ed813 feat(runtime): rename candidate channel to alpha and build it daily from upstream
- Runtime channel "candidate" is now "alpha"; configs, the --candidate flag
  and SetRuntimeChannel("candidate") still map to alpha.
- ListRemote follows GitHub's Link pagination so stable runtimes are not
  pushed off the first page by daily alphas.
- patches/series.txt is the single patch queue for CI and pack-runtime.ps1;
  pack-runtime takes -Patches and derives allowed changed files from the
  patches (fixes a false "undeclared change" with the coroutine patch).
- build-runtime.yml runs daily: resolves upstream HEAD, skips commits already
  released, applies the queue via apply-patch-series.ps1 (skips patches
  already upstream, stops on conflicts), gates with check-runtime-alpha.ps1,
  publishes an alpha prerelease, keeps the 7 newest alphas, and files issues
  on failure or merged patches. Stable promotion stays manual.
- AGENTS.md and runtime docs updated for the alpha channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:42:53 -07:00
Nwflower b2f7f036d8 feat(m5): add macOS prev-lang preset, disk resize/compact, audio diagnostics, and VM thumbnails
- M5.5: add pure-Go internal/opencore reader/in-place patcher for OpenCore NVRAM prev-lang:kbd with sidecar persistence, automatic replay after update-opencore/graphics changes/CoW clones, wizard/settings/CLI (--guest-lang) support
- M5.6: add stopped VM disk resize (qemu-img resize + dynamic macOS APFS expand command) and standalone qcow2 compaction (backing-file guard, free-space check, qemu-img check, atomic swap) in GUI Settings and CLI (vm resize/compact)
- M5.9: add Win32 winmm audio output/input device probing, fix reims-ctl show audio_backend parsing, expose audio backend selector (auto/dsound/none) and latency/mic diagnostics in Settings & CLI
- UI & thumbnails: add QMP screendump VM thumbnails (internal/thumb, thumbnail_flow.go), VMPage/CreateWizard layout polish, and docs/ui-audit.md
- Update docs/roadmap.md for M5.5, M5.6, and M5.9
2026-11-28 10:17:54 -07:00
NwflowerandClaude Opus 5.5 9e4bc98c7d feat(settings): rebuild VM settings as an interactive System Settings-style panel
- Merge 10 categories into 6 (General, CPU & Memory, Graphics & Displays,
  Storage & Network, Input & Audio, Advanced) with coloured nav icons
- New ui/settings.tsx primitives: row shell, switch, segmented control with
  sliding highlight, slider + number field with recommended/risky zones,
  option cards with screen-shape previews
- Host-aware CPU/memory recommendations (recommendedCPUs, memorySafeLimitGB)
- Rows explain why they are disabled (graphics while running, SSH without
  network, controller with installer attached, GPU under VMware SVGA)
- Per-row change marks and revert, per-category change counts, footer
  summary, Revert all, Ctrl+S; Save disabled with no changes
- Validation issues attach to their row and jump to its page; inline check
  for custom resolutions
- Fix duplicate resolution label/input

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:53:05 -07:00
Nwflower 8b6073b6b1 fix(patches): use 64 KiB initial commit and null checks for QEMU Win32 coroutine fibers 2026-11-28 09:40:41 -07:00
Nwflower 105ca9c88e feat(v0.2.2): add Guest Tools 2.0, WebDAV share, HiDPI presets, tray, and resource bar 2026-11-28 09:40:41 -07:00
107 changed files with 11994 additions and 1979 deletions

No files matched your search

+189 -58
View File
@@ -1,24 +1,68 @@
name: Build Portable Runtime (Candidate)
name: Build Portable Runtime (Alpha)
# Daily: build the newest steelbrain/reims-vgpu commit with the patch queue
# (patches/series.txt) and publish it as a GitHub prerelease = the alpha
# channel (portable-runtime-spec.md section 6). Never publishes stable:
# promotion needs a real-host smoke test and a person (AGENTS.md rule 6).
on:
schedule:
- cron: "23 3 * * *" # 03:23 UTC daily; skipped when upstream has not moved
workflow_dispatch:
inputs:
upstream_commit:
description: "Pinned steelbrain/reims-vgpu commit SHA"
required: true
default: "3731afd"
publish_candidate:
description: "Publish as GitHub prerelease (candidate channel only; never stable)"
description: "steelbrain/reims-vgpu commit (empty = upstream default branch HEAD)"
required: false
default: ""
publish:
description: "Publish as an alpha prerelease (never stable)"
type: boolean
default: false
default: true
permissions:
contents: write
issues: write
concurrency:
group: build-runtime
cancel-in-progress: false
env:
UPSTREAM_URL: https://github.com/steelbrain/reims-vgpu.git
KEEP_ALPHAS: "7" # unpromoted alpha prereleases kept; older ones are deleted
jobs:
build-runtime:
resolve:
runs-on: ubuntu-latest
outputs:
commit: ${{ steps.r.outputs.commit }}
skip: ${{ steps.r.outputs.skip }}
steps:
- id: r
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WANT: ${{ inputs.upstream_commit }}
run: |
set -euo pipefail
git clone -q --filter=blob:none --no-checkout "$UPSTREAM_URL" up
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
# Already published (alpha or stable) under any short-hash length?
skip=false
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
case "$commit" in "${tag#runtime-}"*) skip=true; echo "Upstream $commit is already released as $tag";; esac
done
echo "skip=$skip" >> "$GITHUB_OUTPUT"
build:
needs: resolve
if: needs.resolve.outputs.skip != 'true'
runs-on: windows-latest
timeout-minutes: 120
timeout-minutes: 150
outputs:
short: ${{ steps.patches.outputs.short }}
applied: ${{ steps.patches.outputs.applied }}
merged: ${{ steps.patches.outputs.merged }}
conflict: ${{ steps.patches.outputs.conflict }}
steps:
- uses: actions/checkout@v4
@@ -38,28 +82,47 @@ jobs:
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
- name: Checkout upstream reims-vgpu & verify patch queue
- name: Check out upstream and apply the patch queue
id: patches
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
$xdgData = Join-Path $env:RUNNER_TEMP 'xdg-data'
$xdgCache = Join-Path $env:RUNNER_TEMP 'xdg-cache'
New-Item -ItemType Directory -Force -Path $cargoHome, $xdgData, $xdgCache | Out-Null
git clone https://github.com/steelbrain/reims-vgpu.git $work
git -C $work checkout ${{ inputs.upstream_commit }}
# Verify local patches apply cleanly; fail hard on mismatch (AGENTS.md rule 4).
if (Test-Path 'patches/reims-vgpu-cargo-lock.patch') {
git -C $work apply --check (Resolve-Path 'patches/reims-vgpu-cargo-lock.patch')
git -C $work apply (Resolve-Path 'patches/reims-vgpu-cargo-lock.patch')
}
foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null }
# The runner's git defaults to core.autocrlf=true; LF patches need an LF
# checkout (upstream also rewrites CRLF files to LF, install-ctl.sh).
git config --global core.autocrlf false
git clone -q $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'clone failed' }
git -C $work checkout -q '${{ needs.resolve.outputs.commit }}'
if ($LASTEXITCODE) { throw 'checkout failed' }
git -C $work submodule update --init --depth 1 vendor/qemu
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
$short = (git -C $work rev-parse --short HEAD).Trim()
"UPSTREAM_DIR=$work" | Out-File -FilePath $env:GITHUB_ENV -Append
"SHORT_COMMIT=$short" | Out-File -FilePath $env:GITHUB_ENV -Append
"CARGO_HOME=$cargoHome" | Out-File -FilePath $env:GITHUB_ENV -Append
"XDG_DATA_HOME=$xdgData" | Out-File -FilePath $env:GITHUB_ENV -Append
"XDG_CACHE_HOME=$xdgCache" | Out-File -FilePath $env:GITHUB_ENV -Append
"short=$short" >> $env:GITHUB_OUTPUT
# Applies what applies, skips what upstream already has, stops on a
# conflict without touching the patch (AGENTS.md rule 4).
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
try {
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -ResultFile $resultFile
$ok = $LASTEXITCODE -eq 0
} finally {
if (Test-Path $resultFile) {
$r = Get-Content -Raw $resultFile | ConvertFrom-Json
"applied=$(@($r.applied) -join ',')" >> $env:GITHUB_OUTPUT
"merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT
"conflict=$($r.conflict)" >> $env:GITHUB_OUTPUT
"APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV
}
}
if (-not $ok) { throw 'patch queue does not apply' }
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
- name: Build upstream runtime in MSYS2 CLANG64
shell: msys2 {0}
@@ -67,54 +130,122 @@ jobs:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
run: |
set -euo pipefail
UPSTREAM_UNIX="$(cygpath -u "$UPSTREAM_DIR")"
WS_UNIX="$(cygpath -u "$GITHUB_WORKSPACE")"
cd "$UPSTREAM_UNIX"
# Fetch vendor/qemu at the pinned commit before applying patches.
git submodule update --init --depth 1 vendor/qemu || git submodule update --init vendor/qemu
for p in \
"$WS_UNIX/patches/qemu-whpx-win10-compat.patch" \
"$WS_UNIX/patches/qemu-whpx-win10-startup-ipis.patch" \
"$WS_UNIX/patches/qemu-whpx-nested-virt-nonfatal.patch"; do
[ -f "$p" ] || continue
git -C vendor/qemu apply --check "$p"
git -C vendor/qemu apply "$p"
done
# Run upstream's own non-interactive CLANG64 build script.
cd "$(cygpath -u "$UPSTREAM_DIR")"
# Upstream's own non-interactive CLANG64 build script.
bash scripts/install-ctl.sh --yes
- name: Package candidate runtime & source archives
- name: Package alpha runtime and source archives
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
$qemuDir = Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current'
$msys2Root = '${{ steps.msys2.outputs.msys2-location }}'
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
pwsh -File scripts/pack-runtime.ps1 `
# In-process call, so an empty list (every patch already upstream) binds
# as an empty array rather than being dropped as an empty argument.
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
& ./scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-CargoHome $env:CARGO_HOME `
-QemuDir $qemuDir `
-Msys2 $msys2Root `
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
-OutDir $outDir `
-TempRoot $env:RUNNER_TEMP `
-Channel candidate `
-IncludeNestedVirtPatch
-Channel alpha `
-Patches $applied
- name: Upload candidate artifacts
- name: Alpha entry gate
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
& ./scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:SHORT_COMMIT `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
- name: Upload alpha artifacts
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.SHORT_COMMIT }}-candidate
path: ${{ runner.temp }}/releases/*
name: reims-runtime-win-x64-${{ env.SHORT_COMMIT }}-alpha
path: |
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
${{ runner.temp }}/releases/SHA256SUMS.txt
retention-days: 14
- name: Publish candidate prerelease (never stable)
if: ${{ inputs.publish_candidate }}
- name: Publish alpha prerelease (never stable)
if: github.event_name == 'schedule' || inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
MERGED: ${{ steps.patches.outputs.merged }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$c = $env:SHORT_COMMIT
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
$notes = @"
**Alpha** runtime, built automatically from upstream [steelbrain/reims-vgpu@$c](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}).
Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6).
Local patches applied (sources and patches are in the attached source packages):
$applied$merged
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
"@
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
- name: Prune old alpha prereleases
if: github.event_name == 'schedule' || inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
$tag = "runtime-$($env:SHORT_COMMIT)"
gh release create $tag "$($env:RUNNER_TEMP)/releases/*" `
--prerelease `
--title "Portable Runtime $tag (candidate)" `
--notes "Automated candidate build from upstream $($env:SHORT_COMMIT). Must pass scripts/smoke-runtime.ps1 on a real Windows host and human review before promotion to stable."
# Only unpromoted runtime prereleases; stable releases are never touched.
$alphas = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft,createdAt | ConvertFrom-Json |
Where-Object { $_.tagName -like 'runtime-*' -and $_.isPrerelease -and -not $_.isDraft } |
Sort-Object createdAt -Descending
$alphas | Select-Object -Skip ([int]$env:KEEP_ALPHAS) | ForEach-Object {
Write-Host "Deleting old alpha $($_.tagName)"
gh release delete $_.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag
}
report:
needs: [resolve, build]
if: always() && needs.resolve.outputs.skip != 'true' && (failure() || needs.build.outputs.merged != '')
runs-on: ubuntu-latest
steps:
- env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RESULT: ${{ needs.build.result }}
COMMIT: ${{ needs.resolve.outputs.commit }}
CONFLICT: ${{ needs.build.outputs.conflict }}
MERGED: ${{ needs.build.outputs.merged }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
# One open issue per kind; later runs add a comment instead of a new issue.
file_issue() {
local title="$1" body="$2" n
n="$(gh issue list -R "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number,title -q ".[] | select(.title == \"$title\") | .number" | head -n1)"
if [ -n "$n" ]; then
gh issue comment "$n" -R "$GITHUB_REPOSITORY" --body "$body"
else
gh issue create -R "$GITHUB_REPOSITORY" --title "$title" --body "$body"
fi
}
if [ "$RESULT" != "success" ]; then
if [ -n "$CONFLICT" ]; then
why="Patch \`$CONFLICT\` neither applies to upstream \`$COMMIT\` nor is already there. Per AGENTS.md rule 4 the patch was not edited; a person decides how to rebase or retire it."
else
why="The build, packaging or alpha gate failed for upstream \`$COMMIT\`; see the log."
fi
file_issue "Runtime alpha build failed" "$why"$'\n\n'"Run: $RUN_URL"$'\n\n'"No alpha was published."
fi
if [ -n "$MERGED" ]; then
file_issue "Patch queue: patches already upstream" "Upstream \`$COMMIT\` already contains: \`$MERGED\`. They were skipped. Record the merge commit in portable-runtime-spec.md section 5, then remove them from patches/ and patches/series.txt."$'\n\n'"Run: $RUN_URL"
fi
+4 -4
View File
@@ -21,11 +21,11 @@
## 事实核验与安全规则
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时附上游 commit 与 `文件:行号`;未实测项显式标「待验证」。
2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布 Release 等操作由人确认触发。
2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布正式 Release 等操作由人确认触发。唯一例外(2026-11-28 决定):`build-runtime.yml` 每天从上游自动构建,通过 alpha 准入检查后可以自动发布为 GitHub **预发布**(`alpha` 通道),也会自动删除较旧的、未升级的 alpha 预发布。升为 `stable`(正式发布)始终由人触发。
3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。
4. **对上游的修改只走补丁队列**:不长期维护 fork。改动以补丁形式放在 `patches/`,在 `docs/portable-runtime-spec.md` 第 5 节登记,目标是清零。补丁打不上就停下报告,不要自动改补丁。向上游提 PR 由人来做。
5. **运行时包必须如实声明来源**:`manifest.json` 写清上游 commit、`vendor/qemu` commit 和全部补丁。带补丁的包不能写成「纯上游」。
6. **用户只拿 `stable` 通道**:CI 产物只进 `candidate`,经真实宿主冒烟测试并由人确认后才升级(`portable-runtime-spec.md` 第 6 节)。
6. **用户只拿 `stable` 通道**:CI 产物只进 `alpha`(2026-11-28 前叫 `candidate`),经真实宿主冒烟测试并由人确认后才升级(`portable-runtime-spec.md` 第 6 节)。
7. **配置只通过 `reims-ctl set` 写入**:不直接改 `vm.toml`,让上游的校验和 OpenCore 重建逻辑生效(`docs/shell-design.md`)。
## 开源合规边界
@@ -34,7 +34,7 @@
- 运行时组件(`qemu-system-x86_64.exe` 为 GPLv2,`reims-ctl` / `reims-vgpu` / `metal2vulkan` 为 `GPL-2.0-or-later OR LGPL-3.0-or-later`,以及 CLANG64/libva 动态库)以**独立子进程与独立运行时压缩包**形态集成。发布二进制时必须同时提供**对应源码包**(含本地补丁,只给上游链接不够)和完整许可证文本(`NOTICE.md` / `licenses/`),见 `docs/portable-runtime-spec.md` 第 7 节。
- 不打包、不托管任何 Apple 系统文件;macOS 恢复镜像一律由用户端运行 `reims-util` 直连 Apple 服务器拉取或本地导入。
- macOS 的软件许可只允许在 Apple 硬件上虚拟化。上游也处在同样的位置,但一键工具公开发布会放大风险。**是否公开发布由人决定**,在此之前 Release 保持私有。
- 2026-11-28 已决定:仓库 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go) 公开,便携运行时通过它的 GitHub Release 分发。因此每个运行时 Release **必须**附带对应源码包和许可证文本,缺一不可。新包先进 `candidate`(GitHub 预发布),经真实宿主冒烟并由人确认后才升为 `stable`。
- 2026-11-28 已决定:仓库 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go) 公开,便携运行时通过它的 GitHub Release 分发。因此每个运行时 Release **必须**附带对应源码包和许可证文本,缺一不可。新包先进 `alpha`(GitHub 预发布,由 CI 每天从上游自动构建),经真实宿主冒烟并由人确认后才升为 `stable`。
## 文档导航
@@ -43,5 +43,5 @@
- [`docs/architecture.md`](docs/architecture.md) — Go + Wails 分层架构、环境隔离、WHPX/GPU/P-Core 自动调优与控制面设计
- [`docs/shell-design.md`](docs/shell-design.md) — 外壳设计原语:配置模型与交互对齐 macOS(Virtualization.framework 与 macOS 人机界面规范)
- [`docs/ui-redesign.md`](docs/ui-redesign.md) — 前端改版方案:VM 主面板信息架构、视觉令牌、进度与日志、分阶段计划
- [`patches/`](patches/) — 对上游的补丁队列(当前只有 Win10 WHPX 兼容补丁)
- [`patches/`](patches/) — 对上游的补丁队列,清单见 `patches/README.md`
- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 里程碑与验收标准
+231 -78
View File
@@ -1,7 +1,6 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
@@ -18,7 +17,9 @@ import (
"github.com/Nwflower/reims-go/internal/i18n"
"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/version"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -57,6 +58,11 @@ type App struct {
nextWatcherID uint64
stopPoll context.CancelFunc
guestTools *guesttools.Server
imeBridge *host.IMEBridge
trayMgr *tray.Manager
allowQuit bool
lastVMs []reims.VMListItem
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
}
@@ -72,6 +78,7 @@ func NewApp() *App {
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
procSamples: make(map[string]host.ProcessSample),
}
}
@@ -79,10 +86,38 @@ func (a *App) startup(ctx context.Context) {
a.ctx = ctx
pollCtx, cancel := context.WithCancel(ctx)
a.stopPoll = cancel
a.startTray()
a.startIMEBridge()
go a.registerExistingGuestTools(pollCtx)
go a.pollVMs(pollCtx)
}
func (a *App) startIMEBridge() {
bridge, err := host.StartIMEBridge(func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
})
if err != nil {
a.emitLog("app", "Remote IME hook unavailable: "+err.Error())
return
}
a.mu.Lock()
a.imeBridge = bridge
a.mu.Unlock()
}
func (a *App) beforeClose(ctx context.Context) bool {
a.mu.Lock()
allow := a.allowQuit
toTray := a.cfg.ShouldMinimizeToTray()
hasTray := a.trayMgr != nil
a.mu.Unlock()
if !allow && toTray && hasTray {
wailsRuntime.WindowHide(ctx)
return true
}
return false
}
func (a *App) shutdown(ctx context.Context) {
if a.stopPoll != nil {
a.stopPoll()
@@ -95,7 +130,17 @@ func (a *App) shutdown(ctx context.Context) {
delete(a.rebootWatchers, name)
}
gt := a.guestTools
ib := a.imeBridge
tm := a.trayMgr
a.imeBridge = nil
a.trayMgr = nil
a.mu.Unlock()
if ib != nil {
ib.Close()
}
if tm != nil {
tm.Close()
}
if gt != nil {
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = gt.Close(shutCtx)
@@ -131,8 +176,22 @@ func (a *App) pollVMs(ctx context.Context) {
a.mu.Lock()
loc := a.cfg.Locale
autoPin := a.cfg.AutoPinPCores
a.lastVMs = append([]reims.VMListItem(nil), vms...)
tm := a.trayMgr
runningCount := 0
var b strings.Builder
var imeTargets []host.IMETarget
for _, vm := range vms {
if vm.State == "running" {
runningCount++
if vm.PID != nil && *vm.PID > 0 {
imeTargets = append(imeTargets, host.IMETarget{
VMName: vm.Name,
VMDir: vm.Dir,
PID: uint32(*vm.PID),
})
}
}
if tr, ok := a.transitions[vm.Name]; ok {
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
delete(a.transitions, vm.Name)
@@ -150,7 +209,22 @@ func (a *App) pollVMs(ctx context.Context) {
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
}
sig := b.String()
ib := a.imeBridge
a.mu.Unlock()
if ib != nil {
ib.SetTargets(imeTargets)
}
if tm != nil {
if runningCount > 0 {
if loc == i18n.ZhCN {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount))
} else {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount))
}
} else {
tm.UpdateTooltip("Reims-Go")
}
}
for _, cand := range toPin {
vmCPUs := 0
if c, cerr := a.client(); cerr == nil {
@@ -158,42 +232,7 @@ func (a *App) pollVMs(ctx context.Context) {
vmCPUs = det.CPUs
}
}
plan := host.SelectSafeAffinity(cachedHost, vmCPUs)
switch plan.Mode {
case "all":
if loc == i18n.ZhCN {
a.emitLog(cand.name, fmt.Sprintf("[CPU] 跳过绑核:虚拟机配置了 %d vCPU,超过可用安全绑定线程上限(P 核仅 %d 线程),已使用全部核心避免超售卡顿",
vmCPUs, plan.PThreads))
} else {
a.emitLog(cand.name, fmt.Sprintf("[CPU] Skipped CPU pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all host CPUs to avoid spinlock stall",
vmCPUs, plan.PThreads))
}
continue
case "non_lpe":
if err := host.PinProcessToPCores(uint32(cand.pid), plan.Mask); err == nil {
if loc == i18n.ZhCN {
a.emitLog(cand.name, fmt.Sprintf("[CPU] 虚拟机配置了 %d vCPU(超过 %d 个 P 核线程),已自动将 QEMU (PID %d) 绑定到 P+E 核(%d 核 / %d 线程,掩码 %s;仅排除 %d 个慢速 LP-E 核)",
vmCPUs, plan.PThreads, cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.LPECoreCount))
} else {
a.emitLog(cand.name, fmt.Sprintf("[CPU] VM has %d vCPUs (exceeds %d P-core threads); pinned QEMU (PID %d) to P+E cores (%d cores / %d logical CPUs, mask %s; %d slow LP-E cores excluded)",
vmCPUs, plan.PThreads, cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.LPECoreCount))
}
} else {
a.emitLog(cand.name, fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", cand.pid, err))
}
default:
if err := host.PinProcessToPCores(uint32(cand.pid), plan.Mask); err == nil {
if loc == i18n.ZhCN {
a.emitLog(cand.name, fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 %d 个 P 核(%d 个逻辑线程,掩码 %s;未占用 %d 个 E 核)",
cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.ECoreCount+cachedHost.LPECoreCount))
} else {
a.emitLog(cand.name, fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to %d P-cores (%d logical CPUs, mask %s; %d E/LP-E cores excluded)",
cand.pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, cachedHost.ECoreCount+cachedHost.LPECoreCount))
}
} else {
a.emitLog(cand.name, fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", cand.pid, err))
}
}
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
}
if sig != lastSig {
lastSig = sig
@@ -241,22 +280,6 @@ func (a *App) emitLog(source, line string) {
})
}
type logWriter struct {
emit func(string)
buf strings.Builder
}
func (w *logWriter) Write(p []byte) (int, error) {
sc := bufio.NewScanner(strings.NewReader(string(p)))
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line != "" {
w.emit(line)
}
}
return len(p), nil
}
func (a *App) GetState() AppState {
a.mu.Lock()
cfgCopy := *a.cfg
@@ -309,6 +332,7 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
}
d.RecoveryMode = isRecoveryModeActive(d)
a.populateGuestToolsDetail(&d)
a.populateGuestLangDetail(&d)
return d, nil
}
@@ -326,6 +350,100 @@ func (a *App) SetAutoPinPCores(enabled bool) error {
return config.Save("", a.cfg)
}
func (a *App) SetMinimizeToTray(enabled bool) error {
a.mu.Lock()
v := enabled
a.cfg.MinimizeToTray = &v
err := config.Save("", a.cfg)
a.mu.Unlock()
return err
}
// ShowMainWindow restores and focuses the Wails window from the system tray.
func (a *App) ShowMainWindow() {
if a.ctx == nil {
return
}
wailsRuntime.WindowUnminimise(a.ctx)
wailsRuntime.WindowShow(a.ctx)
}
// RequestClose handles the custom titlebar close button: hides to system tray
// when MinimizeToTray is enabled, or quits the application otherwise.
func (a *App) RequestClose() {
if a.ctx == nil {
return
}
a.mu.Lock()
toTray := a.cfg.ShouldMinimizeToTray()
hasTray := a.trayMgr != nil
a.mu.Unlock()
if toTray && hasTray {
wailsRuntime.WindowHide(a.ctx)
return
}
a.QuitApp()
}
// QuitApp exits Reims-Go completely (bypassing minimize-to-tray).
func (a *App) QuitApp() {
a.mu.Lock()
a.allowQuit = true
a.mu.Unlock()
if a.ctx != nil {
wailsRuntime.Quit(a.ctx)
}
}
func (a *App) startTray() {
mgr, err := tray.Start(trayIconPNG, "Reims-Go", tray.Callbacks{
OnShow: func() {
a.ShowMainWindow()
},
OnStartVM: func(name string) {
_ = a.StartVM(name)
},
OnStopVM: func(name string) {
_ = a.StopVM(name, false)
},
OnOpenSharedDir: func(name string) {
_ = a.OpenSharedFolder(name)
},
OnQuit: func() {
a.QuitApp()
},
GetSnapshot: func() tray.Snapshot {
a.mu.Lock()
loc := a.cfg.Locale
cached := append([]reims.VMListItem(nil), a.lastVMs...)
a.mu.Unlock()
if len(cached) == 0 {
if vms, err := a.listVMsInternal(context.Background()); err == nil {
cached = vms
}
}
items := make([]tray.VMItem, 0, len(cached))
for _, vm := range cached {
items = append(items, tray.VMItem{
Name: vm.Name,
Running: vm.State == "running",
})
}
return tray.Snapshot{
LocaleZh: loc == i18n.ZhCN,
VMs: items,
}
},
})
if err != nil {
a.emitLog("app", "Warning: system tray unavailable: "+err.Error())
return
}
a.mu.Lock()
a.trayMgr = mgr
a.mu.Unlock()
}
func (a *App) SetDataRoot(dir string) error {
dir = strings.TrimSpace(dir)
if dir == "" {
@@ -439,10 +557,28 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
if err != nil {
return err
}
w := &logWriter{emit: func(line string) { a.emitLog(opts.Name, line) }}
if err := c.Set(context.Background(), opts, w, w); err != nil {
a.emitLog(opts.Name, "Set error: "+err.Error())
return err
w := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) })
if reims.HasCtlSetChanges(opts) {
if err := c.Set(context.Background(), opts, w, w); err != nil {
a.emitLog(opts.Name, "Set error: "+err.Error())
return err
}
}
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
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.emitLog(opts.Name, "Guest language error: "+err.Error())
return err
}
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
// Switching graphics rebuilds opencore.qcow2; replay any saved prev-lang:kbd.
if prep, err := a.prep(opts.Name); err == nil {
prep.ReplayGuestLang(context.Background(), cur.Directory)
}
}
if cur.State == "running" {
var diffs []PendingChange
@@ -458,6 +594,29 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
if opts.GPU != "" && opts.GPU != cur.GPU {
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
}
if opts.Displays > 0 && opts.Displays != cur.Displays {
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
}
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
}
if opts.Audio != nil && *opts.Audio != cur.Audio {
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
}
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
from := cur.AudioBackend
if from == "" {
from = "auto"
}
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
}
if guestLangChanged {
from := cur.GuestLang
if from == "" {
from = "en-US:0"
}
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[opts.Name] = append(a.pendingChanges[opts.Name], diffs...)
@@ -469,13 +628,6 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
return nil
}
func (a *App) needsColdRebootWorkaround() bool {
a.mu.Lock()
root := a.cfg.DataRoot
a.mu.Unlock()
return host.Inspect(root).NeedsColdRebootWorkaround
}
func (a *App) cancelRebootWatcher(name string) {
a.mu.Lock()
if entry, ok := a.rebootWatchers[name]; ok {
@@ -565,27 +717,28 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}
func (a *App) StartVM(name string) error {
c, err := a.client()
prep, err := a.prep(name)
if err != nil {
return err
}
if err := a.checkStartMemory(c, name); err != nil {
a.emitLog(name, "Start refused: "+err.Error())
return err
}
a.cancelRebootWatcher(name)
c := prep.Client
a.mu.Lock()
root := a.cfg.DataRoot
tmpDir := a.cfg.TempDir()
a.mu.Unlock()
rep := host.Inspect(root)
curDetail, _ := c.Show(context.Background(), name)
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
a.emitLog(name, "Start refused: "+err.Error())
return err
}
a.cancelRebootWatcher(name)
a.syncOfflineHelper(c, name, &curDetail)
a.syncGuestTools(c, name, &curDetail)
a.syncRecoveryBootPicker(c, name, &curDetail)
a.applyProbedWHPXCompat(c, name, rep, &curDetail)
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
c.Env = append(c.Env, env...)
}
prep.Prepare(context.Background(), name, rep, &curDetail)
var qmpAddr string
if rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
@@ -608,7 +761,7 @@ func (a *App) StartVM(name string) error {
startAt := time.Now()
a.emitStartSummary(name, curDetail, rep, qmpAddr)
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, "Starting "+name+"...")
if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
a.emitLog(name, msg)
@@ -640,7 +793,7 @@ func (a *App) StopVM(name string, force bool) error {
a.mu.Unlock()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
if force {
err = c.StopForce(context.Background(), name, w, w)
@@ -673,7 +826,7 @@ func (a *App) EjectInstaller(name string) error {
if err != nil {
return err
}
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, "Ejecting installer from "+name+"...")
if err := c.Eject(context.Background(), name, w, w); err != nil {
a.emitLog(name, "Eject error: "+err.Error())
@@ -691,7 +844,7 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
}
a.cancelRebootWatcher(name)
stopVMMonitor(name)
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
a.emitLog(name, "Delete error: "+err.Error())
+13 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -77,7 +78,7 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
return fmt.Errorf("CoW overlay file already exists: %s", overlayPath)
}
w := &logWriter{emit: func(line string) { a.emitLog(cloneName, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
env := rt.BuildChildEnv(&cfgCopy, *active)
a.emitLog(cloneName, fmt.Sprintf("Creating CoW overlay for %s backed by %s...", cloneName, filepath.Base(srcDisk)))
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, w, w); err != nil {
@@ -115,6 +116,17 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
}
}
if src.GuestLang != "" {
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
prep, lerr := a.prep(cloneName)
if lerr == nil {
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
}
if lerr != nil {
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
}
}
}
a.emitLog(cloneName, fmt.Sprintf("CoW clone %s ready (backing image %s untouched)", cloneName, srcDisk))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
+119 -28
View File
@@ -15,9 +15,11 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func main() {
@@ -84,7 +86,7 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
fmt.Println("\n命令:")
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--candidate 含候选版)")
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)")
fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)")
fmt.Println(" runtime install <archive> 导入并校验本地运行时包(.tar.zst 或 .zip)")
fmt.Println(" runtime list 查看已安装的便携运行时版本")
@@ -92,6 +94,8 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" vm list 列出已创建的虚拟机")
fmt.Println(" vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)")
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
fmt.Println(" vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)")
fmt.Println(" vm compact <name> 停机回收 .qcow2 磁盘未用空间")
fmt.Println(" vm start|stop|eject <name> 启动 / 停止 / 弹出安装盘")
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
@@ -106,7 +110,7 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
fmt.Println("\nCommands:")
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
fmt.Println(" runtime available List runtimes published on GitHub (--candidate includes candidates)")
fmt.Println(" runtime available List runtimes published on GitHub (--alpha includes alpha builds)")
fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)")
fmt.Println(" runtime install <archive> Verify and install a local runtime package (.tar.zst or .zip)")
fmt.Println(" runtime list List installed portable runtimes")
@@ -114,6 +118,8 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" vm list List virtual machines")
fmt.Println(" vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)")
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
fmt.Println(" vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)")
fmt.Println(" vm compact <name> Compact stopped .qcow2 disk to reclaim unused space")
fmt.Println(" vm start|stop|eject <name> Start / stop / eject installer")
fmt.Println(" vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)")
fmt.Println(" installer list List offline macOS installers Apple offers (needs network)")
@@ -257,11 +263,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
}
active, err := rt.ResolveActive(cfg)
prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
if err != nil {
return fmt.Errorf("%s", i18n.T(loc, "err.runtime_not_installed"))
return err
}
client := reims.NewClient(cfg, *active)
client, active := prep.Client, &prep.Runtime
ctx := context.Background()
switch args[0] {
@@ -287,6 +293,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
guestLang := fs.String("guest-lang", opencore.DefaultGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
start := fs.Bool("start", false, "Start VM immediately after creation")
if err := fs.Parse(args[1:]); err != nil {
return err
@@ -297,16 +304,17 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
name := fs.Arg(0)
startAfterCreate := *start
opts := reims.CreateOpts{
Name: name,
Dir: *dir,
MacOS: *macos,
CPUs: *cpus,
Memory: *mem,
DiskSize: *diskSize,
GPU: *gpu,
Capture: capture,
Logs: logs,
Start: false,
Name: name,
Dir: *dir,
MacOS: *macos,
CPUs: *cpus,
Memory: *mem,
DiskSize: *diskSize,
GPU: *gpu,
Capture: capture,
Logs: logs,
GuestLang: strings.TrimSpace(*guestLang),
Start: false,
}
existingVMs, _ := client.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
@@ -325,10 +333,19 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", serr)
}
}
if opts.GuestLang != "" {
vmDir := opts.Dir
if d, serr := client.Show(ctx, name); serr == nil && d.Directory != "" {
vmDir = d.Directory
} else if vmDir == "" {
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", name)
}
if lerr := prep.ApplyGuestLang(ctx, vmDir, opts.GuestLang, false); lerr != nil {
fmt.Fprintf(os.Stderr, "Warning: could not apply macOS language (%s): %v\n", opts.GuestLang, lerr)
}
}
if startAfterCreate {
if err := client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
fmt.Fprintln(os.Stderr, msg)
}); err != nil {
if err := startVM(ctx, cfg, prep, name); err != nil {
return err
}
}
@@ -343,26 +360,43 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
mem := fs.String("memory", "", "RAM size")
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm set [flags] <name>")
}
return client.Set(ctx, reims.SetOpts{
Name: fs.Arg(0),
CPUs: *cpus,
Memory: *mem,
GPU: *gpu,
Resolution: *res,
}, os.Stdout, os.Stderr)
setOpts := reims.SetOpts{
Name: fs.Arg(0),
CPUs: *cpus,
Memory: *mem,
GPU: *gpu,
Resolution: *res,
AudioBackend: strings.TrimSpace(*audioBackend),
GuestLang: strings.TrimSpace(*guestLang),
}
if reims.HasCtlSetChanges(setOpts) {
if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil {
return err
}
}
if setOpts.GuestLang != "" {
d, err := client.Show(ctx, setOpts.Name)
if err != nil {
return err
}
if err := prep.ApplyGuestLang(ctx, d.Directory, setOpts.GuestLang, d.State == "running"); err != nil {
return err
}
}
return nil
case "start":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm start <name>")
}
return client.StartWithCompat(ctx, args[1], os.Stdout, os.Stderr, func(msg string) {
fmt.Fprintln(os.Stderr, msg)
})
return startVM(ctx, cfg, prep, args[1])
case "stop":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm stop <name>")
@@ -396,7 +430,64 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
}
fmt.Println(i18n.T(loc, "vm.typed", n))
return nil
case "resize":
if len(args) < 3 {
return fmt.Errorf("usage: reims-go vm resize <name> <size> (e.g. 256G or +64G)")
}
d, err := client.Show(ctx, args[1])
if err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("stop %s before resizing its disk", args[1])
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("%s: expanded disk %.0f GB -> %.0f GB\nRun inside macOS Terminal to expand APFS:\n %s\n",
args[1], float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd)
return nil
case "compact":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm compact <name>")
}
d, err := client.Show(ctx, args[1])
if err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("stop %s before compacting its disk", args[1])
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("%s: compacted disk %.2f GB -> %.2f GB (reclaimed %.2f GB)\n",
args[1], float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30))
return nil
default:
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
}
}
func resolveCLIDiskPath(d reims.VMDetail) string {
raw := strings.TrimSpace(d.Disk)
if idx := strings.Index(raw, " ("); idx > 0 {
raw = strings.TrimSpace(raw[:idx])
}
if raw != "" {
if filepath.IsAbs(raw) {
return raw
}
if d.Directory != "" {
return filepath.Join(d.Directory, raw)
}
}
if d.Directory != "" {
return filepath.Join(d.Directory, "disk.qcow2")
}
return ""
}
+15 -7
View File
@@ -14,14 +14,14 @@ import (
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// runtime available [--candidate]: published runtimes on GitHub Releases.
// runtime available [--alpha]: published runtimes on GitHub Releases.
func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("runtime available", flag.ContinueOnError)
candidate := fs.Bool("candidate", cfg.RuntimeChannel == rt.ChannelCandidate, "Include candidate runtimes")
alpha := alphaFlag(fs, cfg, "Include alpha runtimes")
if err := fs.Parse(flagsFirst(args)); err != nil {
return err
}
list, err := rt.DefaultSource().ListRemote(context.Background(), *candidate)
list, err := rt.DefaultSource().ListRemote(context.Background(), *alpha)
if err != nil {
return err
}
@@ -44,10 +44,10 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
return nil
}
// runtime fetch [commit|latest] [--candidate]: download, verify, install, activate.
// runtime fetch [commit|latest] [--alpha]: download, verify, install, activate.
func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError)
candidate := fs.Bool("candidate", cfg.RuntimeChannel == rt.ChannelCandidate, "Allow candidate runtimes for \"latest\"")
alpha := alphaFlag(fs, cfg, "Allow alpha runtimes for \"latest\"")
if err := fs.Parse(flagsFirst(args)); err != nil {
return err
}
@@ -57,7 +57,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
src := rt.DefaultSource()
list, err := src.ListRemote(ctx, *candidate || explicit)
list, err := src.ListRemote(ctx, *alpha || explicit)
if err != nil {
return err
}
@@ -98,8 +98,16 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
return nil
}
// alphaFlag registers --alpha, defaulting to the configured channel, and
// --candidate as an alias for scripts written before the rename.
func alphaFlag(fs *flag.FlagSet, cfg *config.Config, usage string) *bool {
v := fs.Bool("alpha", rt.NormalizeChannel(cfg.RuntimeChannel) == rt.ChannelAlpha, usage)
fs.BoolVar(v, "candidate", *v, "Deprecated alias of --alpha")
return v
}
// flagsFirst moves "-x" arguments before positional ones, so
// "fetch latest --candidate" works like "fetch --candidate latest" (the flag
// "fetch latest --alpha" works like "fetch --alpha latest" (the flag
// package stops at the first positional argument).
func flagsFirst(args []string) []string {
var flags, rest []string
+49
View File
@@ -0,0 +1,49 @@
package main
import (
"context"
"fmt"
"os"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// startVM runs the same checks and preparation as the GUI's StartVM
// (internal/vmstart), then pins QEMU to P-cores once it runs. Guest Tools and
// the Win10 cold-reboot watcher are left out: both need the GUI process to
// keep running after the VM starts.
func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
rep := host.Inspect(cfg.DataRoot)
d, err := prep.Client.Show(ctx, name)
if err != nil {
return err
}
if d.State == "running" {
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
return fmt.Errorf("%s is already running", name)
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
return err
}
prep.Prepare(ctx, name, rep, &d)
if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
fmt.Fprintln(os.Stderr, msg)
}); err != nil {
return err
}
if !cfg.AutoPinPCores || !rep.HasHybridCores || rep.PCoreMask == 0 {
return nil
}
vms, err := prep.Client.List(ctx)
if err != nil {
return nil
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
fmt.Fprintln(os.Stderr, vmstart.PinQEMU(cfg.Locale, rep, *vm.PID, d.CPUs))
}
}
return nil
}
+20
View File
@@ -11,6 +11,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -101,6 +102,25 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
}
}
guestLang := strings.TrimSpace(opts.GuestLang)
if guestLang == "" && opts.SourceMode != "disk" {
guestLang = opencore.DefaultGuestLang(cfgCopy.Locale)
}
if guestLang != "" {
vmDir := strings.TrimSpace(opts.Dir)
if d, serr := c.Show(ctx, opts.Name); serr == nil && d.Directory != "" {
vmDir = d.Directory
} else if vmDir == "" {
vmDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
}
prep, lerr := a.prep(opts.Name)
if lerr == nil {
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
}
if lerr != nil {
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
}
}
finishTask(nil)
a.emitLog(opts.Name, "VM "+opts.Name+" ready.")
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
+107
View File
@@ -0,0 +1,107 @@
package main
import (
"context"
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// ResizeVMDisk expands a stopped VM's virtual disk via `qemu-img resize` and
// returns the macOS `diskutil` command needed to grow the APFS container inside
// the guest.
func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return reims.DiskResizeResult{}, err
}
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
if err != nil {
return reims.DiskResizeResult{}, err
}
if a.isVMRunning(ctx, c, name, d) {
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
}
taskCtx, cancel := context.WithCancel(ctx)
defer cancel()
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", name, cancel)
a.emitLog(name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
env := rt.BuildChildEnv(&cfgCopy, *active)
res, err := reims.ResizeDisk(taskCtx, active.QemuImgPath(), env, diskPath, newSize, w, w)
if err != nil {
finishTask(err)
a.emitLog(name, "Disk resize error: "+err.Error())
return reims.DiskResizeResult{}, err
}
finishTask(nil)
a.emitLog(name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB (run diskutil inside macOS to expand APFS)",
name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return res, nil
}
// CompactVMDisk rewrites a stopped VM's standalone qcow2 image into a freshly
// compacted sparse qcow2 file to reclaim unused/TRIMmed host disk space.
func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return reims.DiskCompactResult{}, err
}
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
if err != nil {
return reims.DiskCompactResult{}, err
}
if a.isVMRunning(ctx, c, name, d) {
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
}
taskCtx, cancel := context.WithCancel(ctx)
defer cancel()
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", name, cancel)
a.emitLog(name, fmt.Sprintf("Compacting qcow2 disk for %s to reclaim unused space...", name))
env := rt.BuildChildEnv(&cfgCopy, *active)
res, err := reims.CompactDisk(taskCtx, active.QemuImgPath(), env, diskPath, w, w)
if err != nil {
finishTask(err)
a.emitLog(name, "Disk compact error: "+err.Error())
return reims.DiskCompactResult{}, err
}
finishTask(nil)
a.emitLog(name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)",
name,
float64(res.BeforeBytes)/float64(1<<30),
float64(res.AfterBytes)/float64(1<<30),
float64(res.ReclaimedBytes)/float64(1<<30)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return res, nil
}
+27 -16
View File
@@ -10,7 +10,6 @@
4. **C 盘零污染**:所有运行时、下载缓存、VM 磁盘与快照严格留在用户选定的 `<DataRoot>` 下。
5. **Day-1 中英双语(`zh-CN` / `en-US`)**:前端界面、装机引导文案(默认贴合简体中文 macOS 恢复与安装界面术语,如「磁盘工具 → 抹掉为 APFS → 重新安装 macOS」)与 CLI 输出从第一天即内置双语字典,自动跟随系统语言并支持在界面顶部实时切换(持久化到 `reims-go.json`)。
6. **跨平台开发友好**:虽然宿主机运行目标优先面向 Windows x86-64(WHPX),但所有 Windows 原生 API(`WinHvPlatform.dll`、注册表 Vulkan ICD、`GetLogicalProcessorInformationEx`、进程亲和性)严格隔离在 `*_windows.go` 构建标签中,提供 `*_other.go` 桩实现,确保在中文 macOS 开发环境上也能直接进行前端开发、`go build` 与 `go test ./...`。
7. **面向未来扩展**:驱动层抽象出 `Engine` 接口,当前实现 `reims`(macOS x86-64 WHPX),预留扩展位以对接后续 `vphone`(iOS)或远程宿主模式。
## 2. 总体分层架构
@@ -18,15 +17,15 @@
flowchart TB
subgraph UI["交互层"]
GUI["Wails 桌面界面\n(React / Vite + WebView2)"]
CLI["CLI 子命令\n(reims-go doctor/runtime/vm/clone/exec)"]
CLI["CLI 子命令\n(reims-go doctor/runtime/installer/vm)"]
end
subgraph Core["Go 核心服务层 (internal/)"]
Preflight["host/ 环境体检与调优\n(WHPX检测与一键提权、提交内存预检、\nVulkan ICD扫描、P/E核亲和性绑核)"]
RuntimeMgr["runtime/ 便携运行时管理\n(Release拉取、SHA256校验、\n原子解压、版本切换与回滚)"]
InstallerMgr["installer/ 离线安装包下载管理\n(reims-util --json 宿主机直连下载、\n断点续传、版本目录与缓存清理)"]
VMMgr["vm/ 生命周期与工作流\n(向导创建、日志流、eject、\nGolden Image、CoW 派生与快照)"]
Control["control/ 带外控制\n(独立QMP客户端、SSH执行、\n截屏与状态监控)"]
VMMgr["driver/reims 与 App 编排\n(创建、启停、eject、日志流、\nCoW 派生、磁盘扩容与回收)"]
Control["qmp/ guesttools/ opencore/\n(QMP 键入与截屏、冷重启监视、\n剪贴板与共享目录、客体语言)"]
end
subgraph External["外部运行时(独立子进程,全部在 DataRoot 下)"]
@@ -60,18 +59,17 @@ flowchart TB
### 3.2 `internal/runtime` — 便携运行时管理
- 维护 `<DataRoot>\runtimes\` 下的多版本便携运行时包:
- **可选 CDN / 镜像端点 + 环境自动探测**:支持配置多下载端点(`GitHub 官方`、可选国内加速镜像或用户自定义镜像前缀)及「导入本地 `.tar.zst` 包」离线安装;拉取前对已启用端点并行发轻量 `HEAD` 探测(2 秒超时),按延迟自动择优,也允许用户在设置中手动锁定端点;
- **来源**:本仓库的 GitHub Release(tag `runtime-<commit>`,预发布为 `alpha`(CI 每天自动构建),正式发布为 `stable`),支持断点续传,并对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包。下载端点只有这一个,没有镜像,也不测速选路;
- 校验 `manifest.json` 与 SHA256 后解压至 `<commit>.tmp` 再原子重命名,失败不破坏现有版本;
- 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖;
- **可承接上游未来官方发布**:运行时源采用清单化拉取协议,若上游 `steelbrain/reims-vgpu` 日后提供官方 Windows 预编译包,可直接切换源承接。
### 3.3 `internal/installer` — GUI 离线安装包下载管理器(2026-11-28 实测沉淀)
- **背景与痛点**:实测通过在线恢复镜像(`--macos tahoe`)在 Guest Recovery 内经 QEMU 用户态 NAT(`slirp`)拉取 ~17 GB 系统包时,受限于 Apple CDN 频繁 `Peer disconnected` 与 `OSISDownloadOperation` 抗断流能力弱,极易在耗时数十分钟后接近完成时失败重来。
- **方案设计(基于 `reims-util 0.1.0` 一手 CLI 能力)**:
1. **动态版本列表**:调用 `reims-util.exe offline-installer list --json` 获取 Apple 目录可用的 macOS Tahoe 精确版本(如 `26.7.3`),供 GUI 下拉选择(同时保留在线恢复模式作为备选)。
2. **下载路由可选 + 环境自动探测(合规直连 Apple 官方源)**:macOS 系统包一律从 Apple 官方软件更新目录拉取并校验 chunklist 哈希(不接入第三方非官方镜像)。支持在设置与下载页配置路由模式:`自动探测(推荐)` / `直连 Apple CDN(绕过系统代理,清空代理环境变量并注入 NO_PROXY=*)` / `跟随系统代理` / `自定义 HTTP/SOCKS5 代理`。自动模式下在下载前花 1–2 秒并行探测直连与系统代理访问 Apple 目录的连通性与首字节延迟,国内环境自动命中 Apple 国内边缘节点(2026-11-28 实测直连 `220.194.76.155` 稳定 11.2 MiB/s、零断流),直连受限时自动回退系统代理。
2. **只从 Apple 官方源下载**:macOS 系统包由 `reims-util` 从 Apple 软件更新目录拉取,并校验 chunklist,不接第三方镜像。`reims-go` 不做路由选择,`reims-util` 使用进程环境里的代理变量(2026-11-28 实测,国内直连 Apple 边缘节点稳定在 11.2 MiB/s)。
3. **宿主机直连下载 + 结构化进度条**:调用 `reims-util.exe offline-installer <version> -o <DataRoot>\data\reims-ctl\installers --json`(或在建机时走 `reims-ctl create --macos <version> --offline --network false` 共享同一缓存目录)。`reims-util --json` 原生按行输出 JSON 进度事件,Go 后端实时解析并通过 Wails `EventsEmit` 推送进度百分比、已下载字节、速率与断流重试状态,无需脆弱正则匹配。
4. **暂停 / 断点续传与空间预警**:`reims-util` 原生支持中断后重跑同命令自动断点续传;GUI 提供「暂停/取消」与「继续下载」按钮,并在目标盘剩余空间不足 40 GB 时前置预警。
4. **暂停 / 断点续传与空间预警**:`reims-util` 原生支持中断后重跑同命令自动断点续传;GUI 提供「暂停/取消」与「继续下载」按钮。`reims-util` 一开始就会创建与完整镜像同样大小的 `.part` 文件,所以下载前先检查剩余空间是否够安装包大小的 1.1 倍。
5. **缓存复用与可视化清理**:已下载的离线镜像常驻 `<DataRoot>\data\reims-ctl\installers\`,GUI 包装 `reims-ctl downloads` 与 `reims-ctl downloads delete <NAME>` 展示体积并支持一键清理;后续新建 VM 直接通过 `--installer <path>` 复用本地镜像,零重复下载。
6. **离线装机 3 步引导卡**:使用离线包创建 VM 时默认开启 `--network false`(遵从 `reims-ctl create --help` 建议,阻止安装器联网拉更新),并在 GUI 突出提示:① 磁盘工具抹掉最大 `QEMU HARDDISK Media` 为 APFS → ② 打开终端执行 `sh /Volumes/Installer/install-macos.sh` → ③ 装完点击「弹出安装盘并恢复网络」。
@@ -79,14 +77,19 @@ flowchart TB
- 包装 `list --json`、`show`、`create`、`start`、`stop`、`set`、`eject`、`delete`、`logs`、`command`、`doctor`、`downloads`。
- 流式捕获 stdout/stderr 与串口日志,实时推送到 Wails 前端事件总线(`runtime.EventsEmit`),让用户在安装 macOS Tahoe 期间直观看到进度与内核启动日志。
- **Win10 自动冷重启补偿(2026-11-28 实测沉淀)**:Win10 19045 缺少 `WHvResetPartition`,Guest 内部热重启时 QEMU 会停在 `WHPX: Unexpected VP exit code 4`。在 Win10 宿主上可通过 `--extra-args "-no-reboot"` 让 QEMU 收到 Guest 重启请求时干净退出,再由 `reims-go` 自动重新 `start` 建立新分区,实现无感重启体验(待实测验证)。
- **QMP 不抢上游的 socket**:上游 `reims-ctl` 自己就有 QMP 客户端,走每台 VM 的 `qmp.sock`(Windows 上是 Winsock AF_UNIX,`crates/reims-ctl/src/qmp.rs:1-8`、`vm.rs:1000-1027`)。QEMU 的一个 `-qmp` 同一时间只接受一个客户端,第二个连接会一直等到超时(同上 `qmp.rs` 注释,引自 QEMU `chardev/char-socket.c`)。所以 `reims-go` **不连这个 socket**,否则会卡住 `reims-ctl stop` 等命令;它通过 `reims-ctl set --extra-args` 另开一个自己的 monitor(`-qmp tcp:127.0.0.1:<port>,server=on,wait=off`)。QEMU 允许多个 `-qmp`,但与上游参数是否冲突仍**待 M3.2 实测**。
- **两条 QMP 通道**:上游 `reims-ctl` 给每台 VM 开一个 `qmp.sock`(Windows 上是 Winsock AF_UNIX,`crates/reims-ctl/src/qmp.rs:1-8`、`vm.rs:1000-1027`)。QEMU 的一个 `-qmp` 同一时间只接受一个客户端,第二个连接会一直等到超时(同上 `qmp.rs` 注释,引自 QEMU `chardev/char-socket.c`)。
- 键入(`qmp.TypeIntoVM`)和截屏缩略图(`qmp.Screendump`)都是短连接,直接连 `qmp.sock`,并且按 VM 串行(`type_flow.go` 的 `typing`、`thumbnail_flow.go` 的 `thumbLocks`);键入期间不截屏。它们连着的时候,`reims-ctl stop` 要等它们断开,实际延迟**待验证**。
- Win10 冷重启监视需要长连接,所以通过 `reims-ctl set --extra-args` 另开一个 AF_UNIX monitor(`qmp.RebootSocketPath`),不占用 `qmp.sock`。不用 TCP,是为了不让客体经 SLIRP 的 `10.0.2.2` 访问到这个 monitor。
- **配置写入只用 `set`**:`reims-ctl set` 的修改在**下次启动**时生效(`cli.rs:73`);改图形会在 VM 停止时重建 OpenCore 镜像(`cli.rs:242`)。可改字段见 `cli.rs:551-616`,外壳如何呈现见 [`shell-design.md`](shell-design.md)。
### 3.5 `internal/vm` 与 `internal/control` — 开发者进阶能力(M3)
- **CoW 秒级派生**:使用便携运行时自带的 `qemu-img.exe create -f qcow2 -F qcow2 -b <golden> <overlay>` 生成写时复制派生盘,挂入临时实例,实现秒级拉起与无痕销毁(待验证 `reims-ctl create --disk <overlay> --disk-mode in-place` 对 backing file 的兼容性)。
- **带外控制**:通过 QMP 查询运行态、优雅关机(失败再回退终止,避免粗暴 `taskkill` 伤盘)、截屏与键鼠注入;结合 `--ssh-port` 提供命令执行通道。
### 3.5 启动编排:`internal/vmstart` 与 GUI 编排层
- `internal/vmstart` 是 GUI 和 CLI 共用的启动步骤:提交内存预检、离线辅助盘、恢复模式引导菜单、客体语言重放、WHPX 嵌套虚拟化兼容,以及启动后的 P 核绑定。GUI 的 `StartVM`(`app.go`)和 CLI 的 `vm start`(`cmd/reims-go/start.go`)都调用它。
- 只有 GUI 做的两步:Guest Tools 桥接(`guesttools_flow.go`)和 Win10 冷重启监视(`app.go`)。这两步都需要启动后仍在运行的进程,CLI 命令执行完就退出了,所以做不了。用 CLI 启动的 VM 没有剪贴板和共享目录;在 Win10 上,客体重启后 VM 会停下来,不会自动重新拉起。
- GUI 的其余编排仍在根目录的 `App`(`app.go`)和各个 `*_flow.go` 里:CoW 派生(`clone_flow.go`)、磁盘扩容与回收(`disk_flow.go`)、运行监视与里程碑日志(`vm_monitor.go`)。
- **CoW 派生**:先 `qemu-img create -f qcow2 -F qcow2 -b <golden> <overlay>`,再 `reims-ctl create --disk <overlay> --disk-mode in-place`,原盘不改。真机上从派生盘启动**待验证**。
- **SSH**:只展示 `reims-ctl` 的 `--ssh-port` 转发端口,没有命令执行通道。
## 4. 建议代码目录结构
## 4. 代码目录结构
```text
reims-go/
@@ -100,12 +103,20 @@ reims-go/
│ ├── installer/ # reims-util --json 离线安装包下载、断点续传、缓存管理
│ ├── driver/
│ │ └── reims/ # reims-ctl 子进程包装与 JSON/日志解析
│ ├── qmp/ # 独立 QMP TCP 客户端
│ └── vm/ # VM 编排、CoW 派生、向导状态机
│ ├── qmp/ # QMP 客户端:键入、截屏、Win10 冷重启监视
│ ├── vmstart/ # GUI 与 CLI 共用的启动前检查、准备与绑核
│ ├── guesttools/ # 宿客剪贴板与 WebDAV 共享目录、REIMSTOOLS 辅助盘
│ ├── opencore/ # 改写 OpenCore 镜像里的 prev-lang:kbd
│ ├── thumb/ # 把截屏缩小成 JPEG
│ ├── tray/ # 系统托盘
│ └── version/ # 版本号与更新检查
├── *.go # GUI 的 App 与各 *_flow.go 编排(package main)
├── frontend/ # Wails 前端(轻量 React + Vite + TypeScript + zh-CN/en-US i18n)
├── patches/ # 上游临时补丁队列(合入即退役)
├── scripts/
│ └── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest)
│ ├── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest)
│ ├── pack-msys2-sources.ps1 # 打包对应的 MSYS2 copyleft 源码
│ └── smoke-runtime.ps1 # 生成 alpha → stable 冒烟报告
└── docs/
```
+28 -13
View File
@@ -89,13 +89,21 @@ reims-runtime-<commit>/
## 4. 打包与发布流水线(M0 / M4)
- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。
- **本地打包与发布(2026-11-28 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel candidate` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有未登记的改动,就直接停止,不会自动修改补丁。
- **本地打包与发布(2026-11-28 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。补丁按 `patches/series.txt` 的顺序取,`-Patches` 可以只列实际打上的那几个。
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有补丁没涉及的文件被改动,就直接停止,不会自动修改补丁。允许改动的文件从补丁本身读出(2026-11-28 前写死为 `whpx-all.c`,带上 fiber 补丁就会误报)。
- **manifest 版本 2**:比版本 1 多记录 `vendor_qemu_commit`、`util_commit`、`metal2vulkan_commit`、`patches`(名称、作用对象、SHA256)、`channel`、`source_package`。`dll_count` 改为按实际文件统计;版本 1 的统计有误,记为 0。
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件就是上面三个文件。GitHub 的预发布对应 `candidate`,正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件就是上面三个文件。GitHub 的预发布对应 `alpha`(2026-11-28 前叫 `candidate`),正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
- **客户端安装**(`internal/runtime/remote.go`):从 GitHub API 列出版本 → 下载运行时包,支持续传 → 对照 `SHA256SUMS.txt` 校验,不一致就丢弃 → 用原有的导入流程解压并激活 → 删除下载的压缩包。
- **已发布**:`runtime-3731afd`,候选版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
- **自动化 CI(M4)**:在 GitHub Actions `windows-latest` runner 上使用 MSYS2 CLANG64,先打上第 5 节的补丁队列,再执行上游构建脚本,产出 `reims-runtime-win-x64-<commit>.tar.zst`、`SHA256SUMS.txt` 和对应源码包(第 7 节)。CI 产物只进 `candidate` 通道,不直接发给用户(第 6 节)。
- **已发布**:`runtime-3731afd`,先以候选版(即现在的 alpha)发布,同日升为稳定版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
- **自动化 CI(M4,2026-11-28 改为每日自动构建)**:[`build-runtime.yml`](../.github/workflows/build-runtime.yml) 每天 03:23 UTC 运行,也可手动触发并指定上游 commit。流程:
1. 取上游默认分支的 HEAD。已有 `runtime-<commit>` 的 Release(alpha 或 stable)就跳过,所以上游不动时不消耗构建时间。
2. 在 `windows-latest` 上用 MSYS2 CLANG64,由 `scripts/apply-patch-series.ps1` 按 `patches/series.txt` 逐个处理补丁:能打上就打;反向检查通过(上游已经包含)就跳过并提醒退役;两者都不行就停止,不改补丁(AGENTS.md 规则 4)。
3. 执行上游 `scripts/install-ctl.sh --yes`,再用 `pack-runtime.ps1 -Channel alpha -Patches <实际打上的补丁>` 打包,manifest 只写实际打上的补丁(规则 5)。
4. `scripts/check-runtime-alpha.ps1` 做 alpha 准入检查(第 6 节),通过后发布为 GitHub 预发布,附件四个缺一不可。
5. 只保留最近 7 个未升级的 alpha 预发布,更早的连同 tag 删除;正式发布不受影响。
6. 构建失败、或有补丁已被上游合并时,在本仓库开一个 issue(已有同名的未关闭 issue 就追加评论)。
CI 产物只进 `alpha` 通道,不直接发给用户(第 6 节)。注意 GitHub 会在仓库 60 天无活动后停用定时 workflow。
- **CI 测不到 Win10**:`windows-latest` 是 Windows Server 2022/2025,复现不了第 5 节的 Win10 问题,而且 GitHub 托管 runner 一般不提供 WHPX。CI 只能保证「能构建、`-device help` 列出 `reims-graphics-pci`」,能不能启动 VM 要靠第 6 节的本机冒烟测试。
## 5. 补丁队列(把上游当内核来优化的方式)
@@ -104,9 +112,12 @@ reims-runtime-<commit>/
| 补丁 | 作用对象 | 解决的问题 | 状态 |
| :--- | :--- | :--- | :--- |
| `reims-vgpu-win32-unicode-input.patch` | `reims-vgpu` 的 `crates/reims-vgpu-window`(`native/windows.rs`、`native/sdl_thread/ui.rs`) | SDL3 窗口层未开启 TextInput 且只转发 `0x04..=0xE7` 物理扫描码,导致直接投递 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR` 或宿主机 IME 上屏的文字被吞;通过 `SDL_SetWindowsMessageHook` 仅在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时异步转发非物理按键字符给宿主机文本注入桥 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时冒烟验证后提 PR |
| `reims-vgpu-cargo-lock.patch` | 上游 `reims-vgpu`(`3731afd`)的 `Cargo.lock` | 不改代码。cargo 构建时会给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 补上 `source = "git+…metal2vulkan?rev=0b0ac58…"`;带上这个补丁,源码包才和实际构建一致 | 不需要上游 PR;上游 `Cargo.lock` 补齐后删除 |
| `qemu-whpx-win10-compat.patch` | `vendor/qemu` 的 `target/i386/whpx/whpx-all.c` | ① `whpx_tsc_deadline_refused()`(`3210-3230`)原实现在真实分区上建、删 vCPU 0,Win10 19045 上随后 `whpx_init_vcpu()` 再次创建 vCPU 0 时必现 `WHvCreateVirtualProcessor` 返回 `E_INVALIDARG`(`hr=80070057`),改为独立临时探测分区;② `whpx_set_registers()`(`534`)直接调用 `WHvResetPartition` 未判空,Win10 19045 的 `WinHvPlatform.dll` 不导出该接口导致重置阶段必现 `0xc0000005 at 0x0` 崩溃(已核对导出表,10 个 supplemental API 中仅此一处漏判空) | 2026-11-28 实测复现并修复,待提交上游 PR(由人操作) |
| `qemu-whpx-win10-startup-ipis.patch` | 同上(在前一项之后应用) | Win10 开启内核 irqchip 时转发多核 INIT/SIPI,避免 XNU 从核启动停住 | 已合入补丁队列,客体冷重启待验证,待提交上游 PR |
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上(在前两项之后应用) | 部分 Win11 宿主 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)导致 QEMU 在 `whpx-all.c:3479-3483` 直接致命退出,改为非致命警告并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 内核态 x2APIC 加速 | 2026-11-28 新增补丁,待编入下一版 candidate 运行时并在 Win11 真机冒烟验证后提 PR |
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上(在前两项之后应用) | 部分 Win11 宿主 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)导致 QEMU 在 `whpx-all.c:3479-3483` 直接致命退出,改为非致命警告并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 内核态 x2APIC 加速 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时并在 Win11 真机冒烟验证后提 PR |
| `qemu-win32-coroutine-fiber-commit.patch` | `vendor/qemu` 的 `util/coroutine-windows.c` | 登录 Apple ID 等高并发 VA-API + 磁盘 I/O 场景下,`CreateFiber(1 MiB)` 预先提交整块 1 MiB 协程栈易耗尽 Windows Commit Charge 返回 `NULL`,未判空即调用 `SwitchToFiber(NULL)` 触发 `0xc0000005`(读 `0x0000000000000010`)崩溃;改用 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 并将 `NULL` 与 `IsThreadAFiber()` 纳入显式处理 | 2026-11-28 符号化定位并新增补丁,待编入下一版 alpha 运行时实测验证后提 PR |
### 5.1 本机实测排障与待验证优化沉淀(2026-11-28,Win10 19045)
1. **Win10 下默认关闭 `kernel-irqchip` 导致高 CPU 开销(待验证优化)**:
@@ -116,31 +127,35 @@ reims-runtime-<commit>/
- 32 GB 物理内存宿主在开启常见软件后,实测可用提交内存(`FreeVirtualMemory`)仅 `14.7 GiB`(即使空闲物理内存仍有 `17.3 GiB`);QEMU 启动时一次性 `CreateFileMapping` 提交全部 Guest RAM,分配 `16G` 直接退出报 `Cannot set up guest memory 'ram': 系统资源不足`。`reims-go` 必须在体检与启动前检测提交内存并动态限位(详见 [`architecture.md`](architecture.md) 3.1 节)。
3. **在线 Recovery 拉取 17 GB 极易因 Apple CDN 断流失败**:
- 实测拉取 961 MB 恢复镜像期间 Apple CDN 即出现 6 次 `Peer disconnected`;在 Recovery 内经 QEMU 用户态 NAT(`slirp`)拉取 ~17 GB 系统包时,`OSISDownloadOperation` 抗断流能力差,易在接近完成(实测 `disk.qcow2` 已达 `16.95 GiB`)时失败。因此 `reims-go` GUI 默认改为宿主机调用 `reims-util offline-installer --json` 断点续传下载离线安装包(详见 [`architecture.md`](architecture.md) 3.3 节)。
4. **登录 Apple ID 后 `SwitchToFiber(NULL)` 崩溃(`0xc0000005`,读 `0x10`)**:
- 2026-11-28 对真实崩溃栈在 `runtime-3731afd` 上符号化定位:`whpx_vcpu_run` → `execute_ncq_command`(`hw/ide/ahci.c:1096`)→ `blk_aio_prwv`(`block/block-backend.c:1624`)→ `qemu_aio_coroutine_enter`(`util/qemu-coroutine.c:298`)→ `qemu_coroutine_switch`(`util/coroutine-windows.c:59`)→ `KERNELBASE!SwitchToFiber`(`movq 0x10(%rcx), %rax`)。
- 根因是 `util/coroutine-windows.c:78` 调用 `CreateFiber(COROUTINE_STACK_SIZE, ...)` 预提交整块 1 MiB 栈,在 VA-API HEVC 批量解码 + iCloud/AHCI 并发读盘叠加导致 Commit Charge 见底时返回 `NULL`,且未判空直接传给 `SwitchToFiber`。补丁 [`qemu-win32-coroutine-fiber-commit.patch`](../patches/qemu-win32-coroutine-fiber-commit.patch) 改用 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 并补齐空指针诊断与 `IsThreadAFiber()` 保护。
规则:
1. 补丁原文的权威副本放在 `reims-go/patches/`。macos-vm-lab 的那份是研究时的原始记录。
2. 每次跟进上游 commit 时,先 `git apply --check`。打不上就停在 `candidate`,不要自动改补丁。
2. 每次跟进上游 commit 时,先 `git apply --check`(CI 中由 `scripts/apply-patch-series.ps1` 执行)。打不上就停下,不发布 alpha,不要自动改补丁。
3. 补丁文件必须是**无 BOM、LF 行尾**,由 `.gitattributes` 的 `*.patch -text` 保证。用 PowerShell 5.1 的 `Out-File` 或 `>` 生成的补丁会带 BOM 和 CRLF,`git apply` 不认(2026-11-28 实测,原始副本就是这样)。
4. 上游合并之后,在表里记下合并 commit,然后删掉补丁。
5. `patches/series.txt` 是补丁队列的唯一清单,规定作用对象和应用顺序;CI 和 `pack-runtime.ps1` 都从它读取。加、删补丁只改这个文件和本节的表。
## 6. 发布通道(已验证通道)
上游变动非常快(2026-11-21 到 11-28 有 100 多个提交,截至 2026-11-28 没有任何 GitHub Release),出现过某个提交弄坏 `reims-ctl` 安装的情况([issue #138](https://github.com/steelbrain/reims-vgpu/issues/138))。所以运行时**不跟上游最新 commit**,而是分两级:
上游变动非常快(2026-11-21 到 11-28 有 100 多个提交,截至 2026-11-28 没有任何 GitHub Release),出现过某个提交弄坏 `reims-ctl` 安装的情况([issue #138](https://github.com/steelbrain/reims-vgpu/issues/138))。所以用户默认拿到的运行时**不跟上游最新 commit**,而是分两级:CI 每天把上游最新 commit 构建成 `alpha`,人从 alpha 中挑一个冒烟通过的升为 `stable`。
| 通道 | 来源 | 进入条件 |
| :--- | :--- | :--- |
| `candidate` | CI 按指定上游 commit 构建并打补丁 | 能构建;`qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci`;SHA256 清单齐全 |
| `stable` | 从 `candidate` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
| `alpha` | CI 每天从上游最新 commit 自动构建并打补丁(2026-11-28 前叫 `candidate`,当时是人工指定 commit) | 由 `scripts/check-runtime-alpha.ps1` 自动检查:能构建;四个附件齐全;`SHA256SUMS.txt` 覆盖三个压缩包且校验一致;manifest 的 commit、通道、补丁与实际一致;在不含 MSYS2 的 PATH 下 `qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci` |
| `stable` | 从 `alpha` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
`reims-go` 客户端默认只拉 `stable`,`candidate` 要用户主动打开。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
`reims-go` 客户端默认只拉 `stable`,`alpha` 要用户主动打开(界面开关「接收 Alpha 版」,CLI `--alpha`)。旧配置里的 `runtime_channel: "candidate"` 读作 `alpha`,CLI 的 `--candidate` 保留为 `--alpha` 的别名。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
升级记录:
| 运行时 | 候选版发布 | 冒烟测试 | 升为稳定版 |
| 运行时 | alpha 发布 | 冒烟测试 | 升为稳定版 |
| :-- | :-- | :-- | :-- |
| `runtime-3731afd` | 2026-11-28 | 真实宿主 Windows 10 19045,启动到 macOS 桌面并正常关机,由人确认通过 | 2026-11-28 |
升级不重新打包,只把 GitHub Release 从预发布改为正式发布,所以用户拿到的文件与冒烟测试用的完全相同。包内 `manifest.json` 的 `channel` 字段记录的是构建时的通道,会一直是 `candidate`;客户端只看 Release 的发布状态。
升级不重新打包,只把 GitHub Release 从预发布改为正式发布,所以用户拿到的文件与冒烟测试用的完全相同。包内 `manifest.json` 的 `channel` 字段记录的是构建时的通道,会一直是 `alpha`(2026-11-28 前的包是 `candidate`);客户端只看 Release 的发布状态。alpha 预发布只保留最近 7 个,正在冒烟的那个如果被挤出,可以用手动触发重新构建同一 commit。
## 7. 许可证与源码义务
+161 -17
View File
@@ -1,13 +1,23 @@
# 开发路线图与里程碑(Roadmap)
> 原则:先打通“最小可用闭环”(本地打包便携运行时 → Go 核心驱动 → Wails GUI),再扩展自动化与 CI 自动发版。每个里程碑均有明确的可验证验收标准(DoD)。
>
> 后续规划从用户任务出发:先让用户装得上、用得稳、改坏了能恢复,再减少开发工作流中的手工步骤。功能数量、参数覆盖率和竞品对标不单独构成立项理由。
## 规划与验收口径
- **[x] 只表示代码或脚本已经实现**,不自动表示已进入公开 Release,也不代表真机验收通过;是否达成 DoD 以各里程碑的状态说明和实测记录为准。
- **已发布**:用户能从公开 `stable` Release 获得,且应用、运行时、manifest、补丁与源码包描述一致。
- **已验收**:在记录清楚的 Windows、GPU、运行时和 macOS 版本组合上完成真实用户任务,并留下可复核结果;单元测试或 CI 构建成功不能代替这一步。
- **后续条目必须先回答**:服务哪类用户、解决哪一步阻塞、现有替代办法是什么、怎样验收、失败如何恢复。没有这些内容的点子留在候选池,不占版本计划。
```mermaid
flowchart LR
M0["M0 便携包与环境验证\n(2–3 天)"] --> M1["M1 Go 核心层与 CLI\n(1 周)"]
M1 --> M2["M2 Wails 桌面 GUI MVP\n(1–2 周)"]
M2 --> M3["M3 硬件调优与 CoW/QMP\n(1–2 周)"]
M3 --> M4["M4 CI 自动构建与发版\n(1 周)"]
M3 --> M4["M4 CI 自动构建与发版"]
M4 --> M5["M5 macOS 日常主力体验\n(v0.2.2+)"]
```
---
@@ -33,7 +43,7 @@ flowchart LR
- [x] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`:含 WHPX、**物理内存与可用提交内存 `FreeVirtualMemory` 安全档位推荐**、Vulkan ICD、三层 P/E/LP-E 核拓扑、磁盘总线类型探测)与非 Windows 桩(`*_other.go`)。
- [x] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。
- 2026-11-28:补上在线安装,运行时从本仓库的 GitHub Release 下载(`runtime-<commit>` tag,候选版和稳定版两个通道),支持续传,并对照 `SHA256SUMS.txt` 校验。CLI 用 `reims-go runtime available` 和 `reims-go runtime fetch [commit]`;界面在宿主页和首次启动页。细节见 `portable-runtime-spec.md` 第 4 节。
- 2026-11-28:补上在线安装,运行时从本仓库的 GitHub Release 下载(`runtime-<commit>` tag,alpha 和稳定版两个通道;alpha 在 2026-11-28 前叫候选版),支持续传,并对照 `SHA256SUMS.txt` 校验。CLI 用 `reims-go runtime available` 和 `reims-go runtime fetch [commit]`;界面在宿主页和首次启动页。细节见 `portable-runtime-spec.md` 第 4 节。
- [x] **M1.3**:`internal/installer` — 封装 `reims-util offline-installer list --json`、`reims-util offline-installer <ver> -o <DataRoot>\data\reims-ctl\installers --json` 与 `reims-ctl downloads`:实现结构化 JSON 进度流解析、取消/断点续传与缓存清理。
- 2026-11-28 完成。
- CLI:`reims-go installer list | download <版本> | cached | delete <文件名>`。
@@ -80,41 +90,175 @@ flowchart LR
---
## M3(v0.3):硬件自动调优、宿客互通与开发者进阶能力
## M3:硬件自动调优、宿客互通与开发者进阶能力
**目标**:拉平并超越社区 Windows 管理器体验,补齐宿客互通、安全边界与工程化能力。
**目标**:补齐硬件调优、宿客互通、安全边界与工程化能力。M3 的功能随 v0.2.1 发布。
- [x] **M3.1**:**三层大小核防超售绑核与 WHPX 兼容自愈** — 识别三层混合架构(P + E + LP-E,如 Intel Core Ultra 200 无超线程 CPU),`vCPU < P 核逻辑线程数` 时绑 P 核,超出时自动改绑 `P + E`(仅排除慢速 LP-E 核)避免自旋锁超售卡顿;自动探测 Win11 `hr=0x80370302` 嵌套虚拟化属性并预置/补丁化处理;新建 VM 默认 `NVMe` 控制器。
- [x] **M3.2**:**安全 AF_UNIX QMP 通道与键入** — Win10 冷重启辅助 QMP 通道已迁至 Windows `AF_UNIX` 套接字(杜绝 SLIRP 下 `10.0.2.2:<port>` 宿主机逃逸风险,自动清理旧 TCP 参数);已基于 `reims-ctl` 的 `qmp.sock` 实现 QMP 键盘一键键入。后续按需补齐优雅关机增强与 QMP 截屏。
- [x] **M3.3(v0.3 核心)**:**安全鉴权 Guest Tools(双向剪贴板 + 共享目录)** — 内置仅监听 `127.0.0.1` 的纯 Go HTTP 宿客桥接(每台 VM 独立 256-bit 随机 Bearer Token + 严格共享目录路径隔离),通过纯 Go HFS+ 辅助盘 `REIMSTOOLS` 一键安装免 Xcode/Python 的 macOS LaunchAgent,支持双向 UTF-8 剪贴板与 `~/Desktop/ReimsShare` ↔ `<DataRoot>/shared/<vm>` 双向文件同步。**(macOS 桌面端真机联调待验证)**
- [x] **M3.4(v0.3 后续)**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时自动切至 `NVMe`,并在 VM 主页提供一键升级按钮;自动检测外置 USB/网络盘(`GetDriveTypeW` + `IOCTL_STORAGE_QUERY_PROPERTY` `BusTypeUsb`)与高内存负载(≥ 85%)并展示可操作提示。
- [x] **M3.5(v0.3 后续)**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、运行时清单、VM 配置、自动脱敏(序列号/MAC/SMC OSK/Bearer Token)的 QEMU、串口与应用日志,一键导出到 `<DataRoot>/reports/` 并定位目录(已通过单测验证零敏感信息泄漏)。
- [x] **M3.6(v0.3 后续)**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,新建向导支持直接选择 `.vmdk` / `.raw` 并自动转为 `.qcow2` 导入。**(真机大容量 VMDK 转换待验证)**
- [x] **M3.7(v0.4 差异化王牌)**:**Golden Image 与 CoW 秒级派生** — 已停止的已装系统 VM 支持在「更多」里通过 `qemu-img create -f qcow2 -b <golden> -F qcow2` + `reims-ctl create --disk --disk-mode in-place` 秒级派生独立身份副本,原盘只读不改。**(真机 CoW 派生启动待验证)**
- [x] **M3.3**:**安全鉴权 Guest Tools(双向剪贴板 + 共享目录)** — 内置仅监听 `127.0.0.1` 的纯 Go HTTP 宿客桥接(每台 VM 独立 256-bit 随机 Bearer Token + 严格共享目录路径隔离),通过纯 Go HFS+ 辅助盘 `REIMSTOOLS` 一键安装免 Xcode/Python 的 macOS LaunchAgent,支持双向 UTF-8 剪贴板与 `~/Desktop/ReimsShare` ↔ `<DataRoot>/shared/<vm>` 双向文件同步。**(macOS 桌面端真机联调待验证)**
- [x] **M3.4**:**退出恢复模式自动升级 `NVMe` + 存储/内存性能诊断** — 对旧 `AHCI` VM 在退出恢复模式时自动切至 `NVMe`,并在 VM 主页提供一键升级按钮;自动检测外置 USB/网络盘(`GetDriveTypeW` + `IOCTL_STORAGE_QUERY_PROPERTY` `BusTypeUsb`)与高内存负载(≥ 85%)并展示可操作提示。
- [x] **M3.5**:**一键导出脱敏排障日志包(`.zip`)** — 收集体检报告、运行时清单、VM 配置、自动脱敏(序列号/MAC/SMC OSK/Bearer Token)的 QEMU、串口与应用日志,一键导出到 `<DataRoot>/reports/` 并定位目录(已通过单测验证零敏感信息泄漏)。
- [x] **M3.6**:**磁盘导入增强(VMDK / RAW 自动转 qcow2)** — 复用便携运行时内置 `qemu-img convert`,新建向导支持直接选择 `.vmdk` / `.raw` 并自动转为 `.qcow2` 导入。**(真机大容量 VMDK 转换待验证)**
- [x] **M3.7**:**Golden Image 与 CoW 秒级派生** — 已停止的已装系统 VM 支持在「更多」里通过 `qemu-img create -f qcow2 -b <golden> -F qcow2` + `reims-ctl create --disk --disk-mode in-place` 秒级派生独立身份副本,原盘只读不改。**(真机 CoW 派生启动待验证)**
**DoD**:
- 三层大小核防超售绑核、`AF_UNIX` QMP、Guest Tools 剪贴板与共享目录、CoW 派生在真实宿主均有实测通过记录。
**状态**:功能都已实现,但 DoD 还没达成。M3.3(Guest Tools 真机联调)、M3.6(大容量 VMDK 转换)、M3.7(CoW 派生启动)还没有真机实测记录。
---
## M4(v0.4):上游性能/窗口跟进与 CI 自动发布
## M4:上游性能/窗口跟进与 CI 自动发布
**目标**:自动化跟进上游 Windows 性能与窗口体验改进,建立 `candidate` → `stable` 冒烟发布闭环。
**目标**:自动化跟进上游 Windows 性能与窗口体验改进,建立 `alpha` → `stable` 冒烟发布闭环。
- [ ] **M4.1**:**上游窗口与性能 PR 跟进(运行时升级,持续跟踪)** — 已建立跟踪清单 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md),跟踪上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 关键 Windows PR(`#153`、`#152`、`#107`、`#123`、`#172` 与 Win→Command)合入后触发 `build-runtime.yml` 升级 `candidate` 运行时。
- [x] **M4.2**:编写 GitHub Actions workflow([ci.yml](../.github/workflows/ci.yml) + [build-runtime.yml](../.github/workflows/build-runtime.yml)):CI 自动先构建前端再跑 `go test` / `go vet` 并编译 CLI 与 GUI;手动运行时构建 workflow 在 `windows-latest` 上通过 MSYS2 CLANG64 拉取 `vendor/qemu`、硬校验并应用 `patches/`、调用上游 `scripts/install-ctl.sh --yes` 并执行 `scripts/pack-runtime.ps1` 产出 `candidate` 预发布包与对应源码包。**(GitHub Actions 运行时编译待首次手动触发实跑验证)**
- [x] **M4.3**:**`candidate` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](../scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。
- [ ] **M4.1**:**上游窗口与性能 PR 跟进(运行时升级,持续跟踪)** — 已建立跟踪清单 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md),跟踪上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 关键 Windows PR(`#153`、`#152`、`#107`、`#123`、`#172` 与 Win→Command)合入后由 `build-runtime.yml` 的每日构建自动产出 `alpha` 运行时。
- [x] **M4.2**:编写 GitHub Actions workflow([ci.yml](../.github/workflows/ci.yml) + [build-runtime.yml](../.github/workflows/build-runtime.yml)):CI 自动先构建前端再跑 `go test` / `go vet` 并编译 CLI 与 GUI;运行时构建 workflow 每天从上游最新 commit 自动构建(2026-11-28 起;已发布过的 commit 跳过),在 `windows-latest` 上通过 MSYS2 CLANG64 拉取 `vendor/qemu`、按 `patches/series.txt` 应用补丁(已被上游合并的跳过并开 issue 提醒,冲突就停止)、调用上游 `scripts/install-ctl.sh --yes`、执行 `scripts/pack-runtime.ps1`,经 `scripts/check-runtime-alpha.ps1` 准入检查后发布 `alpha` 预发布包与对应源码包,并只保留最近 7 个 alpha。**(GitHub Actions 运行时编译待首次手动触发实跑验证)**
- [x] **M4.3**:**`alpha` → `stable` 冒烟脚本** — 已编写 [scripts/smoke-runtime.ps1](../scripts/smoke-runtime.ps1),支持校验 SHA-256、在干净隔离目录(无 MSYS2 PATH)解压并跑 `reims-ctl doctor` / `list --json` 与合规文件核查,产出供人工评审的 Markdown 冒烟报告。
- [x] **M4.4**:**客户端自动发布与在线更新检查** — 已新增 [.github/workflows/release.yml](../.github/workflows/release.yml)(打 `v*` tag 自动跑测、构建 `reims-go-<tag>-windows-amd64.exe` / `reims-go-cli-<tag>-windows-amd64.exe` + `SHA256SUMS.txt` 并发布 GitHub Release);客户端与 CLI 接入 `internal/version` 版本号与稳定版在线更新检查(`HostView` 一键检查/跳转下载,运行时支持多版本回滚切换);合规文件(`NOTICE.md`、`LICENSE`、运行时源码包与 `MSYS2-PACKAGES.txt`)已随构建脚本落盘。
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 3 个 QEMU WHPX 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 4 个 QEMU 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
**DoD**:
- 触发一次 tag/手动 workflow 即可产出完整的 `candidate`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
- 触发一次 tag/手动 workflow 即可产出完整的 `alpha`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。
**状态**:客户端 Release(`release.yml`)已随 v0.2.1 跑通;运行时构建(`build-runtime.yml`)还没在 GitHub Actions 上实跑过,所以 DoD 还没达成。
---
## M5(v0.2.2+):macOS 日常主力体验与性能优化
**目标**:让 macOS 虚拟机真正脱离「仅供测试与点亮」,在图形/磁盘性能、窗口与键鼠直觉、宿客无缝协作和长期运维安全性上达到可作为日常主力/开发机使用的水准。本阶段优先验收已有能力;除“可反悔的停机快照”外,不因竞品具有类似功能就新增独立子系统。
### 核心体验的实现与跟进清单
- [ ] **M5.1(上游运行时联动)**:**沉浸全屏、无黑边缩放与 GPU 性能升级**
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」一键开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与 `Ctrl+Alt+Enter` / `Ctrl+Alt+G` 热切快捷键提示条;
- 待上游跟进:待 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 中上游 `reims-vgpu` PR 合入后由 `build-runtime.yml` 产出新 `alpha`,冒烟后升为 `stable`:`#123`(`Ctrl+Alt+Enter` 运行中热切全屏)、`#172`(Windows 拖动窗口动态贴合、消除黑边)、`#152`(原生 Windows Vulkan 后端)、`#153`(NVIDIA MAILBOX/FIFO 首帧优化)、`#107`(采样纹理回读就地消费)。
- [ ] **M5.2(本仓 + 上游)**:**HiDPI 智能推荐与 Mac 键位习惯适配**
- 本仓已完成:`internal/host` 新增原生 Windows 物理显示器与 DPI 缩放探测(`EnumDisplayMonitors` + `EnumDisplaySettingsW` + `GetDpiForMonitor`),按主屏分辨率与 DPI 缩放自动推荐 1× / 2× HiDPI 预设(2K/2.5K/4K/16:10),并在宿主页、新建向导第 4 步与设置页展示智能推荐与多屏引导;设置页键盘分类补齐 Mac 键位提示;
- 待验证:自由指针模式下 `Win` 键映射 macOS `Command`(优先随上游 PR 落地,避免维护私有分叉)。
- [x] **M5.3(本仓)**:**Guest Tools 2.0(图片剪贴板 + 真挂载式共享目录)**
- 剪贴板 2.0:Windows 端支持原生 `"PNG"` 与 32-bit `CF_DIB` 双向图片剪贴板编解码(纯 Go,零外部依赖),服务端基于 `GetClipboardSequenceNumber()` 实现低延迟长轮询事件唤醒(`?since=&wait=&accept=image`),Guest POSIX 脚本使用 macOS 原生 `osascript` + `sips` 实现零 Xcode/Python 的文本 + PNG 截图双向剪贴板;
- 共享目录 2.0:在 `reims-go` 内置仅监听 `127.0.0.1`、带 per-VM 256-bit Basic/Bearer Token 鉴权与严格目录防穿越的纯 Go **WebDAV 服务**(`/dav/<vm>/`),Guest 侧优先 `mount_webdav` 实时零双份挂载到 `~/Desktop/ReimsShare` 并在不可用时自动回退同步模式;
- UI 升级:主界面实时显示 Guest Tools 连接状态、`WebDAV 挂载` / `文件同步` 模式徽章、旧版工具升级提示与「投递文件到 macOS」快捷入口。**(macOS 桌面端真机 WebDAV 挂载与图片剪贴板联调待验证)**
- [x] **M5.4(本仓)**:**防休眠守护、系统托盘驻留与资源状态条**
- 防休眠守护:Guest Tools 2.0 支持由宿主机 UI 一键实时开关 `caffeinate -dims`(免 sudo,通过 `/v1/config` 实时下发),并在 `REIMSTOOLS` 附带可选 `Apply-Prevent-Sleep-pmset.command`;
- Windows 系统托盘驻留:新增纯 Go Win32 `internal/tray`(`Shell_NotifyIconW` + 动态中英文右键菜单,含 VM 状态/快捷启停/打开共享目录/显示窗口/退出),默认关闭主窗口最小化到托盘(可在宿主页开关),保障后台 Guest Tools 桥接不断线;
- VM 实时资源条:新增 `internal/host` 进程 CPU%/内存采样与纯 Go `.qcow2` 实际占用 vs 逻辑容量解析,在 VM 详情页每 3 秒轻量展示 QEMU CPU、宿主机内存、磁盘占比与运行时长。
- [x] **M5.5(本仓 + 上游化)**:**系统外预设 macOS 系统语言(`prev-lang:kbd`)**
- 根因:`reims-util@7867384`(`src/opencore/config.rs:216-228`)在生成 `opencore.qcow2` 时将 `NVRAM > Add/Delete > prev-lang:kbd` 硬编码为 `en-US:0`,导致每次进入恢复模式、设置助理和登录界面均强制回退为英文。
- 本仓已实现:新增纯 Go `internal/opencore`(直读/原地改写 `opencore.qcow2` / `opencore.img` 的 GPT+FAT32 `EFI/OC/config.plist` 中 `NVRAM > Add/Delete > prev-lang:kbd`,必要时自动回退 `qemu-img` 原子转换);新建向导、VM 设置「通用」页、VM 详情页与 CLI(`--guest-lang`)均已支持预设(默认跟随界面语言,如 `zh-Hans:0` / `zh-Hans:252` / `zh-Hant:0` / `en-US:0` / `ja-JP:0` / `ko-KR:0`),偏好持久化到 `.reims-go-guest-lang` 并在 `update-opencore`、显卡切换、CoW 克隆与 `StartVM` 前自动重放(`zh-Hans:0` vs `zh-Hans:252` 在 Tahoe Recovery 下的真机键盘布局表现**待验证**)。
- 长期上游化:向 `reims-util` / `reims-ctl` 提议支持 `opencore --lang` 并在 `update-opencore` 重建时保留原有 `prev-lang:kbd`(登记在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md))。
### 运维与开发工作流的实现清单
- [x] **M5.6(本仓)**:**磁盘 I/O 进阶调优与空间生命周期管理**
- 已实现:封装 `qemu-img resize` 停机扩容(支持 `+32G`/`+64G`/`+128G`/`256G` 等增量与绝对目标,防误缩容,完成后自动生成不依赖盘符序号的 macOS `diskutil repairDisk` + `apfs resizeContainer` 一键扩展命令);封装停机「回收未用空间」(校验非 CoW overlay 与剩余空间后重写稀疏 `.qcow2` 并通过 `qemu-img check` 完整性校验再原子替换);补齐 `NVMe` / `VirtIO-blk` / `SATA` 控制器说明并接入设置页「存储与网络」与 CLI(`vm resize` / `vm compact`);
- 待验证:已装 macOS 26 真机下 `nvme` vs `virtio-blk` 实际编译/读写基准对比。
- [ ] **M5.7(本仓)**:**可视化停机快照与一键回滚**
- 基于 M3.7 已落地的 CoW / Golden Image 基础设施,提供命名停机检查点(如「升级 macOS 26.8 前」)、历史列表与一键回滚,确保日常环境改坏或 OTA 失败可秒级恢复。
- [ ] **M5.8(本仓)**:**多端口转发与开发者工作流直连**
- 网络设置页支持自定义多条宿客 TCP 端口转发(如 `3000→3000`、`8080→8080`,安全合并至 `--extra-args` 或跟进上游多 `hostfwd`);
- 详情页提供「打开 SSH 终端」、一键写入 `~/.ssh/config`(`Host reims-<vm>`)与 VS Code / Cursor Remote-SSH 直连入口;
- Guest Tools 提供可选「宿主机代理快捷配置」(经 `10.0.2.2:<port>` 显式开启/一键清除,方便 Homebrew / Xcode / npm 下载)。
- [x] **M5.9(本仓 + 上游验证)**:**音频延迟与麦克风链路打磨**
- 已实现:`internal/host` 接入原生 Win32 `winmm.dll`(`waveOutGetNumDevs` / `waveInGetNumDevs` + 设备名枚举,与上游 `reims-ctl` `sound_devices()` 探测一致);修复 `ParseShow` 在指定显式 `--audio-backend`(如 `dsound`/`none`)时误判音频关闭的 Bug;设置页「输入与音频」与 CLI(`vm set --audio-backend`)支持切换音频后端(`自动(dsound)` / `DirectSound` / `静音设备`),实时展示宿主播放与录音设备状态(无输出/无麦克风时明确提示上游 `reims-ctl` 路由到 `none` 的行为)及 48 kHz / P-Core / 麦克风权限排查指引;
- 待验证:真实 macOS 桌面下 DirectSound 播放延迟与麦克风会议录音实测记录。
### 按需评估的能力
- [ ] **M5.10(按需评估)**:**Windows USB 设备直通可行性评估** — 上游 `crates/reims-ctl/src/usb.rs` 当前仅枚举 Linux sysfs,Windows 需依赖 WinUSB / UsbDk 驱动替换,复杂度与风险较高;仅在核心体验稳定后评估作为可选高级功能(用于 iPhone 真机调试 / 硬件密钥)。
- [ ] **M5.11(按需评估)**:**QMP 实时缩略图与自动化脚本接口** — 复用现有 QMP 通道补齐 VM 画面缩略图预览与 CLI 自动化操作。
**DoD(v0.2.2 验收标准)**:
- 在真实 Windows 宿主上,使用 `reims-go` 启动 macOS 可完成:**新建/恢复阶段即可外部预设中文语言(`prev-lang:kbd`)、热切沉浸全屏/无黑边缩放、清晰 HiDPI 显示、图文双向剪贴板、零双份占用的挂载式共享目录、托盘后台常驻不掉线**,且持续高负载开发(编译/浏览器/多任务)稳定无明显卡顿或意外断连。
---
## 后续执行顺序:按用户任务验收
上面的 M5.x 是实现索引,不代表执行顺序,也不构成持续增加功能的承诺。后续迭代按下面的用户任务排序;同一任务优先修复和验证已有能力,只有现有路径确实无法完成任务时才新增功能。P0 表示任务优先级,不表示全部塞进同一个版本;每轮只选择能够完整验收的范围。
### U1(P0):第一次使用就能装到桌面,失败也知道怎么处理
**用户故事**:我只按向导操作,不需要理解 WHPX、Vulkan、OpenCore 或 QEMU 参数,就能得到可用的 macOS 桌面;下载中断、磁盘不足或提权取消时,可以安全重试。
**实现范围**:
1. 先完成 M4 的发布闭环:实跑运行时 CI;确保公开资产的 manifest、补丁和源码包一致;冒烟报告记录最终资产完整 SHA-256,发布后替换资产必须退回 `alpha` 重新验收。
2. 用公开应用和运行时,在声明支持的 Windows / GPU / macOS 组合上跑「干净用户目录 → 体检 → 下载/导入 → 创建 → 安装 → 退出恢复模式」完整流程,而不是只跑 `doctor` 和单元测试。
3. 针对用户真实会遇到的中断做故障注入:暂停/断网后续传、磁盘不足、UAC 取消、运行时损坏、安装进程退出。界面说明发生了什么、数据是否保留以及下一步怎么做。
**验收证据**:每个受支持组合都有版本、耗时、结果和日志记录;失败后可以重试或安全清理,不留下无法解释的半配置 VM;公开文档描述与用户实际下载的稳定资产一致。
**不扩大范围**:不为了增加“支持数量”贸然承诺未测试的 GPU、Windows 或 macOS 版本,也不把高级参数暴露给首次使用者。
### U2(P0):一天开发工作不被显示、输入和宿客协作打断
**用户故事**:我在 macOS 里使用 IDE、浏览器和构建工具,同时与 Windows 交换文字、图片和文件;全屏、HiDPI、快捷键、声音和共享目录应当稳定,不需要反复重连或调整底层参数。
**实现范围**:
1. 集中验收 M5.1–M5.5 和 M5.9 的已有实现;上游图形 PR 只有在能改善可测的全屏、缩放、帧率、首帧延迟或稳定性时才进入新运行时。
2. 在真实宿主完成一个完整工作日(8 小时)的编译、浏览器、多任务、图文剪贴板和共享目录混合负载,并覆盖窗口尺寸/DPI 变化、宿主睡眠唤醒、Guest Tools 重连和音频/麦克风场景。
3. 资源条和诊断信息用于解释卡顿、内存压力、磁盘压力和断连,不继续增加没有明确排障用途的指标。
**验收证据**:记录宿主硬件、运行时和 macOS 版本,以及卡顿、断连、延迟和恢复结果;未通过的组合明确限制或降级,不把“有开关”写成“体验已完成”。
**不扩大范围**:现有剪贴板和 WebDAV 能完成任务时,不另做一套拖放协议、共享文件系统或无缝窗口模式。
### U3(P0):升级系统和调整环境之前,用户可以反悔
**用户故事**:在 macOS OTA、开发环境大改或磁盘整理之前,我能留下一个有名字的恢复点;改坏后可以回到之前状态,操作中断也不会弄坏原盘。
**实现范围**:
1. 将 M5.7 的**停机快照与一键回滚**作为本任务的核心新增能力:名称、说明、创建时间、历史列表、删除和带确认的回滚;不要求运行中内存热快照。
2. 校验可用空间、VM 停机状态和 CoW backing file 链;创建、删除、回滚及磁盘 compact/resize 都要考虑进程中断和空间不足,禁止误删仍被派生盘依赖的基盘。
3. 明确“快照不是备份”。先验证数据目录的离线备份与恢复说明;只有用户确实需要跨机器迁移或自动保留策略时,才评估独立导出格式和调度功能。
**验收证据**:真实执行“创建恢复点 → 修改/升级系统 → 回滚 → 启动并核对应用与文件”;对创建和回滚过程做中断测试,原盘与可用恢复点均不受损。
**不扩大范围**:在显存和设备状态序列化未经上游验证前,不做运行中内存快照、快照树花哨可视化或 instant clone 承诺。
### U4(P1):Windows 与 macOS 开发工具可以直接接起来
**用户故事**:我在 Windows 编辑代码,在 macOS 构建和签名,再从 Windows 浏览器或 IDE 访问客体服务;常用连接可以保存,重启 VM 后仍可使用。
**实现范围**:
1. 围绕一条完整链路实现 M5.8:多 TCP 端口转发、端口冲突检测、SSH 终端与 SSH config、VS Code / Cursor Remote-SSH,以及明确开关和一键清除的宿主代理配置。
2. 复用已经验收的剪贴板、文件投递和共享目录,把连接入口放在用户执行任务的页面,而不是再增加一个堆满网络参数的“高级中心”。
3. 默认仅绑定需要的宿主地址,清楚展示暴露端口和代理状态;CLI 只补这条工作流需要的命令,不追求完整封装所有 QMP 能力。
**验收证据**:不手写 `--extra-args` 或网络命令,完成「Windows 编辑 → macOS 构建 → Windows 浏览器预览 → 取回日志/产物」,并在 VM 重启后验证连接恢复。
**不扩大范围**:不为对标通用虚拟机而引入桥接网络、虚拟交换机等子系统;SLIRP 无法覆盖具体任务时再重新评估。
### U5(按需候选):只有明确场景和验证路径,才进入版本计划
- **iPhone 真机调试 / 硬件密钥**:先确认目标用户和现有替代办法,再评估 M5.10 的 Windows USB 原型、驱动签名与恢复风险;不直接扩展成全量 USB 直通。
- **自动化脚本接口**:先有一个会反复执行的真实流程,例如每日创建干净测试机、运行测试并回收,再设计最小 CLI/API;不为“自动化能力完整”封装全部上游命令。
- **独立备份、迁移和保留策略**:先证明离线备份说明不够,再确定格式、兼容与恢复验收;不能只实现“导出”而没有“恢复”测试。
- **拖放、无缝窗口、更多客户机系统、企业管理**:暂不排期。只有现有方案被真实任务证明不足,且收益高于维护成本时才重新讨论。
### 新功能进入迭代前的统一门槛
1. 写明用户故事、受阻步骤、当前替代办法和不做的后果。
2. 优先复用现有 GUI、CLI、Guest Tools 与上游能力,说明为什么不能只靠文档或默认配置解决。
3. 同时设计校验、失败恢复、隐私与安全边界;涉及磁盘和身份配置的操作必须可回退或可重建。
4. 写明真实用户任务 DoD、测试矩阵和证据形式;只有单元测试的功能保持“已实现”,不得写成“已验收”。
5. 发布时核对用户实际获得的稳定资产和文档。P0 任务未通过时,不用新增 P1 功能代替修复。
---
## 不做的事
- **不为功能列表更好看而做功能**:不盲目扩张企业管理、多平台、多客户机或全量 QMP/API 封装;所有新增能力先经过上面的用户任务与验收门槛。
- **不维护长期 fork**:对上游的改动只走补丁队列,目标是清零(见 `portable-runtime-spec.md` 第 5 节)。
- **不跟踪上游最新 commit**:用户只拿到冒烟过的 `stable`。
- **暂不做 TAP / Wi-Fi MacNAT 虚拟网卡驱动安装器**:维护与签名风险高,优先服务好 SLIRP + SSH 端口转发 + Guest Tools 共享目录。
- **暂不做 TAP / Wi-Fi MacNAT 虚拟网卡驱动安装器**:维护与签名风险高,优先服务好 SLIRP + 多端口转发 + Guest Tools 共享目录。
- **暂不强推运行中内存热快照(`savevm`)**:在未验证 `reims-vgpu` 显存与设备状态序列化前,以可靠的停机快照与 CoW 派生为准。
- **暂不兼容已淘汰的 `apple-gfx` 旧图形栈**,暂不实现 `vphone` 等其他 `Engine`(接口位置保留)。
+100
View File
@@ -0,0 +1,100 @@
# UI 审视(2026-11-28)
> 标准:[dickwu/apple-design-skill](https://github.com/dickwu/apple-design-skill)(MIT;其中 `references/hig/*.md` 为 Apple HIG 原文镜像,版权归 Apple)。按它的五个视角依次看:无障碍 → 平台惯例 → 视觉与工艺 → 交互 → 文案。每条标严重度(Critical / High / Medium / Low),写清现状、依据、改法。
> 范围:VM 主页、VM 设置、宿主与运行时、安装包、新建向导。截图取自 `wails dev`,1280×820,浅色与深色两种外观。
## 结论:需要改进(Needs work)
没有 Critical。High 有 5 条,集中在两点:
- **主页什么都想放**。同一份配置在一页里出现三到四次,功能介绍也写在页面上。
- **上游原始字符串直接给人看**。
留白不够,主要不是间距数值的问题,而是内容太多,又层层套框。
## High
**H1 · VM 主页信息重复,层级是平的**
- 现状:一页从上到下堆了 9 块:标题栏、iMac 主视觉、资源条、提示条、装机引导、Guest Tools 卡片、SSH 行、规格清单、macOS 分组、显示器分组、快捷键条、技术信息。
- CPU 型号出现 2 次,「类型」2 次,分辨率 2 次。
- 网络在规格清单里写一次(原始字符串),在 SSH 行又写一次。
- 依据:`layout.md > Best practices`:把最重要的放在最上方;用留白和分组表达关系;用渐进披露代替堆叠。
- 改法:按「关于本机」的模式重排。
- 第一屏只留四样:主视觉、名称、一行规格、主操作。
- 规格只说一次。
- 连接相关(SSH、Guest Tools、共享文件夹)收成一个分组列表。
- 原始值全部收进底部的「技术信息」折叠区。
**H2 · Guest Tools 卡片写成了功能介绍**
- 现状:
- 第一句是 80 多字的卖点:「免 Xcode/Python 的 Guest Tools 2.0:支持文本 + PNG 截图双向剪贴板(长轮询低延迟)、WebDAV 零双份挂载……」。
- 卡片里又套了一层带边框的开关行,下面还有三个并排按钮。
- 依据:
- `writing.md`:说清楚,删掉多余的字。
- `layout.md`:用容器或留白分组,二选一,不要层层套框。
- 改法:
- 卡片改成分组列表里的普通行:状态写在描述里,操作放右侧。
- 安装命令只在工具盘已插入时出现。
- 功能介绍删掉,交给 README。
**H3 · 上游原始字符串直接展示**
- 现状:
- 网络显示 `user (MAC configured), ssh on 127.0.0.1:2222`。
- 类型显示 `x86-64 macOS guest (q35 and OpenCore, WHPX)`。
- 设置项标题里直接带 `(REIMS_VGPU_LOG)`、`kernel-irqchip`。
- 依据:`writing.md`:标签描述效果,不描述实现。
- 改法:
- 主界面只用人话:「NAT · SSH 2222」。
- 环境变量和参数名放进描述或「技术信息」,标题只保留名词。
**H4 · 系统原生下拉框和自绘控件混在一起**
- 现状:设置「通用」页和新建向导里的 `<select>` 一展开就是 Windows 原生黑底列表,和周围的分段控件、卡片完全不搭(用户截图)。
- 依据:`pop-up-buttons.md`:弹出按钮用于一组互斥选项,要给默认值,标签要让人不展开也能预判。
- 改法:
- 做一个与 macOS 弹出按钮同形的 `PopupSelect`:当前值加 ⌃⌄ 箭头;菜单里当前项带 ✓;次要信息(键盘布局、构建号)用灰字跟在后面。
- 全局替换所有 `<select>`。
**H5 · 窗口和分组标题重复**
- 现状:
- 设置窗口标题是「macos-tahoe 设置」。
- 「通用」页的分组标题「macOS 系统语言」下面,行标题还是「macOS 系统语言」。
- 主页标题「关于此虚拟机」正下方是一个更大的「macos-tahoe」。
- 依据:
- `settings.md`:多页设置窗口的标题就是当前那一页。
- `writing.md`:删掉多余的字。
- 改法:
- 设置窗口标题只写实例名,副标题写状态。
- 分组标题和行标题不能同名。
- 主页去掉「关于此虚拟机」。
## Medium
- **M1 文案没有统一风格**:同一层级里,有的写短语,有的写两三句并用分号连接,还有的夹着 `#123`、`docs/upstream-pr-prep.md` 这种开发者引用。
- 规则:标题是名词;描述一句话,说开启后的效果;不写「需支持……的运行时」这类条件链,条件放进禁用原因。
- **M2 字号层级太多**:同一页里用了 22 / 16 / 13.5 / 13 / 12 / 11.5 / 11 七档。
- 对齐 macOS 文字样式:Large Title 26、Title 3 15、Body 13、Callout 12、Subheadline 11。主页只用其中四档。
- **M3 状态说了三遍**:侧栏圆点、主视觉下的胶囊、主按钮文字都在表达同一个状态。保留侧栏和副标题两处即可。
- **M4 卡片里再套卡片**:Guest Tools 卡片里的开关行、命令行各自有边框。全局规定框最多一层。
- **M5 宿主页**:四个指标卡加五个分组,每组都带灰色提示,看起来很满。指标卡可以保留,提示文字要压到一行以内。
- **M6 新建向导**:每个字段下面都有一两行灰字,例如「留空则使用数据目录」这种可以改成占位文字的说明。
## Low
- 快捷键条只是普通信息,却装在一个框里。改成页面底部的一行脚注。
- 安装包页的「正在读取 Apple 的版本列表…」也放在列表框里,看上去像是一条数据。
## 做得好的
- 侧栏图标、分段控件、开关已经有 macOS 的样子;深色和浅色外观都完整。
- 设置窗口刚改成分组行加依赖置灰,`pop-up` 以外的控件已经统一。
- 主操作每个状态只有一个,符合 `buttons.md`「每个视图一到两个主按钮」。
## 改版落地
| 项 | 处理 |
| --- | --- |
| H1、H2、H3、M3、M4、Low-1 | 重写 `VMPage`:主视觉 → 一行规格 → 操作按钮 → 上下文提示 → 「连接」分组 → 「技术信息」折叠 → 快捷键脚注 |
| H4 | 新增 `ui/settings.tsx > PopupSelect`,替换设置和向导中的 `<select>` |
| H5、M1 | 设置窗口标题只用实例名;分组标题去重;精简设置、主页、向导文案 |
| M2 | 主页只用 26 / 15 / 13 / 12 四档 |
| M5、M6、Low-2 | 本轮不做,留作后续 |
+3 -1
View File
@@ -258,6 +258,8 @@ macos-tahoe ● 运行中 · 12 分钟 [▣ 显示 VM 窗
### 7.2 目录结构
> 现状:没有照这个结构拆分,zustand 也没有引入。实际目录是 `components/`(页面与对话框)、`ui/`(基件封装)、`lib/`(格式化、日志、任务)、`styles/`,状态仍集中在 `App.tsx`。下面是原计划,保留作参考。
```text
src/
app/ AppShell, TitleBar, Sidebar, StatusBar
@@ -318,7 +320,7 @@ src/
### 阶段 1:结构改版(约 1 周,需要 B1–B4、B7)
- 引入 Radix、lucide、zustand,按 7.2 拆分目录。
- 引入 Radix、lucide、zustand,按 7.2 拆分目录。(Radix 和 lucide 已在阶段 0 引入;zustand 和目录拆分没有做,见 7.2)
- 实现新页头(按状态切换主操作)、「⋯」菜单、右键菜单。
- 状态栏 + 任务进度 + 三页签日志面板。
- 装机步骤条、概要卡片、技术信息折叠区。
+20 -5
View File
@@ -10,12 +10,13 @@
| 上游 PR | 方向 | 价值与影响 | 建议动作 |
| :--- | :--- | :--- | :--- |
| `#153` | 图形呈现 | Windows NVIDIA MAILBOX 经 FIFO 首帧优化,改善高帧率与首帧延迟 | 合入后触发 `build-runtime.yml` 产出 `candidate` 并跑冒烟 |
| `#153` | 图形呈现 | Windows NVIDIA MAILBOX 经 FIFO 首帧优化,改善高帧率与首帧延迟 | 合入后 `build-runtime.yml` 每日构建自动产出 `alpha`,再跑冒烟 |
| `#152` | 平台层 | 原生 Windows Vulkan 后端,减少 Windows 图形适配开销 | 合入后升级运行时并对比帧率/稳定性 |
| `#107` | 图形内存 | 采样纹理回读就地消费,降低显存/内存拷贝开销 | 合入后随运行时一并纳入 |
| `#123` | 窗口体验 | `Ctrl+Alt+Enter` 热切全屏 | 合入后在前端文档/帮助提示同步快捷键 |
| `#172` | 窗口体验 | Windows 拖动窗口贴合,消除缩放黑边 | 合入后验证高 DPI 与多显示器缩放 |
| Win → Command | 键位映射 | 自由指针下 Windows 键映射为 macOS Command | 优先向上游提议/提交 PR,避免长期维护私有补丁 |
| `reims-util` `--lang` / `prev-lang:kbd` | 客体语言预设 | `reims-util@7867384` `src/opencore/config.rs:216-228` 硬编码 `prev-lang:kbd=en-US:0` 并置于 `NVRAM > Delete`,导致恢复模式/设置助理强制回退英文 | 短期本仓停机改写 `opencore.qcow2` 并在 `update-opencore` 后重放;长期向上游提议 `opencore --lang` 与重建保留 |
---
@@ -54,13 +55,27 @@
- 上游原代码(`target/i386/whpx/whpx-all.c:3533-3545`)将该错误当作致命错误直接 `goto error` 中止 VM 启动,迫使用户退回 `kernel-irqchip=off`(损失 Hyper-V 内核态 x2APIC / SynIC 加速)。
- **最小修复**:
- 将 `error_report` + `goto error` 改为 `warn_report` 并将 `processor_features.Bank1.NestedVirtSupport` 清零,继续保留完整 `kernel-irqchip=on` 启动。
- **实测状态**:已在 `Reims-Go` 宿主探测逻辑(`internal/host/whpx_probe_windows.go`)复现 `hr=0x80370302`;带该补丁的 `candidate` 运行时需经真机编译冒烟验证后再提上游 PR(**待验证**)。
- **实测状态**:已在 `Reims-Go` 宿主探测逻辑(`internal/host/whpx_probe_windows.go`)复现 `hr=0x80370302`;带该补丁的 `alpha` 运行时需经真机编译冒烟验证后再提上游 PR(**待验证**)。
### PR 4:`util/coroutine-windows: reserve 1 MiB stack with 64 KiB initial commit and check fiber creation`
- **补丁文件**:[`patches/qemu-win32-coroutine-fiber-commit.patch`](../patches/qemu-win32-coroutine-fiber-commit.patch)(独立于 PR 1–3,修改 `util/coroutine-windows.c`)
- **影响环境**:Windows 10 / 11 宿主在高并发磁盘 I/O + GPU/VA-API 显存提交叠加场景(如登录 Apple ID 触发 iCloud/Spotlight 并发读盘与 HEVC 硬解)。
- **复现与根因**:
1. `runtime-3731afd` 真机崩溃日志在 `CPU 0/WHPX` 线程触发 `0xc0000005`(read of `0x0000000000000010`),符号化调用栈为 `execute_ncq_command`(`hw/ide/ahci.c:1096`)→ `blk_aio_prwv`(`block/block-backend.c:1624`)→ `qemu_aio_coroutine_enter`(`util/qemu-coroutine.c:298`)→ `qemu_coroutine_switch`(`util/coroutine-windows.c:58`)→ `KERNELBASE!SwitchToFiber`(`movq 0x10(%rcx), %rax`)。
2. `qemu_coroutine_new()`(`util/coroutine-windows.c:78`)调用 `CreateFiber(COROUTINE_STACK_SIZE, ...)`,Windows 会将 `1 MiB` 全部作为初始 Commit Size 立即扣除系统 Commit Charge;当提交内存见底时 `CreateFiber` 返回 `NULL`,原代码未判空即返回并在 `SwitchToFiber(NULL)` 崩溃。
3. 同时 `qemu_coroutine_self()`(`util/coroutine-windows.c:99`)直接调用 `ConvertThreadToFiber(NULL)`,若线程已被外部库转为 Fiber 会返回 `NULL`(`ERROR_ALREADY_FIBER`)且同样未检查。
- **最小修复**:
1. 改用 `CreateFiberEx(64 * 1024, COROUTINE_STACK_SIZE, 0, ...)`,保留完整 1 MiB 栈空间但将每个协程初始提交降为 64 KiB(提交开销降低 16 倍);
2. 在 `qemu_coroutine_self()` 中通过 `IsThreadAFiber()` 复用现有 Fiber;
3. 对 `co->fiber == NULL` 与 `leader->fiber == NULL` 打印 `GetLastError()` 并显式 `abort()`,杜绝静默空指针解引用。
- **实测状态**:补丁已通过 `git apply --check`(基于 `4571bc5`);需编入下一版 `alpha` 运行时并在真机验证登录后高负载场景(**待验证**)。
---
## 三、补丁退役检查表
每当上游合入对应 PR 并产出新 `candidate` 运行时后:
1. 移除 `patches/` 下对应 `.patch` 文件,并同步更新 `patches/README.md` 与 `scripts/pack-runtime.ps1`;
2. 触发 `.github/workflows/build-runtime.yml` 构建新 `candidate`;
每当上游合入对应 PR(每日构建会跳过该补丁,并开 issue「Patch queue: patches already upstream」提醒)后:
1. 移除 `patches/` 下对应 `.patch` 文件,并同步更新 `patches/series.txt` 与 `patches/README.md`;
2. 等下一次每日构建,或手动触发 `.github/workflows/build-runtime.yml`,产出新 `alpha`;
3. 在真机运行 `scripts/smoke-runtime.ps1` 并人工确认通过后升级为 `stable`。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.1",
"version": "0.2.2",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1 +1 @@
63074d720d82ba66da97ce3a9813911e
7782101f68324d7c033ce75c59399d77
+107 -47
View File
@@ -4,6 +4,7 @@ import { CreateWizard, WizardDraft } from './components/CreateWizard'
import { DeleteDialog } from './components/DeleteDialog'
import { CloneDialog } from './components/CloneDialog'
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
import { SendTextDialog } from './components/SendTextDialog'
import { HostView } from './components/HostView'
import { LogPanel, LogTab } from './components/LogPanel'
import { SettingsModal } from './components/SettingsModal'
@@ -12,13 +13,14 @@ import { HOST_ID, INSTALLERS_ID, Sidebar } from './components/Sidebar'
import { InstallersPage } from './components/InstallersPage'
import { VMAction, VMPage } from './components/VMPage'
import { I18nKey, t } from './i18n'
import { recommendedMemoryGB } from './lib/format'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { LogLine, appendLog } from './lib/logs'
import { currentTask, upsertTask } from './lib/tasks'
import { AppState, CachedInstaller, CreateOpts, Locale, Task, VMDetail } from './types'
import { AppState, CachedInstaller, CreateOpts, Locale, Task, VMDetail, VMStats } from './types'
import { TooltipProvider } from './ui/controls'
import { Toaster, useToasts } from './ui/toast'
import { backend } from './wails'
import { api, events } from './wails'
import { WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime'
const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '')
@@ -38,6 +40,7 @@ const failKey: Record<VMAction, I18nKey> = {
exportDiagnostics: 'failExportDiagnostics',
cloneVM: 'failCloneVM',
type: 'failType',
sendText: 'failType',
delete: 'failDelete',
openFolder: 'failOpenFolder',
}
@@ -46,12 +49,14 @@ export const App: React.FC = () => {
const [state, setState] = useState<AppState | null>(null)
const [selected, setSelected] = useState<string>(HOST_ID)
const [detail, setDetail] = useState<VMDetail | null>(null)
const [vmStats, setVmStats] = useState<VMStats | null>(null)
const [showWizard, setShowWizard] = useState(false)
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
const [showSettings, setShowSettings] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [busy, setBusy] = useState<Record<string, VMAction>>({})
const [loadError, setLoadError] = useState('')
const [theme, setTheme] = useState<'light' | 'dark'>(() => {
@@ -80,7 +85,7 @@ export const App: React.FC = () => {
const refresh = useCallback(async () => {
try {
const s = await backend.getState()
const s = await api.GetState()
setState(s)
setLoadError('')
setSelected((cur) => {
@@ -95,9 +100,9 @@ export const App: React.FC = () => {
useEffect(() => {
refresh()
const offState = backend.onStateChanged(() => { refresh() })
const offState = events.onStateChanged(() => { refresh() })
// Logs never pop the panel open (docs/ui-redesign.md §5.2); errors only bump a badge.
const offLog = backend.onLog((entry) => {
const offLog = events.onLog((entry) => {
setLogLines((prev) => {
const next = appendLog(prev, entry)
const last = next[next.length - 1]
@@ -108,10 +113,10 @@ export const App: React.FC = () => {
})
})
// Tasks (docs/ui-redesign.md §6 B1): seed from the backend, then follow events.
backend.getTasks().then((list) => {
api.GetTasks().then((list) => {
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
}).catch(() => {})
const offTask = backend.onTask((task) => onTaskRef.current(task))
const offTask = events.onTask((task) => onTaskRef.current(task))
return () => { offState(); offLog(); offTask() }
}, [refresh])
@@ -119,10 +124,22 @@ export const App: React.FC = () => {
const selectedVM = selected !== HOST_ID ? vms.find((v) => v.name === selected) : undefined
useEffect(() => {
if (!selectedVM) { setDetail(null); return }
backend.getVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
if (!selectedVM) { setDetail(null); setVmStats(null); return }
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
}, [selectedVM?.name, state])
useEffect(() => {
if (!selectedVM) { setVmStats(null); return }
let live = true
const vmName = selectedVM.name
const sample = () => {
api.GetVMStats(vmName).then((st) => { if (live) setVmStats(st) }).catch(() => {})
}
sample()
const timer = window.setInterval(sample, 3000)
return () => { live = false; window.clearInterval(timer) }
}, [selectedVM?.name, selectedVM?.state])
const locale: Locale = state?.config.locale ?? 'zh-CN'
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
@@ -154,24 +171,24 @@ export const App: React.FC = () => {
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
const installRuntime = (commit: string) => {
backend.installRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e))
api.InstallRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e))
}
const setChannel = (candidate: boolean) => {
backend.setRuntimeChannel(candidate ? 'candidate' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
const setChannel = (alpha: boolean) => {
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
}
const cancelTask = (id: string) => { backend.cancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
const importRuntime = async () => {
try {
const file = await backend.pickFile(tr('importRuntime'), '*.tar.zst;*.zip')
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
if (!file) return
await backend.installRuntimeArchive(file)
await api.InstallRuntimeArchive(file)
await refresh()
} catch (e) {
fail(tr('failRuntime'), e)
}
}
const folderDone = async () => {
const s = await backend.getState().catch(() => null)
const s = await api.GetState().catch(() => null)
if (s) setState(s)
setSetupStage(s?.active_runtime ? null : 'runtime')
}
@@ -191,7 +208,7 @@ export const App: React.FC = () => {
const loadVMLog = async (serial: boolean, name = selectedVM?.name) => {
if (!name) return
try {
const text = await backend.readVMLogs(name, serial)
const text = await api.ReadVMLogs(name, serial)
if (serial) setSerialLog(text)
else setQemuLog(text)
} catch (e) {
@@ -245,13 +262,13 @@ export const App: React.FC = () => {
const attachInstaller = async (name: string, running: boolean) => {
try {
const cached = (await backend.listInstallers()) ?? []
const cached = (await api.ListInstallers()) ?? []
const hasCached = cached.some(
(x) => !x.partial && (x.kind === 'offline' || x.kind === 'online' || /\.(img|dmg)$/i.test(x.name)),
)
let picked = ''
if (!hasCached) {
picked = await backend.pickFile(tr('pickRecoveryTitle'), '*.img;*.dmg')
picked = await api.PickFile(tr('pickRecoveryTitle'), '*.img;*.dmg')
if (!picked) {
setOnlineRecoveryTarget(name)
return
@@ -259,7 +276,7 @@ export const App: React.FC = () => {
}
setBusy((b) => ({ ...b, [name]: 'attachInstaller' }))
try {
const fileName = await backend.attachInstaller(name, picked)
const fileName = await api.AttachInstaller(name, picked)
toasts.push({
kind: 'ok',
title: tr(running ? 'toastInstallerAttachedNextStart' : 'toastInstallerAttached', { name: fileName }),
@@ -281,27 +298,28 @@ export const App: React.FC = () => {
const name = selectedVM.name
const isRunning = selectedVM.state === 'running'
switch (action) {
case 'start': return runVMAction(name, action, () => backend.startVM(name))
case 'stop': return runVMAction(name, action, () => backend.stopVM(name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => backend.stopVM(name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => backend.restartVM(name))
case 'eject': return runVMAction(name, action, () => backend.ejectInstaller(name), tr('toastEjected'))
case 'finishInstall': return runVMAction(name, action, () => backend.finishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
case 'enterRecovery': return runVMAction(name, action, () => backend.enterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
case 'start': return runVMAction(name, action, () => api.StartVM(name))
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
case 'attachInstaller': return attachInstaller(name, isRunning)
case 'attachGuestTools': return runVMAction(name, action, () => backend.attachGuestTools(name), tr(isRunning ? 'toastGuestToolsAttachedNextStart' : 'toastGuestToolsAttached'))
case 'detachGuestTools': return runVMAction(name, action, () => backend.detachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached'))
case 'attachGuestTools': return runVMAction(name, action, () => api.AttachGuestTools(name), tr(isRunning ? 'toastGuestToolsAttachedNextStart' : 'toastGuestToolsAttached'))
case 'detachGuestTools': return runVMAction(name, action, () => api.DetachGuestTools(name), tr(isRunning ? 'toastGuestToolsDetachedNextStart' : 'toastGuestToolsDetached'))
case 'openSharedFolder':
return backend.openSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
return api.OpenSharedFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
case 'upgradeNVMe':
return runVMAction(name, action, () => backend.upgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
return runVMAction(name, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
case 'exportDiagnostics':
return runVMAction(name, action, async () => { await backend.exportDiagnostics(name) }, tr('toastDiagExported'))
return runVMAction(name, action, async () => { await api.ExportDiagnostics(name) }, tr('toastDiagExported'))
case 'cloneVM':
return setCloneSource(name)
case 'type': return typeInto(name, () => backend.typeClipboard(name))
case 'type': return typeInto(name, () => api.TypeClipboard(name))
case 'sendText': return setSendTextTarget(name)
case 'openFolder':
return backend.openVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
case 'delete': return setDeleteTarget(name)
}
}
@@ -309,14 +327,14 @@ export const App: React.FC = () => {
const confirmDelete = (keepFiles: boolean) => {
const name = deleteTarget
setDeleteTarget(null)
if (name) runVMAction(name, 'delete', () => backend.deleteVM(name, keepFiles), tr('toastDeleted', { name }))
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
}
const confirmOnlineRecovery = () => {
const name = onlineRecoveryTarget
setOnlineRecoveryTarget(null)
if (!name) return
backend.downloadAndAttachOnlineRecovery(name, 'latest')
api.DownloadAndAttachOnlineRecovery(name, 'latest')
.then(() => toasts.push({ kind: 'ok', title: tr('toastOnlineRecoveryStarted') }))
.catch((e) => fail(tr('failAttachInstaller'), e))
}
@@ -326,7 +344,7 @@ export const App: React.FC = () => {
setCloneSource(null)
if (!src) return
runVMAction(src, 'cloneVM', async () => {
await backend.cloneVMCoW(src, cloneName)
await api.CloneVMCoW(src, cloneName)
setSelected(cloneName)
}, tr('toastCloned', { name: cloneName }))
}
@@ -369,7 +387,7 @@ export const App: React.FC = () => {
disk_controller: 'nvme',
graphics: 'reims-vgpu',
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
resolution: '1920x1080',
resolution: recommendedResolution(state.host),
displays: 1,
borderless: false,
capture: false,
@@ -377,6 +395,7 @@ export const App: React.FC = () => {
network: !isOffline,
ssh_port: 0,
logs: true,
guest_lang: defaultGuestLang(locale),
start: true,
},
})
@@ -389,7 +408,7 @@ export const App: React.FC = () => {
setShowWizard(false)
setWizardDraft(null)
const name = payload.name
backend.createVM(payload)
api.CreateVM(payload)
.then(() => {
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
setSelected(name)
@@ -416,7 +435,7 @@ export const App: React.FC = () => {
}
const setLang = async (l: Locale) => {
await backend.setLocale(l)
await api.SetLocale(l)
refresh()
}
@@ -424,7 +443,7 @@ export const App: React.FC = () => {
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showWizard || showSettings || deleteTarget) return
if (showWizard || showSettings || deleteTarget || sendTextTarget) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
@@ -439,7 +458,7 @@ export const App: React.FC = () => {
return (
<TooltipProvider>
<div className="app-shell">
<header className="titlebar" onDoubleClick={() => backend.winToggleMaximise()}>
<header className="titlebar" onDoubleClick={() => WindowToggleMaximise()}>
<div className="brand">
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
Reims-Go
@@ -455,9 +474,9 @@ export const App: React.FC = () => {
{theme === 'light' ? <Moon size={14} /> : <Sun size={14} />}
</button>
<div className="win-controls">
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => backend.winMinimise()}><Minus size={14} /></button>
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => backend.winToggleMaximise()}><Square size={12} /></button>
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => backend.winQuit()}><X size={15} /></button>
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} /></button>
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} /></button>
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} /></button>
</div>
</div>
</header>
@@ -511,6 +530,7 @@ export const App: React.FC = () => {
name={selectedVM.name}
state={effectiveState}
detail={detail}
stats={vmStats}
host={state.host}
pending={pending}
busyAction={busy[selectedVM.name]}
@@ -519,7 +539,30 @@ export const App: React.FC = () => {
onDelete={() => setDeleteTarget(selectedVM.name)}
onViewLogs={() => { openLogs('serial'); loadSerial() }}
onCopy={copy}
onTypeText={(text) => typeInto(selectedVM.name, () => backend.typeText(selectedVM.name, text))}
onTypeText={(text) => typeInto(selectedVM.name, () => api.TypeText(selectedVM.name, text))}
onToggleBorderless={(enabled) => {
api.ToggleBorderless(selectedVM.name, enabled)
.then(() => {
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastBorderlessNextStart' : 'toastBorderlessUpdated') })
return refresh()
})
.catch((e) => fail(tr('failGeneric'), e))
}}
onTogglePreventSleep={(enabled) => {
api.SetGuestPreventSleep(selectedVM.name, enabled)
.then(() => {
toasts.push({ kind: 'ok', title: tr(enabled ? 'toastPreventSleepOn' : 'toastPreventSleepOff') })
return refresh()
})
.catch((e) => fail(tr('failGuestTools'), e))
}}
onDeliverFile={() => {
api.DeliverFileToGuest(selectedVM.name)
.then((fileName) => {
if (fileName) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: fileName }) })
})
.catch((e) => fail(tr('failGuestTools'), e))
}}
/>
) : (
<HostView
@@ -572,9 +615,12 @@ export const App: React.FC = () => {
<SettingsModal
locale={locale}
detail={detail}
stats={vmStats}
host={state.host}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
onDiskChanged={refresh}
onClose={() => setShowSettings(false)}
onSaved={() => {
setShowSettings(false)
@@ -607,6 +653,20 @@ export const App: React.FC = () => {
/>
)}
{sendTextTarget && (
<SendTextDialog
locale={locale}
vmName={sendTextTarget}
guestToolsConnected={Boolean(vmStats?.guest_tools_connected ?? detail?.guest_tools_connected)}
onCancel={() => setSendTextTarget(null)}
onConfirm={(text) => {
const target = sendTextTarget
setSendTextTarget(null)
typeInto(target, () => api.TypeText(target, text))
}}
/>
)}
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} />
</div>
</TooltipProvider>
+369 -246
View File
@@ -1,11 +1,29 @@
import { ChevronRight, CircleAlert, CircleCheck, Check, Copy } from 'lucide-react'
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { formatMemory, gpuLabel, recommendedMemoryGB, shortGPUName } from '../lib/format'
import {
GUEST_LANG_PRESETS,
MEMORY_MARKS,
controllerLabel,
defaultGuestLang,
formatMemory,
gpuLabel,
guestLangLabel,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
recommendedDisplayPresets,
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
splitLangLabel,
sshCommand,
} from '../lib/format'
import { CachedInstaller, CreateOpts, HostReport, Locale, Release, ValidationIssue } from '../types'
import { Button, IconButton } from '../ui/controls'
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Modal } from '../ui/dialog'
import { backend } from '../wails'
import { api } from '../wails'
/** Reopen the wizard where the user left it (e.g. after a failed create). */
export interface WizardDraft {
@@ -26,13 +44,21 @@ const REVIEW_STEP = 5
// Which wizard step owns each ValidationIssue.field (internal/driver/reims/reims.go ValidateCreate).
const STEP_OF_FIELD: Record<string, number> = {
name: 1, installer: 1, disk: 1, macos: 1,
installer: 1, disk: 1, macos: 1, guest_lang: 1,
cpus: 2, memory: 2,
disk_size: 3, disk_controller: 3,
graphics: 4, gpu: 4, resolution: 4, displays: 4, ssh_port: 4,
}
const stepOfIssue = (i: ValidationIssue) => STEP_OF_FIELD[i.field] ?? REVIEW_STEP
// Step ① as large cards, one per way to get macOS (Parallels / UTM style).
const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideIcon; title: I18nKey; sub: I18nKey }[] = [
{ mode: 'offline', icon: Package, title: 'srcOfflineTitle', sub: 'srcOfflineSub' },
{ mode: 'apple', icon: CloudDownload, title: 'srcAppleTitle', sub: 'srcAppleSub' },
{ mode: 'installer', icon: Disc3, title: 'srcInstallerTitle', sub: 'srcInstallerSub' },
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
]
export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, onSubmit }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [step, setStep] = useState(draft?.step ?? 1)
@@ -52,7 +78,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
macos: '',
offline: true,
installer: '',
cpus: host.logical_cpus >= 12 ? 8 : 4,
cpus: recommendedCPUs(host),
memory: `${recommendedMemoryGB(host)}G`,
disk_size: '128G',
disk: '',
@@ -60,7 +86,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
disk_controller: 'nvme',
graphics: 'reims-vgpu',
gpu: host.recommended_gpu?.vulkan_icd ?? 'auto',
resolution: '1920x1080',
resolution: recommendedResolution(host),
displays: 1,
borderless: false,
capture: false,
@@ -68,6 +94,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
network: false,
ssh_port: 0,
logs: true,
guest_lang: defaultGuestLang(locale),
start: true,
})
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
@@ -102,8 +129,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
useEffect(() => {
if (opts.source_mode !== 'offline' || releases) return
let live = true
backend.listInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
backend.listOfflineReleases()
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
api.ListOfflineReleases()
.then((list) => {
if (!live) return
setReleases(list ?? [])
@@ -123,7 +150,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
setChecking(true)
const timer = setTimeout(() => {
const payload = buildPayload()
Promise.all([backend.validateCreate(payload), backend.previewCreate(payload)])
Promise.all([api.ValidateCreate(payload), api.PreviewCreate(payload)])
.then(([iss, cmd]) => {
if (!live) return
setIssues(iss ?? [])
@@ -137,12 +164,12 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
}, [step, reviewed, opts])
const pickDir = async () => {
const dir = await backend.pickDirectory(tr('vmDir'))
const dir = await api.PickDirectory(tr('vmDir'))
if (dir) set({ dir })
}
const pickFile = async (field: 'installer' | 'disk', pattern: string) => {
const f = await backend.pickFile(tr(field === 'installer' ? 'sourceInstaller' : 'sourceDisk'), pattern)
const f = await api.PickFile(tr(field === 'installer' ? 'sourceInstaller' : 'sourceDisk'), pattern)
if (f) set({ [field]: f })
}
@@ -150,20 +177,17 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
const threads = Math.max(host.logical_cpus || 0, 1)
const cpuRec = recommendedCPUs(host)
const memRec = recommendedMemoryGB(host)
const memSafe = memorySafeLimitGB(host)
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
const memGB = Math.round(parseMemoryGB(opts.memory) ?? memRec)
const steps: I18nKey[] = ['step1', 'step2', 'step3', 'step4', 'step5']
const presets = <T extends string | number>(values: T[], current: T | undefined, label: (v: T) => string, pick: (v: T) => void) => (
<div className="presets">
{values.map((v) => (
<button key={v} type="button" className="preset" aria-pressed={current === v} onClick={() => pick(v)}>
{label(v)}
</button>
))}
</div>
)
return (
<Modal title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{steps.map((key, idx) => {
const n = idx + 1
@@ -187,246 +211,315 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
<div className="dialog-body">
{err && <div className="notice notice-error">{err}</div>}
<div key={step} className="step-anim">
{step === 1 && (
<>
<div className="field">
<label className="field-label" htmlFor="vm-name">{tr('vmName')}</label>
<input id="vm-name" className="input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
{SOURCES.map((s) => {
const Icon = s.icon
const on = opts.source_mode === s.mode
return (
<label key={s.mode} className="source-card" data-selected={on || undefined}>
<input
type="radio"
name="source"
checked={on}
onChange={() => set({
source_mode: s.mode,
network: s.mode !== 'offline',
...(s.mode === 'apple' ? { macos: 'tahoe' } : {}),
...(s.mode === 'offline' ? { macos: releases?.[0]?.version ?? '' } : {}),
})}
/>
<span className={`source-icon source-icon-${s.mode}`} aria-hidden="true"><Icon size={20} /></span>
<span className="source-title">
{tr(s.title)}
{s.mode === 'offline' && <span className="badge badge-accent">{tr('recommendedBadge')}</span>}
</span>
<span className="source-sub">{tr(s.sub)}</span>
</label>
)
})}
</div>
<div className="field">
<label className="field-label" htmlFor="vm-dir">{tr('vmDir')}</label>
<div className="input-group">
<input id="vm-dir" className="input mono" value={opts.dir ?? ''} onChange={(e) => set({ dir: e.target.value })} />
<Button onClick={pickDir}>{tr('choose')}</Button>
</div>
<span className="hint">{tr('vmDirHint')}</span>
</div>
<fieldset className="field choices fieldset">
<legend className="field-label">{tr('step1')}</legend>
{(['offline', 'apple', 'installer', 'disk'] as const).map((mode) => (
<label key={mode} className="choice">
<input
type="radio"
name="source"
checked={opts.source_mode === mode}
onChange={() => set({
source_mode: mode,
network: mode !== 'offline',
...(mode === 'apple' ? { macos: 'tahoe' } : {}),
...(mode === 'offline' ? { macos: releases?.[0]?.version ?? '' } : {}),
})}
<SetGroup>
{opts.source_mode === 'apple' && (
<SetRow
title={tr('macosVersion')}
control={<PopupSelect id="vm-macos" label={tr('macosVersion')} value={opts.macos} onChange={(macos) => set({ macos })} options={[{ value: 'tahoe', label: 'macOS Tahoe' }]} />}
/>
)}
{opts.source_mode === 'offline' && (
<SetRow
title={tr('macosVersion')}
desc={releasesErr
? <span className="warn-text">{tr('offlineListFailed')}:{releasesErr}</span>
: needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10
? <span className="warn-text">{tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })}</span>
: tr('offlineHint')}
control={!releases
? <span className="muted">{releasesErr ? '—' : tr('offlineLoading')}</span>
: (
<PopupSelect
id="vm-release"
label={tr('macosVersion')}
value={opts.macos}
onChange={(macos) => set({ macos })}
options={releases.map((r) => ({
value: r.version,
label: `macOS ${r.version}`,
detail: `${(r.size / 1e9).toFixed(1)} GB${isCached(r.version) ? ` · ${tr('offlineCached')}` : ''}`,
}))}
/>
)}
/>
)}
{(opts.source_mode === 'installer' || opts.source_mode === 'disk') && (() => {
const isInstaller = opts.source_mode === 'installer'
const file = (isInstaller ? opts.installer : opts.disk) ?? ''
return (
<SetRow
title={tr(isInstaller ? 'srcInstallerTitle' : 'srcDiskTitle')}
desc={file ? <span className="mono path-text" title={file}>{file}</span> : tr('wizNoFile')}
control={
<Button onClick={() => (isInstaller
? pickFile('installer', '*.img;*.dmg')
: pickFile('disk', '*.qcow2;*.img;*.vmdk;*.raw'))}
>
{tr('wizChooseFile')}
</Button>
}
/>
{tr(mode === 'offline' ? 'sourceOffline' : mode === 'apple' ? 'sourceApple' : mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
</label>
))}
</fieldset>
{opts.source_mode === 'apple' && (
<div className="field">
<label className="field-label" htmlFor="vm-macos">{tr('macosVersion')}</label>
<select id="vm-macos" className="select" value={opts.macos} onChange={(e) => set({ macos: e.target.value })}>
<option value="tahoe">{tr('macosTahoe')}</option>
</select>
</div>
)}
{opts.source_mode === 'offline' && (
<div className="field">
<label className="field-label" htmlFor="vm-release">{tr('macosVersion')}</label>
{releasesErr ? (
<div className="notice notice-error">{tr('offlineListFailed')}:{releasesErr}</div>
) : !releases ? (
<span className="hint">{tr('offlineLoading')}</span>
) : (
<select id="vm-release" className="select" value={opts.macos} onChange={(e) => set({ macos: e.target.value })}>
{releases.map((r) => (
<option key={r.product} value={r.version}>
{r.title} {r.version} ({r.build}) · {(r.size / 1e9).toFixed(1)} GB{isCached(r.version) ? ` · ${tr('offlineCached')}` : ''}
</option>
))}
</select>
)}
<span className="hint">{tr('offlineHint')}</span>
{needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10 && (
<span className="hint warn">{tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })}</span>
)}
</div>
)}
{(opts.source_mode === 'installer' || opts.source_mode === 'disk') && (
<div className="field">
<label className="field-label" htmlFor="vm-src">
{tr(opts.source_mode === 'installer' ? 'sourceInstaller' : 'sourceDisk')}
</label>
<div className="input-group">
<input
id="vm-src"
className="input mono"
value={(opts.source_mode === 'installer' ? opts.installer : opts.disk) ?? ''}
onChange={(e) => set(opts.source_mode === 'installer' ? { installer: e.target.value } : { disk: e.target.value })}
)
})()}
<SetRow
title={tr('guestLangShort')}
desc={tr('guestLangHint')}
control={
<PopupSelect
id="vm-guest-lang"
label={tr('guestLangShort')}
value={opts.guest_lang || defaultGuestLang(locale)}
onChange={(guest_lang) => set({ guest_lang })}
options={GUEST_LANG_PRESETS.map((p) => splitLangLabel(p.value, locale === 'zh-CN' ? p.zh : p.en))}
/>
<Button
onClick={() => (opts.source_mode === 'installer'
? pickFile('installer', '*.img;*.dmg')
: pickFile('disk', '*.qcow2;*.img;*.vmdk;*.raw'))}
>
{tr('choose')}
</Button>
</div>
</div>
)}
}
/>
</SetGroup>
</>
)}
{step === 2 && (
<>
<div className="field">
<span className="field-label">{tr('factCPU')} · {tr('hostThreads', { n: host.logical_cpus })}</span>
{presets(
[4, 6, 8, 12].filter((n) => n <= Math.max(host.logical_cpus, 4)),
opts.cpus,
(n) => tr('cores', { n }),
(cpus) => set({ cpus }),
)}
<span className="hint">{tr('cpuHint')}</span>
</div>
<div className="field">
<label className="field-label" htmlFor="vm-mem">{tr('factMemory')} · {tr('hostMemory', { n: host.total_ram_gb.toFixed(0) })}</label>
{presets(['4G', '8G', '12G', '16G', '24G'], opts.memory, (m) => m, (memory) => set({ memory }))}
<input id="vm-mem" className="input" value={opts.memory} onChange={(e) => set({ memory: e.target.value })} />
<span className="hint">
{host.commit_avail_gb > 0
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recommendedMemoryGB(host) })
: tr('memHint')}
</span>
</div>
</>
<SetGroup>
<SetRow
title={tr('vcpus')}
desc={(opts.cpus ?? 0) > threads - 2 && threads > 2
? <span className="warn-text">{tr('cpuOverHint')}</span>
: tr('cpuRecHint', { rec: cpuRec, n: threads })}
block={
<RangeField
label={tr('vcpus')}
value={opts.cpus ?? cpuRec}
min={1}
max={threads}
unit={tr('coresUnit')}
onChange={(cpus) => set({ cpus })}
recommend={[Math.min(4, cpuRec), cpuRec]}
warnFrom={threads > 2 ? threads - 1 : undefined}
marks={[1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64].concat(threads).map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
<SetRow
title={tr('guestMemory')}
desc={memGB > memSafe
? <span className="warn-text">{tr('memOverHint')}</span>
: host.commit_avail_gb > 0
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: memRec })
: tr('memRecHint', { rec: memRec, n: host.total_ram_gb.toFixed(0) })}
block={
<RangeField
label={tr('guestMemory')}
value={memGB}
min={2}
max={memMax}
unit="GB"
onChange={(gb) => set({ memory: `${gb}G` })}
recommend={[Math.min(4, memRec), memRec]}
warnFrom={memSafe + 1}
marks={MEMORY_MARKS.concat(memMax).map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
</SetGroup>
)}
{step === 3 && (
<>
<SetGroup>
{opts.source_mode !== 'disk' ? (
<div className="field">
<label className="field-label" htmlFor="vm-disk">{tr('diskSize')}</label>
{presets(['64G', '128G', '256G', '512G'], opts.disk_size, (s) => s, (disk_size) => set({ disk_size }))}
<input id="vm-disk" className="input" value={opts.disk_size ?? ''} onChange={(e) => set({ disk_size: e.target.value })} />
<span className="hint">{tr('diskSizeHint')}</span>
</div>
<SetRow
title={tr('diskSize')}
desc={tr('diskSizeHint')}
control={
<Segmented
label={tr('diskSize')}
value={opts.disk_size}
onChange={(disk_size) => set({ disk_size })}
options={Array.from(new Set(['64G', '128G', '256G', '512G', opts.disk_size ?? '128G'])).map((v) => ({ value: v, label: formatMemory(v) }))}
/>
}
/>
) : (
<div className="field">
<label className="field-label" htmlFor="vm-diskmode">{tr('diskMode')}</label>
<select
id="vm-diskmode"
className="select"
value={opts.disk_mode}
onChange={(e) => set({ disk_mode: e.target.value as 'copy' | 'in-place' })}
>
<option value="copy">{tr('diskModeCopy')}</option>
<option value="in-place">{tr('diskModeInPlace')}</option>
</select>
</div>
<SetRow
title={tr('diskMode')}
control={
<Segmented
label={tr('diskMode')}
value={opts.disk_mode}
onChange={(disk_mode) => set({ disk_mode })}
options={[
{ value: 'copy' as const, label: tr('diskModeCopy') },
{ value: 'in-place' as const, label: tr('diskModeInPlace') },
]}
/>
}
/>
)}
<div className="field">
<label className="field-label" htmlFor="vm-diskctl">{tr('diskController')}</label>
<select
id="vm-diskctl"
className="select"
value={opts.disk_controller ?? 'nvme'}
onChange={(e) => set({ disk_controller: e.target.value as 'nvme' | 'ahci' | 'virtio' })}
>
<option value="nvme">NVMe ({locale === 'zh-CN' ? '推荐' : 'Recommended'})</option>
<option value="ahci">SATA (AHCI)</option>
{opts.source_mode === 'disk' && <option value="virtio">VirtIO</option>}
</select>
<span className="hint">{tr('diskControllerNvmeHint')}</span>
</div>
</>
<SetRow
title={tr('diskController')}
desc={tr('diskControllerNvmeHint')}
control={
<Segmented
label={tr('diskController')}
value={opts.disk_controller ?? 'nvme'}
onChange={(disk_controller) => set({ disk_controller })}
options={[
{ value: 'nvme' as const, label: 'NVMe' },
{ value: 'ahci' as const, label: 'SATA' },
...(opts.source_mode === 'disk' ? [{ value: 'virtio' as const, label: 'VirtIO' }] : []),
]}
/>
}
/>
</SetGroup>
)}
{step === 4 && (
<>
<div className="field">
<label className="field-label" htmlFor="vm-gfx">{tr('graphicsBackend')}</label>
<select
id="vm-gfx"
className="select"
value={opts.graphics}
onChange={(e) => set({ graphics: e.target.value as 'reims-vgpu' | 'vmware-svga' })}
>
<option value="reims-vgpu">{tr('graphicsReims')}</option>
<option value="vmware-svga">{tr('graphicsSvga')}</option>
</select>
</div>
{opts.graphics === 'reims-vgpu' && (
<>
<div className="field">
<label className="field-label" htmlFor="vm-gpu">{tr('gpuSelect')}</label>
<select id="vm-gpu" className="select" value={opts.gpu} onChange={(e) => set({ gpu: e.target.value })}>
<option value="auto">{tr('gpuAutoOption')}</option>
{realGPUs.map((g) => (
<option key={g.vulkan_icd} value={g.vulkan_icd}>{shortGPUName(g.name)}</option>
))}
</select>
</div>
<div className="field-row">
<div className="field">
<label className="field-label" htmlFor="vm-res">{tr('resolution')}</label>
<select id="vm-res" className="select" value={opts.resolution} onChange={(e) => set({ resolution: e.target.value })}>
<option value="1920x1080">1920 × 1080</option>
<option value="2560x1440">2560 × 1440</option>
<option value="2880x1800">2880 × 1800 HiDPI</option>
<option value="3840x2160">3840 × 2160 HiDPI</option>
</select>
</div>
<div className="field">
<label className="field-label" htmlFor="vm-displays">{tr('displays')}</label>
<select id="vm-displays" className="select" value={opts.displays} onChange={(e) => set({ displays: Number(e.target.value) })}>
{[1, 2, 3, 4].map((d) => <option key={d} value={d}>{d}</option>)}
</select>
</div>
</div>
</>
)}
<div className="field">
<label className="field-label" htmlFor="vm-ssh">{tr('sshPort')}</label>
<input
id="vm-ssh"
className="input"
type="number"
min={0}
max={65535}
value={opts.ssh_port ?? 0}
onChange={(e) => set({ ssh_port: Number(e.target.value) })}
/>
<span className="hint">{tr('sshPortHint')}</span>
</div>
<div className="choices">
{([
['audio', 'enableAudio'],
['network', 'enableNetwork'],
['capture', 'captureInput'],
['logs', 'enableLogs'],
['start', 'startAfterCreate'],
] as const).map(([key, label]) => (
<label key={key} className="choice">
<input
type="checkbox"
checked={!!opts[key]}
onChange={(e) => set({ [key]: e.target.checked })}
<SetGroup title={tr('groupGraphics')}>
<SetRow
title={tr('graphicsBackend')}
desc={opts.graphics === 'vmware-svga' ? tr('graphicsSvgaDesc') : tr('graphicsReimsDesc')}
control={
<Segmented
label={tr('graphicsBackend')}
value={opts.graphics}
onChange={(graphics) => set({ graphics })}
options={[
{ value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') },
{ value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') },
]}
/>
{tr(label)}
</label>
))}
</div>
<span className="hint">{tr('captureInputHint')}</span>
{opts.source_mode === 'offline' && <span className="hint">{tr('networkOfflineHint')}</span>}
}
/>
<SetRow
title={tr('gpuSelect')}
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
control={
<PopupSelect
id="vm-gpu"
label={tr('gpuSelect')}
value={opts.gpu}
onChange={(gpu) => set({ gpu })}
options={[
{ value: 'auto', label: tr('gpuAutoTitle'), detail: host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : undefined },
...realGPUs.map((g) => ({ value: g.vulkan_icd, label: shortGPUName(g.name) })),
]}
/>
}
/>
<SetRow
title={tr('resolution')}
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
desc={host.primary_display
? tr('hostDisplayHint', {
w: host.primary_display.width,
h: host.primary_display.height,
scale: host.primary_display.scale_pct || 100,
rec: host.recommended_resolution || '1920x1080',
})
: undefined}
control={
<PopupSelect
id="vm-res"
label={tr('resolution')}
value={opts.resolution}
onChange={(resolution) => set({ resolution })}
options={recommendedDisplayPresets(host).map((p) => ({
value: p.resolution,
label: p.label,
detail: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
}))}
/>
}
/>
<SetRow
title={tr('displays')}
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
control={
<Segmented
label={tr('displays')}
value={opts.displays}
onChange={(displays) => set({ displays })}
options={[1, 2, 3, 4].map((d) => ({ value: d, label: String(d) }))}
/>
}
/>
</SetGroup>
<SetGroup title={tr('wizOptions')}>
<SetRow
title={tr('networkTitle')}
desc={opts.source_mode === 'offline' ? tr('networkOfflineHint') : tr('networkDesc')}
control={<Switch label={tr('networkTitle')} checked={!!opts.network} onChange={(network) => set({ network })} />}
/>
<SetRow
title={tr('sshForward')}
desc={(opts.ssh_port ?? 0) > 0 ? <code className="inline-code">{sshCommand(opts.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
disabled={!opts.network}
reason={tr('sshNeedsNetwork')}
control={
<div className="hstack">
{(opts.ssh_port ?? 0) > 0 && (
<NumberField label={tr('sshPort')} value={opts.ssh_port ?? 0} min={1} max={65535} onChange={(ssh_port) => set({ ssh_port })} />
)}
<Switch label={tr('sshForward')} checked={(opts.ssh_port ?? 0) > 0} onChange={(on) => set({ ssh_port: on ? 2222 : 0 })} />
</div>
}
/>
<SetRow
title={tr('enableAudio')}
control={<Switch label={tr('enableAudio')} checked={!!opts.audio} onChange={(audio) => set({ audio })} />}
/>
<SetRow
title={tr('captureInput')}
desc={tr('captureInputHint')}
control={<Switch label={tr('captureInput')} checked={!!opts.capture} onChange={(capture) => set({ capture })} />}
/>
<SetRow
title={tr('fullscreenLaunch')}
desc={tr('fullscreenLaunchHint')}
control={<Switch label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => set({ borderless })} />}
/>
<SetRow
title={tr('enableLogs')}
control={<Switch label={tr('enableLogs')} checked={!!opts.logs} onChange={(logs) => set({ logs })} />}
/>
</SetGroup>
</>
)}
@@ -439,8 +532,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
checking={checking}
command={cmdPreview}
onEdit={setStep}
onName={(name) => set({ name })}
onPickDir={pickDir}
onDir={(dir) => set({ dir })}
onStartAfter={(start) => set({ start })}
/>
)}
</div>
</div>
<div className="dialog-foot">
@@ -470,6 +568,10 @@ interface ReviewProps {
checking: boolean
command: string
onEdit: (step: number) => void
onName: (name: string) => void
onDir: (dir: string) => void
onPickDir: () => void
onStartAfter: (start: boolean) => void
}
type Row = { label: string; value: string; mono?: boolean }
@@ -477,7 +579,7 @@ type Row = { label: string; value: string; mono?: boolean }
const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '')
/** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit }) => {
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [copied, setCopied] = useState(false)
const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off')
@@ -503,9 +605,8 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
step: 1,
title: 'step1',
rows: [
{ label: tr('vmName'), value: opts.name },
{ label: tr('summarySource'), value: source },
{ label: tr('vmDir'), value: opts.dir || tr('summaryDefaultDir'), mono: !!opts.dir },
{ label: tr('guestLangShort'), value: guestLangLabel(locale, opts.guest_lang) },
],
},
{
@@ -523,7 +624,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
...(opts.source_mode !== 'disk'
? [{ label: tr('diskSize'), value: tr('summaryDiskGrow', { size: formatMemory(opts.disk_size ?? '') }) }]
: [{ label: tr('diskMode'), value: tr(opts.disk_mode === 'in-place' ? 'diskModeInPlace' : 'diskModeCopy') }]),
{ label: tr('diskController'), value: (opts.disk_controller ?? 'nvme').toUpperCase() === 'AHCI' ? 'SATA' : (opts.disk_controller ?? 'nvme').toUpperCase() },
{ label: tr('diskController'), value: controllerLabel(opts.disk_controller ?? 'nvme') },
],
},
{
@@ -536,12 +637,12 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
{ label: tr('captureInput'), value: onOff(opts.capture) },
{ label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') },
{ label: tr('summaryLogs'), value: onOff(opts.logs) },
{ label: tr('summaryStartAfter'), value: onOff(opts.start) },
],
},
]
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP)
const nameIssue = issues.find((i) => i.field === 'name')?.message
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name')
const copy = async () => {
try {
@@ -553,6 +654,28 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
return (
<>
<SetGroup>
<SetRow
title={tr('vmName')}
error={nameIssue}
control={<input className="input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
/>
<SetRow
title={tr('vmDir')}
desc={opts.dir ? <span className="mono path-text" title={opts.dir}>{opts.dir}</span> : tr('summaryDefaultDir')}
control={
<div className="hstack">
{opts.dir && <Button variant="ghost" onClick={() => onDir('')}>{tr('useDefault')}</Button>}
<Button onClick={onPickDir}>{tr('wizChooseFile')}</Button>
</div>
}
/>
<SetRow
title={tr('startAfterCreate')}
control={<Switch label={tr('startAfterCreate')} checked={!!opts.start} onChange={onStartAfter} />}
/>
</SetGroup>
{checking && issues.length === 0 ? (
<div className="review-status">{tr('validationChecking')}</div>
) : issues.length > 0 ? (
+49 -13
View File
@@ -4,7 +4,7 @@ import { I18nKey, t } from '../i18n'
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import { AppState, AppUpdateInfo, Locale, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { backend } from '../wails'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
@@ -14,7 +14,7 @@ interface Props {
onError: (title: string, e: unknown) => void
onSetLocale: (l: Locale) => void
runtimeTask: Task | null
onChannel: (candidate: boolean) => void
onChannel: (alpha: boolean) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
}
@@ -32,7 +32,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
setCheckingUpdate(true)
setUpdateErr('')
try {
const info = await backend.checkAppUpdate(force)
const info = await api.CheckAppUpdate(force)
setAppUpdate(info)
} catch (e) {
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
@@ -67,20 +67,20 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
const enableWHPX = async () => {
setEnabling(true)
await guard(() => backend.enableWHPX())()
await guard(() => api.EnableWHPX())()
setEnabling(false)
}
const pickDataRoot = guard(async () => {
const dir = await backend.pickDirectory(tr('hostDataRoot'))
if (dir) await backend.setDataRoot(dir)
const dir = await api.PickDirectory(tr('hostDataRoot'))
if (dir) await api.SetDataRoot(dir)
})
const importRuntime = async () => {
setImporting(true)
await guard(async () => {
const file = await backend.pickFile(tr('importRuntime'), '*.tar.zst;*.zip')
if (file) await backend.installRuntimeArchive(file)
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
if (file) await api.InstallRuntimeArchive(file)
})()
setImporting(false)
}
@@ -134,7 +134,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
<div className="list">
<RuntimeOnline
locale={locale}
channel={config.runtime_channel === 'candidate' ? 'candidate' : 'stable'}
channel={config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
installed={runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
@@ -148,7 +148,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
</div>
<div className="row-right">
<Button onClick={guard(() => backend.useRuntime(rt.commit))}>{tr('activate')}</Button>
<Button onClick={guard(() => api.UseRuntime(rt.commit))}>{tr('activate')}</Button>
</div>
</div>
))}
@@ -186,7 +186,24 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
aria-label={tr('autoPinPCores')}
disabled={!pcoreOpt?.supported}
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
onChange={(e) => guard(() => backend.setAutoPinPCores(e.target.checked))()}
onChange={(e) => guard(() => api.SetAutoPinPCores(e.target.checked))()}
/>
<span className="slider" />
</label>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('minimizeToTray')}</div>
<div className="row-sub">{tr('minimizeToTraySub')}</div>
</div>
<div className="row-right">
<label className="switch">
<input
type="checkbox"
aria-label={tr('minimizeToTray')}
checked={config.minimize_to_tray !== false}
onChange={(e) => guard(() => api.SetMinimizeToTray(e.target.checked))()}
/>
<span className="slider" />
</label>
@@ -204,7 +221,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
<div className="row">
<div className="row-main">
<div className="row-title">
{tr('appVersionTitle')} <span className="mono">{state.app_version ?? appUpdate?.current ?? 'v0.2.1'}</span>
{tr('appVersionTitle')} <span className="mono">{state.app_version ?? appUpdate?.current ?? 'v0.2.2'}</span>
{appUpdate && !appUpdate.has_update && (
<span className="badge badge-ok">{tr('appUpToDate')}</span>
)}
@@ -220,7 +237,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
<Button
variant="primary"
icon={<Download size={14} />}
onClick={() => guard(() => backend.openURL(appUpdate.page_url || appUpdate.download_url || ''))()}
onClick={() => guard(() => api.OpenURL(appUpdate.page_url || appUpdate.download_url || ''))()}
>
{tr('appDownloadUpdate')}
</Button>
@@ -295,6 +312,25 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
)}
</div>
</section>
{(host.displays?.length ?? 0) > 0 && (
<section className="section">
<div className="section-title">{tr('hostDisplays')}</div>
<div className="list">
{(host.displays ?? []).map((d, idx) => (
<div className="row" key={d.name || idx}>
<div className="row-main">
<div className="row-title">
{d.width} × {d.height}
{d.refresh_hz ? ` @ ${d.refresh_hz}Hz` : ''}
<span className="badge">{d.scale_pct || 100}%</span>
{d.primary && <span className="badge badge-ok">{tr('hostDisplayPrimary')}</span>}
</div>
</div>
</div>
))}
</div>
</section>
)}
</div>
)
}
+7 -7
View File
@@ -4,7 +4,7 @@ import { I18nKey, t } from '../i18n'
import { taskDetail } from '../lib/tasks'
import { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { backend } from '../wails'
import { api } from '../wails'
interface Props {
locale: Locale
@@ -33,11 +33,11 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
const running = (version: string) => downloads.find((x) => x.status === 'running' && x.subject === version)
const finishedCount = downloads.filter((x) => x.status !== 'running').length
const loadCached = () => backend.listInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
const loadCached = () => api.ListInstallers().then((l) => setCached(l ?? [])).catch((e) => onError(tr('failGeneric'), e))
const loadReleases = () => {
setReleases(null)
setReleasesErr('')
backend.listOfflineReleases()
api.ListOfflineReleases()
.then((l) => setReleases(l ?? []))
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
}
@@ -48,14 +48,14 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
const isDownloaded = (v: string) => (cached ?? []).some((c) => c.kind === 'offline' && !c.partial && c.version === v)
const download = (version: string) => {
backend.downloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
}
const remove = async (name: string) => {
if (confirmDelete !== name) { setConfirmDelete(name); return }
setConfirmDelete('')
try {
await backend.deleteInstaller(name)
await api.DeleteInstaller(name)
onToast(tr('toastDeleted', { name }))
loadCached()
} catch (e) {
@@ -103,7 +103,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
</div>
<div className="row-right">
{task ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => backend.cancelTask(task.id)} />
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
) : (
<>
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
@@ -155,7 +155,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
</div>
<div className="row-right">
{task ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => backend.cancelTask(task.id)} />
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
) : done ? (
<span className="badge badge-ok">{tr('offlineCached')}</span>
) : (
+9 -9
View File
@@ -4,14 +4,14 @@ import { I18nKey, t } from '../i18n'
import { taskDetail } from '../lib/tasks'
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { backend } from '../wails'
import { api } from '../wails'
interface Props {
locale: Locale
channel: 'stable' | 'candidate'
channel: 'stable' | 'alpha'
installed: InstalledRuntime[]
task: Task | null
onChannel: (candidate: boolean) => void
onChannel: (alpha: boolean) => void
onInstall: (commit: string) => void
onCancel: (taskId: string) => void
}
@@ -23,7 +23,7 @@ const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU '
/**
* The runtime rows: the active runtime and whether it is current (or, with
* none installed, the newest release to install), then the candidate switch.
* none installed, the newest release to install), then the alpha switch.
*/
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
@@ -34,7 +34,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
let live = true
setRemote(null)
setError('')
backend.listRemoteRuntimes()
api.ListRemoteRuntimes()
.then((list) => { if (live) setRemote(list ?? []) })
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
return () => { live = false }
@@ -95,15 +95,15 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('runtimeCandidate')}</div>
<div className="row-sub">{tr('runtimeCandidateHint')}</div>
<div className="row-title">{tr('runtimeAlpha')}</div>
<div className="row-sub">{tr('runtimeAlphaHint')}</div>
</div>
<div className="row-right">
<label className="switch">
<input
type="checkbox"
aria-label={tr('runtimeCandidate')}
checked={channel === 'candidate'}
aria-label={tr('runtimeAlpha')}
checked={channel === 'alpha'}
onChange={(e) => onChannel(e.target.checked)}
/>
<span className="slider" />
@@ -0,0 +1,60 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React, { useState } from 'react'
import { t } from '../i18n'
import { Locale } from '../types'
interface Props {
locale: Locale
vmName: string
guestToolsConnected: boolean
onCancel: () => void
onConfirm: (text: string) => void
}
export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConnected, onCancel, onConfirm }) => {
const [text, setText] = useState('')
const canSend = text.length > 0
return (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'sendTextTitle', { name: vmName })}</Alert.Title>
<Alert.Description className="dialog-desc">
{t(locale, guestToolsConnected ? 'sendTextDesc' : 'sendTextDescNoGT')}
</Alert.Description>
<div className="field" style={{ marginTop: 10 }}>
<textarea
className="input"
rows={4}
style={{ height: 'auto', minHeight: 88, resize: 'vertical', padding: '8px 10px', lineHeight: 1.5 }}
placeholder={t(locale, 'sendTextPlaceholder')}
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && canSend) {
e.preventDefault()
onConfirm(text)
}
}}
autoFocus
/>
</div>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
{t(locale, 'sendTextConfirm')}
</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
}
File diff suppressed because it is too large. Load diff
+8 -8
View File
@@ -4,7 +4,7 @@ import { I18nKey, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, Task } from '../types'
import { Button } from '../ui/controls'
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
import { backend } from '../wails'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
@@ -16,7 +16,7 @@ interface Props {
onFolderDone: () => void
onFinish: () => void
onError: (title: string, e: unknown) => void
onChannel: (candidate: boolean) => void
onChannel: (alpha: boolean) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
onImportRuntime: () => void
@@ -47,7 +47,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
const [busy, setBusy] = useState(false)
useEffect(() => {
backend.suggestDataRoots().then((list) => {
api.SuggestDataRoots().then((list) => {
const l = list ?? []
setChoices(l)
const rec = l.find((c) => c.recommended) ?? l[0]
@@ -58,19 +58,19 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
useEffect(() => {
if (!selected) { setCheck(null); return }
let live = true
backend.checkDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
api.CheckDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
return () => { live = false }
}, [selected])
const browse = async () => {
const dir = await backend.pickDirectory(tr('setupTitle')).catch(() => '')
const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '')
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
}
const next = async () => {
setBusy(true)
try {
await backend.completeSetup(selected)
await api.CompleteSetup(selected)
onFolderDone()
} catch (e) {
onError(tr('failGeneric'), e)
@@ -154,7 +154,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
const [enabling, setEnabling] = useState(false)
const enableWHPX = async () => {
setEnabling(true)
try { await backend.enableWHPX() } catch (e) { onError(tr('failGeneric'), e) } finally { setEnabling(false) }
try { await api.EnableWHPX() } catch (e) { onError(tr('failGeneric'), e) } finally { setEnabling(false) }
}
const whpxOK = host.whpx === 'ready'
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
@@ -214,7 +214,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
<div className="list">
<RuntimeOnline
locale={locale}
channel={state.config.runtime_channel === 'candidate' ? 'candidate' : 'stable'}
channel={state.config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
installed={state.runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
+274 -216
View File
@@ -1,14 +1,18 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import {
Activity,
Archive,
ChevronRight,
Copy,
CopyPlus,
Cpu,
Disc,
Ellipsis,
FolderOpen,
HardDrive,
Keyboard,
LifeBuoy,
MemoryStick,
Play,
Power,
RotateCw,
@@ -16,12 +20,15 @@ import {
Square,
Terminal,
Trash,
Upload,
} from 'lucide-react'
import React from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { controllerLabel, formatMemory, graphicsLabel, sshCommand } from '../lib/format'
import { HostReport, Locale, PendingChange, VMDetail } from '../types'
import { controllerLabel, formatBytes, formatMemory, formatUptime, graphicsLabel, guestLangLabel, splitLangLabel, sshCommand } from '../lib/format'
import { HostReport, Locale, PendingChange, VMDetail, VMStats, VMThumbnail } from '../types'
import { api } from '../wails'
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { SetGroup, SetRow, Switch } from '../ui/settings'
export type VMAction =
| 'start'
@@ -39,6 +46,7 @@ export type VMAction =
| 'exportDiagnostics'
| 'cloneVM'
| 'type'
| 'sendText'
| 'delete'
| 'openFolder'
@@ -52,6 +60,7 @@ interface Props {
name: string
state: string
detail: VMDetail | null
stats: VMStats | null
host: HostReport
pending: PendingChange[]
busyAction?: VMAction
@@ -61,16 +70,34 @@ interface Props {
onViewLogs: () => void
onCopy: (text: string) => void
onTypeText: (text: string) => void
onToggleBorderless: (enabled: boolean) => void
onTogglePreventSleep: (enabled: boolean) => void
onDeliverFile: () => void
}
export const VMPage: React.FC<Props> = ({
locale, name, state, detail, host, pending, busyAction, onAction, onSettings, onDelete, onViewLogs, onCopy, onTypeText,
locale, name, state, detail, stats, host, pending, busyAction, onAction, onSettings, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const running = state === 'running'
const transitioning = state === 'starting' || state === 'stopping'
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 5 s while the VM
// runs, otherwise the last frame saved. Skipped while the window is hidden.
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
useEffect(() => { setThumb(null) }, [name])
useEffect(() => {
let live = true
const pull = () => {
if (document.hidden) return
api.GetVMThumbnail(name).then((t) => { if (live && t.data_url) setThumb(t) }).catch(() => {})
}
pull()
const timer = running ? window.setInterval(pull, 5000) : undefined
return () => { live = false; if (timer) window.clearInterval(timer) }
}, [name, running])
// One primary action per state (docs/ui-redesign.md §3.2). Running has none
// until "Show VM window" (B5) exists.
let primary: React.ReactNode = null
@@ -86,85 +113,140 @@ export const VMPage: React.FC<Props> = ({
primary = <Button variant="primary" icon={<Terminal size={14} />} onClick={onViewLogs}>{tr('viewLogs')}</Button>
}
return (
<div className="page">
<header className="page-head">
<div className="page-title">
<h1>{locale === 'zh-CN' ? '关于此虚拟机' : 'About This VM'}</h1>
</div>
<div className="actions">
{primary}
const menu = (
<Menu.Root>
<Tip label={tr('more')}>
<Menu.Trigger asChild>
<button type="button" className="icon-btn" aria-label={tr('more')}>
<Ellipsis size={15} />
</button>
</Menu.Trigger>
</Tip>
<Menu.Portal>
<Menu.Content className="menu" align="end" sideOffset={4} collisionPadding={8}>
{running && (
<IconButton label={tr('stop')} icon={<Square size={14} />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')} />
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('restart')}>
<RotateCw size={14} /> {tr('restart')}
</Menu.Item>
)}
<IconButton label={tr('settings')} shortcut="Ctrl+," icon={<Settings size={15} />} disabled={!detail} onClick={onSettings} />
<Menu.Root>
<Tip label={tr('more')}>
<Menu.Trigger asChild>
<button type="button" className="icon-btn" aria-label={tr('more')}>
<Ellipsis size={15} />
</button>
</Menu.Trigger>
</Tip>
<Menu.Portal>
<Menu.Content className="menu" align="end" sideOffset={4} collisionPadding={8}>
{running && (
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('restart')}>
<RotateCw size={14} /> {tr('restart')}
</Menu.Item>
)}
{running && (
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('type')}>
<Keyboard size={14} /> {tr('typeClipboard')}
</Menu.Item>
)}
{(running || transitioning) && (
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
<Power size={14} /> {tr('forceStop')}
</Menu.Item>
)}
{detail && !detail.has_installer && !detail.recovery_mode && (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('enterRecovery')}>
<LifeBuoy size={14} /> {tr('enterRecovery')}
</Menu.Item>
)}
{detail && (detail.has_installer || detail.recovery_mode) && (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('finishInstall')}>
<LifeBuoy size={14} /> {tr('finishInstall')}
</Menu.Item>
)}
{detail && !detail.has_installer && !detail.recovery_mode && (
<Menu.Item className="menu-item" disabled={running || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
</Menu.Item>
)}
<Menu.Item className="menu-item" onSelect={() => onAction('openFolder')}>
<FolderOpen size={14} /> {tr('openFolder')}
</Menu.Item>
<Menu.Item className="menu-item" onSelect={onViewLogs}>
<Terminal size={14} /> {tr('viewLogs')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
<Menu.Separator className="menu-sep" />
<Menu.Item className="menu-item danger" disabled={running || transitioning || busy} onSelect={onDelete}>
<Trash size={14} /> {tr('delete')}
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu.Root>
</div>
</header>
{running && (
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('sendText')}>
<Keyboard size={14} /> {tr('sendText')}
</Menu.Item>
)}
{running && (
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('type')}>
<Keyboard size={14} /> {tr('typeClipboard')}
</Menu.Item>
)}
{(running || transitioning) && (
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
<Power size={14} /> {tr('forceStop')}
</Menu.Item>
)}
{detail && !detail.has_installer && !detail.recovery_mode && (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('enterRecovery')}>
<LifeBuoy size={14} /> {tr('enterRecovery')}
</Menu.Item>
)}
{detail && (detail.has_installer || detail.recovery_mode) && (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('finishInstall')}>
<LifeBuoy size={14} /> {tr('finishInstall')}
</Menu.Item>
)}
{detail && !detail.has_installer && !detail.recovery_mode && (
<Menu.Item className="menu-item" disabled={running || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
</Menu.Item>
)}
<Menu.Item className="menu-item" onSelect={() => onAction('openFolder')}>
<FolderOpen size={14} /> {tr('openFolder')}
</Menu.Item>
<Menu.Item className="menu-item" onSelect={onViewLogs}>
<Terminal size={14} /> {tr('viewLogs')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
<Menu.Separator className="menu-sep" />
<Menu.Item className="menu-item danger" disabled={running || transitioning || busy} onSelect={onDelete}>
<Trash size={14} /> {tr('delete')}
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu.Root>
)
<div className="vm-hero">
<IMacIcon running={running} />
<div className="vm-hero-name">{name}</div>
<span className="vm-hero-pill">
// Each fact is said once (docs/ui-audit.md H1); raw upstream values live in
// "Technical details" at the bottom.
const diskUsed = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
const specs: { label: string; value: string }[] = detail
? [
{ label: tr('factCPU'), value: tr('cores', { n: detail.cpus }) },
{ label: tr('factMemory'), value: formatMemory(detail.memory) },
{ label: tr('factGraphics'), value: graphicsLabel(locale, detail, host) + (detail.displays > 1 ? ` × ${detail.displays}` : '') },
{
label: tr('factDisk'),
value: diskUsed && stats
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats.disk_actual_bytes), max: formatBytes(stats.disk_virtual_bytes) })
: controllerLabel(detail.disk_controller),
},
{ label: tr('fieldNetwork'), value: detail.network ? (detail.ssh_port > 0 ? `NAT · SSH ${detail.ssh_port}` : 'NAT') : tr('off') },
...(detail.guest_lang ? [{ label: tr('specLang'), value: splitLangLabel('', guestLangLabel(locale, detail.guest_lang)).label }] : []),
]
: []
// QEMU's working set runs a little above the guest's RAM, so the bar is the
// share of host memory it takes (the label says "host memory").
const hostBytes = (host.total_ram_gb || 0) * 1024 ** 3
const memPct = running && stats && hostBytes > 0 ? Math.min(100, (stats.memory_rss_bytes / hostBytes) * 100) : 0
return (
<div className="page vm-page">
<section className="vm-hero" aria-labelledby="vm-name">
<VMScreen thumb={thumb} running={running} startLabel={tr('start')} onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined} />
<h1 className="vm-hero-name" id="vm-name">{name}</h1>
<div className="vm-hero-sub">
<StatusShape kind={statusKind(state)} />
{tr(`state_${state}` as I18nKey)}
</span>
</div>
{running && stats && stats.uptime_seconds > 0 && <span className="muted">· {formatUptime(stats.uptime_seconds, locale)}</span>}
</div>
{specs.length > 0 && (
<dl className="vm-specs">
{specs.map((s) => (
<React.Fragment key={s.label}>
<dt>{s.label}</dt>
<dd>{s.value}</dd>
</React.Fragment>
))}
</dl>
)}
<div className="vm-hero-actions">
{primary}
{running && (
<Button icon={<Square size={13} />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
)}
<Tip label={tr('settings')} shortcut="Ctrl+,">
<Button icon={<Settings size={14} />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
</Tip>
{menu}
</div>
</section>
{running && stats && (
<div className="vm-meters">
<div className="vm-meter">
<span className="vm-meter-label"><Cpu size={12} aria-hidden="true" />{tr('statsCPU')}</span>
<span className="vm-meter-value">{Math.round(Math.min(100, Math.max(0, stats.cpu_percent || 0)))}%</span>
<div className="resource-meter"><span style={{ width: `${Math.min(100, Math.max(0, stats.cpu_percent || 0))}%` }} /></div>
</div>
<div className="vm-meter">
<span className="vm-meter-label"><MemoryStick size={12} aria-hidden="true" />{tr('statsMemory')}</span>
<span className="vm-meter-value">{stats.memory_rss_bytes > 0 ? formatBytes(stats.memory_rss_bytes) : '—'}</span>
<div className="resource-meter"><span style={{ width: `${memPct}%` }} /></div>
</div>
</div>
)}
{state === 'broken' && <div className="notice notice-error">{tr('brokenHint')}</div>}
@@ -303,143 +385,84 @@ export const VMPage: React.FC<Props> = ({
)
})()}
{detail && !detail.has_installer && !detail.recovery_mode && (
<section className="card" aria-labelledby="guest-tools-title">
<h2 className="card-title" id="guest-tools-title">
{tr('guestToolsTitle')}{' '}
<span className={`badge ${detail.guest_tools_connected ? 'badge-ok' : ''}`}>
{tr(
detail.guest_tools_connected
? 'guestToolsConnected'
: detail.guest_tools_configured
? 'guestToolsReady'
: 'guestToolsNotInstalled',
)}
</span>
</h2>
<p className="hint" style={{ margin: '0 0 10px' }}>
{tr('guestToolsDesc')}
</p>
{detail.guest_tools_attached && (
<div style={{ marginBottom: 10 }}>
<div className="hint" style={{ marginBottom: 6 }}>{tr('guestToolsInstallHint')}</div>
<div className="cmd-line guide-cmd">
<code>{GUEST_TOOLS_INSTALL_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
{running && (
<IconButton
small
label={tr('typeIntoVM')}
icon={<Keyboard size={14} />}
busy={busyAction === 'type'}
disabled={busy}
onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)}
/>
)}
</div>
</div>
)}
<div className="card-foot">
<Button
variant="secondary"
icon={<FolderOpen size={14} />}
disabled={busy}
onClick={() => onAction('openSharedFolder')}
>
{tr('openSharedFolder')}
</Button>
{detail.guest_tools_attached ? (
<Button
variant="secondary"
busy={busyAction === 'detachGuestTools'}
disabled={busy}
onClick={() => onAction('detachGuestTools')}
>
{tr('detachGuestTools')}
</Button>
) : (
<Button
variant={detail.guest_tools_configured ? 'secondary' : 'primary'}
icon={<Disc size={14} />}
busy={busyAction === 'attachGuestTools'}
disabled={busy}
onClick={() => onAction('attachGuestTools')}
>
{tr('attachGuestTools')}
</Button>
{detail && (() => {
const tools = !detail.has_installer && !detail.recovery_mode
if (!tools && detail.ssh_port <= 0) return null
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3
const gtStatus = gtConnected
? [tr('guestToolsConnected'), gtMountMode === 'webdav' ? tr('guestToolsModeWebDAV') : gtMountMode === 'sync' ? tr('guestToolsModeSync') : ''].filter(Boolean).join(' · ')
: detail.guest_tools_configured ? tr('guestToolsReady') : tr('gtNotInstalledDesc')
return (
<SetGroup title={tr('connGroup')}>
{detail.ssh_port > 0 && (
<SetRow
title="SSH"
desc={<code className="inline-code">{sshCommand(detail.ssh_port)}</code>}
control={<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(sshCommand(detail.ssh_port))} />}
/>
)}
</div>
</section>
)}
{detail && detail.ssh_port > 0 && (
<div className="cmd-line">
<Terminal size={16} aria-hidden="true" />
<code>{sshCommand(detail.ssh_port)}</code>
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(sshCommand(detail.ssh_port))} />
</div>
)}
{detail && (
<div className="tahoe-group">
<div className="tahoe-row">
<span className="tahoe-label">{locale === 'zh-CN' ? '名称' : 'Name'}</span>
<span className="tahoe-value">{name}</span>
</div>
<div className="tahoe-row">
<span className="tahoe-label">{tr('factCPU')}</span>
<span className="tahoe-value">{tr('cores', { n: detail.cpus })}{detail.cpu_model ? ` · ${detail.cpu_model}` : ''}</span>
</div>
<div className="tahoe-row">
<span className="tahoe-label">{tr('factGraphics')}</span>
<span className="tahoe-value">{graphicsLabel(locale, detail, host)}</span>
</div>
<div className="tahoe-row">
<span className="tahoe-label">{tr('factMemory')}</span>
<span className="tahoe-value">{formatMemory(detail.memory)}</span>
</div>
<div className="tahoe-row">
<span className="tahoe-label">{tr('factDisk')}</span>
<span className="tahoe-value">{controllerLabel(detail.disk_controller)}</span>
</div>
<div className="tahoe-row">
<span className="tahoe-label">{tr('fieldNetwork')}</span>
<span className="tahoe-value">{detail.network_summary || tr('off')}</span>
</div>
</div>
)}
{detail && (
<section className="section">
<div className="section-title">macOS</div>
<div className="tahoe-group">
<div className="tahoe-row">
<span className="tahoe-label">
<span className="tahoe-orb" aria-hidden="true" />
macOS Tahoe
</span>
<span className="tahoe-value">{detail.kind || 'x86-64 WHPX'}</span>
</div>
</div>
</section>
)}
{detail && (
<section className="section">
<div className="section-title">{tr('fieldDisplays')}</div>
<div className="tahoe-group">
<div className="tahoe-row">
<span className="tahoe-label">
<span className="tahoe-display-icon" aria-hidden="true" />
{locale === 'zh-CN' ? '虚拟显示器' : 'Virtual Display'}
</span>
<span className="tahoe-value">
{detail.displays} × {detail.resolution} · {detail.capture ? (locale === 'zh-CN' ? '输入捕获' : 'Input capture') : (locale === 'zh-CN' ? '自由指针' : 'Free pointer')}
</span>
</div>
</div>
</section>
)}
{tools && (
<SetRow
title={tr('guestToolsTitle')}
desc={needsUpgrade ? <span className="warn-text">{tr('guestToolsUpgradeHint')}</span> : gtStatus}
control={detail.guest_tools_attached ? (
<Button busy={busyAction === 'detachGuestTools'} disabled={busy} onClick={() => onAction('detachGuestTools')}>
{tr('detachGuestTools')}
</Button>
) : (
<Button
variant={detail.guest_tools_configured ? 'secondary' : 'primary'}
icon={<Disc size={14} />}
busy={busyAction === 'attachGuestTools'}
disabled={busy}
onClick={() => onAction('attachGuestTools')}
>
{tr('attachGuestTools')}
</Button>
)}
/>
)}
{tools && detail.guest_tools_attached && (
<SetRow
title={tr('gtInstallCmd')}
desc={<code className="inline-code">{GUEST_TOOLS_INSTALL_CMD}</code>}
control={
<div className="hstack">
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={14} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)} />
)}
</div>
}
/>
)}
{tools && (
<SetRow
title={tr('sharedFolder')}
desc="~/Desktop/ReimsShare"
control={
<div className="hstack">
<Button icon={<Upload size={14} />} disabled={busy} onClick={onDeliverFile}>{tr('deliverFileShort')}</Button>
<Button icon={<FolderOpen size={14} />} disabled={busy} onClick={() => onAction('openSharedFolder')}>{tr('openShort')}</Button>
</div>
}
/>
)}
{tools && (
<SetRow
title={tr('guestToolsPreventSleep')}
desc={gtSleepActive
? <span className="ok-text"><Activity size={11} aria-hidden="true" /> {tr('guestToolsSleepActive')}</span>
: tr('guestToolsPreventSleepSub')}
control={<Switch label={tr('guestToolsPreventSleep')} checked={!!detail.guest_tools_prevent_sleep} onChange={onTogglePreventSleep} />}
/>
)}
</SetGroup>
)
})()}
{detail && (
<details className="tech">
@@ -447,15 +470,50 @@ export const VMPage: React.FC<Props> = ({
<dl className="kv-list">
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</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('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>
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
{detail.guest_lang && (<><dt>{tr('guestLang')}</dt><dd className="mono">{detail.guest_lang}</dd></>)}
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
</dl>
</details>
)}
{detail && (
<p className="vm-footnote">
<kbd>Ctrl+Alt+Enter</kbd> {tr('shortcutBarFullscreen')}
{detail.capture && <><span className="sep">·</span><kbd>Ctrl+Alt+G</kbd> {tr('shortcutBarRelease')}</>}
</p>
)}
</div>
)
}
/**
* The VM's own screen as its picture (as UTM and Parallels do): live while it
* runs, the last frame dimmed with a start button while it is stopped, and
* the iMac drawing until a frame exists. Each new frame fades in over the
* previous one.
*/
const VMScreen: React.FC<{ thumb: VMThumbnail | null; running: boolean; startLabel: string; onStart?: () => void }> = ({ thumb, running, startLabel, onStart }) => {
const prev = useRef<string>('')
const shown = thumb?.data_url ?? ''
const under = prev.current !== shown ? prev.current : ''
useEffect(() => { prev.current = shown }, [shown])
if (!shown) return <IMacIcon running={running} />
return (
<div className={`vm-screen${running ? ' is-live' : ' is-idle'}`} style={under ? { backgroundImage: `url(${under})` } : undefined}>
<img key={thumb?.captured_at} className="vm-screen-img" src={shown} alt="" draggable={false} />
{running && <span className="vm-screen-live" aria-hidden="true" />}
{onStart && (
<button type="button" className="vm-screen-play" aria-label={startLabel} onClick={onStart}>
<Play size={22} fill="currentColor" />
</button>
)}
</div>
)
}
+346 -134
View File
@@ -18,7 +18,7 @@ const dict = {
installersDelete: '删除',
installersDeleteConfirm: '确认删除',
installersNoSpace: '空间不足:需要约 {need} GB,可用 {free} GB',
installersHint: '离线安装包可以重复用来新建虚拟机;点已下载条目右侧「新建虚拟机」可直接使用。正在使用或下载中的不能删除',
installersHint: '下载好的安装包可以重复用来新建虚拟机',
installersCreateVM: '新建虚拟机',
installersKindOffline: '离线完整包',
installersKindOnline: '在线恢复镜像',
@@ -69,41 +69,44 @@ const dict = {
guideKindBuiltIn: '内置恢复',
guideKindOffline: '离线完整安装',
guideKindOnline: '在线恢复安装',
guideBuiltIn1: '启动(或重启)虚拟机后,在 OpenCore 引导菜单中选择「Recovery」即可进入系统自带恢复模式',
guideBuiltIn2: '内置 Recovery 已支持联网重装;如果虚拟盘为空或需要离线安装,可点下方「挂载离线镜像」',
guideBuiltIn3: '操作完成后点下方「退出恢复模式」,恢复开机直进 macOS',
guideStep1: '在虚拟机窗口选「磁盘工具(Disk Utility)」→ 点 Continue → 选中左侧容量最大的「QEMU HARDDISK Media」(看不到时点左上角 View › Show All Devices)→ 点顶部 Erase,名称填 Macintosh HD、格式 APFS、方案 GUID Partition Map(抹除已用过的磁盘时画面可能短暂卡住 10–30 秒并自动恢复,请勿强行关闭),完成后退出磁盘工具',
guideStep2: '回到恢复主界面,选「Reinstall macOS Tahoe」→ 点 Continue,装到刚抹掉的磁盘(中途会自动重启几次)',
guideStep3: '重启看到「设置助理」(选择国家或地区)后,点下方「退出恢复模式」弹出安装盘',
guideOffline1: '在虚拟机恢复窗口不要点「Reinstall macOS Tahoe」;直接点击顶部菜单栏「Utilities › Terminal」(实用工具 › 终端)打开终端',
guideOffline2: '在终端运行下方命令(可点右侧键盘图标一键键入),脚本会自动把空白虚拟硬盘抹成 APFS(Macintosh HD)并开始离线安装(抹除已用过的磁盘会先询问确认,中途会自动重启几次):',
guideOffline3: '重启看到「设置助理」(选择国家或地区)后,点下方「退出恢复模式」(弹出安装盘并恢复网络)',
guideBuiltIn1: '启动后在 OpenCore 引导菜单选择「Recovery」',
guideBuiltIn2: '恢复模式可以联网重装;要离线安装就点「挂载离线镜像」',
guideBuiltIn3: '完成后点「退出恢复模式」',
guideStep1: '打开「磁盘工具」,选中最大的「QEMU HARDDISK Media」(看不到就选 View › Show All Devices),点 Erase:名称 Macintosh HD,格式 APFS,方案 GUID。抹除时可能停顿 10–30 秒,不要强制关机',
guideStep2: '回到恢复主界面,选「Reinstall macOS Tahoe」,装到刚抹好的磁盘,中途会重启几次',
guideStep3: '看到「设置助理」后,点「退出恢复模式」弹出安装盘',
guideOffline1: '不要点「Reinstall macOS Tahoe」,从菜单栏打开「Utilities › Terminal」',
guideOffline2: '运行下面的命令(点键盘图标可直接键入)。它会把空白磁盘抹成 APFS 并开始安装,中途会重启几次:',
guideOffline3: '看到「设置助理」后,点「退出恢复模式」弹出安装盘并恢复网络',
finishInstall: '退出恢复模式',
enterRecovery: '进入恢复模式',
attachInstaller: '挂载离线镜像',
pickRecoveryTitle: '选择离线镜像(.img / .dmg)',
guestToolsTitle: '宿客互通 · Guest Tools',
guestToolsDesc: '提供宿主机 ↔ macOS 双向剪贴板同步与共享文件夹(macOS 桌面 ReimsShare),采用每台虚拟机独立随机 Token 鉴权。',
guestToolsTitle: 'Guest Tools',
guestToolsConnected: '已连接',
guestToolsReady: '已配置',
guestToolsNotInstalled: '未安装',
guestToolsInstallHint: '在 macOS 里双击桌面/访达里的 REIMSTOOLS → Install-Reims-Tools.command,或在终端运行:',
attachGuestTools: '挂载 Guest Tools',
detachGuestTools: '弹出工具盘',
openSharedFolder: '打开共享文件夹',
upgradeToNVMe: '升级到 NVMe',
exportDiagnostics: '导出排障日志 (.zip)',
cloneVM: '秒级派生副本 (CoW)',
diagExternalDriveWarn: '数据目录位于外置/网络盘({dir}),macOS 安装与随机读写会明显偏慢,建议放本地 NVMe SSD',
diagHighMemWarn: '宿主机当前物理内存占用已达 {pct}%,若虚拟机卡顿建议关闭后台程序或适当调小虚拟机内存',
diagAhciUpgradeHint: '当前系统盘仍使用旧版 SATA/AHCI,建议一键升级到 NVMe 以提升读写与 TRIM 性能',
diagExternalDriveWarn: '数据目录在外置或网络盘上({dir}),读写会明显变慢',
diagHighMemWarn: '宿主内存已用 {pct}%,虚拟机可能会卡顿',
diagAhciUpgradeHint: '系统盘还是 SATA,改成 NVMe 读写更快',
cloneTitle: '从「{name}」派生 CoW 副本',
cloneDesc: '通过 qcow2 写时复制(CoW)秒级创建独立副本,几乎不占额外空间,且不会修改原虚拟机磁盘。',
cloneDesc: '用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响',
cloneNameLabel: '新虚拟机名称',
cloneConfirm: '立即派生',
typeClipboard: '粘贴为键入',
typeClipboard: '粘贴剪贴板到虚拟机',
typeIntoVM: '在虚拟机里键入',
typeUntypeable: '只能键入美式键盘上的字符(英文、数字、符号)。中文等字符请换别的方式传。',
typeUntypeable: '未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本',
sendText: '发送文本到虚拟机…',
sendTextTitle: '发送文本到「{name}」',
sendTextDesc: '支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。',
sendTextDescNoGT: '当前未连接 Guest Tools,仅支持英文/数字等美式键盘字符;安装 Guest Tools 后支持中文与任意文本。',
sendTextPlaceholder: '在这里输入或粘贴要发送到虚拟机的文字…',
sendTextConfirm: '发送 (Ctrl+Enter)',
brokenHint: '这台虚拟机的配置无法读取',
techInfo: '技术信息',
factCPU: '处理器',
@@ -119,7 +122,6 @@ const dict = {
fieldController: '磁盘控制器',
fieldGraphicsBackend: '图形后端',
fieldICD: 'Vulkan ICD',
fieldDisplays: '显示器',
fieldNetwork: '网络',
fieldAudio: '音频',
fieldDir: '目录',
@@ -176,9 +178,9 @@ const dict = {
runtimeUpdate: '更新',
runtimeNewer: '有新版本:{v}',
runtimeInstall: '安装',
runtimeCandidate: '接收候选版',
runtimeCandidateHint: '候选版未经真实宿主冒烟测试',
runtimeChannel_candidate: '候选版',
runtimeAlpha: '接收 Alpha 版',
runtimeAlphaHint: 'Alpha 版由 CI 每天从上游自动构建,未经真实宿主冒烟测试',
runtimeChannel_alpha: 'Alpha 版',
runtimeChannel_stable: '稳定版',
runtimeLookupFailed: '无法读取 GitHub 上的运行时列表',
@@ -195,8 +197,8 @@ const dict = {
toastOnlineRecoveryAttached: '在线恢复镜像已挂载到 {name}',
toastGuestToolsAttached: '已挂载 Guest Tools 工具盘(REIMSTOOLS)',
toastGuestToolsAttachedNextStart: '已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见',
toastGuestToolsDetached: '已弹出 Guest Tools 工具盘(剪贴板与共享目录继续生效)',
toastGuestToolsDetachedNextStart: '已弹出工具盘,下次启动生效(剪贴板与共享目录继续生效)',
toastGuestToolsDetached: '已弹出工具盘',
toastGuestToolsDetachedNextStart: '已弹出工具盘,下次启动生效',
toastNVMeReady: '已升级到 NVMe 磁盘控制器',
toastNVMeNextStart: '已切换为 NVMe,下次启动生效',
toastDiagExported: '已导出脱敏排障日志包 (.zip)',
@@ -227,15 +229,13 @@ const dict = {
deleteKeepFiles: '保留磁盘文件',
deleteConfirm: '删除',
onlineRecoveryTitle: '拉取在线恢复镜像?',
onlineRecoveryDesc: '本地没有已缓存的镜像,且未选择离线镜像。是否直接从 Apple 拉取约 1 GB 的在线恢复镜像并自动挂载到「{name}」?',
onlineRecoveryDesc: '本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?',
onlineRecoveryConfirm: '拉取并挂载(约 1 GB)',
noRuntimeAlert: '先在「宿主与运行时」导入运行时包',
// Host
hostRuntime: '运行时',
hostSystem: '系统',
hostGPUs: '显卡',
hostPrefs: '偏好设置',
language: '语言',
appVersionTitle: '客户端版本',
appUpToDate: '已是最新',
@@ -255,17 +255,13 @@ const dict = {
enableWHPX: '启用',
hostCPU: '处理器',
hostCoresThreads: '{c} 核 · {t} 线程',
hostHybrid: '{p} 性能核 + {e} 能效核',
hostSymmetric: '同构核心',
autoPinPCores: '启动后绑定到性能核',
hostRAM: '内存',
hostRAMAvail: '可用 {n} GB',
hostRAMTotal: '共 {n} GB',
hostDisk: '可用空间',
hostDataRoot: '数据目录',
noRuntime: '还没有运行时,导入 reims-runtime-win-x64-*.tar.zst 即可',
importRuntime: '导入运行时包',
activeBadge: '使用中',
activate: '使用',
gpuRecommended: '推荐',
gpuDiscrete: '独显',
@@ -275,40 +271,42 @@ const dict = {
// Wizard
wizardTitle: '新建虚拟机',
srcOfflineTitle: '离线安装包',
srcOfflineSub: '完整安装包,装机时不联网',
srcAppleTitle: '从 Apple 下载',
srcAppleSub: '恢复镜像,系统在装机时在线下载',
srcInstallerTitle: '安装镜像',
srcInstallerSub: '本机上的 .img 或 .dmg',
srcDiskTitle: '已有磁盘',
srcDiskSub: '已装好 macOS 的 .qcow2 等磁盘',
wizChooseFile: '选择…',
wizNoFile: '还没有选择文件',
wizOptions: '选项',
useDefault: '恢复默认',
step1: '系统来源',
step2: 'CPU 与内存',
step2: '处理器与内存',
step3: '存储',
step4: '图形与外设',
step4: '图形与选项',
step5: '确认',
vmName: '名称',
vmDir: '存放目录',
vmDirHint: '留空则使用数据目录',
sourceApple: '从 Apple 下载恢复镜像',
sourceInstaller: '本地安装器镜像(.img / .dmg)',
sourceDisk: '已有虚拟磁盘(.qcow2)',
sourceOffline: '离线安装包(推荐)',
offlineLoading: '正在读取 Apple 的版本列表…',
offlineListFailed: '无法读取 Apple 的版本列表',
offlineCached: '已下载',
offlineHint: '约 20 GB,安装时不联网;装完点「完成安装」会恢复网络',
offlineHint: '约 20 GB,安装时不联网',
offlineSpaceWarn: '可用空间 {free} GB,下载这个版本需要约 {need} GB',
networkOfflineHint: '离线安装默认关闭以避免中途联网更新(可按需手动勾选开启),点「完成安装」时也会自动恢复网络',
networkOfflineHint: '离线安装时默认关闭,装完会自动打开',
summaryOfflineSource: '离线安装包 · macOS {v}',
macosVersion: 'macOS 版本',
macosTahoe: 'macOS 26 Tahoe(硬件加速需要 26.4 及以上)',
diskSize: '磁盘上限',
diskSizeHint: '按实际占用增长,推荐 128G',
diskSizeHint: '按实际占用增长',
diskMode: '使用方式',
diskModeCopy: '复制一份,不改动原盘',
diskModeInPlace: '直接使用原盘',
hostThreads: '宿主 {n} 线程',
hostMemory: '宿主 {n} GB',
cpuHint: '推荐 4 或 8 核',
memHint: '建议不超过宿主内存的 75%',
memCommitHint: 'Windows 现在还能分配 {avail} GB,推荐 {rec} GB',
memCommitHint: 'Windows 还能分配 {avail} GB · 推荐 {rec} GB',
graphicsBackend: '图形后端',
graphicsReims: 'reims-vgpu(硬件加速,推荐)',
graphicsSvga: 'vmware-svga(无加速,用于排障)',
gpuSelect: '宿主 GPU',
gpuAutoOption: '自动(优先独显)',
resolution: '分辨率',
@@ -317,10 +315,9 @@ const dict = {
enableAudio: '音频',
enableNetwork: '网络(NAT)',
sshPort: 'SSH 转发端口',
sshPortHint: '0 表示关闭',
enableLogs: '记录图形与串口日志',
startAfterCreate: '创建后立即启动',
validationPassed: '检查通过,可以创建',
validationPassed: '可以创建',
validationChecking: '正在检查…',
issuesCount: '有 {n} 项需要修改',
summaryEdit: '修改',
@@ -330,7 +327,6 @@ const dict = {
summaryInstallerSource: '本地安装器 · {file}',
summaryDiskSource: '已有磁盘 · {file}',
summaryOn: '开',
summaryStartAfter: '创建后启动',
summaryLogs: '图形与串口日志',
summarySSH: 'SSH 转发',
summarySSHPort: '端口 {n}',
@@ -344,12 +340,22 @@ const dict = {
backToEdit: '返回修改',
// Settings
settingsTitle: '{name} 设置',
settingsTitle: '{name}',
settingsEllipsis: '设置…',
specDiskUsage: '{ctl} · 已用 {used},上限 {max}',
specLang: '语言',
connGroup: '连接',
gtNotInstalledDesc: '未安装:挂载工具盘后在 macOS 中运行安装命令',
gtInstallCmd: '安装命令',
sharedFolder: '共享文件夹',
deliverFileShort: '发送文件…',
openShort: '打开',
networkTitle: '网络',
logLevelDesc: '写入 REIMS_VGPU_LOG',
secondsUnit: '秒',
guestLangShort: '系统语言',
groupMacOS: 'macOS',
appliesNextStart: '下次启动生效',
requiresStop: '部分修改需要先关机',
catPlatform: '平台',
catCPU: 'CPU',
catMemory: '内存',
catStorage: '存储',
catNetwork: '网络',
catGraphics: '图形与显示器',
@@ -358,16 +364,57 @@ const dict = {
catLogs: '串口与日志',
catAdvanced: '高级',
platformReadonly: '机型、序列号等平台身份信息不在界面显示',
catGeneral: '通用',
catCompute: '处理器与内存',
catStorageNet: '存储与网络',
catInputAudio: '输入与音频',
vcpus: '虚拟处理器',
coresUnit: '核',
cpuRecHint: '推荐 {rec} 核 · 宿主共 {n} 线程',
cpuOverHint: '只给宿主留下不到 2 个线程,宿主可能会卡顿',
guestMemory: '分配内存',
memRecHint: '推荐 {rec} GB · 宿主共 {n} GB',
memOverHint: '超过推荐值,启动时可能分配失败',
graphicsReimsShort: 'Reims vGPU',
graphicsSvgaShort: 'VMware SVGA',
graphicsReimsDesc: '用宿主显卡加速 Metal,推荐',
graphicsSvgaDesc: '没有硬件加速,只用于排障',
graphicsRunningReason: '关机后才能切换',
gpuAutoTitle: '自动',
gpuAutoSub: '将使用 {name}',
gpuKindDiscrete: '独立显卡',
gpuKindIntegrated: '集成显卡',
gpuCustomIcd: '自定义 Vulkan ICD',
gpuSvgaReason: 'VMware SVGA 不使用宿主显卡',
groupGraphics: '图形',
displayGroup: '显示器',
resCustom: '自定义',
resCustomSub: '宽 × 高',
resInvalid: '格式为 宽x高,例如 2560x1600',
networkDesc: '通过 NAT 共享宿主的网络连接',
sshForward: 'SSH 端口转发',
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
sshNeedsNetwork: '需要先开启网络',
audioDesc: '把 macOS 的声音输出到宿主',
logLevelCustom: '自定义',
groupPerformance: '性能',
groupQemu: 'QEMU',
extraArgsDesc: '原样追加到 QEMU 命令行',
navHasIssue: '这一页有需要修改的项',
pendingChanges: '{n} 项更改,下次启动生效',
noChanges: '没有更改',
resetAll: '全部还原',
resetField: '还原为当前值',
opencore: 'OpenCore',
configured: '已配置',
diskController: '磁盘控制器',
diskControllerWarn: '切换前先弹出安装盘',
captureInput: '点击窗口时捕获键鼠',
captureInputHint: '默认关闭(自由指针):单按 Win 键与 Alt+Tab 保留给 Windows,不会卡在 macOS 窗口里;需要把 ⌘Tab 等系统快捷键交给 macOS 时再开启',
stopTimeout: '关机等待时间(秒)',
captureInputHint: '开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows',
stopTimeout: '关机等待时间',
stopTimeoutHint: '0 表示一直等待',
extraArgs: '额外 QEMU 参数',
logLevel: '日志级别(REIMS_VGPU_LOG)',
logLevel: '日志级别',
// Host optimization probes & guidance
hostOptimizations: '优化能力',
@@ -378,26 +425,85 @@ const dict = {
optUnavailable: '不可用',
optPCoreSub: '仅调度到性能核({detail}),减少卡顿',
optPCoreUnavailable: '当前处理器无大小核架构,无需开启',
optKernelIrqchipTitle: 'WHPX 内核中断(kernel-irqchip)',
optKernelIrqchipRec: '当前 Windows 与硬件支持,可降低磁盘 I/O 与多核 CPU 开销',
optKernelIrqchipTitle: 'WHPX 内核中断',
optKernelIrqchipRec: '可降低磁盘 I/O 和多核开销',
optKernelIrqchipExp: '当前运行时含 Win10 多核启动补丁,可在虚拟机「高级」设置中手动开启验证',
optKernelIrqchipWin10NoPatch: 'Win10 默认关闭;需更新含 startup-ipis 补丁的运行时',
optKernelIrqchipNestedErr: '当前 Windows 拒绝嵌套虚拟化属性({code}),建议选「兼容模式」',
optKernelIrqchipUnavailable: '当前宿主 WHPX 环境不支持内核中断仿真',
optColdRebootTitle: 'Win10 无感冷重启补偿',
optColdRebootAuto: '检测到系统缺少 WHvResetPartition,启动时自动监控客体重启并冷拉起',
optColdRebootAuto: '系统缺少 WHvResetPartition,会自动处理客体重启',
optColdRebootUnavailable: '当前 Windows 原生支持分区热重启,无需补偿',
optDiscreteGpuTitle: 'Vulkan 独显加速',
optDiscreteGpuRec: '已检测到独立显卡({name}),新建时默认优先使用',
optDiscreteGpuIntegrated: '仅检测到核显({name}),性能弱于独立显卡',
optDiscreteGpuUnavailable: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障',
kernelIrqchipLabel: 'WHPX 内核中断模式',
kernelIrqchipLabel: 'WHPX 中断模式',
kernelIrqchipAuto: '自动',
kernelIrqchipOn: '开启(高性能)',
kernelIrqchipOff: '关闭(兼容)',
diskControllerNvmeHint: '安装盘已弹出,建议切换为 NVMe 以提升磁盘读写性能',
diskControllerInstallHint: '装机阶段建议保持 SATA,装完弹出安装盘后再切 NVMe',
gpuUnavailableHint: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障',
kernelIrqchipOn: '开启',
kernelIrqchipOff: '关闭',
diskControllerNvmeHint: 'NVMe 读写更快',
diskControllerInstallHint: '装机时保持 SATA,装完弹出安装盘再改 NVMe',
gpuUnavailableHint: '没有找到可用的 Vulkan 显卡',
// Tray, Guest Tools, displays, fullscreen & resource bar
minimizeToTray: '关闭窗口时最小化到系统托盘',
minimizeToTraySub: '关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机',
hostDisplays: '物理显示器',
hostDisplayPrimary: '主屏',
hostDisplayHint: '主屏 {w}×{h},{scale}% 缩放 · 推荐 {rec}',
multiDisplayHint: '检测到 {n} 块显示器,排列方式在 macOS「系统设置 › 显示器」里调整',
hidpiPresetBadge: 'HiDPI',
recommendedBadge: '推荐',
fullscreenLaunch: '无边框全屏启动',
fullscreenLaunchHint: '启动后直接进入无边框全屏',
shortcutBarFullscreen: '切换全屏',
shortcutBarRelease: '释放键盘和鼠标',
macKeymapHint: '键盘习惯提示:关闭「输入捕获」时 Alt+Tab / Win 键留在 Windows;上游 Win → Command 键位映射持续跟进中(docs/upstream-pr-prep.md)',
guestToolsModeWebDAV: 'WebDAV 挂载',
guestToolsModeSync: '文件同步模式',
guestToolsUpgradeHint: 'macOS 里的工具是旧版,重新运行安装命令即可升级',
guestToolsPreventSleep: '防止 macOS 睡眠',
guestToolsPreventSleepSub: '闲置时让 macOS 保持唤醒,立即生效',
guestToolsSleepActive: '正在保持唤醒',
toastFileDelivered: '已发送 {name}',
toastPreventSleepOn: '已开启 macOS 防休眠守护',
guestLang: 'macOS 系统语言',
guestLangHint: '恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错',
guestLangSettingsHint: '恢复模式、设置助理和登录界面使用的语言',
diskControllerVirtioHint: 'VirtIO-blk 在已装 macOS 26 上虚拟化开销更低(实验性,仅装机完成后可用;建议结合宿主实测对比 NVMe 与 VirtIO)',
diskControllerNvmeReadyHint: 'NVMe 使用苹果原生驱动、支持 TRIM 空间回收且兼容恢复模式与已装系统(推荐默认)',
diskUsageSummary: '宿主机实际占用 {actual} / 虚拟上限 {virtual}({format})',
diskResizeTitle: '虚拟磁盘扩容',
diskResizeDesc: '停机扩容后,还需在 macOS 终端执行下方 diskutil 命令把 APFS 容器扩展到新容量(只增不减,不损数据)',
diskResizeAction: '扩容',
diskResizeDone: '磁盘上限已扩展至 {size};请在 macOS 终端执行下方命令扩展 APFS 容器:',
diskCompactTitle: '回收未用空间(瘦身)',
diskCompactDesc: '停机重写稀疏 .qcow2 并校验完整性,释放系统内已删除/TRIM 的空间(需留出不低于当前实际占用的临时空闲空间)',
diskCompactAction: '立即回收',
diskCompactDone: '瘦身完成:{before} → {after}(回收 {reclaimed})',
diskCompactNoGain: '磁盘已较紧凑:{before} → {after}(无额外可回收空间)',
diskCompactQcow2Only: '仅独立 .qcow2 磁盘支持回收未用空间',
stopBeforeDiskOp: '请先停止虚拟机再调整磁盘容量或回收空间',
audioBackendTitle: '音频后端',
audioBackendDesc: 'Windows 默认使用 DirectSound(dsound);选「静音设备」可在保留 macOS 虚拟声卡的同时不占用宿主音频设备',
audioBackendAuto: '自动(dsound)',
audioBackendDsound: 'DirectSound',
audioBackendNone: '静音设备',
audioDisabledReason: '请先开启音频',
hostAudioOutput: '宿主播放设备',
hostAudioInput: '宿主录音 / 麦克风',
hostAudioMissingOut: '未检测到音频输出设备,VM 启动后将静音运行(请先连接扬声器或耳机)',
hostAudioMissingIn: '未检测到麦克风/录音设备,macOS 内将录得静音(上游 reims-ctl 会自动路由到 none)',
audioTroubleshootNote: '延迟与麦克风排查:若偶发爆音,建议开启 P-Core 绑核与 WHPX 内核中断,并在 Windows 声音设置将默认播放/录制格式设为 48000 Hz;录音不可用时请检查 Windows「隐私 → 麦克风」权限,并在 macOS「系统设置 → 声音」选择 VirtIO Sound。',
toastPreventSleepOff: '已关闭 macOS 防休眠守护',
toastBorderlessUpdated: '已保存全屏启动偏好',
toastBorderlessNextStart: '已保存全屏启动偏好,重启虚拟机后生效',
statsCPU: 'QEMU CPU',
statsMemory: '宿主机内存',
statsDisk: '磁盘占用',
statsUptime: '运行时长',
statsDiskSub: '实际 {actual} / 上限 {virtual}',
},
'en-US': {
sidebarVMs: 'Virtual machines',
@@ -413,7 +519,7 @@ const dict = {
installersDelete: 'Delete',
installersDeleteConfirm: 'Confirm delete',
installersNoSpace: 'Not enough space: needs about {need} GB, {free} GB free',
installersHint: 'Offline installers can be reused for new VMs — click “Create VM” on any downloaded item to start. Items in use or downloading can’t be deleted',
installersHint: 'Downloaded installers can be reused for new VMs',
installersCreateVM: 'Create VM',
installersKindOffline: 'Offline installer',
installersKindOnline: 'Online recovery',
@@ -461,41 +567,44 @@ const dict = {
guideKindBuiltIn: 'Built-in recovery',
guideKindOffline: 'Offline install',
guideKindOnline: 'Online recovery',
guideBuiltIn1: 'Start (or restart) the VM and choose “Recovery” in OpenCore’s boot menu to enter macOS’s built-in Recovery',
guideBuiltIn2: 'Built-in Recovery already supports online reinstall; for an empty disk or offline install, click “Attach offline image” below',
guideBuiltIn3: 'When done, click “Exit recovery mode” to boot straight into macOS again',
guideStep1: 'Open Disk Utility → Continue → select the largest “QEMU HARDDISK Media” (use View › Show All Devices if hidden) → Erase as APFS (GUID Partition Map, name Macintosh HD; the screen may pause for 10–30s on a previously used disk and recover automatically), then quit Disk Utility',
guideStep2: 'Back in Recovery, choose “Reinstall macOS Tahoe” → Continue and install onto the erased disk (it restarts a few times)',
guideStep3: 'When Setup Assistant asks for your country or region, click “Exit recovery mode” to eject the installer',
guideOffline1: 'In macOS Recovery, do NOT click “Reinstall macOS Tahoe”; open the top menu bar Utilities › Terminal',
guideOffline2: 'Run the command below (or click the keyboard icon to type it into the VM). It automatically formats a blank VM disk as APFS (Macintosh HD) and starts the offline install (asks before erasing non-blank disks; restarts a few times):',
guideOffline3: 'When Setup Assistant asks for your country or region, click “Exit recovery mode” (ejects installer and restores network)',
guideBuiltIn1: 'After starting, choose “Recovery” in the OpenCore boot menu',
guideBuiltIn2: 'Recovery can reinstall over the network; for an offline install, click “Attach offline image”',
guideBuiltIn3: 'When you are done, click “Exit recovery mode”',
guideStep1: 'Open Disk Utility and select the largest “QEMU HARDDISK Media” (View › Show All Devices if it is hidden). Click Erase: name Macintosh HD, format APFS, scheme GUID. It may pause for 10–30 seconds; don’t force it off',
guideStep2: 'Back in Recovery, choose “Reinstall macOS Tahoe” and install to the disk you erased. It restarts a few times',
guideStep3: 'When Setup Assistant appears, click “Exit recovery mode” to eject the installer',
guideOffline1: 'Don’t click “Reinstall macOS Tahoe”; open Utilities › Terminal from the menu bar',
guideOffline2: 'Run the command below (the keyboard icon types it for you). It erases the blank disk as APFS and starts the install; it restarts a few times:',
guideOffline3: 'When Setup Assistant appears, click “Exit recovery mode” to eject the installer and turn the network back on',
finishInstall: 'Exit recovery mode',
enterRecovery: 'Enter recovery mode',
attachInstaller: 'Attach offline image',
pickRecoveryTitle: 'Choose an offline image (.img / .dmg)',
guestToolsTitle: 'Guest Tools',
guestToolsDesc: 'Token-authenticated two-way clipboard sync and shared folder (~/Desktop/ReimsShare ↔ Windows host) with no Xcode required.',
guestToolsConnected: 'Connected',
guestToolsReady: 'Configured',
guestToolsNotInstalled: 'Not installed',
guestToolsInstallHint: 'In macOS, double-click REIMSTOOLS → Install-Reims-Tools.command in Finder, or run in Terminal:',
attachGuestTools: 'Attach Guest Tools',
detachGuestTools: 'Eject tools disk',
openSharedFolder: 'Open shared folder',
upgradeToNVMe: 'Upgrade to NVMe',
exportDiagnostics: 'Export diagnostics (.zip)',
cloneVM: 'Derive CoW clone',
diagExternalDriveWarn: 'Data root ({dir}) is on an external or network drive; macOS install and APFS I/O will be much slower than local NVMe SSD',
diagHighMemWarn: 'Host physical memory usage is at {pct}%; close background apps or lower VM RAM if performance degrades',
diagAhciUpgradeHint: 'This VM still uses legacy SATA/AHCI; upgrade to NVMe for faster I/O and TRIM support',
diagExternalDriveWarn: 'The data folder is on an external or network drive ({dir}); disk access will be slow',
diagHighMemWarn: 'Host memory is {pct}% used; the VM may stutter',
diagAhciUpgradeHint: 'The system disk still uses SATA; NVMe is faster',
cloneTitle: 'Derive CoW clone from “{name}”',
cloneDesc: 'Creates an instant qcow2 copy-on-write overlay with a fresh Mac identity without modifying the source disk.',
cloneDesc: 'Makes an instant copy-on-write clone that takes almost no space and leaves the original untouched',
cloneNameLabel: 'New VM name',
cloneConfirm: 'Create clone',
typeClipboard: 'Paste as keystrokes',
typeClipboard: 'Send clipboard to VM',
typeIntoVM: 'Type into the VM',
typeUntypeable: 'Only characters on a US keyboard can be typed (letters, digits, symbols).',
typeUntypeable: 'Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text',
sendText: 'Send text to VM…',
sendTextTitle: 'Send text to “{name}”',
sendTextDesc: 'Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.',
sendTextDescNoGT: 'Guest Tools is not connected; only US-keyboard ASCII characters are supported until Guest Tools is connected.',
sendTextPlaceholder: 'Type or paste text to send to the VM…',
sendTextConfirm: 'Send (Ctrl+Enter)',
brokenHint: 'This VM’s configuration can’t be read',
techInfo: 'Technical details',
factCPU: 'CPU',
@@ -511,7 +620,6 @@ const dict = {
fieldController: 'Disk controller',
fieldGraphicsBackend: 'Graphics backend',
fieldICD: 'Vulkan ICD',
fieldDisplays: 'Displays',
fieldNetwork: 'Network',
fieldAudio: 'Audio',
fieldDir: 'Directory',
@@ -564,9 +672,9 @@ const dict = {
runtimeUpdate: 'Update',
runtimeNewer: 'New version: {v}',
runtimeInstall: 'Install',
runtimeCandidate: 'Receive candidates',
runtimeCandidateHint: 'Candidates have not passed a real-host smoke test',
runtimeChannel_candidate: 'Candidate',
runtimeAlpha: 'Receive alpha builds',
runtimeAlphaHint: 'Built daily from upstream by CI; not smoke-tested on a real host',
runtimeChannel_alpha: 'Alpha',
runtimeChannel_stable: 'Stable',
runtimeLookupFailed: 'Couldn’t read the runtime list from GitHub',
@@ -582,8 +690,8 @@ const dict = {
toastOnlineRecoveryAttached: 'Online recovery image attached to {name}',
toastGuestToolsAttached: 'Guest Tools disk (REIMSTOOLS) attached',
toastGuestToolsAttachedNextStart: 'Guest Tools disk attached — restart VM to mount in Finder',
toastGuestToolsDetached: 'Guest Tools disk ejected (clipboard & shared folder stay active)',
toastGuestToolsDetachedNextStart: 'Guest Tools disk ejected — applies on next start',
toastGuestToolsDetached: 'Tools disk ejected',
toastGuestToolsDetachedNextStart: 'Tools disk ejected; applies on next start',
toastNVMeReady: 'Upgraded disk controller to NVMe',
toastNVMeNextStart: 'Switched to NVMe — applies on next start',
toastDiagExported: 'Redacted diagnostics archive exported (.zip)',
@@ -614,14 +722,12 @@ const dict = {
deleteKeepFiles: 'Keep disk files',
deleteConfirm: 'Delete',
onlineRecoveryTitle: 'Download online recovery image?',
onlineRecoveryDesc: 'No cached image was found locally and no offline image was selected. Download Apple’s ~1 GB online recovery image and attach it to “{name}” automatically?',
onlineRecoveryDesc: 'No recovery image is on this PC. Download Apple’s recovery image (about 1 GB) and attach it to “{name}”?',
onlineRecoveryConfirm: 'Download & attach (~1 GB)',
noRuntimeAlert: 'Import a runtime under Host & runtime first',
hostRuntime: 'Runtime',
hostSystem: 'System',
hostGPUs: 'Graphics cards',
hostPrefs: 'Preferences',
language: 'Language',
appVersionTitle: 'App version',
appUpToDate: 'Up to date',
@@ -641,17 +747,13 @@ const dict = {
enableWHPX: 'Enable',
hostCPU: 'CPU',
hostCoresThreads: '{c} cores · {t} threads',
hostHybrid: '{p} performance + {e} efficiency',
hostSymmetric: 'Uniform cores',
autoPinPCores: 'Pin to performance cores on start',
hostRAM: 'Memory',
hostRAMAvail: '{n} GB free',
hostRAMTotal: '{n} GB total',
hostDisk: 'Free space',
hostDataRoot: 'Data folder',
noRuntime: 'No runtime yet — import reims-runtime-win-x64-*.tar.zst',
importRuntime: 'Import runtime',
activeBadge: 'In use',
activate: 'Use',
gpuRecommended: 'Recommended',
gpuDiscrete: 'Discrete',
@@ -660,40 +762,42 @@ const dict = {
gpuUnknown: 'Unknown',
wizardTitle: 'New virtual machine',
srcOfflineTitle: 'Offline installer',
srcOfflineSub: 'The full installer; installs with no network',
srcAppleTitle: 'Download from Apple',
srcAppleSub: 'A recovery image; macOS downloads during install',
srcInstallerTitle: 'Installer image',
srcInstallerSub: 'An .img or .dmg on this PC',
srcDiskTitle: 'Existing disk',
srcDiskSub: 'A .qcow2 or other disk with macOS installed',
wizChooseFile: 'Choose…',
wizNoFile: 'No file chosen',
wizOptions: 'Options',
useDefault: 'Use Default',
step1: 'Source',
step2: 'CPU & memory',
step3: 'Storage',
step4: 'Graphics & devices',
step4: 'Graphics & options',
step5: 'Review',
vmName: 'Name',
vmDir: 'Folder',
vmDirHint: 'Leave empty to use the data folder',
sourceApple: 'Download recovery image from Apple',
sourceInstaller: 'Local installer image (.img / .dmg)',
sourceDisk: 'Existing virtual disk (.qcow2)',
sourceOffline: 'Offline installer (recommended)',
offlineLoading: 'Reading Apple’s release list…',
offlineListFailed: 'Couldn’t read Apple’s release list',
offlineCached: 'Downloaded',
offlineHint: 'About 20 GB; installs with no network. “Finish install” turns the network back on',
offlineHint: 'About 20 GB; installs with no network',
offlineSpaceWarn: '{free} GB free; this release needs about {need} GB',
networkOfflineHint: 'Off by default for offline installs so macOS does not download updates mid-install (you can still enable it here, or let “Finish install” turn it on)',
networkOfflineHint: 'Off for offline installs; turned back on after installing',
summaryOfflineSource: 'Offline installer · macOS {v}',
macosVersion: 'macOS version',
macosTahoe: 'macOS 26 Tahoe (acceleration needs 26.4 or later)',
diskSize: 'Disk size',
diskSizeHint: 'Grows with use; 128G recommended',
diskSizeHint: 'Grows as it fills',
diskMode: 'Use disk as',
diskModeCopy: 'A copy — original untouched',
diskModeInPlace: 'In place',
hostThreads: 'Host has {n} threads',
hostMemory: 'Host has {n} GB',
cpuHint: '4 or 8 cores recommended',
memHint: 'Keep under 75% of host memory',
memCommitHint: 'Windows can allocate {avail} GB more right now; {rec} GB recommended',
memCommitHint: 'Windows can allocate {avail} GB more · {rec} GB recommended',
graphicsBackend: 'Graphics backend',
graphicsReims: 'reims-vgpu (accelerated, recommended)',
graphicsSvga: 'vmware-svga (no acceleration, for troubleshooting)',
gpuSelect: 'Host GPU',
gpuAutoOption: 'Automatic (prefers discrete)',
resolution: 'Resolution',
@@ -702,10 +806,9 @@ const dict = {
enableAudio: 'Audio',
enableNetwork: 'Network (NAT)',
sshPort: 'SSH forward port',
sshPortHint: '0 turns it off',
enableLogs: 'Keep graphics and serial logs',
startAfterCreate: 'Start after creating',
validationPassed: 'All checks passed — ready to create',
validationPassed: 'Ready to create',
validationChecking: 'Checking…',
issuesCount: '{n} item(s) need fixing',
summaryEdit: 'Edit',
@@ -715,7 +818,6 @@ const dict = {
summaryInstallerSource: 'Local installer · {file}',
summaryDiskSource: 'Existing disk · {file}',
summaryOn: 'On',
summaryStartAfter: 'Start after creating',
summaryLogs: 'Graphics & serial logs',
summarySSH: 'SSH forwarding',
summarySSHPort: 'Port {n}',
@@ -728,12 +830,22 @@ const dict = {
backToEdit: 'Edit and retry',
createNow: 'Create',
settingsTitle: '{name} settings',
settingsTitle: '{name}',
settingsEllipsis: 'Settings…',
specDiskUsage: '{ctl} · {used} of {max} used',
specLang: 'Language',
connGroup: 'Connection',
gtNotInstalledDesc: 'Not installed: attach the tools disk and run the installer in macOS',
gtInstallCmd: 'Install command',
sharedFolder: 'Shared folder',
deliverFileShort: 'Send File…',
openShort: 'Open',
networkTitle: 'Network',
logLevelDesc: 'Sets REIMS_VGPU_LOG',
secondsUnit: 's',
guestLangShort: 'System language',
groupMacOS: 'macOS',
appliesNextStart: 'Applies on next start',
requiresStop: 'Some changes need the VM shut down',
catPlatform: 'Platform',
catCPU: 'CPU',
catMemory: 'Memory',
catStorage: 'Storage',
catNetwork: 'Network',
catGraphics: 'Graphics & displays',
@@ -742,16 +854,57 @@ const dict = {
catLogs: 'Serial & logs',
catAdvanced: 'Advanced',
platformReadonly: 'Model, serial number and other platform identity are never shown',
catGeneral: 'General',
catCompute: 'CPU & Memory',
catStorageNet: 'Storage & Network',
catInputAudio: 'Input & Audio',
vcpus: 'Virtual CPUs',
coresUnit: 'cores',
cpuRecHint: '{rec} cores recommended · host has {n} threads',
cpuOverHint: 'Leaves the host fewer than 2 threads; Windows may stutter',
guestMemory: 'Memory',
memRecHint: '{rec} GB recommended · host has {n} GB',
memOverHint: 'Above the recommendation; the VM may fail to start',
graphicsReimsShort: 'Reims vGPU',
graphicsSvgaShort: 'VMware SVGA',
graphicsReimsDesc: 'Accelerates Metal on the host GPU. Recommended',
graphicsSvgaDesc: 'No acceleration; for troubleshooting only',
graphicsRunningReason: 'Shut down the VM to change this',
gpuAutoTitle: 'Automatic',
gpuAutoSub: 'Will use {name}',
gpuKindDiscrete: 'Discrete',
gpuKindIntegrated: 'Integrated',
gpuCustomIcd: 'Custom Vulkan ICD',
gpuSvgaReason: 'VMware SVGA does not use the host GPU',
groupGraphics: 'Graphics',
displayGroup: 'Displays',
resCustom: 'Custom',
resCustomSub: 'Width × height',
resInvalid: 'Use WIDTHxHEIGHT, e.g. 2560x1600',
networkDesc: 'Shares the host connection through NAT',
sshForward: 'SSH port forwarding',
sshOffDesc: 'Forwards a host port to port 22 in macOS',
sshNeedsNetwork: 'Turn on the network first',
audioDesc: 'Plays macOS sound on the host',
logLevelCustom: 'Custom',
groupPerformance: 'Performance',
groupQemu: 'QEMU',
extraArgsDesc: 'Appended to the QEMU command line as is',
navHasIssue: 'This page has settings to fix',
pendingChanges: '{n} changes, applied on next start',
noChanges: 'No changes',
resetAll: 'Revert all',
resetField: 'Revert to current value',
opencore: 'OpenCore',
configured: 'Configured',
diskController: 'Disk controller',
diskControllerWarn: 'Eject the installer before switching',
captureInput: 'Capture keyboard and mouse on click',
captureInputHint: 'Off by default (free pointer): Win key and Alt+Tab stay with Windows so you won’t get trapped in the macOS window; enable to send system shortcuts like ⌘Tab to macOS',
stopTimeout: 'Shutdown timeout (seconds)',
captureInputHint: 'When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows',
stopTimeout: 'Shutdown timeout',
stopTimeoutHint: '0 waits indefinitely',
extraArgs: 'Extra QEMU arguments',
logLevel: 'Log level (REIMS_VGPU_LOG)',
logLevel: 'Log level',
// Host optimization probes & guidance
hostOptimizations: 'Optimizations',
@@ -763,25 +916,84 @@ const dict = {
optPCoreSub: 'Schedule QEMU on performance cores only ({detail})',
optPCoreUnavailable: 'CPU has no hybrid P/E cores',
optKernelIrqchipTitle: 'WHPX kernel irqchip',
optKernelIrqchipRec: 'Supported on this host; lowers disk I/O and multi-core CPU overhead',
optKernelIrqchipRec: 'Lowers disk I/O and multi-core overhead',
optKernelIrqchipExp: 'Runtime includes Win10 startup-ipis patch; can be enabled in VM Advanced settings',
optKernelIrqchipWin10NoPatch: 'Off by default on Win10; needs a runtime with the startup-ipis patch',
optKernelIrqchipNestedErr: 'Host rejected nested virtualization property ({code}); use compatibility mode',
optKernelIrqchipUnavailable: 'Kernel APIC emulation is unavailable on this WHPX host',
optColdRebootTitle: 'Win10 cold-reboot workaround',
optColdRebootAuto: 'Host lacks WHvResetPartition; guest reboots are cold-restarted automatically',
optColdRebootAuto: 'WHvResetPartition is missing; guest restarts are handled automatically',
optColdRebootUnavailable: 'Host supports native partition reset; workaround not needed',
optDiscreteGpuTitle: 'Vulkan discrete GPU acceleration',
optDiscreteGpuRec: 'Discrete GPU detected ({name}); preferred automatically',
optDiscreteGpuIntegrated: 'Integrated GPU only ({name})',
optDiscreteGpuUnavailable: 'No Vulkan GPU detected; use vmware-svga for troubleshooting',
kernelIrqchipLabel: 'WHPX kernel irqchip mode',
kernelIrqchipLabel: 'WHPX interrupt mode',
kernelIrqchipAuto: 'Auto',
kernelIrqchipOn: 'On (fast)',
kernelIrqchipOff: 'Off (compat)',
diskControllerNvmeHint: 'Installer ejected — switch to NVMe for faster disk I/O',
kernelIrqchipOn: 'On',
kernelIrqchipOff: 'Off',
diskControllerNvmeHint: 'NVMe is faster',
diskControllerInstallHint: 'Keep SATA while installing; switch to NVMe after ejecting the installer',
gpuUnavailableHint: 'No Vulkan GPU detected; switch to vmware-svga for troubleshooting',
gpuUnavailableHint: 'No Vulkan GPU found',
// Tray, Guest Tools, displays, fullscreen & resource bar
minimizeToTray: 'Minimize to system tray on close',
minimizeToTraySub: 'Clipboard and shared folders keep working; start and stop VMs from the tray',
hostDisplays: 'Physical displays',
hostDisplayPrimary: 'Primary',
hostDisplayHint: 'Main display {w}×{h} at {scale}% · {rec} recommended',
multiDisplayHint: '{n} displays found; arrange them in macOS System Settings › Displays',
hidpiPresetBadge: 'HiDPI',
recommendedBadge: 'Recommended',
fullscreenLaunch: 'Launch borderless fullscreen',
fullscreenLaunchHint: 'Opens macOS in borderless full screen',
shortcutBarFullscreen: 'Toggle full screen',
shortcutBarRelease: 'Release keyboard and mouse',
macKeymapHint: 'Keymap tip: with Input capture off, Alt+Tab and Win stay with Windows; upstream Win → Command mapping is tracked in docs/upstream-pr-prep.md',
guestToolsModeWebDAV: 'WebDAV mount',
guestToolsModeSync: 'Folder sync',
guestToolsUpgradeHint: 'The tools in macOS are out of date; run the install command again to update',
guestToolsPreventSleep: 'Prevent macOS sleep',
guestToolsPreventSleepSub: 'Keeps macOS awake while idle; applies immediately',
guestToolsSleepActive: 'Keeping macOS awake',
toastFileDelivered: 'Sent {name}',
toastPreventSleepOn: 'Prevent-sleep guard enabled',
guestLang: 'macOS system language',
guestLangHint: 'Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable',
guestLangSettingsHint: 'Used by Recovery, Setup Assistant and the login window',
diskControllerVirtioHint: 'VirtIO-blk offers lower virtualization I/O overhead on installed macOS 26 (experimental — eject installer first and benchmark against NVMe on your host)',
diskControllerNvmeReadyHint: 'NVMe uses Apple’s native driver with TRIM/discard support across Recovery and macOS 26 (recommended default)',
diskUsageSummary: 'Host usage {actual} / virtual capacity {virtual} ({format})',
diskResizeTitle: 'Expand virtual disk',
diskResizeDesc: 'Grow-only resize while stopped. After expanding, run the macOS diskutil command shown below to extend the APFS container.',
diskResizeAction: 'Expand',
diskResizeDone: 'Virtual disk expanded to {size}. Run this in macOS Terminal to grow APFS:',
diskCompactTitle: 'Reclaim unused space',
diskCompactDesc: 'Rewrites sparse .qcow2 and verifies integrity to release deleted/TRIMmed blocks (needs temporary free space >= current actual size + 2 GB).',
diskCompactAction: 'Reclaim now',
diskCompactDone: 'Compacted: {before} → {after} (reclaimed {reclaimed})',
diskCompactNoGain: 'Already compact: {before} → {after} (no extra space reclaimed)',
diskCompactQcow2Only: 'Space reclamation is only available for standalone .qcow2 disks',
stopBeforeDiskOp: 'Stop the VM before resizing or compacting its disk',
audioBackendTitle: 'Audio backend',
audioBackendDesc: 'Windows uses DirectSound (dsound) by default; Silent keeps virtual sound hardware in macOS without opening host audio devices',
audioBackendAuto: 'Auto (dsound)',
audioBackendDsound: 'DirectSound',
audioBackendNone: 'Silent',
audioDisabledReason: 'Enable audio first',
hostAudioOutput: 'Host playback devices',
hostAudioInput: 'Host recording / microphone',
hostAudioMissingOut: 'No playback device detected — VM will run silently until speakers/headphones are connected',
hostAudioMissingIn: 'No recording device detected — macOS microphone will record silence (upstream reims-ctl routes input to none)',
audioTroubleshootNote: 'Latency & mic tips: if audio crackles, keep P-Core pinning and WHPX kernel-irqchip on and set Windows default playback/recording format to 48000 Hz; for microphone input, verify Windows Privacy → Microphone access and choose VirtIO Sound in macOS System Settings → Sound.',
toastPreventSleepOff: 'Prevent-sleep guard disabled',
toastBorderlessUpdated: 'Fullscreen launch preference saved',
toastBorderlessNextStart: 'Fullscreen launch saved — applies on next restart',
statsCPU: 'QEMU CPU',
statsMemory: 'Host RAM',
statsDisk: 'Disk usage',
statsUptime: 'Uptime',
statsDiskSub: '{actual} actual / {virtual} max',
},
} as const
+113 -5
View File
@@ -1,5 +1,5 @@
import { t } from '../i18n'
import { GPUInfo, HostReport, Locale, VMDetail } from '../types'
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
// Human-readable values for the main view (docs/ui-redesign.md §4.3).
// Raw values stay available under "Technical details".
@@ -17,13 +17,38 @@ export function recommendedMemoryGB(host: HostReport): number {
return MEMORY_CHOICES.reduce((best, m) => (m <= limit ? m : best), MEMORY_CHOICES[0])
}
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
export function formatMemory(raw: string): string {
/** Memory sizes offered as quick picks, in GB. */
export const MEMORY_MARKS = MEMORY_CHOICES
/**
* Largest memory size in GB that still fits the same limits
* recommendedMemoryGB applies; above it the settings slider turns amber.
*/
export function memorySafeLimitGB(host: HostReport): number {
let limit = host.total_ram_gb * 0.6
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
return Math.max(Math.floor(limit), recommendedMemoryGB(host))
}
/** vCPU count suggested for a new VM; same rule as the create wizard. */
export function recommendedCPUs(host: HostReport): number {
const rec = host.logical_cpus >= 12 ? 8 : 4
return host.logical_cpus > 0 ? Math.min(rec, host.logical_cpus) : rec
}
/** "16G" / "16384M" / "16GiB" → 16. Null when the shape is unknown. */
export function parseMemoryGB(raw: string | undefined): number | null {
const m = /^\s*(\d+(?:\.\d+)?)\s*([KMGT])?(?:i?B)?\s*$/i.exec(raw ?? '')
if (!m) return raw
if (!m) return null
const n = Number(m[1])
const unit = (m[2] ?? 'M').toUpperCase()
const gb = unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
return unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
}
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
export function formatMemory(raw: string): string {
const gb = parseMemoryGB(raw)
if (gb === null) return raw
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
return `${rounded} GB`
}
@@ -79,3 +104,86 @@ export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): st
export function sshCommand(port: number): string {
return `ssh -p ${port} 127.0.0.1`
}
export function formatBytes(bytes: number): string {
if (!bytes || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let v = bytes
let i = 0
while (v >= 1024 && i < units.length - 1) {
v /= 1024
i++
}
const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2
return `${v.toFixed(digits)} ${units[i]}`
}
export function formatUptime(sec: number, locale: Locale): string {
if (!sec || sec <= 0) return '—'
const h = Math.floor(sec / 3600)
const m = Math.floor((sec % 3600) / 60)
const s = sec % 60
if (locale === 'zh-CN') {
if (h > 0) return `${h}小时 ${m}分`
if (m > 0) return `${m}分 ${s}秒`
return `${s}秒`
}
if (h > 0) return `${h}h ${m}m`
if (m > 0) return `${m}m ${s}s`
return `${s}s`
}
const DEFAULT_DISPLAY_PRESETS: DisplayPreset[] = [
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false, recommended: true },
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: true },
{ resolution: '3840x2160', label: '3840 × 2160', hidpi: true },
]
export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
if (host.display_presets && host.display_presets.length > 0) {
return host.display_presets
}
return DEFAULT_DISPLAY_PRESETS
}
export function recommendedResolution(host: HostReport): string {
if (host.recommended_resolution) return host.recommended_resolution
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
return rec?.resolution ?? '1920x1080'
}
export interface GuestLangPreset {
value: string
zh: string
en: string
}
export const GUEST_LANG_PRESETS: GuestLangPreset[] = [
{ value: 'zh-Hans:0', zh: '简体中文(美式键盘,推荐)', en: 'Simplified Chinese (US Keyboard)' },
{ value: 'zh-Hans:252', zh: '简体中文(拼音键盘)', en: 'Simplified Chinese (Pinyin)' },
{ value: 'zh-Hant:0', zh: '繁體中文(美式键盘)', en: 'Traditional Chinese (US Keyboard)' },
{ value: 'en-US:0', zh: 'English (US)', en: 'English (US)' },
{ value: 'ja-JP:0', zh: '日本語(美式键盘)', en: 'Japanese (US Keyboard)' },
{ value: 'ko-KR:0', zh: '한국어(美式键盘)', en: 'Korean (US Keyboard)' },
]
export function defaultGuestLang(locale: Locale): string {
return locale === 'en-US' ? 'en-US:0' : 'zh-Hans:0'
}
export function guestLangLabel(locale: Locale, code: string | undefined): string {
if (!code) return defaultGuestLang(locale)
const hit = GUEST_LANG_PRESETS.find((p) => p.value === code)
if (hit) return locale === 'zh-CN' ? hit.zh : hit.en
return code
}
/**
* Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a
* pop-up label and its grey detail, so the menu reads like macOS.
*/
export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } {
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
}
+383 -6
View File
@@ -148,12 +148,34 @@ h1, h2, h3, p { margin: 0; }
.actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
/* ── macOS Tahoe "About This Mac" Hero ─────────────────── */
/* VM page (docs/ui-audit.md H1): one hero, one spec block, then context.
Type scale on this page: 26 / 15 / 13 / 12 (macOS Large Title, Title 3,
Body, Callout). */
.vm-page { gap: 32px; padding-bottom: 8px; }
.vm-hero {
display: flex; flex-direction: column; align-items: center;
gap: 8px; padding: 4px 0 6px; text-align: center;
gap: 6px; padding: 28px 0 4px; text-align: center;
}
.vm-imac-svg { width: 112px; height: 88px; filter: drop-shadow(0 6px 14px rgba(15, 23, 42, 0.12)); }
.vm-hero-name { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; color: var(--text); }
.vm-imac-svg { width: 140px; height: 112px; margin-bottom: 10px; filter: drop-shadow(0 10px 22px rgba(15, 23, 42, 0.14)); }
.vm-hero-name { margin: 0; font-size: 26px; font-weight: 700; letter-spacing: -0.02em; line-height: 32px; color: var(--text); user-select: text; }
.vm-hero-sub { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-13); color: var(--text-2); }
.vm-specs {
display: grid; grid-template-columns: max-content max-content; column-gap: 14px; row-gap: 5px;
margin: 18px 0 0; font-size: var(--fs-13); line-height: 18px;
}
.vm-specs dt { text-align: right; color: var(--text); font-weight: var(--fw-medium); }
.vm-specs dd { margin: 0; text-align: left; color: var(--text-2); user-select: text; }
.vm-hero-actions { display: flex; align-items: center; justify-content: center; gap: 8px; margin-top: 22px; }
.vm-meters { display: grid; grid-template-columns: 1fr 1fr; gap: 28px; padding: 0 4px; }
.vm-meter { display: grid; grid-template-columns: 1fr auto; row-gap: 6px; align-items: baseline; }
.vm-meter-label { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-12); color: var(--text-3); }
.vm-meter-value { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text); font-variant-numeric: tabular-nums; }
.vm-meter .resource-meter { grid-column: 1 / -1; }
.vm-footnote { margin: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 6px; font-size: var(--fs-12); color: var(--text-3); }
.vm-footnote kbd { font-family: var(--font-mono); font-size: 11px; padding: 1px 5px; border-radius: 4px; border: 1px solid var(--border-strong); color: var(--text-2); background: var(--surface-1); }
.vm-footnote .sep { margin: 0 4px; }
.ok-text { display: inline-flex; align-items: center; gap: 4px; color: #1a9e30; }
:root[data-theme="dark"] .ok-text { color: var(--status-running); }
.vm-hero-pill {
display: inline-flex; align-items: center; gap: 6px;
padding: 3px 10px; border-radius: 999px;
@@ -467,9 +489,170 @@ h1, h2, h3, p { margin: 0; }
.review-cmd-box { display: flex; align-items: flex-start; gap: var(--sp-2); }
.review-cmd-box .code { flex: 1; min-width: 0; }
.settings-split { display: flex; height: 460px; min-height: 0; }
.settings-nav { width: 186px; flex-shrink: 0; padding: 10px 8px; border-right: 1px solid var(--border); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; overflow-y: auto; }
.settings-pane { flex: 1; padding: 20px 24px; overflow-y: auto; display: flex; flex-direction: column; gap: var(--sp-4); }
/* ── VM settings (ui/settings.tsx) ─────────────────────── */
.dialog.settings-dialog { width: 900px; }
.settings-split { display: flex; height: min(600px, calc(100vh - 210px)); min-height: 0; }
.settings-nav { width: 204px; flex-shrink: 0; padding: 10px 8px; border-right: 1px solid var(--border); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; overflow-y: auto; }
.settings-pane { flex: 1; min-width: 0; padding: 18px 24px 28px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; }
.settings-pane-title { margin: 0; font-size: 18px; font-weight: var(--fw-strong); letter-spacing: -0.01em; color: var(--text); }
.nav-icon-cat-general { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); }
.nav-icon-cat-compute { background: linear-gradient(145deg, #7a78ff 0%, #5856d6 100%); }
.nav-icon-cat-display { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
.nav-icon-cat-storage { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
.nav-icon-cat-input { background: linear-gradient(145deg, #ff6482 0%, #ff2d55 100%); }
.nav-icon-cat-advanced { background: linear-gradient(145deg, #aeaeb2 0%, #48484a 100%); }
.nav-count {
min-width: 18px; height: 18px; padding: 0 5px; flex-shrink: 0;
display: grid; place-items: center; border-radius: 999px;
background: var(--accent-soft); color: var(--accent-soft-text);
font-size: 11px; font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
}
.nav-item[aria-selected="true"] .nav-count { background: rgba(255, 255, 255, 0.25); color: var(--accent-text); }
.nav-issue { color: var(--status-error); flex-shrink: 0; }
.nav-item[aria-selected="true"] .nav-issue { color: var(--accent-text); }
.sgroup { display: flex; flex-direction: column; gap: var(--sp-2); }
.sgroup-title { margin: 0 0 0 4px; font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3); }
.sgroup-list { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); overflow: hidden; }
.sgroup-note { margin: 0 4px; font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; }
.srow { position: relative; padding: 12px 16px; display: flex; flex-direction: column; gap: 10px; transition: background var(--dur-fast); }
.srow + .srow::before { content: ""; position: absolute; top: 0; left: 16px; right: 16px; height: 1px; background: var(--border); }
.srow[data-error] { background: var(--danger-soft); }
.srow-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 28px; }
.srow-text { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.srow-title { display: flex; align-items: center; gap: 6px; font-size: 13.5px; color: var(--text); }
.srow-desc { font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; }
.srow-reason { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-12); color: var(--text-2); }
.srow-ctrl { display: flex; align-items: center; gap: var(--sp-2); flex-shrink: 0; }
.srow-fieldset { border: 0; padding: 0; margin: 0; min-width: 0; transition: opacity var(--dur-fast); }
.srow-fieldset:disabled { opacity: 0.42; }
.srow[data-disabled] .srow-title { color: var(--text-2); }
.srow-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); }
.srow-error svg { flex-shrink: 0; margin-top: 2px; }
.srow-kv .srow-value { min-width: 0; text-align: right; font-size: var(--fs-13); color: var(--text-2); overflow-wrap: anywhere; user-select: text; }
.dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; }
.warn-text { color: #b86e00; }
:root[data-theme="dark"] .warn-text { color: var(--status-busy); }
.inline-code { font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); background: var(--surface-active); padding: 1px 6px; border-radius: 4px; user-select: text; }
.stack-2 { display: flex; flex-direction: column; align-items: flex-start; gap: var(--sp-2); }
.stack-2 > .input { max-width: 320px; }
.res-input { margin-top: var(--sp-2); max-width: 220px; }
.foot-status { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); color: var(--text-2); }
.foot-status .link-btn { font-size: var(--fs-13); margin-left: var(--sp-1); }
.foot-status .link-btn:disabled { opacity: 0.5; cursor: default; text-decoration: none; }
/* Segmented control with a sliding highlight */
:root { --seg-thumb: #ffffff; }
:root[data-theme="dark"] { --seg-thumb: #5b5c63; }
.seg { position: relative; display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); isolation: isolate; }
.seg-wide { display: flex; }
.seg-wide button { flex: 1; }
.seg-thumb {
position: absolute; top: 2px; bottom: 2px; left: 0; z-index: 0;
border-radius: var(--r-sm); background: var(--seg-thumb);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 0 0 0.5px rgba(0, 0, 0, 0.06);
transition: transform var(--dur) cubic-bezier(0.3, 0.7, 0.2, 1), width var(--dur) cubic-bezier(0.3, 0.7, 0.2, 1);
}
.seg button {
position: relative; z-index: 1; height: 26px; padding: 0 12px;
border: none; border-radius: var(--r-sm); background: transparent;
color: var(--text-2); font: inherit; font-size: var(--fs-13); white-space: nowrap;
cursor: pointer; transition: color var(--dur-fast);
}
.seg button:hover:not(:disabled) { color: var(--text); }
.seg button[aria-checked="true"] { color: var(--text); font-weight: var(--fw-medium); }
.seg button:disabled { opacity: 0.4; cursor: not-allowed; }
/* Range field: slider + number */
.range-field { display: flex; flex-direction: column; }
.range-main { display: flex; align-items: flex-start; gap: var(--sp-4); }
.range-rail-wrap { position: relative; flex: 1; min-width: 0; height: 42px; }
.range-rail { position: absolute; left: 9px; right: 9px; top: 13px; height: 4px; pointer-events: none; }
.range-track { position: absolute; inset: 0; border-radius: 999px; background: var(--surface-active); }
/* Zones sit as a thin ruler under the track so the fill never hides them. */
.range-band { position: absolute; top: 8px; height: 3px; border-radius: 999px; }
.range-band.rec { background: rgba(40, 205, 65, 0.55); }
.range-band.warn { background: rgba(255, 159, 10, 0.55); }
.range-fill { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 999px; background: var(--accent); transition: background var(--dur-fast); }
.range-field[data-warn] .range-fill { background: var(--status-busy); }
.range {
position: absolute; left: 0; top: 5px; width: 100%; height: 20px; margin: 0;
background: transparent; -webkit-appearance: none; appearance: none; cursor: pointer;
}
.range:focus-visible { box-shadow: none; }
.range::-webkit-slider-runnable-track { height: 20px; background: transparent; }
.range::-webkit-slider-thumb {
-webkit-appearance: none; width: 18px; height: 18px; margin-top: 1px; border-radius: 50%;
background: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 0 0 0.5px rgba(0, 0, 0, 0.14);
transition: transform var(--dur-fast), box-shadow var(--dur-fast);
}
.range:active::-webkit-slider-thumb { transform: scale(1.12); }
.range:focus-visible::-webkit-slider-thumb { box-shadow: var(--focus-ring), 0 1px 3px rgba(0, 0, 0, 0.3); }
.range-marks { position: absolute; left: 9px; right: 9px; top: 25px; height: 17px; }
.range-mark {
position: absolute; top: 0; transform: translateX(-50%); padding: 0 4px;
border: none; border-radius: 4px; background: transparent;
font: inherit; font-size: 11px; line-height: 17px; color: var(--text-3);
font-variant-numeric: tabular-nums; cursor: pointer;
}
.range-mark:hover { color: var(--text); background: var(--surface-hover); }
.range-mark[aria-pressed="true"] { color: var(--accent-soft-text); font-weight: var(--fw-strong); }
.num-field {
display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; flex-shrink: 0;
border-radius: var(--r-md); border: 1px solid var(--border-strong); background: var(--surface-input);
transition: border-color var(--dur-fast), box-shadow var(--dur-fast);
}
.num-field:focus-within { border-color: var(--accent); box-shadow: var(--focus-ring); }
.num-input { min-width: 0; padding: 0; border: none; outline: none; background: transparent; color: var(--text); font: inherit; font-size: var(--fs-13); text-align: right; font-variant-numeric: tabular-nums; }
.num-input:focus-visible { box-shadow: none; }
.num-unit { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; }
/* Option cards */
.opt-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(128px, 1fr)); gap: var(--sp-2); }
.opt-card {
position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 3px; min-width: 0;
padding: 10px 12px; border-radius: var(--r-md); border: 1px solid var(--border-strong);
background: var(--surface-card-elevated); cursor: pointer;
transition: border-color var(--dur-fast), background var(--dur-fast), box-shadow var(--dur-fast);
}
.opt-card:hover { background: var(--surface-hover); }
.opt-card[data-selected] { border-color: var(--accent); background: var(--accent-soft); box-shadow: inset 0 0 0 1px var(--accent); }
.opt-card[data-disabled] { opacity: 0.45; cursor: not-allowed; }
.opt-card input { position: absolute; opacity: 0; pointer-events: none; }
.opt-card:focus-within { box-shadow: var(--focus-ring); }
.opt-card[data-selected]:focus-within { box-shadow: inset 0 0 0 1px var(--accent), var(--focus-ring); }
.opt-card-title { max-width: 100%; font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.opt-card-sub { max-width: 100%; font-size: var(--fs-12); color: var(--text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.opt-card-badges { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 2px; }
.opt-card .badge { height: 18px; padding: 0 6px; font-size: 11px; }
.screen-art { display: block; margin-bottom: 6px; border-radius: 3px; border: 1.5px solid var(--text-3); background: linear-gradient(160deg, var(--accent-soft), transparent 70%); transition: border-color var(--dur-fast); }
.opt-card[data-selected] .screen-art { border-color: var(--accent); }
.screen-art.custom { width: 44px; height: 26px; border-style: dashed; background: none; }
/* Pop-up button (replaces native <select>) */
.popup-btn {
display: inline-flex; align-items: center; justify-content: space-between; gap: 10px;
height: 28px; min-width: 140px; max-width: 100%; padding: 0 8px 0 10px;
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
background: var(--seg-thumb); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
font: inherit; font-size: var(--fs-13); text-align: left; cursor: pointer;
transition: background var(--dur-fast), border-color var(--dur-fast);
}
.popup-btn:hover { border-color: var(--text-3); }
.popup-btn[data-state="open"] { border-color: var(--accent); box-shadow: var(--focus-ring); }
.popup-btn:disabled { opacity: 0.45; cursor: not-allowed; }
.popup-wide { display: flex; width: 100%; height: 32px; }
.popup-value { min-width: 0; display: inline-flex; align-items: baseline; gap: 6px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.popup-chevron { flex-shrink: 0; color: var(--text-3); }
.popup-detail { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; }
.popup-menu { min-width: var(--radix-dropdown-menu-trigger-width); max-height: min(360px, var(--radix-dropdown-menu-content-available-height)); overflow-y: auto; }
.popup-item { position: relative; padding-left: 28px; padding-right: 14px; gap: 8px; }
.popup-check { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
.popup-item-label { white-space: nowrap; }
.popup-item[data-highlighted] .popup-detail { color: rgba(255, 255, 255, 0.78); }
.code { padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border); font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); word-break: break-all; user-select: text; }
.fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
@@ -501,3 +684,197 @@ h1, h2, h3, p { margin: 0; }
.guide-cmd { margin-top: var(--sp-2); }
.warn-text { color: var(--status-busy); }
/* ── v0.2.2 Resource telemetry bar & shortcuts ─────────── */
.resource-bar {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: var(--sp-3);
}
.resource-cell {
padding: 10px 12px;
border-radius: var(--r-lg);
border: 1px solid var(--border);
background: var(--surface-card-elevated);
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.resource-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
font-size: var(--fs-12);
color: var(--text-3);
}
.resource-value {
font-size: var(--fs-15, 15px);
font-weight: var(--fw-strong);
color: var(--text);
font-variant-numeric: tabular-nums;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.resource-sub {
font-size: 11px;
color: var(--text-3);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.resource-meter {
height: 4px;
border-radius: 999px;
background: var(--surface-active);
overflow: hidden;
margin-top: 2px;
}
.resource-meter > span {
display: block;
height: 100%;
border-radius: 999px;
background: var(--accent);
transition: width 0.35s ease;
}
.shortcut-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px 14px;
padding: 8px 12px;
border-radius: var(--r-md);
background: var(--surface-1);
border: 1px solid var(--border);
font-size: var(--fs-12);
color: var(--text-2);
}
.shortcut-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.shortcut-item kbd {
padding: 1px 6px;
border-radius: 5px;
border: 1px solid var(--border-strong);
background: var(--surface-card-elevated);
font-family: var(--font-mono);
font-size: 11px;
color: var(--text);
}
.gt-toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
padding: 10px 12px;
margin-bottom: 10px;
border-radius: var(--r-md);
border: 1px solid var(--border);
background: var(--surface-1);
}
.gt-toggle-main {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.gt-toggle-title {
display: flex;
align-items: center;
gap: 6px;
font-size: var(--fs-13);
font-weight: var(--fw-medium);
color: var(--text);
}
.preset-tag {
margin-left: 5px;
font-size: 10px;
opacity: 0.8;
}
/* ── Motion (docs/ui-audit.md) ─────────────────────────────
Short and quiet: things arrive, they do not perform. Every duration is a
token, so prefers-reduced-motion (tokens.css) turns them all to 0. */
:root { --ease-out: cubic-bezier(0.22, 0.8, 0.3, 1); --dur-slow: 320ms; }
@media (prefers-reduced-motion: reduce) { :root { --dur-slow: 0ms; } }
@keyframes rise-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes pop-in { from { opacity: 0; transform: translate(-50%, -48%) scale(0.97); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
@keyframes menu-in { from { opacity: 0; transform: translateY(-4px) scale(0.98); } to { opacity: 1; transform: none; } }
.page { animation: rise-in var(--dur-slow) var(--ease-out) both; }
.overlay { animation: fade-in var(--dur) ease-out both; }
.dialog { animation: pop-in var(--dur-slow) var(--ease-out) both; }
.menu { transform-origin: var(--radix-dropdown-menu-content-transform-origin, top); animation: menu-in var(--dur) var(--ease-out) both; }
.tooltip { animation: fade-in var(--dur-fast) ease-out both; }
.pane-anim { display: flex; flex-direction: column; gap: 20px; animation: rise-in var(--dur) var(--ease-out) both; }
.step-anim { display: flex; flex-direction: column; gap: var(--sp-4); animation: rise-in var(--dur) var(--ease-out) both; }
.btn:active:not(:disabled), .icon-btn:active:not(:disabled), .popup-btn:active { transform: scale(0.97); }
.vm-hero > * { animation: rise-in var(--dur-slow) var(--ease-out) both; }
.vm-hero > *:nth-child(2) { animation-delay: 30ms; }
.vm-hero > *:nth-child(3) { animation-delay: 60ms; }
.vm-hero > *:nth-child(4) { animation-delay: 90ms; }
.vm-hero > *:nth-child(5) { animation-delay: 120ms; }
.nav-item { transition: background var(--dur-fast), color var(--dur-fast), box-shadow var(--dur); }
/* VM screen thumbnail: the VM's own picture, framed like a display. */
.vm-screen {
position: relative; width: min(440px, 100%); margin-bottom: 14px;
border-radius: 12px; overflow: hidden;
border: 7px solid #1d1e22; background-color: #111; background-size: 100% 100%;
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.22), 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
}
:root[data-theme="dark"] .vm-screen { border-color: #0c0c0e; box-shadow: 0 18px 40px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.1); }
.vm-screen-img { display: block; width: 100%; height: auto; animation: fade-in var(--dur-slow) ease-out both; user-select: none; }
.vm-screen.is-idle .vm-screen-img { filter: saturate(0.4) brightness(0.55); transition: filter var(--dur-slow); }
.vm-screen-live {
position: absolute; top: 10px; right: 10px; width: 8px; height: 8px; border-radius: 50%;
background: var(--status-running); box-shadow: 0 0 0 3px rgba(40, 205, 65, 0.28);
animation: pulse 2s ease-in-out infinite;
}
.vm-screen-play {
position: absolute; inset: 0; margin: auto; width: 58px; height: 58px; padding-left: 3px;
display: grid; place-items: center; border: none; border-radius: 50%; cursor: pointer;
background: rgba(255, 255, 255, 0.88); color: #1d1d1f;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); backdrop-filter: blur(10px);
transition: transform var(--dur) var(--ease-out), background var(--dur-fast);
}
.vm-screen-play:hover { transform: scale(1.07); background: #ffffff; }
.vm-screen-play:active { transform: scale(0.96); }
/* New-VM wizard: source cards */
.source-cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.source-card {
position: relative; display: grid; grid-template-columns: auto 1fr; grid-template-rows: auto auto;
column-gap: 12px; row-gap: 2px; align-items: center;
padding: 14px 16px; border-radius: var(--r-lg); cursor: pointer;
border: 1px solid var(--border-strong); background: var(--surface-card-elevated);
transition: border-color var(--dur-fast), background var(--dur-fast), box-shadow var(--dur), transform var(--dur) var(--ease-out);
}
.source-card:hover { background: var(--surface-hover); transform: translateY(-1px); }
.source-card[data-selected] { border-color: var(--accent); background: var(--accent-soft); box-shadow: inset 0 0 0 1px var(--accent); }
.source-card:focus-within { box-shadow: var(--focus-ring); }
.source-card[data-selected]:focus-within { box-shadow: inset 0 0 0 1px var(--accent), var(--focus-ring); }
.source-card input { position: absolute; opacity: 0; pointer-events: none; }
.source-icon {
grid-row: 1 / 3; width: 40px; height: 40px; border-radius: 10px;
display: grid; place-items: center; color: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.16);
}
.source-icon-offline { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
.source-icon-apple { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
.source-icon-installer { background: linear-gradient(145deg, #ff9f0a 0%, #e07b00 100%); }
.source-icon-disk { background: linear-gradient(145deg, #aeaeb2 0%, #636366 100%); }
.source-title { display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: var(--fw-strong); color: var(--text); }
.source-title .badge { height: 18px; padding: 0 7px; font-size: 11px; }
.source-sub { font-size: var(--fs-12); color: var(--text-3); }
.path-text { display: block; max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-12); }
.name-input { width: 260px; }
/* The assistant keeps one size across steps, like macOS setup assistants. */
.dialog.wizard-dialog { width: 760px; height: min(660px, calc(100vh - 80px)); }
+48 -237
View File
@@ -1,295 +1,106 @@
// Backend types come from the Wails-generated models (wailsjs/go/models.ts,
// regenerated by `wails dev` / `wails build`). This file only adds what Go
// cannot say: string unions, and `| null` for slices Go may send as nil.
import { config, host, installer, main, reims, runtime, version } from '../wailsjs/go/models'
/** A generated class as a plain data shape (no convertValues helper). */
type Model<T> = Omit<T, 'convertValues'>
export type Locale = 'zh-CN' | 'en-US'
export interface Config {
data_root: string
export type Config = Model<config.Config> & {
locale: Locale
active_runtime?: string
auto_pin_pcores: boolean
default_gpu?: string
runtime_channel?: 'stable' | 'candidate' | ''
runtime_channel?: 'stable' | 'alpha' | ''
}
export interface GPUInfo {
name: string
vulkan_icd: string
export type DisplayInfo = host.DisplayInfo
export type DisplayPreset = host.DisplayPreset
export type AudioInfo = host.AudioInfo
export type WHPXCapabilities = host.WHPXCapabilities
export type GPUInfo = Model<host.GPUInfo> & {
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
}
export interface WHPXCapabilities {
modern_os: boolean
apic_emulation: boolean
kernel_irqchip_available: boolean
nested_virt_property: boolean
nested_virt_probe_error?: string
}
export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable'
export interface Optimization {
export type Optimization = Model<host.Optimization> & {
id: 'pcore_pin' | 'kernel_irqchip' | 'cold_reboot' | 'discrete_gpu' | string
status: OptimizationStatus
supported: boolean
recommended: boolean
detail?: string
}
export interface HostReport {
os: string
arch: string
logical_cpus: number
physical_cores: number
has_hybrid_cores: boolean
p_core_count: number
e_core_count: number
p_core_mask: number
p_core_mask_hex: string
p_core_logical_cpus?: number[]
e_core_logical_cpus?: number[]
lpe_core_count?: number
non_lpe_mask?: number
non_lpe_mask_hex?: string
non_lpe_logical_cpus?: number[]
total_ram_gb: number
avail_ram_gb: number
memory_load_pct?: number
/** Windows commit memory: QEMU commits all guest RAM at start. */
commit_avail_gb: number
commit_limit_gb: number
data_root: string
data_root_drive_type?: string
free_disk_gb: number
export type HostReport = Omit<Model<host.Report>, 'gpus' | 'recommended_gpu'> & {
whpx: 'ready' | 'no_hypervisor' | 'missing' | 'unsupported'
whpx_caps?: WHPXCapabilities
needs_cold_reboot_workaround?: boolean
gpus: GPUInfo[]
recommended_gpu?: GPUInfo
}
export interface RuntimeManifest {
commit: string
full_commit: string
qemu_version: string
util_version: string
built_at: string
file_count: number
dll_count: number
raw_bytes: number
export type RuntimeManifest = Model<runtime.Manifest>
export type InstalledRuntime = Model<runtime.Installed>
export type RemoteRuntime = Model<runtime.Remote> & {
channel: 'stable' | 'alpha'
}
export interface InstalledRuntime {
commit: string
dir: string
active: boolean
manifest: RuntimeManifest
}
export interface VMListItem {
name: string
dir: string
pid: number | null
export type VMListItem = Model<reims.VMListItem> & {
state: 'running' | 'stopped' | 'broken'
}
export interface PendingChange {
field: string
from: string
to: string
}
export type PendingChange = main.PendingChange
export interface AppState {
export type AppState = Omit<Model<main.AppState>, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & {
config: Config
host: HostReport
optimizations?: Optimization[]
runtimes: InstalledRuntime[] | null
active_runtime?: InstalledRuntime
vms: VMListItem[] | null
transitions: Record<string, string>
pending_changes: Record<string, PendingChange[]>
/** First launch: no data folder chosen yet (setup.go). */
needs_setup: boolean
app_version?: string
}
export interface AppUpdateInfo {
current: string
latest: string
has_update: boolean
page_url?: string
download_url?: string
asset_name?: string
asset_size?: number
published_at?: string
}
export type AppUpdateInfo = version.UpdateInfo
export type VMDetail = reims.VMDetail
export type VMStats = main.VMStats
/** One frame of a VM's screen (thumbnail_flow.go). Empty data_url: none yet. */
export type VMThumbnail = main.VMThumbnail
export type ValidationIssue = reims.ValidationIssue
export type DiskResizeResult = reims.DiskResizeResult
export type DiskCompactResult = reims.DiskCompactResult
export type SetOpts = reims.SetOpts
export interface VMDetail {
name: string
state: string
kind: string
directory: string
cpus: number
memory: string
disk: string
disk_controller: string
graphics: string
display: string
displays: number
resolution: string
gpu: string
has_opencore: boolean
has_installer: boolean
recovery_mode?: boolean
installer_path?: string
cpu_model: string
audio: boolean
audio_raw: string
network: boolean
network_summary: string
ssh_port: number
logs: boolean
log_level: string
stop_timeout: number
capture: boolean
borderless: boolean
extra_args: string
guest_tools_attached?: boolean
guest_tools_configured?: boolean
guest_tools_connected?: boolean
shared_dir?: string
}
export interface ValidationIssue {
field: string
code: string
message: string
}
export interface CreateOpts {
name: string
dir?: string
export type CreateOpts = Model<reims.CreateOpts> & {
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
/** With macos: an offline installer of that release (reims-ctl create --offline). */
offline?: boolean
macos?: string
installer?: string
cpus: number
memory: string
disk_size?: string
disk?: string
disk_mode?: 'copy' | 'in-place'
disk_controller?: 'nvme' | 'ahci' | 'virtio'
graphics: 'reims-vgpu' | 'vmware-svga'
cpus: number
memory: string
gpu: string
resolution: string
displays: number
borderless?: boolean
capture?: boolean
audio?: boolean
network?: boolean
ssh_port?: number
logs?: boolean
start?: boolean
}
export interface SetOpts {
name: string
cpus?: number
memory?: string
graphics?: string
displays?: number
disk_controller?: string
resolution?: string
borderless?: boolean
capture?: boolean
gpu?: string
logs?: boolean
log_level?: string
audio?: boolean
audio_backend?: string
network?: boolean
ssh_port?: number
stop_timeout?: number
extra_args?: string
}
export interface LogEntry {
ts: string
source: string
line: string
}
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
/** A tracked long-running job pushed as "reims:task" (tasks.go). */
export interface Task {
id: string
export type Task = Model<main.Task> & {
kind: 'installer-download' | 'vm-create' | string
subject: string
vm?: string
step: string
done: number
total: number
/** -1 when unknown */
percent: number
/** bytes per second, 0 when unknown */
rate: number
status: TaskStatus
error?: string
result?: string
cancelable: boolean
started_at: number
updated_at: number
}
/** An offline installer Apple offers (`reims-util offline-installer list`). */
export interface Release {
product: string
title: string
version: string
build: string
posted: string
size: number
}
export type Release = installer.Release
/** A file kept in the installers directory. */
export interface CachedInstaller {
name: string
path: string
bytes: number
export type CachedInstaller = Model<installer.Cached> & {
kind: 'offline' | 'online' | 'ipsw' | 'other'
partial: boolean
title?: string
version?: string
build?: string
}
/** A published runtime (GitHub Release, internal/runtime/remote.go). */
export interface RemoteRuntime {
commit: string
tag: string
channel: 'stable' | 'candidate'
published_at: string
page_url: string
archive_name: string
archive_url: string
archive_size: number
sums_url: string
source_name?: string
source_url?: string
}
export type DataRootChoice = main.DataRootChoice
export type DataRootCheck = main.DataRootCheck
export interface DataRootChoice {
path: string
free_gb: number
system: boolean
external: boolean
recommended: boolean
}
export interface DataRootCheck {
path: string
free_gb: number
system: boolean
external: boolean
has_config: boolean
error?: string
/** A "reims:log" event (app.go emitLog); not a Go struct, so not generated. */
export interface LogEntry {
ts: string
source: string
line: string
}
+4 -2
View File
@@ -10,16 +10,18 @@ interface Props {
/** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */
dismissable?: boolean
onClose: () => void
/** Extra class on the dialog box, e.g. a wider variant. */
className?: string
children: React.ReactNode
}
/** Modal frame: head with title and ✕; children supply body/steps/foot sections. */
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, children }) => (
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => (
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
<RDialog.Portal>
<RDialog.Overlay className="overlay" />
<RDialog.Content
className="dialog"
className={className ? `dialog ${className}` : 'dialog'}
onInteractOutside={(e) => e.preventDefault()}
// Focus the first form field rather than ✕, so the close tooltip doesn't pop on open.
onOpenAutoFocus={(e) => {
+403
View File
@@ -0,0 +1,403 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Check, ChevronsUpDown, CircleAlert, Lock, RotateCcw } from 'lucide-react'
import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { IconButton } from './controls'
// Settings page primitives (docs/ui-redesign.md, docs/shell-design.md §4):
// one row shell — title and description on the left, the control on the
// right — plus the switch, segmented control, range field and option cards
// every category builds its rows from, so the whole panel reads as one set.
/** A labelled block of rows, like a grouped list in macOS System Settings. */
export const SetGroup: React.FC<{ title?: string; note?: React.ReactNode; children: React.ReactNode }> = ({ title, note, children }) => (
<section className="sgroup">
{title && <h3 className="sgroup-title">{title}</h3>}
<div className="sgroup-list">{children}</div>
{note && <p className="sgroup-note">{note}</p>}
</section>
)
interface RowProps {
title: string
desc?: React.ReactNode
/** Control drawn on the right of the title. */
control?: React.ReactNode
/** Control drawn under the title at full width (sliders, cards). */
block?: React.ReactNode
/** The value differs from what the VM has now. */
dirty?: boolean
onReset?: () => void
resetLabel?: string
/** The row can't act right now; `reason` says why. */
disabled?: boolean
reason?: string
error?: string
/** Anchor so a validation error can scroll its row into view. */
field?: string
}
/** One setting: title, one line of description, a control, and its state marks. */
export const SetRow: React.FC<RowProps> = ({ title, desc, control, block, dirty, onReset, resetLabel, disabled, reason, error, field }) => {
const titleId = useId()
return (
<div
className="srow"
data-field={field}
data-dirty={dirty || undefined}
data-disabled={disabled || undefined}
data-error={error ? true : undefined}
role="group"
aria-labelledby={titleId}
>
<div className="srow-head">
<div className="srow-text">
<div className="srow-title" id={titleId}>
{title}
{dirty && <span className="dirty-dot" aria-hidden="true" />}
</div>
{desc && <div className="srow-desc">{desc}</div>}
{disabled && reason && (
<div className="srow-reason"><Lock size={12} aria-hidden="true" />{reason}</div>
)}
</div>
{(control || (dirty && onReset)) && (
<div className="srow-ctrl">
{dirty && onReset && !disabled && (
<IconButton small label={resetLabel ?? 'Reset'} icon={<RotateCcw size={13} />} onClick={onReset} className="srow-reset" tipSide="top" />
)}
{control && <fieldset className="srow-fieldset" disabled={disabled}>{control}</fieldset>}
</div>
)}
</div>
{block && <fieldset className="srow-fieldset srow-block" disabled={disabled}>{block}</fieldset>}
{error && <div className="srow-error" role="alert"><CircleAlert size={13} aria-hidden="true" />{error}</div>}
</div>
)
}
/** Read-only row: a label and its value. */
export const SetValue: React.FC<{ title: string; value: React.ReactNode; mono?: boolean }> = ({ title, value, mono }) => (
<div className="srow srow-kv">
<div className="srow-head">
<div className="srow-title">{title}</div>
<div className={`srow-value${mono ? ' mono' : ''}`}>{value}</div>
</div>
</div>
)
export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean }> = ({ checked, onChange, label, disabled }) => (
<label className="switch">
<input type="checkbox" role="switch" aria-label={label} checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
<span className="slider" />
</label>
)
export interface SegOption<V> {
value: V
label: string
disabled?: boolean
}
/**
* Segmented control with a sliding highlight. A radio group under the hood:
* arrow keys move the choice, Tab leaves the group.
*/
export function Segmented<V extends string | number>({ options, value, onChange, label, wide }: {
options: SegOption<V>[]
value: V | undefined
onChange: (v: V) => void
label: string
/** Stretch to the row's width with equal segments. */
wide?: boolean
}) {
const box = useRef<HTMLDivElement>(null)
const [thumb, setThumb] = useState<{ x: number; w: number } | null>(null)
const measure = () => {
const el = box.current?.querySelector<HTMLElement>('[aria-checked="true"]')
setThumb(el ? { x: el.offsetLeft, w: el.offsetWidth } : null)
}
useLayoutEffect(measure, [value, options])
useEffect(() => {
if (!box.current || typeof ResizeObserver === 'undefined') return
const ro = new ResizeObserver(measure)
ro.observe(box.current)
return () => ro.disconnect()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const onKey = (e: React.KeyboardEvent) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
e.preventDefault()
const enabled = options.filter((o) => !o.disabled)
const i = enabled.findIndex((o) => o.value === value)
const next = enabled[(i + (e.key === 'ArrowRight' ? 1 : -1) + enabled.length) % enabled.length]
if (next) {
onChange(next.value)
requestAnimationFrame(() => box.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus())
}
}
const hasActive = options.some((o) => o.value === value)
return (
<div ref={box} className={`seg${wide ? ' seg-wide' : ''}`} role="radiogroup" aria-label={label} onKeyDown={onKey}>
{thumb && <span className="seg-thumb" style={{ transform: `translateX(${thumb.x}px)`, width: thumb.w }} aria-hidden="true" />}
{options.map((o, i) => {
const on = o.value === value
return (
<button
key={String(o.value)}
type="button"
role="radio"
aria-checked={on}
tabIndex={on || (!hasActive && i === 0) ? 0 : -1}
disabled={o.disabled}
onClick={() => onChange(o.value)}
>
{o.label}
</button>
)
})}
</div>
)
}
interface NumberProps {
value: number
min: number
max: number
step?: number
unit?: string
label: string
onChange: (v: number) => void
/** Width in characters; the default fits five digits. */
size?: number
}
/**
* Number field with a unit suffix and no spinner. It keeps what is typed so
* far and commits a whole, clamped number on Enter or blur; ↑/↓ step it.
*/
export const NumberField: React.FC<NumberProps> = ({ value, min, max, step = 1, unit, label, onChange, size = 5 }) => {
const [text, setText] = useState(String(value))
useEffect(() => { setText(String(value)) }, [value])
const clamp = (v: number) => Math.min(max, Math.max(min, Math.round(v / step) * step))
const commit = () => {
const n = Number.parseFloat(text)
if (!Number.isFinite(n)) { setText(String(value)); return }
const c = clamp(n)
setText(String(c))
if (c !== value) onChange(c)
}
return (
<div className="num-field">
<input
className="num-input"
type="text"
inputMode="numeric"
aria-label={label}
style={{ width: `${size + 1.5}ch` }}
value={text}
onChange={(e) => setText(e.target.value.replace(/[^\d.]/g, ''))}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); commit() }
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault()
onChange(clamp(value + (e.key === 'ArrowUp' ? step : -step)))
}
}}
/>
{unit && <span className="num-unit">{unit}</span>}
</div>
)
}
/** Drop marks that would sit closer than `gap` percent to the one before. */
function thinMarks(marks: RangeMark[], min: number, max: number, gap = 9): RangeMark[] {
const span = Math.max(max - min, 1)
const out: RangeMark[] = []
let last = -Infinity
for (const m of marks) {
if (m.value < min || m.value > max) continue
const p = ((m.value - min) / span) * 100
if (p - last < gap) continue
out.push(m)
last = p
}
return out
}
export interface RangeMark {
value: number
label: string
}
interface RangeProps {
value: number
min: number
max: number
step?: number
unit: string
label: string
onChange: (v: number) => void
/** Clickable labels under the track. */
marks?: RangeMark[]
/** Highlighted "recommended" span of the track. */
recommend?: [number, number]
/** From here to the end the track turns amber. */
warnFrom?: number
}
/**
* Slider and number field bound to one value. The slider and the marks write
* straight away; the field commits on Enter or blur (NumberField).
*/
export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, unit, label, onChange, marks, recommend, warnFrom }) => {
const span = Math.max(max - min, 1)
const pct = (v: number) => `${((Math.min(max, Math.max(min, v)) - min) / span) * 100}%`
const shown = marks ? thinMarks(marks, min, max) : []
const over = warnFrom !== undefined && value >= warnFrom
return (
<div className="range-field" data-warn={over || undefined}>
<div className="range-main">
<div className="range-rail-wrap">
<div className="range-rail" aria-hidden="true">
<div className="range-track" />
{recommend && (
<div className="range-band rec" style={{ left: pct(recommend[0]), width: `calc(${pct(recommend[1])} - ${pct(recommend[0])})` }} />
)}
{warnFrom !== undefined && warnFrom <= max && (
<div className="range-band warn" style={{ left: pct(warnFrom), right: 0 }} />
)}
<div className="range-fill" style={{ width: pct(value) }} />
</div>
<input
className="range"
type="range"
aria-label={label}
min={min}
max={max}
step={step}
value={value}
onChange={(e) => onChange(Number(e.target.value))}
/>
{shown.length > 0 && (
<div className="range-marks">
{shown.map((m) => (
<button
key={m.value}
type="button"
tabIndex={-1}
className="range-mark"
aria-pressed={m.value === value}
style={{ left: pct(m.value) }}
onClick={() => onChange(m.value)}
>
{m.label}
</button>
))}
</div>
)}
</div>
<NumberField value={value} min={min} max={max} step={step} unit={unit} label={label} onChange={onChange} size={3} />
</div>
</div>
)
}
export interface CardOption<V> {
value: V
title: string
sub?: string
badges?: string[]
/** Small picture drawn above the title (e.g. a screen shape). */
art?: React.ReactNode
disabled?: boolean
}
/** A row of option cards, one picked: a radio group with larger targets. */
export function OptionCards<V extends string>({ options, value, onChange, label, columns }: {
options: CardOption<V>[]
value: V | undefined
onChange: (v: V) => void
label: string
columns?: number
}) {
const name = useId()
return (
<div className="opt-cards" role="radiogroup" aria-label={label} style={columns ? { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } : undefined}>
{options.map((o) => (
<label key={o.value} className="opt-card" data-selected={o.value === value || undefined} data-disabled={o.disabled || undefined}>
<input type="radio" name={name} checked={o.value === value} disabled={o.disabled} onChange={() => onChange(o.value)} />
{o.art}
<span className="opt-card-title" title={o.title}>{o.title}</span>
{o.sub && <span className="opt-card-sub">{o.sub}</span>}
{o.badges && o.badges.length > 0 && (
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge badge-accent">{b}</span>)}</span>
)}
</label>
))}
</div>
)
}
export interface PopupOption<V> {
value: V
label: string
/** Secondary text drawn after the label in grey, e.g. a build number. */
detail?: string
disabled?: boolean
}
/**
* Pop-up button (HIG pop-up-buttons.md): shows the current choice with ⌃⌄
* and opens a menu where the current item carries a checkmark. Replaces the
* native <select>, whose Windows list ignores the app's theme.
*/
export function PopupSelect<V extends string>({ value, options, onChange, label, placeholder, wide, id }: {
value: V | undefined
options: PopupOption<V>[]
onChange: (v: V) => void
label: string
placeholder?: string
/** Fill the container's width instead of sizing to the label. */
wide?: boolean
id?: string
}) {
const cur = options.find((o) => o.value === value)
return (
<Menu.Root modal={false}>
<Menu.Trigger asChild>
<button type="button" id={id} className={`popup-btn${wide ? ' popup-wide' : ''}`} aria-label={label}>
<span className="popup-value">
{cur ? cur.label : <span className="muted">{placeholder ?? value ?? ''}</span>}
{cur?.detail && <span className="popup-detail">{cur.detail}</span>}
</span>
<ChevronsUpDown size={13} aria-hidden="true" className="popup-chevron" />
</button>
</Menu.Trigger>
<Menu.Portal>
<Menu.Content className="menu popup-menu" align="start" sideOffset={4} collisionPadding={8}>
<Menu.RadioGroup value={value ?? ''} onValueChange={(v) => onChange(v as V)}>
{options.map((o) => (
<Menu.RadioItem key={o.value} value={o.value} disabled={o.disabled} className="menu-item popup-item">
<Menu.ItemIndicator className="popup-check"><Check size={13} /></Menu.ItemIndicator>
<span className="popup-item-label">{o.label}</span>
{o.detail && <span className="popup-detail">{o.detail}</span>}
</Menu.RadioItem>
))}
</Menu.RadioGroup>
</Menu.Content>
</Menu.Portal>
</Menu.Root>
)
}
/** A screen outline with the resolution's aspect ratio. */
export const ScreenArt: React.FC<{ w: number; h: number }> = ({ w, h }) => {
const W = 44
const H = Math.max(18, Math.min(34, Math.round((W * h) / Math.max(w, 1))))
return <span className="screen-art" style={{ width: W, height: H }} aria-hidden="true" />
}
+17 -144
View File
@@ -1,148 +1,21 @@
import {
AppState,
AppUpdateInfo,
CachedInstaller,
DataRootCheck,
DataRootChoice,
RemoteRuntime,
Release,
Task,
CreateOpts,
InstalledRuntime,
LogEntry,
SetOpts,
ValidationIssue,
VMDetail,
} from './types'
// Backend calls are the Wails-generated bindings (wailsjs/go/main/App). Only
// the calls whose results carry the unions or nil slices added in types.ts are
// re-typed here; everything else passes through unchanged.
import * as Go from '../wailsjs/go/main/App'
import { EventsOn } from '../wailsjs/runtime/runtime'
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task } from './types'
declare global {
interface Window {
go?: {
main?: {
App?: {
GetState(): Promise<AppState>
GetVMDetail(name: string): Promise<VMDetail>
SetLocale(locale: string): Promise<void>
SetAutoPinPCores(enabled: boolean): Promise<void>
SetDataRoot(dir: string): Promise<void>
PickDirectory(title: string): Promise<string>
PickFile(title: string, pattern: string): Promise<string>
EnableWHPX(): Promise<void>
InstallRuntimeArchive(path: string): Promise<InstalledRuntime>
UseRuntime(commit: string): Promise<void>
ValidateCreate(opts: CreateOpts): Promise<ValidationIssue[]>
PreviewCreate(opts: CreateOpts): Promise<string>
CreateVM(opts: CreateOpts): Promise<void>
ValidateSet(opts: SetOpts): Promise<ValidationIssue[]>
ApplyVMSettings(opts: SetOpts): Promise<void>
StartVM(name: string): Promise<void>
StopVM(name: string, force: boolean): Promise<void>
RestartVM(name: string): Promise<void>
EjectInstaller(name: string): Promise<void>
DeleteVM(name: string, keepFiles: boolean): Promise<void>
ReadVMLogs(name: string, serial: boolean): Promise<string>
OpenVMFolder(name: string): Promise<void>
FinishInstall(name: string): Promise<void>
EnterRecovery(name: string): Promise<void>
AttachInstaller(name: string, installerPath: string): Promise<string>
DownloadAndAttachOnlineRecovery(name: string, version: string): Promise<string>
AttachGuestTools(name: string): Promise<void>
DetachGuestTools(name: string): Promise<void>
OpenSharedFolder(name: string): Promise<void>
UpgradeDiskToNVMe(name: string): Promise<void>
ExportDiagnostics(name: string): Promise<string>
CloneVMCoW(sourceName: string, cloneName: string): Promise<void>
TypeText(name: string, text: string): Promise<number>
TypeClipboard(name: string): Promise<number>
GetTasks(): Promise<Task[]>
CancelTask(id: string): Promise<void>
DismissTask(id: string): Promise<void>
ListOfflineReleases(): Promise<Release[]>
DownloadInstaller(version: string): Promise<string>
ListInstallers(): Promise<CachedInstaller[] | null>
DeleteInstaller(name: string): Promise<void>
SuggestDataRoots(): Promise<DataRootChoice[] | null>
CheckDataRoot(dir: string): Promise<DataRootCheck>
CompleteSetup(dir: string): Promise<void>
ListRemoteRuntimes(): Promise<RemoteRuntime[] | null>
SetRuntimeChannel(channel: string): Promise<void>
InstallRuntimeOnline(commit: string): Promise<string>
CheckAppUpdate(force: boolean): Promise<AppUpdateInfo>
OpenURL(url: string): Promise<void>
}
}
}
runtime?: {
EventsOn(event: string, cb: (...args: any[]) => void): () => void
WindowMinimise(): void
WindowToggleMaximise(): void
Quit(): void
}
}
export const api = {
...Go,
GetState: Go.GetState as () => Promise<AppState>,
GetTasks: Go.GetTasks as () => Promise<Task[]>,
ListInstallers: Go.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: Go.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: Go.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
}
function app() {
const api = window.go?.main?.App
if (!api) {
throw new Error('Wails backend not attached')
}
return api
}
export const backend = {
getState: () => app().GetState(),
getVMDetail: (name: string) => app().GetVMDetail(name),
setLocale: (locale: string) => app().SetLocale(locale),
setAutoPinPCores: (enabled: boolean) => app().SetAutoPinPCores(enabled),
setDataRoot: (dir: string) => app().SetDataRoot(dir),
pickDirectory: (title: string) => app().PickDirectory(title),
pickFile: (title: string, pattern: string) => app().PickFile(title, pattern),
enableWHPX: () => app().EnableWHPX(),
installRuntimeArchive: (path: string) => app().InstallRuntimeArchive(path),
useRuntime: (commit: string) => app().UseRuntime(commit),
validateCreate: (opts: CreateOpts) => app().ValidateCreate(opts),
previewCreate: (opts: CreateOpts) => app().PreviewCreate(opts),
createVM: (opts: CreateOpts) => app().CreateVM(opts),
validateSet: (opts: SetOpts) => app().ValidateSet(opts),
applyVMSettings: (opts: SetOpts) => app().ApplyVMSettings(opts),
startVM: (name: string) => app().StartVM(name),
stopVM: (name: string, force: boolean) => app().StopVM(name, force),
restartVM: (name: string) => app().RestartVM(name),
ejectInstaller: (name: string) => app().EjectInstaller(name),
deleteVM: (name: string, keepFiles: boolean) => app().DeleteVM(name, keepFiles),
readVMLogs: (name: string, serial: boolean) => app().ReadVMLogs(name, serial),
openVMFolder: (name: string) => app().OpenVMFolder(name),
finishInstall: (name: string) => app().FinishInstall(name),
enterRecovery: (name: string) => app().EnterRecovery(name),
attachInstaller: (name: string, installerPath = '') => app().AttachInstaller(name, installerPath),
downloadAndAttachOnlineRecovery: (name: string, version = 'latest') => app().DownloadAndAttachOnlineRecovery(name, version),
attachGuestTools: (name: string) => app().AttachGuestTools(name),
detachGuestTools: (name: string) => app().DetachGuestTools(name),
openSharedFolder: (name: string) => app().OpenSharedFolder(name),
upgradeDiskToNVMe: (name: string) => app().UpgradeDiskToNVMe(name),
exportDiagnostics: (name: string) => app().ExportDiagnostics(name),
cloneVMCoW: (sourceName: string, cloneName: string) => app().CloneVMCoW(sourceName, cloneName),
typeText: (name: string, text: string) => app().TypeText(name, text),
typeClipboard: (name: string) => app().TypeClipboard(name),
getTasks: () => app().GetTasks(),
cancelTask: (id: string) => app().CancelTask(id),
dismissTask: (id: string) => app().DismissTask(id),
listOfflineReleases: () => app().ListOfflineReleases(),
downloadInstaller: (version: string) => app().DownloadInstaller(version),
listInstallers: () => app().ListInstallers(),
deleteInstaller: (name: string) => app().DeleteInstaller(name),
suggestDataRoots: () => app().SuggestDataRoots(),
checkDataRoot: (dir: string) => app().CheckDataRoot(dir),
completeSetup: (dir: string) => app().CompleteSetup(dir),
listRemoteRuntimes: () => app().ListRemoteRuntimes(),
setRuntimeChannel: (channel: string) => app().SetRuntimeChannel(channel),
installRuntimeOnline: (commit: string) => app().InstallRuntimeOnline(commit),
checkAppUpdate: (force = false) => app().CheckAppUpdate(force),
openURL: (url: string) => app().OpenURL(url),
onTask: (cb: (task: Task) => void) => window.runtime?.EventsOn('reims:task', cb) ?? (() => {}),
onStateChanged: (cb: () => void) => window.runtime?.EventsOn('reims:state-changed', cb) ?? (() => {}),
onLog: (cb: (entry: LogEntry) => void) => window.runtime?.EventsOn('reims:log', cb) ?? (() => {}),
winMinimise: () => window.runtime?.WindowMinimise(),
winToggleMaximise: () => window.runtime?.WindowToggleMaximise(),
winQuit: () => window.runtime?.Quit(),
export const events = {
onTask: (cb: (task: Task) => void) => EventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => EventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => EventsOn('reims:log', cb),
}
+22
View File
@@ -20,6 +20,8 @@ export function CheckDataRoot(arg1:string):Promise<main.DataRootCheck>;
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
export function CompleteSetup(arg1:string):Promise<void>;
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
@@ -28,6 +30,8 @@ export function DeleteInstaller(arg1:string):Promise<void>;
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
export function DeliverFileToGuest(arg1:string):Promise<string>;
export function DetachGuestTools(arg1:string):Promise<void>;
export function DismissTask(arg1:string):Promise<void>;
@@ -52,6 +56,10 @@ export function GetTasks():Promise<Array<main.Task>>;
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMStats(arg1:string):Promise<main.VMStats>;
export function GetVMThumbnail(arg1:string):Promise<main.VMThumbnail>;
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
export function InstallRuntimeOnline(arg1:string):Promise<string>;
@@ -74,24 +82,38 @@ export function PickFile(arg1:string,arg2:string):Promise<string>;
export function PreviewCreate(arg1:reims.CreateOpts):Promise<string>;
export function QuitApp():Promise<void>;
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
export function RequestClose():Promise<void>;
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
export function RestartVM(arg1:string):Promise<void>;
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
export function SetDataRoot(arg1:string):Promise<void>;
export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise<void>;
export function SetLocale(arg1:string):Promise<void>;
export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function ShowMainWindow():Promise<void>;
export function StartVM(arg1:string):Promise<void>;
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
export function SuggestDataRoots():Promise<Array<main.DataRootChoice>>;
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
export function TypeClipboard(arg1:string):Promise<number>;
export function TypeText(arg1:string,arg2:string):Promise<number>;
+44
View File
@@ -30,6 +30,10 @@ export function CloneVMCoW(arg1, arg2) {
return window['go']['main']['App']['CloneVMCoW'](arg1, arg2);
}
export function CompactVMDisk(arg1) {
return window['go']['main']['App']['CompactVMDisk'](arg1);
}
export function CompleteSetup(arg1) {
return window['go']['main']['App']['CompleteSetup'](arg1);
}
@@ -46,6 +50,10 @@ export function DeleteVM(arg1, arg2) {
return window['go']['main']['App']['DeleteVM'](arg1, arg2);
}
export function DeliverFileToGuest(arg1) {
return window['go']['main']['App']['DeliverFileToGuest'](arg1);
}
export function DetachGuestTools(arg1) {
return window['go']['main']['App']['DetachGuestTools'](arg1);
}
@@ -94,6 +102,14 @@ export function GetVMDetail(arg1) {
return window['go']['main']['App']['GetVMDetail'](arg1);
}
export function GetVMStats(arg1) {
return window['go']['main']['App']['GetVMStats'](arg1);
}
export function GetVMThumbnail(arg1) {
return window['go']['main']['App']['GetVMThumbnail'](arg1);
}
export function InstallRuntimeArchive(arg1) {
return window['go']['main']['App']['InstallRuntimeArchive'](arg1);
}
@@ -138,10 +154,22 @@ export function PreviewCreate(arg1) {
return window['go']['main']['App']['PreviewCreate'](arg1);
}
export function QuitApp() {
return window['go']['main']['App']['QuitApp']();
}
export function ReadVMLogs(arg1, arg2) {
return window['go']['main']['App']['ReadVMLogs'](arg1, arg2);
}
export function RequestClose() {
return window['go']['main']['App']['RequestClose']();
}
export function ResizeVMDisk(arg1, arg2) {
return window['go']['main']['App']['ResizeVMDisk'](arg1, arg2);
}
export function RestartVM(arg1) {
return window['go']['main']['App']['RestartVM'](arg1);
}
@@ -154,14 +182,26 @@ export function SetDataRoot(arg1) {
return window['go']['main']['App']['SetDataRoot'](arg1);
}
export function SetGuestPreventSleep(arg1, arg2) {
return window['go']['main']['App']['SetGuestPreventSleep'](arg1, arg2);
}
export function SetLocale(arg1) {
return window['go']['main']['App']['SetLocale'](arg1);
}
export function SetMinimizeToTray(arg1) {
return window['go']['main']['App']['SetMinimizeToTray'](arg1);
}
export function SetRuntimeChannel(arg1) {
return window['go']['main']['App']['SetRuntimeChannel'](arg1);
}
export function ShowMainWindow() {
return window['go']['main']['App']['ShowMainWindow']();
}
export function StartVM(arg1) {
return window['go']['main']['App']['StartVM'](arg1);
}
@@ -174,6 +214,10 @@ export function SuggestDataRoots() {
return window['go']['main']['App']['SuggestDataRoots']();
}
export function ToggleBorderless(arg1, arg2) {
return window['go']['main']['App']['ToggleBorderless'](arg1, arg2);
}
export function TypeClipboard(arg1) {
return window['go']['main']['App']['TypeClipboard'](arg1);
}
+176
View File
@@ -7,6 +7,7 @@ export namespace config {
auto_pin_pcores: boolean;
default_gpu?: string;
runtime_channel?: string;
minimize_to_tray?: boolean;
static createFrom(source: any = {}) {
return new Config(source);
@@ -20,6 +21,7 @@ export namespace config {
this.auto_pin_pcores = source["auto_pin_pcores"];
this.default_gpu = source["default_gpu"];
this.runtime_channel = source["runtime_channel"];
this.minimize_to_tray = source["minimize_to_tray"];
}
}
@@ -27,6 +29,66 @@ export namespace config {
export namespace host {
export class AudioInfo {
output_count: number;
input_count: number;
output_devices?: string[];
input_devices?: string[];
default_backend?: string;
static createFrom(source: any = {}) {
return new AudioInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.output_count = source["output_count"];
this.input_count = source["input_count"];
this.output_devices = source["output_devices"];
this.input_devices = source["input_devices"];
this.default_backend = source["default_backend"];
}
}
export class DisplayInfo {
name?: string;
width: number;
height: number;
scale_pct: number;
refresh_hz?: number;
primary: boolean;
static createFrom(source: any = {}) {
return new DisplayInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.width = source["width"];
this.height = source["height"];
this.scale_pct = source["scale_pct"];
this.refresh_hz = source["refresh_hz"];
this.primary = source["primary"];
}
}
export class DisplayPreset {
resolution: string;
label: string;
hidpi: boolean;
recommended?: boolean;
static createFrom(source: any = {}) {
return new DisplayPreset(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.resolution = source["resolution"];
this.label = source["label"];
this.hidpi = source["hidpi"];
this.recommended = source["recommended"];
}
}
export class GPUInfo {
name: string;
vulkan_icd: string;
@@ -112,6 +174,11 @@ export namespace host {
needs_cold_reboot_workaround: boolean;
gpus: GPUInfo[];
recommended_gpu?: GPUInfo;
displays?: DisplayInfo[];
primary_display?: DisplayInfo;
recommended_resolution?: string;
display_presets?: DisplayPreset[];
audio: AudioInfo;
static createFrom(source: any = {}) {
return new Report(source);
@@ -147,6 +214,11 @@ export namespace host {
this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"];
this.gpus = this.convertValues(source["gpus"], GPUInfo);
this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo);
this.displays = this.convertValues(source["displays"], DisplayInfo);
this.primary_display = this.convertValues(source["primary_display"], DisplayInfo);
this.recommended_resolution = source["recommended_resolution"];
this.display_presets = this.convertValues(source["display_presets"], DisplayPreset);
this.audio = this.convertValues(source["audio"], AudioInfo);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -371,6 +443,58 @@ export namespace main {
this.updated_at = source["updated_at"];
}
}
export class VMStats {
name: string;
running: boolean;
pid?: number;
cpu_percent: number;
memory_rss_bytes: number;
memory_private_bytes: number;
disk_actual_bytes: number;
disk_virtual_bytes: number;
disk_format?: string;
uptime_seconds: number;
guest_tools_connected: boolean;
guest_tools_mount_mode?: string;
guest_tools_sleep_guard: boolean;
static createFrom(source: any = {}) {
return new VMStats(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.running = source["running"];
this.pid = source["pid"];
this.cpu_percent = source["cpu_percent"];
this.memory_rss_bytes = source["memory_rss_bytes"];
this.memory_private_bytes = source["memory_private_bytes"];
this.disk_actual_bytes = source["disk_actual_bytes"];
this.disk_virtual_bytes = source["disk_virtual_bytes"];
this.disk_format = source["disk_format"];
this.uptime_seconds = source["uptime_seconds"];
this.guest_tools_connected = source["guest_tools_connected"];
this.guest_tools_mount_mode = source["guest_tools_mount_mode"];
this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"];
}
}
export class VMThumbnail {
data_url: string;
captured_at: number;
live: boolean;
static createFrom(source: any = {}) {
return new VMThumbnail(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.data_url = source["data_url"];
this.captured_at = source["captured_at"];
this.live = source["live"];
}
}
}
@@ -399,6 +523,7 @@ export namespace reims {
network?: boolean;
ssh_port?: number;
logs?: boolean;
guest_lang?: string;
start?: boolean;
static createFrom(source: any = {}) {
@@ -429,9 +554,46 @@ export namespace reims {
this.network = source["network"];
this.ssh_port = source["ssh_port"];
this.logs = source["logs"];
this.guest_lang = source["guest_lang"];
this.start = source["start"];
}
}
export class DiskCompactResult {
path: string;
before_bytes: number;
after_bytes: number;
reclaimed_bytes: number;
static createFrom(source: any = {}) {
return new DiskCompactResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.before_bytes = source["before_bytes"];
this.after_bytes = source["after_bytes"];
this.reclaimed_bytes = source["reclaimed_bytes"];
}
}
export class DiskResizeResult {
path: string;
old_virtual_bytes: number;
new_virtual_bytes: number;
guest_expand_cmd: string;
static createFrom(source: any = {}) {
return new DiskResizeResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.path = source["path"];
this.old_virtual_bytes = source["old_virtual_bytes"];
this.new_virtual_bytes = source["new_virtual_bytes"];
this.guest_expand_cmd = source["guest_expand_cmd"];
}
}
export class SetOpts {
name: string;
cpus?: number;
@@ -452,6 +614,7 @@ export namespace reims {
stop_timeout?: number;
extra_args?: string;
env?: string[];
guest_lang?: string;
static createFrom(source: any = {}) {
return new SetOpts(source);
@@ -478,6 +641,7 @@ export namespace reims {
this.stop_timeout = source["stop_timeout"];
this.extra_args = source["extra_args"];
this.env = source["env"];
this.guest_lang = source["guest_lang"];
}
}
export class VMDetail {
@@ -500,6 +664,7 @@ export namespace reims {
installer_path?: string;
cpu_model: string;
audio: boolean;
audio_backend?: string;
audio_raw: string;
network: boolean;
network_summary: string;
@@ -513,7 +678,12 @@ export namespace reims {
guest_tools_attached: boolean;
guest_tools_configured: boolean;
guest_tools_connected: boolean;
guest_tools_mount_mode?: string;
guest_tools_prevent_sleep: boolean;
guest_tools_sleep_active: boolean;
guest_tools_agent_version?: number;
shared_dir?: string;
guest_lang?: string;
static createFrom(source: any = {}) {
return new VMDetail(source);
@@ -540,6 +710,7 @@ export namespace reims {
this.installer_path = source["installer_path"];
this.cpu_model = source["cpu_model"];
this.audio = source["audio"];
this.audio_backend = source["audio_backend"];
this.audio_raw = source["audio_raw"];
this.network = source["network"];
this.network_summary = source["network_summary"];
@@ -553,7 +724,12 @@ export namespace reims {
this.guest_tools_attached = source["guest_tools_attached"];
this.guest_tools_configured = source["guest_tools_configured"];
this.guest_tools_connected = source["guest_tools_connected"];
this.guest_tools_mount_mode = source["guest_tools_mount_mode"];
this.guest_tools_prevent_sleep = source["guest_tools_prevent_sleep"];
this.guest_tools_sleep_active = source["guest_tools_sleep_active"];
this.guest_tools_agent_version = source["guest_tools_agent_version"];
this.shared_dir = source["shared_dir"];
this.guest_lang = source["guest_lang"];
}
}
export class VMListItem {
+1 -1
View File
@@ -5,6 +5,7 @@ go 1.26.0
require (
github.com/ulikunitz/xz v0.5.17
github.com/wailsapp/wails/v2 v2.17.1
golang.org/x/net v0.60.0
golang.org/x/sys v0.48.0
)
@@ -34,6 +35,5 @@ require (
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/wailsapp/go-webview2 v1.0.22 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/net v0.60.0 // indirect
golang.org/x/text v0.42.0 // indirect
)
+112 -3
View File
@@ -11,6 +11,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -36,6 +37,9 @@ func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
srv := a.guestTools
if srv == nil {
srv = guesttools.NewServer(nil)
srv.SetHostTextHandler(func(vmName, text string) {
a.injectRemoteText(vmName, "", text)
})
a.guestTools = srv
}
a.mu.Unlock()
@@ -47,6 +51,28 @@ func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
return srv, port, 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) []string {
if vmDir == "" {
return nil
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil || port <= 0 {
return nil
}
cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, name, a.vmSharedDir(name), port)
if err != nil || cfg.Token == "" {
return nil
}
srv.RegisterVM(cfg)
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) registerExistingGuestTools(ctx context.Context) {
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
@@ -86,12 +112,17 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
d.SharedDir = a.vmSharedDir(d.Name)
if cfg, ok := guesttools.ReadVMConfig(d.Directory); ok {
d.GuestToolsConfigured = true
d.GuestToolsPreventSleep = cfg.PreventSleep
if cfg.SharedDir != "" {
d.SharedDir = cfg.SharedDir
}
if srv, _, err := a.ensureGuestToolsBridge(); err == nil {
srv.RegisterVM(cfg)
d.GuestToolsConnected = srv.IsConnected(d.Name, 12*time.Second)
st := srv.Status(d.Name, 15*time.Second)
d.GuestToolsConnected = st.Connected
d.GuestToolsMountMode = st.MountMode
d.GuestToolsSleepActive = st.SleepActive
d.GuestToolsAgentVersion = st.AgentVersion
}
}
}
@@ -169,7 +200,7 @@ func (a *App) AttachGuestTools(name string) error {
return fmt.Errorf("build REIMSTOOLS disk: %w", err)
}
merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath)
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
if merged != d.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, w, w); err != nil {
@@ -205,7 +236,7 @@ func (a *App) DetachGuestTools(name string) error {
}
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
ctx := context.Background()
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
if stripped != d.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
return err
@@ -235,3 +266,81 @@ func (a *App) OpenSharedFolder(name string) error {
}
return host.OpenFolder(dir)
}
// SetGuestPreventSleep toggles the live macOS prevent-sleep guard (`caffeinate -dims`)
// for a VM and persists the preference in `.reims-go-tools.json`.
func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM %s has no directory", name)
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return err
}
sharedDir := a.vmSharedDir(name)
cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, name, sharedDir, port)
if err != nil {
return err
}
cfg.PreventSleep = enabled
if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil {
return err
}
srv.RegisterVM(cfg)
srv.SetPreventSleep(name, enabled)
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
// DeliverFileToGuest opens a file picker and copies the selected host file into
// `<DataRoot>/shared/<vmName>` so it immediately appears inside macOS ReimsShare.
func (a *App) DeliverFileToGuest(name string) (string, error) {
if a.ctx == nil {
return "", fmt.Errorf("window not ready")
}
picked, err := wailsRuntime.OpenFileDialog(a.ctx, wailsRuntime.OpenDialogOptions{
Title: "Select file to send to " + name,
})
if err != nil || picked == "" {
return "", err
}
sharedDir := a.vmSharedDir(name)
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
return "", err
}
src, err := os.Open(picked)
if err != nil {
return "", err
}
defer src.Close()
base := filepath.Base(picked)
dstPath := filepath.Join(sharedDir, base)
tmp, err := os.CreateTemp(sharedDir, ".reims-deliver-*")
if err != nil {
return "", err
}
tmpName := tmp.Name()
if _, err := io.Copy(tmp, src); err != nil {
_ = tmp.Close()
_ = os.Remove(tmpName)
return "", err
}
if err := tmp.Close(); err != nil {
_ = os.Remove(tmpName)
return "", err
}
if err := os.Rename(tmpName, dstPath); err != nil {
_ = os.Remove(tmpName)
return "", err
}
a.emitLog(name, fmt.Sprintf("Delivered %s to shared folder (%s)", base, sharedDir))
return base, nil
}
+20 -162
View File
@@ -7,17 +7,12 @@ package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -27,157 +22,14 @@ import (
// - "on": --boot-selection=true is active on opencore.qcow2.
// - "restore": FinishInstall ran while VM was running; apply --boot-selection=false before next start.
// - "": Normal direct boot (file absent).
const recoveryPickerMarkerFile = ".reims-go-recovery-picker"
func recoveryPickerMarker(vmDir string) string {
if vmDir == "" {
return ""
}
return filepath.Join(vmDir, recoveryPickerMarkerFile)
}
func readRecoveryPickerMarker(vmDir string) string {
p := recoveryPickerMarker(vmDir)
if p == "" {
return ""
}
b, err := os.ReadFile(p)
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
func writeRecoveryPickerMarker(vmDir, state string) {
p := recoveryPickerMarker(vmDir)
if p == "" {
return
}
if state == "" {
_ = os.Remove(p)
return
}
_ = os.WriteFile(p, []byte(state), 0o644)
}
func isRecoveryModeActive(d reims.VMDetail) bool {
if d.HasInstaller {
return true
}
m := readRecoveryPickerMarker(d.Directory)
m := vmstart.ReadRecoveryMarker(d.Directory)
return m == "on" || m == "want"
}
func (a *App) activeRuntimeHasPatch(substr string) bool {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil || active == nil {
return false
}
needle := strings.ToLower(substr)
for _, p := range active.Manifest.Patches {
if strings.Contains(strings.ToLower(p.Name), needle) {
return true
}
}
return false
}
// applyProbedWHPXCompat pre-applies `-machine kernel-irqchip=off` on Windows 11
// builds where WHvPartitionPropertyCodeNestedVirtualization is probed as
// unsupported (e.g. hr=0x80370302) AND the active runtime lacks
// qemu-whpx-nested-virt-nonfatal.patch, avoiding a noisy first-start crash & retry.
func (a *App) applyProbedWHPXCompat(c *reims.Client, name string, rep host.Report, cur *reims.VMDetail) {
if rep.NeedsColdRebootWorkaround || !rep.WHPXCaps.KernelIrqchipAvailable || rep.WHPXCaps.NestedVirtProperty {
return
}
if a.activeRuntimeHasPatch("nested-virt-nonfatal") {
return
}
if reims.HasKernelIrqchipArg(cur.ExtraArgs) {
return
}
merged := reims.MergeKernelIrqchipOffArgs(cur.ExtraArgs)
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
return
}
cur.ExtraArgs = merged
a.mu.Lock()
loc := a.cfg.Locale
a.mu.Unlock()
code := rep.WHPXCaps.NestedVirtProbeError
if code == "" {
code = "unsupported"
}
if loc == i18n.ZhCN {
a.emitLog(name, fmt.Sprintf("[兼容] 当前 Windows 不支持嵌套虚拟化属性(%s),已自动启用 kernel-irqchip=off", code))
} else {
a.emitLog(name, fmt.Sprintf("[compat] Host rejects nested-virtualization property (%s); enabled kernel-irqchip=off automatically", code))
}
}
// syncOfflineHelper prepares and attaches the REIMSHELP HFS+ helper disk when a
// VM boots with an offline installer attached, or strips it once ejected.
func (a *App) syncOfflineHelper(c *reims.Client, name string, cur *reims.VMDetail) {
ctx := context.Background()
if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) {
a.mu.Lock()
cacheDir := a.cfg.XDGCacheDir()
a.mu.Unlock()
a.emitLog(name, "Preparing offline install helper disk (REIMSHELP)...")
helperPath, err := installer.EnsureOfflineHelperImage(cacheDir, cur.InstallerPath)
if err != nil {
a.emitLog(name, "Warning: offline install helper disk skipped: "+err.Error())
return
}
merged := reims.MergeOfflineHelperArgs(cur.ExtraArgs, helperPath)
if merged != cur.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
a.emitLog(name, "Warning: could not attach REIMSHELP disk: "+err.Error())
return
}
cur.ExtraArgs = merged
}
return
}
stripped := reims.StripOfflineHelperArgs(cur.ExtraArgs)
if stripped != cur.ExtraArgs {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, io.Discard, io.Discard); err == nil {
cur.ExtraArgs = stripped
}
}
}
// syncRecoveryBootPicker reconciles OpenCore's ShowPicker flag when a VM was
// switched into or out of recovery mode while running (update-opencore requires
// a stopped VM: upstream 3731afd opencore.rs:400-402).
func (a *App) syncRecoveryBootPicker(c *reims.Client, name string, cur *reims.VMDetail) {
marker := readRecoveryPickerMarker(cur.Directory)
if marker == "" {
return
}
ctx := context.Background()
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
switch marker {
case "want":
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
a.emitLog(name, "Warning: could not enable OpenCore boot picker: "+err.Error())
return
}
writeRecoveryPickerMarker(cur.Directory, "on")
case "restore":
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
return
}
writeRecoveryPickerMarker(cur.Directory, "")
}
}
func (a *App) pickCachedRecoveryInstaller() (string, error) {
ic, err := a.installerClient()
if err != nil {
@@ -232,13 +84,13 @@ func (a *App) EnterRecovery(name string) error {
if err != nil {
return err
}
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
if a.isVMRunning(ctx, c, name, d) {
marker := readRecoveryPickerMarker(d.Directory)
marker := vmstart.ReadRecoveryMarker(d.Directory)
if marker != "on" {
writeRecoveryPickerMarker(d.Directory, "want")
vmstart.WriteRecoveryMarker(d.Directory, "want")
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
Field: "recovery",
@@ -253,7 +105,10 @@ func (a *App) EnterRecovery(name string) error {
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
return err
}
writeRecoveryPickerMarker(d.Directory, "on")
vmstart.WriteRecoveryMarker(d.Directory, "on")
if prep, err := a.prep(name); err == nil {
prep.ReplayGuestLang(ctx, d.Directory)
}
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
}
if a.ctx != nil {
@@ -285,7 +140,7 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
return "", errors.New("no cached installer image found")
}
}
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
base := filepath.Base(path)
@@ -385,7 +240,7 @@ func (a *App) FinishInstall(name string) error {
if err != nil {
return err
}
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
if d.HasInstaller {
@@ -421,7 +276,7 @@ func (a *App) FinishInstall(name string) error {
}
running := a.isVMRunning(ctx, c, name, d)
marker := readRecoveryPickerMarker(d.Directory)
marker := vmstart.ReadRecoveryMarker(d.Directory)
if running {
var diffs []PendingChange
if d.HasInstaller {
@@ -435,9 +290,9 @@ func (a *App) FinishInstall(name string) error {
}
switch marker {
case "want":
writeRecoveryPickerMarker(d.Directory, "")
vmstart.WriteRecoveryMarker(d.Directory, "")
case "on":
writeRecoveryPickerMarker(d.Directory, "restore")
vmstart.WriteRecoveryMarker(d.Directory, "restore")
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
}
if len(diffs) > 0 {
@@ -451,10 +306,13 @@ func (a *App) FinishInstall(name string) error {
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
} else {
writeRecoveryPickerMarker(d.Directory, "")
vmstart.WriteRecoveryMarker(d.Directory, "")
if prep, err := a.prep(name); err == nil {
prep.ReplayGuestLang(ctx, d.Directory)
}
}
} else if marker != "" {
writeRecoveryPickerMarker(d.Directory, "")
vmstart.WriteRecoveryMarker(d.Directory, "")
}
}
a.emitLog(name, "Exited recovery mode")
@@ -481,7 +339,7 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
if strings.EqualFold(d.DiskController, "nvme") {
return nil
}
w := &logWriter{emit: func(line string) { a.emitLog(name, line) }}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
+17 -2
View File
@@ -16,9 +16,21 @@ type Config struct {
ActiveRuntime string `json:"active_runtime,omitempty"`
AutoPinPCores bool `json:"auto_pin_pcores"`
DefaultGPU string `json:"default_gpu,omitempty"`
// RuntimeChannel is "stable" (default, also when empty) or "candidate":
// whether online install offers candidate runtimes (portable-runtime-spec.md §6).
// RuntimeChannel is "stable" (default, also when empty) or "alpha":
// whether online install offers alpha runtimes (portable-runtime-spec.md §6).
// "candidate", the name used before 2026-11-28, is read as "alpha".
RuntimeChannel string `json:"runtime_channel,omitempty"`
// MinimizeToTray keeps Reims-Go running in the Windows system tray when the
// main window is closed so Guest Tools bridges stay alive. Defaults to true.
MinimizeToTray *bool `json:"minimize_to_tray,omitempty"`
}
// ShouldMinimizeToTray returns true when closing the main window should hide to tray.
func (c *Config) ShouldMinimizeToTray() bool {
if c == nil || c.MinimizeToTray == nil {
return true
}
return *c.MinimizeToTray
}
func DefaultDataRoot() string {
@@ -166,6 +178,9 @@ func Load(path string) (*Config, error) {
cfg.DataRoot = filepath.Dir(path)
}
cfg.Locale = i18n.Normalize(string(cfg.Locale))
if cfg.RuntimeChannel == "candidate" {
cfg.RuntimeChannel = "alpha"
}
return cfg, nil
}
+14
View File
@@ -78,3 +78,17 @@ func TestEnvOverridesEverything(t *testing.T) {
t.Fatal("env override must not write the location file")
}
}
func TestLegacyCandidateChannelReadsAsAlpha(t *testing.T) {
p := filepath.Join(t.TempDir(), "reims-go.json")
if err := os.WriteFile(p, []byte(`{"data_root":"x","runtime_channel":"candidate"}`), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(p)
if err != nil {
t.Fatal(err)
}
if cfg.RuntimeChannel != "alpha" {
t.Fatalf("runtime_channel = %q, want alpha", cfg.RuntimeChannel)
}
}
+217
View File
@@ -2,14 +2,111 @@ package reims
import (
"context"
"encoding/binary"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/Nwflower/reims-go/internal/host"
)
// GuestAPFSExpandCommand repairs the GPT backup header moved by `qemu-img resize`
// and grows the APFS container backing `/` to fill the newly expanded disk,
// regardless of whether macOS assigned the system disk to disk0, disk1, or disk2.
const GuestAPFSExpandCommand = `P=$(diskutil info / | awk '/APFS Container:/{print $3}'); S=$(diskutil apfs list "$P" | awk '/APFS Physical Store Disk:/{print $5}'); D=${S%s*}; diskutil repairDisk "$D" && diskutil apfs resizeContainer "$S" 0`
type DiskResizeResult struct {
Path string `json:"path"`
OldVirtualBytes uint64 `json:"old_virtual_bytes"`
NewVirtualBytes uint64 `json:"new_virtual_bytes"`
GuestExpandCmd string `json:"guest_expand_cmd"`
}
type DiskCompactResult struct {
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
}
var reResizeSpec = regexp.MustCompile(`^(?i)(\+)?\s*(\d+)\s*([GM])$`)
// ParseResizeTarget parses an absolute size ("256G") or relative delta ("+64G")
// and verifies it strictly grows the virtual disk without shrinking.
func ParseResizeTarget(currentVirtualBytes uint64, raw string) (uint64, string, error) {
m := reResizeSpec.FindStringSubmatch(strings.TrimSpace(raw))
if len(m) != 4 {
return 0, "", fmt.Errorf("invalid disk size %q (use e.g. 256G or +64G)", raw)
}
isDelta := m[1] == "+"
n, err := strconv.ParseUint(m[2], 10, 64)
if err != nil || n == 0 {
return 0, "", fmt.Errorf("disk size must be positive")
}
unit := strings.ToUpper(m[3])
var mult uint64 = 1 << 30
if unit == "M" {
mult = 1 << 20
}
const maxDiskBytes = uint64(16384) << 30 // 16 TiB sanity cap
valBytes := n * mult
if valBytes/mult != n {
return 0, "", fmt.Errorf("disk size overflows limit")
}
var newBytes uint64
var arg string
if isDelta {
newBytes = currentVirtualBytes + valBytes
arg = fmt.Sprintf("+%d%s", n, unit)
} else {
newBytes = valBytes
arg = fmt.Sprintf("%d%s", n, unit)
}
if newBytes <= currentVirtualBytes {
curGB := float64(currentVirtualBytes) / float64(1<<30)
return 0, "", fmt.Errorf("new size (%s) must be larger than current capacity (%.0fG); shrinking is not supported", raw, curGB)
}
if newBytes > maxDiskBytes {
return 0, "", fmt.Errorf("target disk size exceeds 16 TB limit")
}
return newBytes, arg, nil
}
// HasQCOW2BackingFile reports whether path is a qcow2 image with a non-zero
// backing_file_offset in its header (i.e. a CoW overlay).
func HasQCOW2BackingFile(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
var hdr [16]byte
if _, err := f.ReadAt(hdr[:], 0); err != nil {
return false, err
}
if string(hdr[:4]) != "QFI\xfb" {
return false, nil
}
return binary.BigEndian.Uint64(hdr[8:16]) != 0, nil
}
// BuildResizeDiskArgs builds `qemu-img resize` arguments.
func BuildResizeDiskArgs(diskPath, sizeArg string) []string {
return []string{"resize", diskPath, sizeArg}
}
// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` arguments
// for reclaiming unallocated/trimmed space into a fresh sparse qcow2 file.
func BuildCompactDiskArgs(srcPath, dstPath string) []string {
return []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2", srcPath, dstPath}
}
// NeedsDiskConversion reports whether srcPath is a disk format (VMDK or RAW)
// that should be converted to qcow2 via qemu-img before handing off to reims-ctl.
func NeedsDiskConversion(srcPath string) bool {
@@ -80,3 +177,123 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac
}
return nil
}
// ResizeDisk expands a stopped VM's disk image via `qemu-img resize`.
func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, sizeSpec string, stdout, stderr io.Writer) (DiskResizeResult, error) {
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskResizeResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskResizeResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
}
newBytes, arg, err := ParseResizeTarget(before.VirtualBytes, sizeSpec)
if err != nil {
return DiskResizeResult{}, err
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildResizeDiskArgs(diskPath, arg)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
if err := cmd.Run(); err != nil {
return DiskResizeResult{}, fmt.Errorf("qemu-img resize %s %s: %w", filepath.Base(diskPath), arg, err)
}
after, err := host.InspectDiskUsage(diskPath)
if err == nil && after.VirtualBytes > 0 {
newBytes = after.VirtualBytes
}
return DiskResizeResult{
Path: diskPath,
OldVirtualBytes: before.VirtualBytes,
NewVirtualBytes: newBytes,
GuestExpandCmd: GuestAPFSExpandCommand,
}, nil
}
// CompactDisk rewrites a stopped VM's standalone qcow2 image into a freshly
// compacted sparse qcow2 file, verifies it with `qemu-img check`, and atomically
// swaps it into place to reclaim deleted/TRIMmed host disk space.
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, stdout, stderr io.Writer) (DiskCompactResult, error) {
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskCompactResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
}
if before.Format != "qcow2" {
return DiskCompactResult{}, fmt.Errorf("only qcow2 disks can be compacted (found %s)", before.Format)
}
if hasBacking, err := HasQCOW2BackingFile(diskPath); err != nil {
return DiskCompactResult{}, err
} else if hasBacking {
return DiskCompactResult{}, fmt.Errorf("cannot compact a CoW overlay disk directly (it shares a backing image); compact the base VM instead")
}
dir := filepath.Dir(diskPath)
const safetyMarginBytes = uint64(2) << 30 // 2 GiB safety headroom
if freeBytes, ok := host.FreeDiskBytesAt(dir); ok {
need := before.ActualBytes + safetyMarginBytes
if freeBytes < need {
return DiskCompactResult{}, fmt.Errorf("not enough free space to compact safely: need ~%.1f GB free, only %.1f GB available",
float64(need)/float64(1<<30), float64(freeBytes)/float64(1<<30))
}
}
tmpPath := diskPath + ".compact.tmp"
bakPath := diskPath + ".compact.bak"
_ = os.Remove(tmpPath)
defer os.Remove(tmpPath)
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
if err := cmd.Run(); err != nil {
return DiskCompactResult{}, fmt.Errorf("qemu-img convert (compact): %w", err)
}
// Verify integrity of the compacted image before touching the original.
chk := exec.CommandContext(ctx, qemuImgPath, "check", "-q", tmpPath)
configureCmd(chk)
chk.Env = env
if out, err := chk.CombinedOutput(); err != nil {
return DiskCompactResult{}, fmt.Errorf("compacted qcow2 integrity check failed: %w (%s)", err, strings.TrimSpace(string(out)))
}
_ = os.Remove(bakPath)
if err := os.Rename(diskPath, bakPath); err != nil {
return DiskCompactResult{}, fmt.Errorf("swap disk backup: %w", err)
}
if err := os.Rename(tmpPath, diskPath); err != nil {
_ = os.Rename(bakPath, diskPath)
return DiskCompactResult{}, fmt.Errorf("replace compacted disk: %w", err)
}
_ = os.Remove(bakPath)
after, err := host.InspectDiskUsage(diskPath)
afterBytes := before.ActualBytes
if err == nil {
afterBytes = after.ActualBytes
}
var reclaimed uint64
if before.ActualBytes > afterBytes {
reclaimed = before.ActualBytes - afterBytes
}
return DiskCompactResult{
Path: diskPath,
BeforeBytes: before.ActualBytes,
AfterBytes: afterBytes,
ReclaimedBytes: reclaimed,
}, nil
}
+100
View File
@@ -0,0 +1,100 @@
package reims
import (
"context"
"encoding/binary"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestParseResizeTarget(t *testing.T) {
const gib = uint64(1) << 30
cur := 128 * gib
got, arg, err := ParseResizeTarget(cur, "256G")
if err != nil || got != 256*gib || arg != "256G" {
t.Fatalf("ParseResizeTarget(256G) = (%d, %q, %v)", got, arg, err)
}
got, arg, err = ParseResizeTarget(cur, "+64g")
if err != nil || got != 192*gib || arg != "+64G" {
t.Fatalf("ParseResizeTarget(+64g) = (%d, %q, %v)", got, arg, err)
}
for _, bad := range []string{"128G", "64G", "-32G", "0G", "+0G", "abc", "99999G"} {
if _, _, err := ParseResizeTarget(cur, bad); err == nil {
t.Fatalf("ParseResizeTarget(%q) expected error", bad)
}
}
}
func TestHasQCOW2BackingFile(t *testing.T) {
dir := t.TempDir()
standalone := filepath.Join(dir, "standalone.qcow2")
overlay := filepath.Join(dir, "overlay.qcow2")
var h [16]byte
copy(h[:4], "QFI\xfb")
binary.BigEndian.PutUint32(h[4:8], 3)
if err := os.WriteFile(standalone, h[:], 0o644); err != nil {
t.Fatal(err)
}
if has, err := HasQCOW2BackingFile(standalone); err != nil || has {
t.Fatalf("standalone HasQCOW2BackingFile = (%v, %v), want (false, nil)", has, err)
}
binary.BigEndian.PutUint64(h[8:16], 104)
if err := os.WriteFile(overlay, h[:], 0o644); err != nil {
t.Fatal(err)
}
if has, err := HasQCOW2BackingFile(overlay); err != nil || !has {
t.Fatalf("overlay HasQCOW2BackingFile = (%v, %v), want (true, nil)", has, err)
}
}
func TestParseShowAudioBackend(t *testing.T) {
cases := []struct {
line string
wantAudio bool
wantBackend string
}{
{" audio on", true, "auto"},
{" audio off", false, "auto"},
{" audio dsound", true, "dsound"},
{" audio none", true, "none"},
{" audio wav", true, "wav"},
}
for _, tc := range cases {
d := ParseShow("vm", "vm\n"+tc.line+"\n")
if d.Audio != tc.wantAudio || d.AudioBackend != tc.wantBackend {
t.Fatalf("ParseShow(%q) = (Audio=%v, Backend=%q), want (%v, %q)",
tc.line, d.Audio, d.AudioBackend, tc.wantAudio, tc.wantBackend)
}
}
}
func TestResizeAndCompactRealQemuImg(t *testing.T) {
qemuImg := os.Getenv("REIMS_GO_TEST_QEMU_IMG")
if qemuImg == "" {
t.Skip("set REIMS_GO_TEST_QEMU_IMG to test ResizeDisk and CompactDisk with real qemu-img")
}
dir := t.TempDir()
disk := filepath.Join(dir, "test.qcow2")
if out, err := exec.Command(qemuImg, "create", "-f", "qcow2", disk, "64M").CombinedOutput(); err != nil {
t.Fatalf("create qcow2: %v (%s)", err, string(out))
}
res, err := ResizeDisk(context.Background(), qemuImg, nil, disk, "+64M", nil, nil)
if err != nil {
t.Fatalf("ResizeDisk(+64M): %v", err)
}
if res.NewVirtualBytes != 128<<20 {
t.Fatalf("NewVirtualBytes = %d, want %d", res.NewVirtualBytes, 128<<20)
}
cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, nil, nil)
if err != nil {
t.Fatalf("CompactDisk: %v", err)
}
if cmp.AfterBytes == 0 {
t.Fatalf("CompactDisk AfterBytes = 0")
}
}
+57 -6
View File
@@ -14,6 +14,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/opencore"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
@@ -57,6 +58,7 @@ type VMDetail struct {
InstallerPath string `json:"installer_path,omitempty"`
CPUModel string `json:"cpu_model"`
Audio bool `json:"audio"`
AudioBackend string `json:"audio_backend,omitempty"`
AudioRaw string `json:"audio_raw"`
Network bool `json:"network"`
NetworkSummary string `json:"network_summary"`
@@ -67,10 +69,15 @@ type VMDetail struct {
Capture bool `json:"capture"`
Borderless bool `json:"borderless"`
ExtraArgs string `json:"extra_args"`
GuestToolsAttached bool `json:"guest_tools_attached"`
GuestToolsConfigured bool `json:"guest_tools_configured"`
GuestToolsConnected bool `json:"guest_tools_connected"`
SharedDir string `json:"shared_dir,omitempty"`
GuestToolsAttached bool `json:"guest_tools_attached"`
GuestToolsConfigured bool `json:"guest_tools_configured"`
GuestToolsConnected bool `json:"guest_tools_connected"`
GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"`
GuestToolsPreventSleep bool `json:"guest_tools_prevent_sleep"`
GuestToolsSleepActive bool `json:"guest_tools_sleep_active"`
GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"`
SharedDir string `json:"shared_dir,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
}
type ValidationIssue struct {
@@ -105,6 +112,7 @@ type CreateOpts struct {
Network *bool `json:"network,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Logs *bool `json:"logs,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
Start bool `json:"start,omitempty"`
}
@@ -128,6 +136,7 @@ type SetOpts struct {
StopTimeout *int `json:"stop_timeout,omitempty"`
ExtraArgs *string `json:"extra_args,omitempty"`
Env []string `json:"env,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
}
var (
@@ -209,6 +218,11 @@ func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue {
if o.SSHPort < 0 || o.SSHPort > 65535 {
issues = append(issues, ValidationIssue{Field: "ssh_port", Code: "invalid_ssh_port", Message: "SSH port must be 0..65535"})
}
if strings.TrimSpace(o.GuestLang) != "" {
if _, err := opencore.NormalizeGuestLang(o.GuestLang); err != nil {
issues = append(issues, ValidationIssue{Field: "guest_lang", Code: "invalid_guest_lang", Message: err.Error()})
}
}
return issues
}
@@ -251,6 +265,19 @@ func ValidateSet(o SetOpts, current VMDetail, rep host.Report) []ValidationIssue
if o.SSHPort != nil && (*o.SSHPort < 0 || *o.SSHPort > 65535) {
issues = append(issues, ValidationIssue{Field: "ssh_port", Code: "invalid_ssh_port", Message: "SSH port must be 0..65535"})
}
if o.AudioBackend != "" {
ab := strings.ToLower(strings.TrimSpace(o.AudioBackend))
switch ab {
case "auto", "dsound", "none", "wav", "dbus", "pipewire", "pa", "alsa", "sdl", "coreaudio":
default:
issues = append(issues, ValidationIssue{Field: "audio_backend", Code: "invalid_audio_backend", Message: fmt.Sprintf("Unsupported audio backend %q", o.AudioBackend)})
}
}
if strings.TrimSpace(o.GuestLang) != "" {
if _, err := opencore.NormalizeGuestLang(o.GuestLang); err != nil {
issues = append(issues, ValidationIssue{Field: "guest_lang", Code: "invalid_guest_lang", Message: err.Error()})
}
}
return issues
}
@@ -456,6 +483,24 @@ func BuildSetArgs(o SetOpts) ([]string, error) {
return args, nil
}
// HasCtlSetChanges reports whether SetOpts carries any fields handled by `reims-ctl set`.
func HasCtlSetChanges(o SetOpts) bool {
args, err := BuildSetArgs(o)
return err == nil && len(args) > 2
}
// showState keeps the leading word of `reims-ctl show`'s state line. While a
// VM runs it prints the PID too ("running (pid 22032)" from the runtime in use
// on 2026-11-28; older output had "running, pid 1234"), but `reims-ctl list`
// and every caller compare against the bare word, so a running VM would
// otherwise never read as "running".
func showState(v string) string {
if i := strings.IndexFunc(v, func(r rune) bool { return r == ' ' || r == ',' || r == '(' || r == ':' }); i > 0 {
return v[:i]
}
return v
}
// ParseShow parses the text output of `reims-ctl show <name>` while redacting MAC addresses.
func ParseShow(name, text string) VMDetail {
d := VMDetail{
@@ -482,7 +527,7 @@ func ParseShow(name, text string) VMDetail {
v := strings.TrimSpace(parts[1])
switch k {
case "state":
d.State = v
d.State = showState(v)
case "kind":
d.Kind = v
case "directory":
@@ -541,7 +586,13 @@ func ParseShow(name, text string) VMDetail {
d.CPUModel = v
case "audio":
d.AudioRaw = v
d.Audio = strings.HasPrefix(strings.ToLower(v), "on")
low := strings.ToLower(strings.TrimSpace(v))
d.Audio = low != "" && !strings.HasPrefix(low, "off")
if d.Audio && low != "on" {
d.AudioBackend = strings.TrimSpace(v)
} else {
d.AudioBackend = "auto"
}
case "network":
// Redact MAC per docs/shell-design.md §3.
d.NetworkSummary = strings.TrimSpace(reMac.ReplaceAllString(v, " (MAC configured)"))
+14
View File
@@ -100,3 +100,17 @@ func TestParseShowCaptureOffAndInlineSSHPort(t *testing.T) {
t.Fatalf("expected SSHPort=2222, got %d", d.SSHPort)
}
}
func TestParseShowStateDropsPID(t *testing.T) {
for raw, want := range map[string]string{
"running (pid 22032)": "running",
"running, pid 1234": "running",
"stopped": "stopped",
"broken: no disk": "broken",
} {
d := ParseShow("m0", "m0\n state "+raw+"\n cpus 4")
if d.State != want {
t.Errorf("state %q parsed as %q, want %q", raw, d.State, want)
}
}
}
+33 -3
View File
@@ -6,18 +6,48 @@ import "sync"
type OSClipboard struct {
mu sync.Mutex
text string
kind ClipKind
data []byte
seq uint32
}
func (c *OSClipboard) SequenceNumber() uint32 {
c.mu.Lock()
defer c.mu.Unlock()
return c.seq
}
func (c *OSClipboard) ReadText() (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.text, nil
if c.kind != ClipText {
return "", nil
}
return string(c.data), nil
}
func (c *OSClipboard) WriteText(text string) error {
c.mu.Lock()
defer c.mu.Unlock()
c.text = text
c.kind = ClipText
c.data = []byte(text)
c.seq++
return nil
}
func (c *OSClipboard) Read() (ClipPayload, error) {
c.mu.Lock()
defer c.mu.Unlock()
cp := make([]byte, len(c.data))
copy(cp, c.data)
return ClipPayload{Kind: c.kind, Data: cp}, nil
}
func (c *OSClipboard) WritePNG(pngBytes []byte) error {
c.mu.Lock()
defer c.mu.Unlock()
c.kind = ClipPNG
c.data = append([]byte(nil), pngBytes...)
c.seq++
return nil
}
+151 -7
View File
@@ -5,6 +5,7 @@ package guesttools
import (
"fmt"
"strings"
"sync"
"syscall"
"time"
"unicode/utf16"
@@ -12,13 +13,15 @@ import (
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procOpenClipboard = user32.NewProc("OpenClipboard")
procCloseClipboard = user32.NewProc("CloseClipboard")
procEmptyClipboard = user32.NewProc("EmptyClipboard")
procGetClipboardData = user32.NewProc("GetClipboardData")
procSetClipboardData = user32.NewProc("SetClipboardData")
procIsClipboardFormatAvail = user32.NewProc("IsClipboardFormatAvailable")
user32 = syscall.NewLazyDLL("user32.dll")
procOpenClipboard = user32.NewProc("OpenClipboard")
procCloseClipboard = user32.NewProc("CloseClipboard")
procEmptyClipboard = user32.NewProc("EmptyClipboard")
procGetClipboardData = user32.NewProc("GetClipboardData")
procSetClipboardData = user32.NewProc("SetClipboardData")
procIsClipboardFormatAvail = user32.NewProc("IsClipboardFormatAvailable")
procGetClipboardSequenceNumber = user32.NewProc("GetClipboardSequenceNumber")
procRegisterClipboardFormatW = user32.NewProc("RegisterClipboardFormatW")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGlobalAlloc = kernel32.NewProc("GlobalAlloc")
@@ -27,15 +30,36 @@ var (
procGlobalUnlock = kernel32.NewProc("GlobalUnlock")
procGlobalSize = kernel32.NewProc("GlobalSize")
procRtlMoveMem = kernel32.NewProc("RtlMoveMemory")
pngFormatOnce sync.Once
pngFormatID uintptr
)
const (
cfDIB = 8
cfUnicodeText = 13
gmemMoveable = 0x0002
)
type OSClipboard struct{}
func registerPNGFormat() uintptr {
pngFormatOnce.Do(func() {
p, err := syscall.UTF16PtrFromString("PNG")
if err != nil {
return
}
id, _, _ := procRegisterClipboardFormatW.Call(uintptr(unsafe.Pointer(p)))
pngFormatID = id
})
return pngFormatID
}
func (OSClipboard) SequenceNumber() uint32 {
r, _, _ := procGetClipboardSequenceNumber.Call()
return uint32(r)
}
func openClipboardWithRetry() error {
var lastErr error
for i := 0; i < 5; i++ {
@@ -49,6 +73,52 @@ func openClipboardWithRetry() error {
return fmt.Errorf("OpenClipboard: %w", lastErr)
}
func readClipboardRawLocked(format uintptr, maxBytes int) ([]byte, error) {
h, _, err := procGetClipboardData.Call(format)
if h == 0 {
return nil, fmt.Errorf("GetClipboardData(%d): %w", format, err)
}
sz, _, _ := procGlobalSize.Call(h)
if sz == 0 {
return nil, nil
}
if int(sz) > maxBytes {
return nil, fmt.Errorf("clipboard data (%d bytes) exceeds limit", sz)
}
ptr, _, err := procGlobalLock.Call(h)
if ptr == 0 {
return nil, fmt.Errorf("GlobalLock: %w", err)
}
defer procGlobalUnlock.Call(h)
buf := make([]byte, int(sz))
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&buf[0])), ptr, sz)
return buf, nil
}
func setClipboardRawLocked(format uintptr, data []byte) error {
if len(data) == 0 {
return nil
}
hMem, _, err := procGlobalAlloc.Call(gmemMoveable, uintptr(len(data)))
if hMem == 0 {
return fmt.Errorf("GlobalAlloc: %w", err)
}
ptr, _, err := procGlobalLock.Call(hMem)
if ptr == 0 {
procGlobalFree.Call(hMem)
return fmt.Errorf("GlobalLock: %w", err)
}
procRtlMoveMem.Call(ptr, uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)))
procGlobalUnlock.Call(hMem)
if r, _, err := procSetClipboardData.Call(format, hMem); r == 0 {
procGlobalFree.Call(hMem)
return fmt.Errorf("SetClipboardData(%d): %w", format, err)
}
return nil
}
// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF
// for macOS guests. Returns ("", nil) when the clipboard has no text.
func (OSClipboard) ReadText() (string, error) {
@@ -60,7 +130,10 @@ func (OSClipboard) ReadText() (string, error) {
return "", err
}
defer procCloseClipboard.Call()
return readUnicodeTextLocked()
}
func readUnicodeTextLocked() (string, error) {
h, _, err := procGetClipboardData.Call(cfUnicodeText)
if h == 0 {
return "", fmt.Errorf("GetClipboardData: %w", err)
@@ -89,6 +162,53 @@ func (OSClipboard) ReadText() (string, error) {
return strings.ReplaceAll(s, "\r\n", "\n"), nil
}
// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image.
func (OSClipboard) Read() (ClipPayload, error) {
hasText, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText)
pngFmt := registerPNGFormat()
var hasPNG uintptr
if pngFmt != 0 {
hasPNG, _, _ = procIsClipboardFormatAvail.Call(pngFmt)
}
hasDIB, _, _ := procIsClipboardFormatAvail.Call(cfDIB)
if hasText == 0 && hasPNG == 0 && hasDIB == 0 {
return ClipPayload{Kind: ClipEmpty}, nil
}
if err := openClipboardWithRetry(); err != nil {
return ClipPayload{}, err
}
defer procCloseClipboard.Call()
if hasText != 0 {
text, err := readUnicodeTextLocked()
if err != nil {
return ClipPayload{}, err
}
return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil
}
if hasPNG != 0 {
if raw, err := readClipboardRawLocked(pngFmt, MaxClipboardBytes); err == nil && IsPNG(raw) {
return ClipPayload{Kind: ClipPNG, Data: raw}, nil
}
}
if hasDIB != 0 {
raw, err := readClipboardRawLocked(cfDIB, MaxClipboardBytes*4)
if err != nil {
return ClipPayload{}, err
}
pngBytes, err := DecodeDIBToPNG(raw)
if err != nil {
return ClipPayload{}, err
}
if len(pngBytes) > MaxClipboardBytes {
return ClipPayload{}, fmt.Errorf("encoded PNG (%d bytes) exceeds clipboard limit", len(pngBytes))
}
return ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil
}
return ClipPayload{Kind: ClipEmpty}, nil
}
// WriteText writes UTF-8 text to the Windows clipboard as CF_UNICODETEXT
// (normalizing bare LF to CRLF for Windows apps).
func (OSClipboard) WriteText(text string) error {
@@ -126,3 +246,27 @@ func (OSClipboard) WriteText(text string) error {
}
return nil
}
// WritePNG writes a PNG image to the Windows clipboard in both native "PNG"
// and universal 32-bit CF_DIB formats.
func (OSClipboard) WritePNG(pngBytes []byte) error {
if len(pngBytes) == 0 || len(pngBytes) > MaxClipboardBytes {
return fmt.Errorf("clipboard PNG size %d out of bounds", len(pngBytes))
}
dib, err := EncodePNGToDIB(pngBytes)
if err != nil {
return err
}
if err := openClipboardWithRetry(); err != nil {
return err
}
defer procCloseClipboard.Call()
if r, _, err := procEmptyClipboard.Call(); r == 0 {
return fmt.Errorf("EmptyClipboard: %w", err)
}
if pngFmt := registerPNGFormat(); pngFmt != 0 {
_ = setClipboardRawLocked(pngFmt, pngBytes)
}
return setClipboardRawLocked(cfDIB, dib)
}
+169
View File
@@ -0,0 +1,169 @@
package guesttools
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
)
// pngMagic is the standard 8-byte PNG file signature.
var pngMagic = []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}
const maxClipboardImageDim = 16384
// IsPNG reports whether data starts with the PNG signature.
func IsPNG(data []byte) bool {
return len(data) >= len(pngMagic) && bytes.Equal(data[:len(pngMagic)], pngMagic)
}
// EncodeImageToDIB encodes an image into a standard 32-bit bottom-up Windows
// CF_DIB (BITMAPINFOHEADER + BGRA pixels) accepted by all Windows applications.
func EncodeImageToDIB(img image.Image) ([]byte, error) {
b := img.Bounds()
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 || w > maxClipboardImageDim || h > maxClipboardImageDim {
return nil, fmt.Errorf("invalid clipboard image dimensions %dx%d", w, h)
}
rgba := image.NewNRGBA(image.Rect(0, 0, w, h))
draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src)
const hdrSize = 40
pixelBytes := w * h * 4
out := make([]byte, hdrSize+pixelBytes)
binary.LittleEndian.PutUint32(out[0:4], hdrSize)
binary.LittleEndian.PutUint32(out[4:8], uint32(w))
binary.LittleEndian.PutUint32(out[8:12], uint32(h)) // positive => bottom-up
binary.LittleEndian.PutUint16(out[12:14], 1) // planes
binary.LittleEndian.PutUint16(out[14:16], 32) // bpp
binary.LittleEndian.PutUint32(out[16:20], 0) // BI_RGB
binary.LittleEndian.PutUint32(out[20:24], uint32(pixelBytes))
for y := 0; y < h; y++ {
srcY := h - 1 - y
srcRow := rgba.Pix[srcY*rgba.Stride:]
dstRow := out[hdrSize+y*w*4:]
for x := 0; x < w; x++ {
si := x * 4
di := x * 4
dstRow[di+0] = srcRow[si+2] // B
dstRow[di+1] = srcRow[si+1] // G
dstRow[di+2] = srcRow[si+0] // R
dstRow[di+3] = srcRow[si+3] // A
}
}
return out, nil
}
// EncodePNGToDIB decodes pngBytes and returns a Windows CF_DIB byte slice.
func EncodePNGToDIB(pngBytes []byte) ([]byte, error) {
if !IsPNG(pngBytes) {
return nil, errors.New("payload is not a valid PNG")
}
cfg, err := png.DecodeConfig(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode PNG config: %w", err)
}
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxClipboardImageDim || cfg.Height > maxClipboardImageDim {
return nil, fmt.Errorf("PNG dimensions out of bounds: %dx%d", cfg.Width, cfg.Height)
}
img, err := png.Decode(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode PNG: %w", err)
}
return EncodeImageToDIB(img)
}
// DecodeDIBToPNG converts Windows CF_DIB bytes (24-bit or 32-bit BI_RGB / BI_BITFIELDS)
// into PNG bytes.
func DecodeDIBToPNG(dib []byte) ([]byte, error) {
if len(dib) < 40 {
return nil, errors.New("CF_DIB too short")
}
hdrSize := int(binary.LittleEndian.Uint32(dib[0:4]))
if hdrSize < 40 || hdrSize > len(dib) {
return nil, fmt.Errorf("unsupported DIB header size %d", hdrSize)
}
w := int(int32(binary.LittleEndian.Uint32(dib[4:8])))
rawH := int(int32(binary.LittleEndian.Uint32(dib[8:12])))
topDown := rawH < 0
h := rawH
if h < 0 {
h = -h
}
if w <= 0 || h <= 0 || w > maxClipboardImageDim || h > maxClipboardImageDim {
return nil, fmt.Errorf("invalid DIB dimensions %dx%d", w, h)
}
bpp := int(binary.LittleEndian.Uint16(dib[14:16]))
comp := binary.LittleEndian.Uint32(dib[16:20])
const (
biRGB = 0
biBitfields = 3
)
if comp != biRGB && comp != biBitfields {
return nil, fmt.Errorf("unsupported DIB compression %d", comp)
}
if bpp != 24 && bpp != 32 {
return nil, fmt.Errorf("unsupported DIB bit depth %d", bpp)
}
pixelOffset := hdrSize
if comp == biBitfields && hdrSize == 40 {
// Standard BITMAPINFOHEADER + BI_BITFIELDS appends 3 DWORD color masks (12 bytes).
pixelOffset += 12
}
if clrUsed := int(binary.LittleEndian.Uint32(dib[32:36])); clrUsed > 0 && bpp <= 8 {
pixelOffset += clrUsed * 4
}
rowStride := ((w*bpp + 31) / 32) * 4
if pixelOffset+rowStride*h > len(dib) {
return nil, errors.New("CF_DIB pixel data truncated")
}
img := image.NewNRGBA(image.Rect(0, 0, w, h))
// Track whether any 32-bit pixel carries non-zero alpha; many Windows apps
// leave the 4th byte of BI_RGB 32-bit DIBs as 0 (opaque XRGB).
hasAlpha := false
if bpp == 32 {
for y := 0; y < h && !hasAlpha; y++ {
row := dib[pixelOffset+y*rowStride:]
for x := 0; x < w; x++ {
if row[x*4+3] != 0 {
hasAlpha = true
break
}
}
}
}
for y := 0; y < h; y++ {
srcY := h - 1 - y
if topDown {
srcY = y
}
row := dib[pixelOffset+srcY*rowStride:]
for x := 0; x < w; x++ {
if bpp == 32 {
off := x * 4
a := row[off+3]
if !hasAlpha {
a = 255
}
img.SetNRGBA(x, y, color.NRGBA{R: row[off+2], G: row[off+1], B: row[off+0], A: a})
} else {
off := x * 3
img.SetNRGBA(x, y, color.NRGBA{R: row[off+2], G: row[off+1], B: row[off+0], A: 255})
}
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
return nil, fmt.Errorf("encode PNG: %w", err)
}
return buf.Bytes(), nil
}
+363 -22
View File
@@ -3,7 +3,11 @@ package guesttools
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
"image/color"
"image/png"
"io"
"net/http"
"net/url"
@@ -20,27 +24,96 @@ import (
type memClipboard struct {
mu sync.Mutex
text string
kind ClipKind
data []byte
seq uint32
}
func (m *memClipboard) SequenceNumber() uint32 {
m.mu.Lock()
defer m.mu.Unlock()
return m.seq
}
func (m *memClipboard) ReadText() (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.text, nil
if m.kind != ClipText && m.kind != "" {
return "", nil
}
return string(m.data), nil
}
func (m *memClipboard) WriteText(s string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.text = s
m.kind = ClipText
m.data = []byte(s)
m.seq++
return nil
}
func (m *memClipboard) Read() (ClipPayload, error) {
m.mu.Lock()
defer m.mu.Unlock()
cp := make([]byte, len(m.data))
copy(cp, m.data)
k := m.kind
if k == "" && len(cp) > 0 {
k = ClipText
}
return ClipPayload{Kind: k, Data: cp}, nil
}
func (m *memClipboard) WritePNG(b []byte) error {
m.mu.Lock()
defer m.mu.Unlock()
m.kind = ClipPNG
m.data = append([]byte(nil), b...)
m.seq++
return nil
}
func makeSamplePNG(t *testing.T, r, g, b uint8) []byte {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, 4, 3))
for y := 0; y < 3; y++ {
for x := 0; x < 4; x++ {
img.SetNRGBA(x, y, color.NRGBA{R: r, G: g, B: b, A: 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestDIBPNGRoundTrip(t *testing.T) {
origPNG := makeSamplePNG(t, 0x12, 0x34, 0x56)
dib, err := EncodePNGToDIB(origPNG)
if err != nil {
t.Fatalf("EncodePNGToDIB: %v", err)
}
roundPNG, err := DecodeDIBToPNG(dib)
if err != nil {
t.Fatalf("DecodeDIBToPNG: %v", err)
}
img, err := png.Decode(bytes.NewReader(roundPNG))
if err != nil {
t.Fatalf("png.Decode: %v", err)
}
got := color.NRGBAModel.Convert(img.At(2, 1)).(color.NRGBA)
if got.R != 0x12 || got.G != 0x34 || got.B != 0x56 || got.A != 255 {
t.Fatalf("pixel = %+v, want {18 52 86 255}", got)
}
}
func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
tmp := t.TempDir()
vmDir := filepath.Join(tmp, "vm")
sharedDir := filepath.Join(tmp, "shared")
clip := &memClipboard{text: "hello from windows"}
clip := &memClipboard{kind: ClipText, data: []byte("hello from windows")}
srv := NewServer(clip)
port, err := srv.Start(-1)
@@ -66,12 +139,15 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
t.Fatalf("unauthenticated ping: got %d, want 401", resp.StatusCode)
}
doReq := func(method, path string, body io.Reader) *http.Response {
req, err := http.NewRequest(method, base+path, body)
doReq := func(method, reqPath string, contentType string, body io.Reader) *http.Response {
req, err := http.NewRequest(method, base+reqPath, body)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
r, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
@@ -80,7 +156,7 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
}
// 2. Authenticated ping marks VM connected.
r := doReq("GET", "/v1/ping", nil)
r := doReq("GET", "/v1/ping", "", nil)
r.Body.Close()
if r.StatusCode != http.StatusOK {
t.Fatalf("ping status=%d", r.StatusCode)
@@ -89,26 +165,26 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
t.Fatalf("expected VM to be marked connected after ping")
}
// 3. Clipboard GET -> 200, then GET with since=<hash> -> 304, then POST updates host clipboard.
r = doReq("GET", "/v1/clipboard", nil)
// 3. Clipboard text GET -> 200, then GET with since=<hash> -> 304, then POST updates host clipboard.
r = doReq("GET", "/v1/clipboard", "", nil)
b, _ := io.ReadAll(r.Body)
h := r.Header.Get("X-Clip-Hash")
r.Body.Close()
if r.StatusCode != 200 || string(b) != "hello from windows" || h == "" {
t.Fatalf("clipboard GET: status=%d body=%q hash=%q", r.StatusCode, string(b), h)
}
r = doReq("GET", "/v1/clipboard?since="+h, nil)
r = doReq("GET", "/v1/clipboard?since="+h, "", nil)
r.Body.Close()
if r.StatusCode != http.StatusNotModified {
t.Fatalf("clipboard unchanged: status=%d, want 304", r.StatusCode)
}
r = doReq("POST", "/v1/clipboard", strings.NewReader("你好 macOS"))
r = doReq("POST", "/v1/clipboard", "text/plain; charset=utf-8", strings.NewReader("你好 macOS"))
r.Body.Close()
if r.StatusCode != 200 {
t.Fatalf("clipboard POST: status=%d", r.StatusCode)
}
// Reject invalid non-UTF-8 (e.g. raw GBK bytes) instead of corrupting host clipboard.
r = doReq("POST", "/v1/clipboard", bytes.NewReader([]byte{0xB6, 0xE0, 0xBA, 0xCB}))
r = doReq("POST", "/v1/clipboard", "text/plain; charset=utf-8", bytes.NewReader([]byte{0xB6, 0xE0, 0xBA, 0xCB}))
r.Body.Close()
if r.StatusCode != http.StatusBadRequest {
t.Fatalf("non-UTF-8 clipboard POST: got %d, want 400", r.StatusCode)
@@ -117,24 +193,82 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
t.Fatalf("host clipboard = %q, want %q", got, "你好 macOS")
}
// 4. Shared files: reject path traversal, allow upload & download with UTF-8/spaces.
r = doReq("GET", "/v1/file?path="+url.QueryEscape("../secret.txt"), nil)
// 4. Image (PNG) clipboard POST + GET with accept=image + long-poll immediate wake.
samplePNG := makeSamplePNG(t, 200, 100, 50)
r = doReq("POST", "/v1/clipboard", "image/png", bytes.NewReader(samplePNG))
pngHash := r.Header.Get("X-Clip-Hash")
r.Body.Close()
if r.StatusCode != 200 || pngHash == "" {
t.Fatalf("PNG clipboard POST: status=%d hash=%q", r.StatusCode, pngHash)
}
r = doReq("GET", "/v1/clipboard?accept=image", "", nil)
gotPNG, _ := io.ReadAll(r.Body)
gotKind := r.Header.Get("X-Clip-Kind")
r.Body.Close()
if r.StatusCode != 200 || gotKind != "png" || !bytes.Equal(gotPNG, samplePNG) {
t.Fatalf("PNG clipboard GET: status=%d kind=%q len=%d", r.StatusCode, gotKind, len(gotPNG))
}
// Long-poll wakes up immediately when host clipboard changes.
doneCh := make(chan string, 1)
go func() {
lr := doReq("GET", "/v1/clipboard?since="+pngHash+"&wait=5&accept=image", "", nil)
body, _ := io.ReadAll(lr.Body)
lr.Body.Close()
doneCh <- fmt.Sprintf("%d:%s", lr.StatusCode, string(body))
}()
time.Sleep(100 * time.Millisecond)
_ = clip.WriteText("woken immediately")
srv.NotifyClipboardChanged()
select {
case got := <-doneCh:
if got != "200:woken immediately" {
t.Fatalf("long-poll result = %q, want 200:woken immediately", got)
}
case <-time.After(2 * time.Second):
t.Fatalf("long-poll timed out instead of waking on change")
}
// 5. Config & Status endpoints (prevent-sleep + mount mode).
srv.SetPreventSleep("macos-tahoe", true)
r = doReq("GET", "/v1/config", "", nil)
var cfgResp struct {
PreventSleep bool `json:"prevent_sleep"`
WebDAVPath string `json:"webdav_path"`
}
_ = json.NewDecoder(r.Body).Decode(&cfgResp)
r.Body.Close()
if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" {
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.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 {
t.Fatalf("unexpected status: %+v", st)
}
// 6. Legacy shared files: reject path traversal, allow upload & download with UTF-8/spaces.
r = doReq("GET", "/v1/file?path="+url.QueryEscape("../secret.txt"), "", nil)
r.Body.Close()
if r.StatusCode != http.StatusBadRequest {
t.Fatalf("traversal must be 400, got %d", r.StatusCode)
}
r = doReq("PUT", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt")+"&mtime=1700000100", bytes.NewBufferString("shared payload"))
r = doReq("PUT", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt")+"&mtime=1700000100", "", bytes.NewBufferString("shared payload"))
r.Body.Close()
if r.StatusCode != http.StatusOK {
t.Fatalf("file PUT status=%d", r.StatusCode)
}
r = doReq("GET", "/v1/files", nil)
r = doReq("GET", "/v1/files", "", nil)
listBytes, _ := io.ReadAll(r.Body)
r.Body.Close()
if !strings.Contains(string(listBytes), "1700000100\t14\tnotes/测试 file.txt") {
t.Fatalf("unexpected /v1/files listing:\n%s", string(listBytes))
}
r = doReq("GET", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt"), nil)
r = doReq("GET", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt"), "", nil)
dlBytes, _ := io.ReadAll(r.Body)
r.Body.Close()
if r.StatusCode != 200 || string(dlBytes) != "shared payload" {
@@ -142,10 +276,85 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
}
}
func TestServerWebDAVAuthAndOperations(t *testing.T) {
tmp := t.TempDir()
vmDir := filepath.Join(tmp, "vm")
sharedDir := filepath.Join(tmp, "shared")
srv := NewServer(&memClipboard{})
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
defer srv.Close(context.Background())
cfg, err := LoadOrCreateVMConfig(vmDir, "dev-mac", sharedDir, port)
if err != nil {
t.Fatal(err)
}
srv.RegisterVM(cfg)
base := fmt.Sprintf("http://127.0.0.1:%d", port)
doDAV := func(method, reqPath string, auth bool, body io.Reader) *http.Response {
req, err := http.NewRequest(method, base+reqPath, body)
if err != nil {
t.Fatal(err)
}
if auth {
req.SetBasicAuth("reims", cfg.Token)
}
if method == "PROPFIND" {
req.Header.Set("Depth", "1")
}
r, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
return r
}
// Unauthenticated request gets 401 with Basic challenge.
r := doDAV("PROPFIND", "/dav/dev-mac/", false, nil)
r.Body.Close()
if r.StatusCode != http.StatusUnauthorized || !strings.Contains(r.Header.Get("WWW-Authenticate"), "Basic") {
t.Fatalf("unauth WebDAV: status=%d www-auth=%q", r.StatusCode, r.Header.Get("WWW-Authenticate"))
}
// Cross-VM path is forbidden even with valid token.
r = doDAV("PROPFIND", "/dav/other-vm/", true, nil)
r.Body.Close()
if r.StatusCode != http.StatusForbidden {
t.Fatalf("cross-VM WebDAV: status=%d, want 403", r.StatusCode)
}
// PUT -> GET -> PROPFIND -> DELETE over WebDAV Basic auth.
r = doDAV("PUT", "/dav/dev-mac/hello.txt", true, strings.NewReader("webdav live data"))
r.Body.Close()
if r.StatusCode != http.StatusCreated && r.StatusCode != http.StatusOK && r.StatusCode != http.StatusNoContent {
t.Fatalf("WebDAV PUT status=%d", r.StatusCode)
}
if diskBytes, err := os.ReadFile(filepath.Join(sharedDir, "hello.txt")); err != nil || string(diskBytes) != "webdav live data" {
t.Fatalf("host shared file mismatch: err=%v body=%q", err, string(diskBytes))
}
r = doDAV("PROPFIND", "/dav/dev-mac/", true, nil)
propBody, _ := io.ReadAll(r.Body)
r.Body.Close()
if r.StatusCode != http.StatusMultiStatus || !strings.Contains(string(propBody), "hello.txt") {
t.Fatalf("WebDAV PROPFIND: status=%d body=%s", r.StatusCode, string(propBody))
}
r = doDAV("DELETE", "/dav/dev-mac/hello.txt", true, nil)
r.Body.Close()
if r.StatusCode != http.StatusNoContent && r.StatusCode != http.StatusOK {
t.Fatalf("WebDAV DELETE status=%d", r.StatusCode)
}
if _, err := os.Stat(filepath.Join(sharedDir, "hello.txt")); !os.IsNotExist(err) {
t.Fatalf("expected file to be deleted on host")
}
}
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}
cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847, PreventSleep: true}
if err := BuildToolsDiskImage(imgPath, cfg); err != nil {
t.Fatalf("BuildToolsDiskImage: %v", err)
}
@@ -154,7 +363,13 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
t.Fatal(err)
}
defer f.Close()
for _, name := range []string{"config", "guest-tools.sh", "Install-Reims-Tools.command", "Uninstall-Reims-Tools.command"} {
for _, name := range []string{
"config",
"guest-tools.sh",
"Install-Reims-Tools.command",
"Uninstall-Reims-Tools.command",
"Apply-Prevent-Sleep-pmset.command",
} {
if _, sz, err := installer.FindFileInHFSPlusImage(f, name); err != nil || sz == 0 {
t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", name, err, sz)
}
@@ -174,9 +389,10 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
return
}
for name, content := range map[string][]byte{
"guest-tools.sh": GuestAgentScript(),
"Install-Reims-Tools.command": GuestInstallScript(),
"Uninstall-Reims-Tools.command": GuestUninstallScript(),
"guest-tools.sh": GuestAgentScript(),
"Install-Reims-Tools.command": GuestInstallScript(),
"Uninstall-Reims-Tools.command": GuestUninstallScript(),
"Apply-Prevent-Sleep-pmset.command": GuestPmsetScript(),
} {
p := filepath.Join(tmp, name)
if err := os.WriteFile(p, content, 0o755); err != nil {
@@ -187,3 +403,128 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
}
}
}
func TestTextInputV3HandshakeAndV2Fallback(t *testing.T) {
tmp := t.TempDir()
srv := NewServer(&memClipboard{kind: ClipText, data: []byte("host-clip")})
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
defer srv.Close(context.Background())
cfg, err := LoadOrCreateVMConfig(filepath.Join(tmp, "vm"), "mac", filepath.Join(tmp, "share"), port)
if err != nil {
t.Fatal(err)
}
srv.RegisterVM(cfg)
base := fmt.Sprintf("http://127.0.0.1:%d", port)
// Disconnected VM returns ErrGuestToolsNotConnected.
if _, err := srv.InjectText(context.Background(), "mac", "你好", nil); err != ErrGuestToolsNotConnected {
t.Fatalf("disconnected InjectText err = %v, want ErrGuestToolsNotConnected", err)
}
// Simulate Guest Tools v2 (only polls /v1/clipboard, never /v1/text-input).
v2Done := make(chan string, 1)
go func() {
req, _ := http.NewRequest("GET", base+"/v1/clipboard?since="+textHash("host-clip")+"&wait=5", nil)
req.Header.Set("Authorization", "Bearer "+cfg.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
v2Done <- string(b)
}()
// Wait briefly until v2 long-poll authenticates and marks lastSeen.
deadline := time.Now().Add(2 * time.Second)
for !srv.IsConnected("mac", 5*time.Second) && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
pastedV2 := false
mode, err := srv.InjectText(context.Background(), "mac", "远程中文v2", func(context.Context) error {
pastedV2 = true
return nil
})
if err != nil || mode != "v2" || !pastedV2 {
t.Fatalf("v2 fallback: mode=%q pasted=%v err=%v", mode, pastedV2, err)
}
if got := <-v2Done; got != "远程中文v2" {
t.Fatalf("v2 guest received %q, want 远程中文v2", got)
}
// Simulate Guest Tools v3 worker on /v1/text-input + /v1/text-input/ack.
var order []string
var orderMu sync.Mutex
record := func(step string) {
orderMu.Lock()
order = append(order, step)
orderMu.Unlock()
}
v3Err := make(chan error, 1)
go func() {
req, _ := http.NewRequest("GET", base+"/v1/text-input?wait=5", nil)
req.Header.Set("Authorization", "Bearer "+cfg.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
v3Err <- err
return
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
id := resp.Header.Get("X-Input-Id")
if string(body) != "你好世界🎉" || id == "" {
v3Err <- fmt.Errorf("unexpected v3 payload=%q id=%q", string(body), id)
return
}
record("guest-pbcopy")
ackReq, _ := http.NewRequest("POST", base+"/v1/text-input/ack?id="+id, nil)
ackReq.Header.Set("Authorization", "Bearer "+cfg.Token)
ackResp, err := http.DefaultClient.Do(ackReq)
if err != nil {
v3Err <- err
return
}
ackResp.Body.Close()
record("guest-restore")
v3Err <- nil
}()
time.Sleep(40 * time.Millisecond)
mode, err = srv.InjectText(context.Background(), "mac", "你好世界🎉", func(context.Context) error {
record("host-cmd-v")
return nil
})
if err != nil || mode != "v3" {
t.Fatalf("v3 InjectText: mode=%q err=%v", mode, err)
}
if err := <-v3Err; err != nil {
t.Fatalf("v3 guest worker: %v", err)
}
wantOrder := "guest-pbcopy,host-cmd-v,guest-restore"
if got := strings.Join(order, ","); got != wantOrder {
t.Fatalf("handshake order = %s, want %s", got, wantOrder)
}
// Test POST /v1/host-text callback.
hostTextCh := make(chan string, 1)
srv.SetHostTextHandler(func(vmName, text string) {
hostTextCh <- vmName + ":" + text
})
req, _ := http.NewRequest("POST", base+"/v1/host-text", strings.NewReader("语音输入测试"))
req.Header.Set("Authorization", "Bearer "+cfg.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != http.StatusAccepted {
t.Fatalf("host-text: status=%v err=%v", resp, err)
}
resp.Body.Close()
select {
case got := <-hostTextCh:
if got != "mac:语音输入测试" {
t.Fatalf("host-text callback got %q", got)
}
case <-time.After(time.Second):
t.Fatal("host-text callback not called")
}
}
+269 -32
View File
@@ -16,17 +16,19 @@ const (
)
// BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS")
// containing the per-VM Bearer token config, POSIX guest agent script (two-way
// clipboard + ReimsShare folder sync), and one-click install/uninstall commands.
// containing the per-VM Bearer token config, Guest Tools 2.0 POSIX agent script
// (text + PNG image clipboard with long-poll, WebDAV live mount with fallback
// sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts.
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return err
}
confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL=\"http://10.0.2.2:%d\"\nREIMS_TOKEN=\"%s\"\nREIMS_VM=\"%s\"\n",
cfg.Port, cfg.Token, cfg.VMName))
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, cfg.Token, cfg.VMName))
agentBytes := GuestAgentScript()
installBytes := GuestInstallScript()
uninstallBytes := GuestUninstallScript()
pmsetBytes := GuestPmsetScript()
files := []installer.HFSFile{
{
@@ -53,16 +55,24 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
Size: int64(len(uninstallBytes)),
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(uninstallBytes)), nil },
},
{
Name: "Apply-Prevent-Sleep-pmset.command",
Mode: 0o100755,
Size: int64(len(pmsetBytes)),
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(pmsetBytes)), nil },
},
}
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
}
// GuestAgentScript returns the stock-macOS POSIX shell daemon (no Xcode or
// Python required) that syncs UTF-8 clipboard text every 1s and ~/ReimsShare
// files every 3s over the token-authenticated host bridge.
// GuestAgentScript returns the Guest Tools 2.0 stock-macOS POSIX shell daemon
// (no Xcode or Python required):
// - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling
// - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback
// - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required)
func GuestAgentScript() []byte {
return []byte(`#!/bin/sh
# Reims Guest Tools: token-authenticated two-way clipboard & ReimsShare sync.
# Reims Guest Tools 2.0: text+PNG clipboard (long-poll), WebDAV shared folder, prevent-sleep.
set -u
# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified
@@ -74,10 +84,27 @@ export __CF_USER_TEXT_ENCODING="0x$(printf '%X' "$(id -u)"):0x08000100:0x0800010
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
CONF="$APP_DIR/config"
SHARE="$HOME/ReimsShare"
SHARE_SYNC="$HOME/ReimsShare"
SHARE_MOUNT="$HOME/ReimsShareMount"
DESKTOP_LINK="$HOME/Desktop/ReimsShare"
TMP_DIR="$APP_DIR/tmp"
mkdir -p "$APP_DIR" "$SHARE" "$TMP_DIR"
[ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true
INJECT_LOCK="$TMP_DIR/injecting"
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$TMP_DIR"
rm -f "$INJECT_LOCK" 2>/dev/null || true
CAFFEINATE_PID=""
TEXT_INPUT_PID=""
cleanup() {
if [ -n "$CAFFEINATE_PID" ]; then
kill "$CAFFEINATE_PID" 2>/dev/null || true
fi
if [ -n "$TEXT_INPUT_PID" ]; then
kill "$TEXT_INPUT_PID" 2>/dev/null || true
fi
rm -f "$INJECT_LOCK" 2>/dev/null || true
}
trap cleanup EXIT INT TERM
load_conf() {
if [ -f "/Volumes/REIMSTOOLS/config" ]; then
@@ -91,11 +118,12 @@ load_conf() {
}
REIMS_HOST_URL=""
REIMS_HOST_PORT=""
REIMS_TOKEN=""
REIMS_VM=""
load_conf
urlencode() {
# Percent-encodes UTF-8 paths cleanly with stock macOS tools (LC_ALL=C awk).
LC_ALL=C awk 'BEGIN {
for (i = 0; i < 256; i++) ord[sprintf("%c", i)] = i
s = ARGV[1]
@@ -113,23 +141,165 @@ hash_file() {
shasum -a 256 "$1" 2>/dev/null | awk '{print $1}'
}
hash_png_file() {
# Matches server payloadHash(ClipPNG): sha256("png:" + bytes)
{ printf 'png:'; cat "$1"; } | shasum -a 256 2>/dev/null | awk '{print $1}'
}
update_desktop_link() {
target="$1"
if [ -L "$DESKTOP_LINK" ]; then
cur=$(readlink "$DESKTOP_LINK" 2>/dev/null || true)
[ "$cur" = "$target" ] && return 0
rm -f "$DESKTOP_LINK" 2>/dev/null || true
elif [ -e "$DESKTOP_LINK" ]; then
return 0
fi
ln -s "$target" "$DESKTOP_LINK" 2>/dev/null || true
}
is_webdav_mounted() {
mount 2>/dev/null | grep -F "on $SHARE_MOUNT (" >/dev/null 2>&1
}
mount_mode="sync"
ensure_webdav_mount() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] && [ -n "$REIMS_VM" ] || return 0
if is_webdav_mounted; then
mount_mode="webdav"
update_desktop_link "$SHARE_MOUNT"
return 0
fi
if ! command -v mount_webdav >/dev/null 2>&1; then
mount_mode="sync"
update_desktop_link "$SHARE_SYNC"
return 0
fi
host_addr=${REIMS_HOST_URL#http://}
host_addr=${host_addr#https://}
host_addr=${host_addr%/}
dav_url="http://reims:${REIMS_TOKEN}@${host_addr}/dav/${REIMS_VM}/"
mkdir -p "$SHARE_MOUNT"
if mount_webdav -v "ReimsShare" "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1 || \
mount_webdav "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1; then
mount_mode="webdav"
update_desktop_link "$SHARE_MOUNT"
else
mount_mode="sync"
update_desktop_link "$SHARE_SYNC"
fi
}
sleep_active="false"
apply_prevent_sleep() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true)
[ -n "$cfg_json" ] || return 0
if printf '%s' "$cfg_json" | grep -q '"prevent_sleep"[[:space:]]*:[[:space:]]*true'; then
if [ -z "$CAFFEINATE_PID" ] || ! kill -0 "$CAFFEINATE_PID" 2>/dev/null; then
if command -v caffeinate >/dev/null 2>&1; then
caffeinate -dims >/dev/null 2>&1 &
CAFFEINATE_PID=$!
fi
fi
if [ -n "$CAFFEINATE_PID" ] && kill -0 "$CAFFEINATE_PID" 2>/dev/null; then
sleep_active="true"
else
sleep_active="false"
fi
else
if [ -n "$CAFFEINATE_PID" ]; then
kill "$CAFFEINATE_PID" 2>/dev/null || true
CAFFEINATE_PID=""
fi
sleep_active="false"
fi
}
report_status() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
curl -fsS -m 3 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":3}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
read_local_clipboard() {
out_file="$1"
# Fast path: inspect macOS clipboard types via osascript to detect screenshots/images.
cinfo=$(osascript -e 'clipboard info' 2>/dev/null || true)
has_text=0
case "$cinfo" in
*utf8*|*"Unicode text"*|*string*) has_text=1 ;;
esac
if [ "$has_text" -eq 0 ]; then
case "$cinfo" in
*PNGf*)
rm -f "$out_file"
if osascript -e "set fp to open for access POSIX file \"$out_file\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as «class PNGf») to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$out_file" ]; then
echo "png"
return 0
fi
;;
*TIFF*)
tiff_tmp="$TMP_DIR/clip_in.tiff"
rm -f "$tiff_tmp" "$out_file"
if osascript -e "set fp to open for access POSIX file \"$tiff_tmp\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as TIFF picture) to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ]; then
if sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then
rm -f "$tiff_tmp"
echo "png"
return 0
fi
fi
rm -f "$tiff_tmp"
;;
esac
fi
pbpaste >"$out_file" 2>/dev/null || : >"$out_file"
echo "text"
}
write_local_png() {
in_file="$1"
osascript -e "set the clipboard to (read (POSIX file \"$in_file\") as «class PNGf»)" >/dev/null 2>&1 || true
}
last_clip_hash=""
tick=0
TAB=$(printf '\t')
sync_clipboard() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
if [ -f "$INJECT_LOCK" ]; then
sleep 1
return 0
fi
clip_in="$TMP_DIR/clip_in"
clip_out="$TMP_DIR/clip_out"
hdr_out="$TMP_DIR/clip_hdr"
pbpaste >"$clip_in" 2>/dev/null || : >"$clip_in"
cur_hash=$(hash_file "$clip_in")
local_kind=$(read_local_clipboard "$clip_in")
if [ "$local_kind" = "png" ]; then
cur_hash=$(hash_png_file "$clip_in")
else
cur_hash=$(hash_file "$clip_in")
fi
if [ -n "$last_clip_hash" ] && [ "$cur_hash" != "$last_clip_hash" ]; then
if curl -fsS -m 3 -X POST \
ct="text/plain; charset=utf-8"
[ "$local_kind" = "png" ] && ct="image/png"
if curl -fsS -m 5 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: text/plain; charset=utf-8" \
-H "Content-Type: $ct" \
--data-binary "@$clip_in" \
"$REIMS_HOST_URL/v1/clipboard" >/dev/null 2>&1; then
last_clip_hash="$cur_hash"
@@ -137,13 +307,19 @@ sync_clipboard() {
return 0
fi
code=$(curl -sS -m 3 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \
# Long-poll up to 2s: host changes return immediately (~150ms), idle stays quiet.
code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/clipboard?since=$last_clip_hash" 2>/dev/null || echo "000")
"$REIMS_HOST_URL/v1/clipboard?since=$last_clip_hash&wait=2&accept=image" 2>/dev/null || echo "000")
if [ "$code" = "200" ]; then
new_hash=$(awk 'tolower($1)=="x-clip-hash:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out")
new_kind=$(awk 'tolower($1)=="x-clip-kind:" {gsub(/\r/,"",$2); print tolower($2); exit}' "$hdr_out")
if [ -n "$new_hash" ] && [ "$new_hash" != "$cur_hash" ]; then
pbcopy <"$clip_out" 2>/dev/null || true
if [ "$new_kind" = "png" ]; then
write_local_png "$clip_out"
else
pbcopy <"$clip_out" 2>/dev/null || true
fi
last_clip_hash="$new_hash"
elif [ -n "$new_hash" ]; then
last_clip_hash="$new_hash"
@@ -154,6 +330,7 @@ sync_clipboard() {
}
sync_files() {
[ "$mount_mode" = "webdav" ] && return 0
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
remote_list="$TMP_DIR/remote_files.tsv"
if ! curl -fsS -m 5 \
@@ -165,7 +342,7 @@ sync_files() {
# 1. Host -> Guest (download new or strictly newer files)
while IFS="$TAB" read -r rmtime rsize rrel; do
[ -n "$rrel" ] || continue
local_path="$SHARE/$rrel"
local_path="$SHARE_SYNC/$rrel"
need_dl=0
if [ ! -f "$local_path" ]; then
need_dl=1
@@ -191,8 +368,8 @@ sync_files() {
done <"$remote_list"
# 2. Guest -> Host (upload new or strictly newer files)
find "$SHARE" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do
rel=${fpath#"$SHARE/"}
find "$SHARE_SYNC" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do
rel=${fpath#"$SHARE_SYNC/"}
[ -n "$rel" ] || continue
lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0)
lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0)
@@ -209,16 +386,59 @@ sync_files() {
done
}
while :; do
if [ $((tick % 10)) -eq 0 ]; then
text_input_loop() {
hdr="$TMP_DIR/txt_hdr"
body="$TMP_DIR/txt_body"
bak="$TMP_DIR/txt_clip_bak"
cur_chk="$TMP_DIR/txt_clip_chk"
while :; do
load_conf
if [ -z "$REIMS_HOST_URL" ] || [ -z "$REIMS_TOKEN" ]; then
sleep 2
continue
fi
code=$(curl -sS -m 30 -D "$hdr" -o "$body" -w '%{http_code}' \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/text-input?wait=25" 2>/dev/null || echo "000")
if [ "$code" = "200" ]; then
input_id=$(awk 'tolower($1)=="x-input-id:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr")
: > "$INJECT_LOCK"
pbpaste >"$bak" 2>/dev/null || : >"$bak"
pbcopy <"$body" 2>/dev/null || true
inj_hash=$(hash_file "$body")
if [ -n "$input_id" ]; then
curl -fsS -m 8 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/text-input/ack?id=$input_id" >/dev/null 2>&1 || true
fi
# Restore prior text clipboard unless user copied something else during paste.
pbpaste >"$cur_chk" 2>/dev/null || : >"$cur_chk"
cur_after=$(hash_file "$cur_chk")
if [ "$cur_after" = "$inj_hash" ] && [ -s "$bak" ]; then
pbcopy <"$bak" 2>/dev/null || true
fi
rm -f "$INJECT_LOCK" 2>/dev/null || true
elif [ "$code" != "204" ]; then
sleep 1
fi
done
}
text_input_loop &
TEXT_INPUT_PID=$!
while :; do
if [ $((tick % 5)) -eq 0 ]; then
load_conf
ensure_webdav_mount
apply_prevent_sleep
report_status
fi
sync_clipboard
if [ $((tick % 3)) -eq 0 ]; then
if [ "$mount_mode" != "webdav" ] && [ $((tick % 2)) -eq 0 ]; then
sync_files
fi
tick=$((tick + 1))
sleep 1
done
`)
}
@@ -232,19 +452,20 @@ set -e
SRC="/Volumes/REIMSTOOLS"
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist"
SHARE="$HOME/ReimsShare"
SHARE_SYNC="$HOME/ReimsShare"
SHARE_MOUNT="$HOME/ReimsShareMount"
if [ ! -f "$SRC/config" ] || [ ! -f "$SRC/guest-tools.sh" ]; then
echo "REIMSTOOLS volume not found at $SRC" >&2
exit 1
fi
mkdir -p "$APP_DIR" "$HOME/Library/LaunchAgents" "$SHARE"
mkdir -p "$APP_DIR" "$HOME/Library/LaunchAgents" "$SHARE_SYNC" "$SHARE_MOUNT"
cp "$SRC/config" "$APP_DIR/config"
cp "$SRC/guest-tools.sh" "$APP_DIR/guest-tools.sh"
chmod 600 "$APP_DIR/config"
chmod 755 "$APP_DIR/guest-tools.sh"
[ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE" "$HOME/Desktop/ReimsShare" 2>/dev/null || true
[ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE_SYNC" "$HOME/Desktop/ReimsShare" 2>/dev/null || true
uid=$(id -u)
cf_enc="0x$(printf '%X' "$uid"):0x08000100:0x08000100"
@@ -288,10 +509,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST
# Verify host bridge connectivity immediately.
. "$APP_DIR/config"
if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then
echo "Reims Guest Tools installed and connected!"
echo "Shared folder: ~/Desktop/ReimsShare (synced with Windows host)"
echo "Reims Guest Tools 2.0 installed and connected!"
echo "Clipboard: UTF-8 text + PNG screenshots (two-way)"
echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)"
echo "Prevent-sleep: controlled live from Reims-Go host UI"
else
echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
echo "Reims Guest Tools 2.0 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
fi
`)
}
@@ -302,10 +525,24 @@ func GuestUninstallScript() []byte {
set -e
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist"
SHARE_MOUNT="$HOME/ReimsShareMount"
uid=$(id -u)
launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
umount "$SHARE_MOUNT" 2>/dev/null || true
rm -f "$PLIST"
rm -rf "$APP_DIR"
echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept."
`)
}
// GuestPmsetScript offers an optional system-wide pmset configuration command
// for users who want persistent no-sleep settings even before login.
func GuestPmsetScript() []byte {
return []byte(`#!/bin/sh
set -e
echo "Applying recommended macOS VM power settings (disables idle/display/disk sleep and Power Nap)..."
sudo pmset -a sleep 0 displaysleep 0 disksleep 0 powernap 0
echo "Done! Current pmset settings:"
pmset -g custom
`)
}
+711 -50
View File
@@ -22,31 +22,68 @@ import (
"sync"
"time"
"unicode/utf8"
"golang.org/x/net/webdav"
)
const (
DefaultPort = 19847
MaxPort = 19860
MaxClipboardBytes = 4 << 20 // 4 MiB
MaxClipboardBytes = 16 << 20 // 16 MiB (supports Retina PNG screenshots)
MaxTextInputBytes = 1 << 20 // 1 MiB per injected text payload
MaxUploadBytes = 256 << 20 // 256 MiB
MaxSharedFiles = 2000
MaxSharedDepth = 8
MaxLongPollSec = 25
ConfigFileName = ".reims-go-tools.json"
)
// ErrGuestToolsNotConnected is returned when a guest-assisted operation
// requires a live Guest Tools agent inside macOS.
var ErrGuestToolsNotConnected = errors.New("guest tools not connected")
// ClipKind identifies the format carried in a clipboard payload.
type ClipKind string
const (
ClipEmpty ClipKind = ""
ClipText ClipKind = "text"
ClipPNG ClipKind = "png"
)
// ClipPayload holds a single clipboard item (either UTF-8 text or PNG bytes).
type ClipPayload struct {
Kind ClipKind
Data []byte
}
// Clipboard abstracts host OS clipboard reads/writes for testing.
type Clipboard interface {
ReadText() (string, error)
WriteText(text string) error
Read() (ClipPayload, error)
WritePNG(pngBytes []byte) error
SequenceNumber() uint32
}
// VMConfig is persisted per VM in <vmDir>/.reims-go-tools.json (0600) so the
// guest's Bearer token survives reims-go restarts without reinstalling Guest Tools.
type VMConfig struct {
VMName string `json:"vm_name"`
Token string `json:"token"`
Port int `json:"port"`
SharedDir string `json:"shared_dir"`
VMName string `json:"vm_name"`
Token string `json:"token"`
Port int `json:"port"`
SharedDir string `json:"shared_dir"`
PreventSleep bool `json:"prevent_sleep"`
}
// GuestStatus summarizes live Guest Tools 2.0 connection and capability state.
type GuestStatus struct {
Connected bool `json:"connected"`
MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync"
PreventSleep bool `json:"prevent_sleep"`
SleepActive bool `json:"sleep_active"`
AgentVersion int `json:"agent_version,omitempty"`
LastSeen time.Time `json:"last_seen,omitempty"`
}
// LoadOrCreateVMConfig loads an existing per-VM Guest Tools config or generates
@@ -75,10 +112,11 @@ func LoadOrCreateVMConfig(vmDir, vmName, sharedDir string, port int) (VMConfig,
port = DefaultPort
}
cfg = VMConfig{
VMName: vmName,
Token: hex.EncodeToString(raw[:]),
Port: port,
SharedDir: sharedDir,
VMName: vmName,
Token: hex.EncodeToString(raw[:]),
Port: port,
SharedDir: sharedDir,
PreventSleep: true,
}
if err := SaveVMConfig(vmDir, cfg); err != nil {
return VMConfig{}, err
@@ -114,22 +152,53 @@ func SaveVMConfig(vmDir string, cfg VMConfig) error {
return os.WriteFile(filepath.Join(vmDir, ConfigFileName), b, 0o600)
}
type pendingTextInput struct {
id string
text string
ackCh chan struct{}
doneCh chan struct{}
}
type pendingClipOverride struct {
text string
hash string
servedCh chan struct{}
}
type registeredVM struct {
name string
token string
sharedDir string
lastSeen time.Time
name string
token string
sharedDir string
preventSleep bool
mountMode string
sleepActive bool
agentVersion int
lastSeen time.Time
injectMu sync.Mutex
textSeq uint64
textQueue []*pendingTextInput
textActive map[string]*pendingTextInput
textNotify chan struct{}
textWaiters int
lastTextPoll time.Time
clipOverride *pendingClipOverride
}
// Server serves the token-authenticated host ↔ guest bridge over 127.0.0.1
// (reachable from QEMU SLIRP guests as http://10.0.2.2:<port>).
type Server struct {
mu sync.RWMutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
port int
listener net.Listener
httpSrv *http.Server
mu sync.RWMutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
davHandlers map[string]*webdav.Handler
davRoots map[string]string
port int
listener net.Listener
httpSrv *http.Server
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmName, text string)
}
// NewServer constructs a Guest Tools HTTP bridge. Pass nil for clip to use the
@@ -139,8 +208,11 @@ func NewServer(clip Clipboard) *Server {
clip = &OSClipboard{}
}
return &Server{
clip: clip,
vms: make(map[string]*registeredVM),
clip: clip,
vms: make(map[string]*registeredVM),
davHandlers: make(map[string]*webdav.Handler),
davRoots: make(map[string]string),
clipNotify: make(chan struct{}),
}
}
@@ -183,19 +255,68 @@ func (s *Server) Start(preferredPort int) (int, error) {
s.port = tcpAddr.Port
mux := http.NewServeMux()
mux.HandleFunc("/v1/ping", s.handlePing)
mux.HandleFunc("/v1/config", s.handleConfig)
mux.HandleFunc("/v1/status", s.handleStatus)
mux.HandleFunc("/v1/clipboard", s.handleClipboard)
mux.HandleFunc("/v1/text-input", s.handleTextInput)
mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck)
mux.HandleFunc("/v1/host-text", s.handleHostText)
mux.HandleFunc("/v1/files", s.handleListFiles)
mux.HandleFunc("/v1/file", s.handleFile)
mux.HandleFunc("/dav/", s.handleWebDAV)
s.httpSrv = &http.Server{
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
watchCtx, watchCancel := context.WithCancel(context.Background())
s.watchCancel = watchCancel
go s.watchClipboardLoop(watchCtx)
go func() {
_ = s.httpSrv.Serve(ln)
}()
return s.port, nil
}
func (s *Server) watchClipboardLoop(ctx context.Context) {
ticker := time.NewTicker(150 * time.Millisecond)
defer ticker.Stop()
lastSeq := s.clip.SequenceNumber()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
seq := s.clip.SequenceNumber()
if seq != lastSeq {
lastSeq = seq
s.broadcastClipChange()
}
}
}
}
func (s *Server) clipNotifyChan() <-chan struct{} {
s.mu.RLock()
ch := s.clipNotify
s.mu.RUnlock()
return ch
}
func (s *Server) broadcastClipChange() {
s.mu.Lock()
old := s.clipNotify
s.clipNotify = make(chan struct{})
s.mu.Unlock()
if old != nil {
close(old)
}
}
// NotifyClipboardChanged explicitly wakes any pending long-poll clipboard waiters.
func (s *Server) NotifyClipboardChanged() {
s.broadcastClipChange()
}
func (s *Server) Port() int {
s.mu.RLock()
defer s.mu.RUnlock()
@@ -205,9 +326,15 @@ func (s *Server) Port() int {
func (s *Server) Close(ctx context.Context) error {
s.mu.Lock()
srv := s.httpSrv
cancel := s.watchCancel
s.httpSrv = nil
s.listener = nil
s.watchCancel = nil
s.mu.Unlock()
if cancel != nil {
cancel()
}
s.broadcastClipChange()
if srv == nil {
return nil
}
@@ -223,38 +350,219 @@ func (s *Server) RegisterVM(cfg VMConfig) {
_ = os.MkdirAll(cfg.SharedDir, 0o755)
}
s.mu.Lock()
prev := s.vms[cfg.VMName]
var lastSeen time.Time
if prev != nil {
lastSeen = prev.lastSeen
if cur := s.vms[cfg.VMName]; cur != nil {
cur.token = cfg.Token
cur.sharedDir = cfg.SharedDir
cur.preventSleep = cfg.PreventSleep
s.mu.Unlock()
return
}
s.vms[cfg.VMName] = &registeredVM{
name: cfg.VMName,
token: cfg.Token,
sharedDir: cfg.SharedDir,
lastSeen: lastSeen,
name: cfg.VMName,
token: cfg.Token,
sharedDir: cfg.SharedDir,
preventSleep: cfg.PreventSleep,
textActive: make(map[string]*pendingTextInput),
textNotify: make(chan struct{}),
}
s.mu.Unlock()
}
// SetHostTextHandler registers a callback invoked when a host-side window hook
// (e.g. reims-vgpu-window WM_CHAR bridge) submits Unicode text to POST /v1/host-text.
func (s *Server) SetHostTextHandler(fn func(vmName, text string)) {
s.mu.Lock()
s.onHostText = fn
s.mu.Unlock()
}
// InjectText delivers arbitrary UTF-8 text (including CJK/emoji) into a running
// macOS VM without Accessibility permissions:
// - Guest Tools v3 (preferred): pushes text over /v1/text-input, waits for
// the guest to run pbcopy and POST /v1/text-input/ack, invokes pasteFn
// (QMP Command+V), waits briefly for the focused app to consume NSPasteboard,
// then unblocks the ack so the guest restores its previous clipboard.
// - Guest Tools v2 (fallback): serves a one-shot clipboard override on
// /v1/clipboard without mutating the Windows clipboard, wakes the v2
// long-poll immediately, waits for pbcopy, then invokes pasteFn.
func (s *Server) InjectText(ctx context.Context, vmName, text string, pasteFn func(context.Context) error) (string, error) {
if text == "" {
return "", errors.New("empty text")
}
if len(text) > MaxTextInputBytes {
return "", fmt.Errorf("text exceeds %d byte limit", MaxTextInputBytes)
}
if !utf8.ValidString(text) {
return "", errors.New("text must be valid UTF-8")
}
text = strings.ReplaceAll(text, "\r\n", "\n")
text = strings.ReplaceAll(text, "\r", "\n")
s.mu.RLock()
vm := s.vms[vmName]
s.mu.RUnlock()
if vm == nil {
return "", ErrGuestToolsNotConnected
}
// Serialize per-VM injections so two phrases never overlap pbcopy/Cmd+V.
vm.injectMu.Lock()
defer vm.injectMu.Unlock()
s.mu.Lock()
v3Ready := vm.textWaiters > 0 || (!vm.lastTextPoll.IsZero() && time.Since(vm.lastTextPoll) <= 35*time.Second)
connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= 15*time.Second
if v3Ready {
vm.textSeq++
id := strconv.FormatUint(vm.textSeq, 10)
item := &pendingTextInput{
id: id,
text: text,
ackCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
vm.textQueue = append(vm.textQueue, item)
if vm.textNotify != nil {
close(vm.textNotify)
}
vm.textNotify = make(chan struct{})
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(vm.textActive, item.id)
for i, q := range vm.textQueue {
if q == item {
vm.textQueue = append(vm.textQueue[:i], vm.textQueue[i+1:]...)
break
}
}
s.mu.Unlock()
select {
case <-item.doneCh:
default:
close(item.doneCh)
}
}()
timer := time.NewTimer(4 * time.Second)
defer timer.Stop()
select {
case <-item.ackCh:
case <-timer.C:
return "v3", errors.New("timed out waiting for guest tools to receive text")
case <-ctx.Done():
return "v3", ctx.Err()
}
var pasteErr error
if pasteFn != nil {
pasteErr = pasteFn(ctx)
}
if pasteErr == nil {
select {
case <-time.After(120 * time.Millisecond):
case <-ctx.Done():
}
}
return "v3", pasteErr
}
if !connected {
s.mu.Unlock()
return "", ErrGuestToolsNotConnected
}
// Guest Tools v2 fallback: serve one-shot override via /v1/clipboard.
ov := &pendingClipOverride{
text: text,
hash: textHash(text),
servedCh: make(chan struct{}),
}
vm.clipOverride = ov
s.mu.Unlock()
defer func() {
s.mu.Lock()
if vm.clipOverride == ov {
vm.clipOverride = nil
}
s.mu.Unlock()
}()
s.broadcastClipChange()
timer := time.NewTimer(4 * time.Second)
defer timer.Stop()
select {
case <-ov.servedCh:
case <-timer.C:
return "v2", errors.New("timed out waiting for guest tools v2 clipboard poll")
case <-ctx.Done():
return "v2", ctx.Err()
}
// Give macOS guest-tools.sh time to finish `pbcopy < "$clip_out"`.
select {
case <-time.After(110 * time.Millisecond):
case <-ctx.Done():
return "v2", ctx.Err()
}
if pasteFn != nil {
return "v2", pasteFn(ctx)
}
return "v2", nil
}
// SetPreventSleep updates the desired prevent-sleep state for a registered VM.
func (s *Server) SetPreventSleep(vmName string, enabled bool) {
s.mu.Lock()
if vm := s.vms[vmName]; vm != nil {
vm.preventSleep = enabled
}
s.mu.Unlock()
}
// IsConnected reports whether the guest agent has authenticated within maxAge.
func (s *Server) IsConnected(vmName string, maxAge time.Duration) bool {
return s.Status(vmName, maxAge).Connected
}
// Status returns the live connection, mount mode, and prevent-sleep status of vmName.
func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus {
s.mu.RLock()
defer s.mu.RUnlock()
vm := s.vms[vmName]
if vm == nil || vm.lastSeen.IsZero() {
return false
if vm == nil {
return GuestStatus{}
}
return time.Since(vm.lastSeen) <= maxAge
connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge
return GuestStatus{
Connected: connected,
MountMode: vm.mountMode,
PreventSleep: vm.preventSleep,
SleepActive: connected && vm.sleepActive,
AgentVersion: vm.agentVersion,
LastSeen: vm.lastSeen,
}
}
func (s *Server) touchLastSeen(vmName string) {
s.mu.Lock()
if vm := s.vms[vmName]; vm != nil {
vm.lastSeen = time.Now()
}
s.mu.Unlock()
}
func (s *Server) authenticate(r *http.Request) *registeredVM {
var tok string
auth := strings.TrimSpace(r.Header.Get("Authorization"))
const prefix = "Bearer "
if !strings.HasPrefix(auth, prefix) {
return nil
const bearerPrefix = "Bearer "
if strings.HasPrefix(auth, bearerPrefix) {
tok = strings.TrimSpace(auth[len(bearerPrefix):])
} else if _, pass, ok := r.BasicAuth(); ok {
tok = strings.TrimSpace(pass)
}
tok := strings.TrimSpace(auth[len(prefix):])
if tok == "" {
return nil
}
@@ -263,7 +571,19 @@ func (s *Server) authenticate(r *http.Request) *registeredVM {
for _, vm := range s.vms {
if len(vm.token) == len(tok) && subtle.ConstantTimeCompare([]byte(vm.token), []byte(tok)) == 1 {
vm.lastSeen = time.Now()
cp := *vm
// 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{
name: vm.name,
token: vm.token,
sharedDir: vm.sharedDir,
preventSleep: vm.preventSleep,
mountMode: vm.mountMode,
sleepActive: vm.sleepActive,
agentVersion: vm.agentVersion,
lastSeen: vm.lastSeen,
}
return &cp
}
}
@@ -275,6 +595,20 @@ func textHash(s string) string {
return hex.EncodeToString(sum[:])
}
func payloadHash(p ClipPayload) string {
switch p.Kind {
case ClipPNG:
h := sha256.New()
h.Write([]byte("png:"))
h.Write(p.Data)
return hex.EncodeToString(h.Sum(nil))
case ClipText:
return textHash(string(p.Data))
default:
return textHash("")
}
}
func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
@@ -282,29 +616,164 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "vm": vm.name})
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": true,
"vm": vm.name,
"version": 3,
"capabilities": []string{"clipboard-text", "clipboard-png", "clipboard-longpoll", "webdav", "prevent-sleep", "text-input"},
})
}
func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"vm": vm.name,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
})
}
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost && r.Method != http.MethodPut {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
MountMode string `json:"mount_mode"`
SleepActive bool `json:"sleep_active"`
AgentVersion int `json:"agent_version"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
mode := strings.ToLower(strings.TrimSpace(req.MountMode))
if mode != "webdav" && mode != "sync" {
mode = ""
}
s.mu.Lock()
if cur := s.vms[vm.name]; cur != nil {
if mode != "" {
cur.mountMode = mode
}
cur.sleepActive = req.SleepActive
if req.AgentVersion > 0 {
cur.agentVersion = req.AgentVersion
}
cur.lastSeen = time.Now()
}
s.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func (s *Server) readClipboardPayload(acceptImage bool) (ClipPayload, error) {
if acceptImage {
return s.clip.Read()
}
text, err := s.clip.ReadText()
if err != nil {
return ClipPayload{}, err
}
return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil
}
func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
if s.authenticate(r) == nil {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
switch r.Method {
case http.MethodGet:
text, err := s.clip.ReadText()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
acceptImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
since := r.URL.Query().Get("since")
waitSec := 0
if rawWait := r.URL.Query().Get("wait"); rawWait != "" {
if n, err := strconv.Atoi(rawWait); err == nil && n > 0 {
if n > MaxLongPollSec {
n = MaxLongPollSec
}
waitSec = n
}
}
h := textHash(text)
w.Header().Set("X-Clip-Hash", h)
if r.URL.Query().Get("since") == h {
w.WriteHeader(http.StatusNotModified)
return
deadline := time.Now().Add(time.Duration(waitSec) * time.Second)
for {
if ov := s.takeClipOverride(vm.name); ov != nil {
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", ov.hash)
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte(ov.text))
close(ov.servedCh)
return
}
payload, err := s.readClipboardPayload(acceptImage)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h := payloadHash(payload)
if since == "" || since != h {
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
if payload.Kind == ClipPNG {
w.Header().Set("X-Clip-Kind", string(ClipPNG))
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(payload.Data)
} else {
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write(payload.Data)
}
return
}
if waitSec <= 0 {
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
}
rem := time.Until(deadline)
if rem <= 0 {
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
}
ch := s.clipNotifyChan()
timer := time.NewTimer(rem)
select {
case <-ch:
timer.Stop()
case <-timer.C:
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
case <-r.Context().Done():
timer.Stop()
return
}
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = io.WriteString(w, text)
case http.MethodPost, http.MethodPut:
body, err := io.ReadAll(io.LimitReader(r.Body, MaxClipboardBytes+1))
if err != nil {
@@ -315,6 +784,26 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge)
return
}
ct := strings.ToLower(r.Header.Get("Content-Type"))
if strings.Contains(ct, "image/png") {
if !IsPNG(body) {
http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest)
return
}
h := payloadHash(ClipPayload{Kind: ClipPNG, Data: body})
if cur, err := s.clip.Read(); err != nil || payloadHash(cur) != h {
if err := s.clip.WritePNG(body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipPNG))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
return
}
if !utf8.Valid(body) {
http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest)
return
@@ -326,7 +815,9 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
default:
@@ -334,6 +825,176 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
}
}
func (s *Server) takeClipOverride(vmName string) *pendingClipOverride {
s.mu.Lock()
defer s.mu.Unlock()
vm := s.vms[vmName]
if vm == nil || vm.clipOverride == nil {
return nil
}
ov := vm.clipOverride
vm.clipOverride = nil
return ov
}
func (s *Server) handleTextInput(w http.ResponseWriter, r *http.Request) {
vmSnap := s.authenticate(r)
if vmSnap == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
waitSec := MaxLongPollSec
if rawWait := r.URL.Query().Get("wait"); rawWait != "" {
if n, err := strconv.Atoi(rawWait); err == nil && n >= 0 {
if n > MaxLongPollSec {
n = MaxLongPollSec
}
waitSec = n
}
}
s.mu.Lock()
vm := s.vms[vmSnap.name]
if vm == nil {
s.mu.Unlock()
http.Error(w, "vm not found", http.StatusNotFound)
return
}
vm.textWaiters++
vm.lastTextPoll = time.Now()
s.mu.Unlock()
defer func() {
s.mu.Lock()
if cur := s.vms[vmSnap.name]; cur != nil {
if cur.textWaiters > 0 {
cur.textWaiters--
}
cur.lastTextPoll = time.Now()
}
s.mu.Unlock()
}()
deadline := time.Now().Add(time.Duration(waitSec) * time.Second)
for {
s.mu.Lock()
cur := s.vms[vmSnap.name]
if cur == nil {
s.mu.Unlock()
w.WriteHeader(http.StatusNoContent)
return
}
if len(cur.textQueue) > 0 {
item := cur.textQueue[0]
cur.textQueue = cur.textQueue[1:]
cur.textActive[item.id] = item
cur.lastSeen = time.Now()
cur.lastTextPoll = time.Now()
s.mu.Unlock()
w.Header().Set("X-Input-Id", item.id)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte(item.text))
return
}
ch := cur.textNotify
s.mu.Unlock()
rem := time.Until(deadline)
if waitSec <= 0 || rem <= 0 {
s.touchLastSeen(vmSnap.name)
w.WriteHeader(http.StatusNoContent)
return
}
timer := time.NewTimer(rem)
select {
case <-ch:
timer.Stop()
case <-timer.C:
s.touchLastSeen(vmSnap.name)
w.WriteHeader(http.StatusNoContent)
return
case <-r.Context().Done():
timer.Stop()
return
}
}
}
func (s *Server) handleTextInputAck(w http.ResponseWriter, r *http.Request) {
vmSnap := s.authenticate(r)
if vmSnap == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost && r.Method != http.MethodPut {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
id := strings.TrimSpace(r.URL.Query().Get("id"))
if id == "" {
http.Error(w, "missing id", http.StatusBadRequest)
return
}
s.mu.Lock()
vm := s.vms[vmSnap.name]
var item *pendingTextInput
if vm != nil {
item = vm.textActive[id]
}
s.mu.Unlock()
if item == nil {
w.WriteHeader(http.StatusOK)
return
}
select {
case <-item.ackCh:
default:
close(item.ackCh)
}
// Block until host finishes QMP Command+V + settle so the guest does not
// restore its previous clipboard before macOS reads NSPasteboard.
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
select {
case <-item.doneCh:
case <-timer.C:
case <-r.Context().Done():
}
w.WriteHeader(http.StatusOK)
}
func (s *Server) handleHostText(w http.ResponseWriter, r *http.Request) {
vmSnap := s.authenticate(r)
if vmSnap == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, MaxTextInputBytes+1))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(body) == 0 || len(body) > MaxTextInputBytes || !utf8.Valid(body) {
http.Error(w, "invalid utf-8 text", http.StatusBadRequest)
return
}
s.mu.RLock()
fn := s.onHostText
s.mu.RUnlock()
if fn != nil {
go fn(vmSnap.name, string(body))
}
w.WriteHeader(http.StatusAccepted)
}
func isIgnoredSharedName(name string) bool {
return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._")
}
+146
View File
@@ -0,0 +1,146 @@
package guesttools
import (
"context"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"golang.org/x/net/webdav"
)
// safeWebDAVFS wraps webdav.Dir to guarantee every path stays strictly inside
// rootAbs and never traverses symlinks escaping the shared directory.
type safeWebDAVFS struct {
rootAbs string
inner webdav.Dir
}
func newSafeWebDAVFS(root string) (*safeWebDAVFS, error) {
if err := os.MkdirAll(root, 0o755); err != nil {
return nil, err
}
abs, err := filepath.Abs(root)
if err != nil {
return nil, err
}
return &safeWebDAVFS{
rootAbs: abs,
inner: webdav.Dir(abs),
}, nil
}
func (f *safeWebDAVFS) validate(name string) error {
if strings.ContainsRune(name, 0) || strings.Contains(name, `\`) {
return os.ErrInvalid
}
clean := path.Clean("/" + name)
rel := strings.TrimPrefix(clean, "/")
full := filepath.Join(f.rootAbs, filepath.FromSlash(rel))
relBack, err := filepath.Rel(f.rootAbs, full)
if err != nil || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) {
return os.ErrPermission
}
// Reject existing symlinks inside the tree so host files outside rootAbs cannot be exposed.
if info, err := os.Lstat(full); err == nil && info.Mode()&os.ModeSymlink != 0 {
return os.ErrPermission
}
return nil
}
func (f *safeWebDAVFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
if err := f.validate(name); err != nil {
return err
}
return f.inner.Mkdir(ctx, name, perm)
}
func (f *safeWebDAVFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
if err := f.validate(name); err != nil {
return nil, err
}
return f.inner.OpenFile(ctx, name, flag, perm)
}
func (f *safeWebDAVFS) RemoveAll(ctx context.Context, name string) error {
if err := f.validate(name); err != nil {
return err
}
// Never allow deleting the shared directory root itself.
if path.Clean("/"+name) == "/" {
return os.ErrPermission
}
return f.inner.RemoveAll(ctx, name)
}
func (f *safeWebDAVFS) Rename(ctx context.Context, oldName, newName string) error {
if err := f.validate(oldName); err != nil {
return err
}
if err := f.validate(newName); err != nil {
return err
}
return f.inner.Rename(ctx, oldName, newName)
}
func (f *safeWebDAVFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
if err := f.validate(name); err != nil {
return nil, err
}
return f.inner.Stat(ctx, name)
}
// handleWebDAV serves RFC 4918 WebDAV at /dav/<vmName>/... authenticated via
// HTTP Basic (username "reims", password = per-VM 256-bit token) or Bearer token.
func (s *Server) handleWebDAV(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
w.Header().Set("WWW-Authenticate", `Basic realm="ReimsShare"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// Extract requested VM name from /dav/<vmName>/...
trimmed := strings.TrimPrefix(r.URL.Path, "/dav/")
vmPart := trimmed
if idx := strings.IndexByte(trimmed, '/'); idx >= 0 {
vmPart = trimmed[:idx]
}
if vmPart == "" || vmPart != vm.name {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if vm.sharedDir == "" {
http.Error(w, "shared directory not configured", http.StatusNotFound)
return
}
handler, err := s.getOrCreateDAVHandler(vm.name, vm.sharedDir)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
handler.ServeHTTP(w, r)
}
func (s *Server) getOrCreateDAVHandler(vmName, sharedDir string) (*webdav.Handler, error) {
s.mu.Lock()
defer s.mu.Unlock()
if cur := s.davHandlers[vmName]; cur != nil && s.davRoots[vmName] == sharedDir {
return cur, nil
}
fsys, err := newSafeWebDAVFS(sharedDir)
if err != nil {
return nil, err
}
h := &webdav.Handler{
Prefix: "/dav/" + vmName,
FileSystem: fsys,
LockSystem: webdav.NewMemLS(),
}
s.davHandlers[vmName] = h
s.davRoots[vmName] = sharedDir
return h, nil
}
+14
View File
@@ -0,0 +1,14 @@
package host
// AudioInfo summarizes host audio playback and recording devices detected via
// the same OS primitives upstream reims-ctl checks (Windows waveOut/waveIn).
// Upstream reims-ctl (3731afd, qemu.rs:635-690) routes QEMU DirectSound to
// `none` when no output device exists, and routes the VM microphone alone to
// `none` (silence) when no recording device exists.
type AudioInfo struct {
OutputCount int `json:"output_count"`
InputCount int `json:"input_count"`
OutputDevices []string `json:"output_devices,omitempty"`
InputDevices []string `json:"input_devices,omitempty"`
DefaultBackend string `json:"default_backend,omitempty"`
}
+23
View File
@@ -0,0 +1,23 @@
//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
}
+86
View File
@@ -0,0 +1,86 @@
//go:build windows
package host
import (
"strings"
"syscall"
"unicode/utf16"
"unsafe"
)
var (
winmm = syscall.NewLazyDLL("winmm.dll")
procWaveOutGetNumDevs = winmm.NewProc("waveOutGetNumDevs")
procWaveOutGetDevCaps = winmm.NewProc("waveOutGetDevCapsW")
procWaveInGetNumDevs = winmm.NewProc("waveInGetNumDevs")
procWaveInGetDevCaps = winmm.NewProc("waveInGetDevCapsW")
)
// ProbeAudio enumerates Windows playback and recording devices via winmm
// (waveOutGetNumDevs/waveInGetNumDevs + wave*GetDevCapsW), matching upstream
// reims-ctl's sound_devices() check (crates/reims-ctl/src/os/windows.rs:699-708).
func ProbeAudio() AudioInfo {
info := AudioInfo{DefaultBackend: "dsound"}
if n, _, _ := procWaveOutGetNumDevs.Call(); n > 0 {
count := int(n)
info.OutputCount = count
limit := count
if limit > 16 {
limit = 16
}
for i := 0; i < limit; i++ {
// WAVEOUTCAPSW is 84 bytes; szPname[32] is at bytes 8..72.
var buf [84]byte
r, _, _ := procWaveOutGetDevCaps.Call(uintptr(i), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if r == 0 {
if name := decodeUTF16Z(buf[8:72]); name != "" {
info.OutputDevices = append(info.OutputDevices, name)
}
}
}
}
if n, _, _ := procWaveInGetNumDevs.Call(); n > 0 {
count := int(n)
info.InputCount = count
limit := count
if limit > 16 {
limit = 16
}
for i := 0; i < limit; i++ {
// WAVEINCAPSW is 80 bytes; szPname[32] is at bytes 8..72.
var buf [80]byte
r, _, _ := procWaveInGetDevCaps.Call(uintptr(i), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if r == 0 {
if name := decodeUTF16Z(buf[8:72]); name != "" {
info.InputDevices = append(info.InputDevices, name)
}
}
}
}
return info
}
func decodeUTF16Z(raw []byte) string {
u16 := make([]uint16, 0, len(raw)/2)
for i := 0; i+1 < len(raw); i += 2 {
v := uint16(raw[i]) | uint16(raw[i+1])<<8
if v == 0 {
break
}
u16 = append(u16, v)
}
return strings.TrimSpace(string(utf16.Decode(u16)))
}
// FreeDiskBytesAt returns free bytes available to the current user on the volume containing dir.
func FreeDiskBytesAt(dir string) (uint64, bool) {
gb, ok := probeFreeDiskGB(dir)
if !ok {
return 0, false
}
return uint64(gb * (1 << 30)), true
}
+176
View File
@@ -0,0 +1,176 @@
package host
import (
"fmt"
"math"
)
// DisplayInfo describes a connected physical monitor on the host.
type DisplayInfo struct {
Name string `json:"name,omitempty"`
Width int `json:"width"`
Height int `json:"height"`
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"`
}
// DisplayPreset is a suggested macOS VM resolution option tailored to the host monitor.
type DisplayPreset struct {
Resolution string `json:"resolution"`
Label string `json:"label"`
HiDPI bool `json:"hidpi"`
Recommended bool `json:"recommended,omitempty"`
}
// PrimaryDisplayOf picks the primary monitor (or the first detected monitor).
func PrimaryDisplayOf(displays []DisplayInfo) *DisplayInfo {
for i := range displays {
if displays[i].Primary {
cp := displays[i]
return &cp
}
}
if len(displays) > 0 {
cp := displays[0]
return &cp
}
return nil
}
// RecommendDisplayPresets computes crisp 1x / 2x HiDPI resolution presets
// based on the host primary monitor's physical pixel dimensions and Windows DPI scaling.
func RecommendDisplayPresets(primary *DisplayInfo) ([]DisplayPreset, string) {
if primary == nil || primary.Width <= 0 || primary.Height <= 0 {
presets := []DisplayPreset{
{Resolution: "1920x1080", Label: "1920 × 1080", Recommended: true},
{Resolution: "2560x1440", Label: "2560 × 1440"},
{Resolution: "2880x1800", Label: "2880 × 1800", HiDPI: true},
{Resolution: "3840x2160", Label: "3840 × 2160", HiDPI: true},
}
return presets, "1920x1080"
}
w, h := primary.Width, primary.Height
scale := primary.ScalePct
if scale <= 0 {
scale = 100
}
aspect := float64(w) / float64(h)
is16by10 := math.Abs(aspect-1.6) < 0.08
type cand struct {
res string
label string
hidpi bool
}
var list []cand
var rec string
add := func(res string, hidpi bool) {
for _, existing := range list {
if existing.res == res {
return
}
}
var cw, ch int
_, _ = fmt.Sscanf(res, "%dx%d", &cw, &ch)
lbl := res
if cw > 0 && ch > 0 {
lbl = fmt.Sprintf("%d × %d", cw, ch)
}
list = append(list, cand{res: res, label: lbl, hidpi: hidpi})
}
switch {
case w >= 3440:
// 4K / ultrawide 4K host: 3840x2160 gives razor-sharp 2x HiDPI (1920x1080 logical).
rec = "3840x2160"
add("3840x2160", true)
add("2880x1800", true)
add("2560x1440", scale >= 150)
add("1920x1080", false)
case w >= 2880:
// 3K / 2880x1800 laptop or 3200x1800 display.
if is16by10 {
rec = "2880x1800"
add("2880x1800", true)
add("2560x1600", scale >= 150)
add("2560x1440", false)
add("1920x1080", false)
} else {
rec = "2560x1440"
add("2560x1440", scale >= 150)
add("2880x1800", true)
add("3840x2160", true)
add("1920x1080", false)
}
case w >= 2560:
// 2K / QHD (2560x1440 or 2560x1600): match aspect ratio cleanly.
if is16by10 {
rec = "2560x1600"
add("2560x1600", scale >= 150)
add("2880x1800", true)
add("2560x1440", false)
add("1920x1080", false)
} else {
rec = "2560x1440"
add("2560x1440", scale >= 150)
add("2880x1800", true)
add("1920x1080", false)
add("3840x2160", true)
}
case w >= 1920:
// 1080p / 1920x1200 display.
if is16by10 {
rec = "1920x1200"
add("1920x1200", false)
add("1920x1080", false)
add("2560x1600", true)
add("2880x1800", true)
} else {
rec = "1920x1080"
add("1920x1080", false)
add("2560x1440", true)
add("2880x1800", true)
add("1600x900", false)
}
default:
// Smaller laptops (e.g., 1366x768 or 1600x900).
rec = "1600x900"
if w >= 1280 && h >= 720 {
native := fmt.Sprintf("%dx%d", w, h)
rec = native
add(native, false)
}
add("1600x900", false)
add("1920x1080", false)
}
// If host native resolution is standard even dimensions and not yet listed, offer it too.
if w >= 1280 && h >= 720 && w%2 == 0 && h%2 == 0 {
native := fmt.Sprintf("%dx%d", w, h)
hasNative := false
for _, c := range list {
if c.res == native {
hasNative = true
break
}
}
if !hasNative && len(list) < 5 {
list = append(list, cand{res: native, label: fmt.Sprintf("%d × %d", w, h), hidpi: scale >= 150})
}
}
out := make([]DisplayPreset, 0, len(list))
for _, c := range list {
out = append(out, DisplayPreset{
Resolution: c.res,
Label: c.label,
HiDPI: c.hidpi,
Recommended: c.res == rec,
})
}
return out, rec
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package host
func probeDisplays() []DisplayInfo {
return nil
}
+128
View File
@@ -0,0 +1,128 @@
package host
import (
"encoding/binary"
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
func TestRecommendDisplayPresets(t *testing.T) {
cases := []struct {
name string
primary *DisplayInfo
wantRec string
wantHi bool
}{
{
name: "4K at 150%",
primary: &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, Primary: true},
wantRec: "3840x2160",
wantHi: true,
},
{
name: "2K 16:9 at 125%",
primary: &DisplayInfo{Width: 2560, Height: 1440, ScalePct: 125, Primary: true},
wantRec: "2560x1440",
wantHi: false,
},
{
name: "2.5K 16:10 at 150%",
primary: &DisplayInfo{Width: 2560, Height: 1600, ScalePct: 150, Primary: true},
wantRec: "2560x1600",
wantHi: true,
},
{
name: "1080p at 100%",
primary: &DisplayInfo{Width: 1920, Height: 1080, ScalePct: 100, Primary: true},
wantRec: "1920x1080",
wantHi: false,
},
{
name: "nil fallback",
primary: nil,
wantRec: "1920x1080",
wantHi: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
presets, rec := RecommendDisplayPresets(tc.primary)
if rec != tc.wantRec {
t.Fatalf("rec = %q, want %q", rec, tc.wantRec)
}
if len(presets) < 3 {
t.Fatalf("expected >= 3 presets, got %d", len(presets))
}
var foundRec bool
for _, p := range presets {
if p.Recommended {
foundRec = true
if p.Resolution != tc.wantRec {
t.Fatalf("recommended preset %q != %q", p.Resolution, tc.wantRec)
}
if p.HiDPI != tc.wantHi {
t.Fatalf("recommended preset HiDPI = %v, want %v", p.HiDPI, tc.wantHi)
}
}
}
if !foundRec {
t.Fatalf("no preset marked recommended")
}
})
}
}
func TestInspectDiskUsageQCOW2(t *testing.T) {
tmp := t.TempDir()
qcow := filepath.Join(tmp, "disk.qcow2")
hdr := make([]byte, 1024)
copy(hdr[0:4], []byte{'Q', 'F', 'I', 0xfb})
binary.BigEndian.PutUint32(hdr[4:8], 3)
const wantVirtual uint64 = 128 << 30
binary.BigEndian.PutUint64(hdr[24:32], wantVirtual)
if err := os.WriteFile(qcow, hdr, 0o644); err != nil {
t.Fatal(err)
}
usage, err := InspectDiskUsage(qcow)
if err != nil {
t.Fatalf("InspectDiskUsage: %v", err)
}
if usage.Format != "qcow2" {
t.Fatalf("Format = %q, want qcow2", usage.Format)
}
if usage.VirtualBytes != wantVirtual {
t.Fatalf("VirtualBytes = %d, want %d", usage.VirtualBytes, wantVirtual)
}
if usage.ActualBytes == 0 {
t.Fatalf("ActualBytes should be non-zero")
}
}
func TestComputeCPUPercentAndSelfSample(t *testing.T) {
t0 := time.Now()
s1 := ProcessSample{PID: 42, CPUDuration: 200 * time.Millisecond, SampledAt: t0}
s2 := ProcessSample{PID: 42, CPUDuration: 600 * time.Millisecond, SampledAt: t0.Add(time.Second)}
pct := ComputeCPUPercent(s1, s2, 8)
if pct < 4.9 || pct > 5.1 {
t.Fatalf("ComputeCPUPercent = %.2f, want ~5.0", pct)
}
if runtime.GOOS == "windows" {
self, err := SampleProcessStats(os.Getpid())
if err != nil {
t.Fatalf("SampleProcessStats(self): %v", err)
}
if self.WorkingSet == 0 {
t.Fatalf("expected non-zero WorkingSet for current process")
}
// Ensure Inspect populates displays cleanly without panicking.
rep := Inspect(t.TempDir())
if rep.RecommendedResolution == "" || len(rep.DisplayPresets) == 0 {
t.Fatalf("Inspect should always populate display presets & recommended resolution")
}
}
}
+132
View File
@@ -0,0 +1,132 @@
//go:build windows
package host
import (
"syscall"
"unsafe"
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procEnumDisplayMonitors = user32.NewProc("EnumDisplayMonitors")
procGetMonitorInfoW = user32.NewProc("GetMonitorInfoW")
procEnumDisplaySettings = user32.NewProc("EnumDisplaySettingsW")
procGetDC = user32.NewProc("GetDC")
procReleaseDC = user32.NewProc("ReleaseDC")
gdi32 = syscall.NewLazyDLL("gdi32.dll")
procGetDeviceCaps = gdi32.NewProc("GetDeviceCaps")
shcore = syscall.NewLazyDLL("shcore.dll")
procGetDpiForMonitor = shcore.NewProc("GetDpiForMonitor")
)
const (
monitorInfoPrimary = 0x00000001
enumCurrentSettings = 0xFFFFFFFF
mdtEffectiveDPI = 0
logPixelsX = 88
)
type winRect struct {
Left, Top, Right, Bottom int32
}
type monitorInfoExW struct {
Size uint32
Monitor winRect
Work winRect
Flags uint32
Device [32]uint16
}
type devModeW struct {
DeviceName [32]uint16
SpecVersion uint16
DriverVersion uint16
Size uint16
DriverExtra uint16
Fields uint32
PositionX int32
PositionY int32
DisplayOrientation uint32
DisplayFixedOutput uint32
Color int16
Duplex int16
YResolution int16
TTOption int16
Collate int16
FormName [32]uint16
LogPixels uint16
BitsPerPel uint32
PelsWidth uint32
PelsHeight uint32
DisplayFlags uint32
DisplayFrequency uint32
Extra [8]uint32
}
func probeDisplays() []DisplayInfo {
var displays []DisplayInfo
cb := syscall.NewCallback(func(hMon uintptr, hdc uintptr, lprc uintptr, data uintptr) uintptr {
var mi monitorInfoExW
mi.Size = uint32(unsafe.Sizeof(mi))
r, _, _ := procGetMonitorInfoW.Call(hMon, uintptr(unsafe.Pointer(&mi)))
if r == 0 {
return 1
}
name := syscall.UTF16ToString(mi.Device[:])
w := int(mi.Monitor.Right - mi.Monitor.Left)
h := int(mi.Monitor.Bottom - mi.Monitor.Top)
refresh := 0
// Query real physical mode dimensions via EnumDisplaySettingsW so DPI
// virtualization never under-reports a 4K/2K display as 1080p.
var dm devModeW
dm.Size = uint16(unsafe.Sizeof(dm))
if ok, _, _ := procEnumDisplaySettings.Call(
uintptr(unsafe.Pointer(&mi.Device[0])),
uintptr(enumCurrentSettings),
uintptr(unsafe.Pointer(&dm)),
); ok != 0 && dm.PelsWidth > 0 && dm.PelsHeight > 0 {
w = int(dm.PelsWidth)
h = int(dm.PelsHeight)
refresh = int(dm.DisplayFrequency)
}
scalePct := 100
if procGetDpiForMonitor.Find() == nil {
var dpiX, dpiY uint32
hr, _, _ := procGetDpiForMonitor.Call(
hMon,
uintptr(mdtEffectiveDPI),
uintptr(unsafe.Pointer(&dpiX)),
uintptr(unsafe.Pointer(&dpiY)),
)
if hr == 0 && dpiX >= 96 {
scalePct = int((dpiX*100 + 48) / 96)
}
} else if hdcScreen, _, _ := procGetDC.Call(0); hdcScreen != 0 {
dpi, _, _ := procGetDeviceCaps.Call(hdcScreen, uintptr(logPixelsX))
procReleaseDC.Call(0, hdcScreen)
if dpi >= 96 {
scalePct = int((dpi*100 + 48) / 96)
}
}
if w > 0 && h > 0 {
displays = append(displays, DisplayInfo{
Name: name,
Width: w,
Height: h,
ScalePct: scalePct,
RefreshHz: refresh,
Primary: mi.Flags&monitorInfoPrimary != 0,
})
}
return 1
})
_, _, _ = procEnumDisplayMonitors.Call(0, 0, cb, 0)
return displays
}
+5
View File
@@ -67,6 +67,11 @@ type Report struct {
NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"`
GPUs []GPUInfo `json:"gpus"`
RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"`
Displays []DisplayInfo `json:"displays,omitempty"`
PrimaryDisplay *DisplayInfo `json:"primary_display,omitempty"`
RecommendedResolution string `json:"recommended_resolution,omitempty"`
DisplayPresets []DisplayPreset `json:"display_presets,omitempty"`
Audio AudioInfo `json:"audio"`
}
// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters.
+9 -5
View File
@@ -9,12 +9,16 @@ import (
// Inspect returns basic host facts on non-Windows dev machines (e.g., macOS).
func Inspect(dataRoot string) Report {
presets, rec := RecommendDisplayPresets(nil)
return Report{
OS: runtime.GOOS,
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
DataRoot: dataRoot,
WHPX: WHPXUnsupported,
OS: runtime.GOOS,
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
DataRoot: dataRoot,
WHPX: WHPXUnsupported,
RecommendedResolution: rec,
DisplayPresets: presets,
Audio: ProbeAudio(),
}
}
+4
View File
@@ -100,6 +100,10 @@ func Inspect(dataRoot string) Report {
rep.FreeDiskGB = freeGB
}
rep.DataRootDriveType = probeDriveType(dataRoot)
rep.Displays = probeDisplays()
rep.PrimaryDisplay = PrimaryDisplayOf(rep.Displays)
rep.DisplayPresets, rep.RecommendedResolution = RecommendDisplayPresets(rep.PrimaryDisplay)
rep.Audio = ProbeAudio()
return rep
}
+197
View File
@@ -0,0 +1,197 @@
package host
import (
"strings"
"sync"
"time"
"unicode/utf16"
)
// IMETarget identifies a running QEMU VM window that should receive remote IME
// / VK_PACKET Unicode text events when focused.
type IMETarget struct {
VMName string
VMDir string
PID uint32
}
type imeCharEvent struct {
target IMETarget
codeUnit uint16
}
// IMECoalescer decodes a stream of Win32 VK_PACKET UTF-16 code units (including
// surrogate pairs for emoji) and groups rapid remote-IME bursts into phrases
// before invoking onFlush.
type IMECoalescer struct {
flushDelay time.Duration
onFlush func(target IMETarget, text string)
ch chan imeCharEvent
stop chan struct{}
done chan struct{}
closeOnce sync.Once
}
const (
defaultIMEFlushDelay = 40 * time.Millisecond
maxIMECoalesceRunes = 128
)
// NewIMECoalescer starts a background coalescer goroutine.
func NewIMECoalescer(flushDelay time.Duration, onFlush func(target IMETarget, text string)) *IMECoalescer {
if flushDelay <= 0 {
flushDelay = defaultIMEFlushDelay
}
c := &IMECoalescer{
flushDelay: flushDelay,
onFlush: onFlush,
ch: make(chan imeCharEvent, 512),
stop: make(chan struct{}),
done: make(chan struct{}),
}
go c.run()
return c
}
// Push enqueues one UTF-16 code unit without blocking the caller (safe to call
// directly from a Windows WH_KEYBOARD_LL hook).
func (c *IMECoalescer) Push(target IMETarget, codeUnit uint16) {
if c == nil || codeUnit == 0 {
return
}
select {
case c.ch <- imeCharEvent{target: target, codeUnit: codeUnit}:
default:
}
}
// Close flushes any pending text and stops the background goroutine.
func (c *IMECoalescer) Close() {
if c == nil {
return
}
c.closeOnce.Do(func() {
close(c.stop)
<-c.done
})
}
func (c *IMECoalescer) run() {
defer close(c.done)
var (
hasTarget bool
curTarget IMETarget
highSurr uint16
buf strings.Builder
runeCount int
timer *time.Timer
timerCh <-chan time.Time
)
stopTimer := func() {
if timer != nil {
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer = nil
timerCh = nil
}
}
resetTimer := func() {
stopTimer()
timer = time.NewTimer(c.flushDelay)
timerCh = timer.C
}
flush := func() {
stopTimer()
highSurr = 0
if !hasTarget || buf.Len() == 0 {
buf.Reset()
runeCount = 0
return
}
text := buf.String()
target := curTarget
buf.Reset()
runeCount = 0
if c.onFlush != nil {
c.onFlush(target, text)
}
}
for {
select {
case <-c.stop:
// Drain any already-queued events before final flush.
for {
select {
case ev := <-c.ch:
c.consume(&hasTarget, &curTarget, &highSurr, &buf, &runeCount, ev, flush)
default:
flush()
return
}
}
case <-timerCh:
flush()
case ev := <-c.ch:
needFlush := c.consume(&hasTarget, &curTarget, &highSurr, &buf, &runeCount, ev, flush)
if needFlush {
flush()
} else if buf.Len() > 0 || highSurr != 0 {
resetTimer()
}
}
}
}
func (c *IMECoalescer) consume(
hasTarget *bool,
curTarget *IMETarget,
highSurr *uint16,
buf *strings.Builder,
runeCount *int,
ev imeCharEvent,
flush func(),
) bool {
if *hasTarget && curTarget.VMName != ev.target.VMName {
flush()
}
*hasTarget = true
*curTarget = ev.target
u := ev.codeUnit
// High surrogate (0xD800..0xDBFF): wait for matching low surrogate.
if u >= 0xD800 && u <= 0xDBFF {
*highSurr = u
return false
}
// Low surrogate (0xDC00..0xDFFF): combine with pending high surrogate.
if u >= 0xDC00 && u <= 0xDFFF {
if *highSurr != 0 {
r := utf16.DecodeRune(rune(*highSurr), rune(u))
*highSurr = 0
if r != 0xFFFD {
buf.WriteRune(r)
*runeCount++
}
}
return *runeCount >= maxIMECoalesceRunes
}
// Normal BMP code unit: clear any orphaned high surrogate.
*highSurr = 0
if u == '\r' {
u = '\n'
}
r := rune(u)
buf.WriteRune(r)
*runeCount++
// Flush immediately on newline or large batch so chat/terminal submits feel instant.
return r == '\n' || *runeCount >= maxIMECoalesceRunes
}
+14
View File
@@ -0,0 +1,14 @@
//go:build !windows
package host
// IMEBridge is a no-op stub on non-Windows hosts.
type IMEBridge struct{}
func StartIMEBridge(onText func(target IMETarget, text string)) (*IMEBridge, error) {
return &IMEBridge{}, nil
}
func (b *IMEBridge) SetTargets(targets []IMETarget) {}
func (b *IMEBridge) SetEnabled(enabled bool) {}
func (b *IMEBridge) Close() {}
+68
View File
@@ -0,0 +1,68 @@
package host
import (
"sync"
"testing"
"time"
"unicode/utf16"
)
func TestIMECoalescerCJKAndEmojiSurrogates(t *testing.T) {
type gotItem struct {
vm string
text string
}
var (
mu sync.Mutex
got []gotItem
done = make(chan struct{}, 4)
)
c := NewIMECoalescer(25*time.Millisecond, func(target IMETarget, text string) {
mu.Lock()
got = append(got, gotItem{vm: target.VMName, text: text})
mu.Unlock()
done <- struct{}{}
})
defer c.Close()
vmA := IMETarget{VMName: "mac-a", PID: 1001}
vmB := IMETarget{VMName: "mac-b", PID: 1002}
// Push Chinese + ASCII + Emoji (surrogate pair) rapidly -> single coalesced phrase.
for _, u := range utf16.Encode([]rune("你好ABC🎉")) {
c.Push(vmA, u)
}
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("timed out waiting for coalesced phrase")
}
// Switching target VM flushes immediately, and '\r' normalizes to '\n' + flushes.
c.Push(vmA, 'x')
c.Push(vmB, 'y')
c.Push(vmB, '\r')
for i := 0; i < 2; i++ {
select {
case <-done:
case <-time.After(time.Second):
t.Fatalf("timed out waiting for flush %d", i+2)
}
}
mu.Lock()
defer mu.Unlock()
if len(got) != 3 {
t.Fatalf("got %d flushes: %+v", len(got), got)
}
if got[0] != (gotItem{vm: "mac-a", text: "你好ABC🎉"}) {
t.Fatalf("flush[0] = %+v", got[0])
}
if got[1] != (gotItem{vm: "mac-a", text: "x"}) {
t.Fatalf("flush[1] = %+v", got[1])
}
if got[2] != (gotItem{vm: "mac-b", text: "y\n"}) {
t.Fatalf("flush[2] = %+v", got[2])
}
}
+211
View File
@@ -0,0 +1,211 @@
//go:build windows
package host
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
var (
procSetWindowsHookExW = user32.NewProc("SetWindowsHookExW")
procUnhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx")
procCallNextHookEx = user32.NewProc("CallNextHookEx")
procGetMessageW = user32.NewProc("GetMessageW")
procPeekMessageW = user32.NewProc("PeekMessageW")
procPostThreadMessageW = user32.NewProc("PostThreadMessageW")
procGetForegroundWindow = user32.NewProc("GetForegroundWindow")
procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId")
imeKernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetModuleHandleW = imeKernel32.NewProc("GetModuleHandleW")
procGetCurrentThreadId = imeKernel32.NewProc("GetCurrentThreadId")
)
const (
whKeyboardLL = 13
hcAction = 0
wmKeyDown = 0x0100
wmKeyUp = 0x0101
wmSysKeyDown = 0x0104
wmSysKeyUp = 0x0105
wmQuit = 0x0012
vkPacket = 0xE7
pmNoRemove = 0x0000
)
type kbdLLHookStruct struct {
vkCode uint32
scanCode uint32
flags uint32
time uint32
dwExtraInfo uintptr
}
type winMsg struct {
hwnd uintptr
message uint32
wParam uintptr
lParam uintptr
time uint32
ptX int32
ptY int32
}
var (
activeIMEBridge atomic.Pointer[IMEBridge]
imeHookCBOnce sync.Once
imeHookCB uintptr
)
func getIMEHookCallback() uintptr {
imeHookCBOnce.Do(func() {
imeHookCB = syscall.NewCallback(imeLowLevelKeyboardProc)
})
return imeHookCB
}
// imeLowLevelKeyboardProc intercepts ONLY VK_PACKET (SendInput KEYEVENTF_UNICODE)
// events targeted at a running Reims-Go QEMU VM window. Physical keyboard events
// return immediately via CallNextHookEx with zero latency or interference.
//
// lParam is declared as the KBDLLHOOKSTRUCT pointer Windows passes, so no
// uintptr-to-pointer conversion is needed (go vet's unsafeptr check).
func imeLowLevelKeyboardProc(nCode int32, wParam uintptr, kbd *kbdLLHookStruct) uintptr {
if nCode == hcAction && kbd != nil && (wParam == wmKeyDown || wParam == wmSysKeyDown || wParam == wmKeyUp || wParam == wmSysKeyUp) {
if kbd.vkCode == vkPacket {
if b := activeIMEBridge.Load(); b != nil && b.enabled.Load() {
if target, ok := b.matchForegroundTarget(); ok {
if wParam == wmKeyDown || wParam == wmSysKeyDown {
b.coalescer.Push(target, uint16(kbd.scanCode))
}
return 1
}
}
}
}
r, _, _ := procCallNextHookEx.Call(0, uintptr(nCode), wParam, uintptr(unsafe.Pointer(kbd)))
return r
}
// IMEBridge listens for Windows VK_PACKET (remote IME / voice / emoji /
// SendInput KEYEVENTF_UNICODE) text directed at running QEMU VM windows.
type IMEBridge struct {
enabled atomic.Bool
targets atomic.Pointer[map[uint32]IMETarget]
coalescer *IMECoalescer
threadID uint32
done chan struct{}
closeOnce sync.Once
}
// StartIMEBridge installs the Windows low-level keyboard hook on a dedicated
// message-pumping OS thread. Only one active bridge is supported per process.
func StartIMEBridge(onText func(target IMETarget, text string)) (*IMEBridge, error) {
b := &IMEBridge{
coalescer: NewIMECoalescer(defaultIMEFlushDelay, onText),
done: make(chan struct{}),
}
b.enabled.Store(true)
empty := make(map[uint32]IMETarget)
b.targets.Store(&empty)
activeIMEBridge.Store(b)
ready := make(chan error, 1)
go b.hookThread(ready)
if err := <-ready; err != nil {
activeIMEBridge.CompareAndSwap(b, nil)
b.coalescer.Close()
return nil, err
}
return b, nil
}
func (b *IMEBridge) hookThread(ready chan<- error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(b.done)
tid, _, _ := procGetCurrentThreadId.Call()
b.threadID = uint32(tid)
// Force creation of this thread's message queue before signalling ready so
// PostThreadMessageW(WM_QUIT) from Close() can never race.
var msg winMsg
_, _, _ = procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove)
hMod, _, _ := procGetModuleHandleW.Call(0)
hhook, _, err := procSetWindowsHookExW.Call(whKeyboardLL, getIMEHookCallback(), hMod, 0)
if hhook == 0 {
ready <- fmt.Errorf("SetWindowsHookExW(WH_KEYBOARD_LL): %w", err)
return
}
defer procUnhookWindowsHookEx.Call(hhook)
ready <- nil
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) <= 0 {
return
}
}
}
// SetTargets atomically replaces the map of active QEMU VM PIDs.
func (b *IMEBridge) SetTargets(targets []IMETarget) {
if b == nil {
return
}
m := make(map[uint32]IMETarget, len(targets))
for _, t := range targets {
if t.PID > 0 {
m[t.PID] = t
}
}
b.targets.Store(&m)
}
// SetEnabled toggles interception without uninstalling the hook.
func (b *IMEBridge) SetEnabled(enabled bool) {
if b == nil {
return
}
b.enabled.Store(enabled)
}
func (b *IMEBridge) matchForegroundTarget() (IMETarget, bool) {
m := b.targets.Load()
if m == nil || len(*m) == 0 {
return IMETarget{}, false
}
hwnd, _, _ := procGetForegroundWindow.Call()
if hwnd == 0 {
return IMETarget{}, false
}
var pid uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
if pid == 0 {
return IMETarget{}, false
}
t, ok := (*m)[pid]
return t, ok
}
// Close removes the Windows keyboard hook and shuts down the coalescer cleanly.
func (b *IMEBridge) Close() {
if b == nil {
return
}
b.closeOnce.Do(func() {
b.enabled.Store(false)
activeIMEBridge.CompareAndSwap(b, nil)
if b.threadID != 0 {
_, _, _ = procPostThreadMessageW.Call(uintptr(b.threadID), wmQuit, 0, 0)
}
<-b.done
b.coalescer.Close()
})
}
+95
View File
@@ -0,0 +1,95 @@
package host
import (
"encoding/binary"
"os"
"time"
)
// ProcessSample is a point-in-time CPU time + memory snapshot for a running process.
type ProcessSample struct {
PID int
CPUDuration time.Duration // kernel + user CPU time accumulated
SampledAt time.Time
WorkingSet uint64 // RSS / working set bytes
PrivateBytes uint64 // private committed bytes
CreatedAt time.Time
}
// DiskUsage reports host-allocated vs virtual logical capacity of a VM disk image.
type DiskUsage struct {
Path string `json:"path,omitempty"`
ActualBytes uint64 `json:"actual_bytes"`
VirtualBytes uint64 `json:"virtual_bytes"`
Format string `json:"format,omitempty"`
}
// ComputeCPUPercent computes host CPU utilization percentage between two samples.
// Returns a value normalized to 0..100 across logicalCPUs (matching Windows Task Manager).
func ComputeCPUPercent(prev, cur ProcessSample, logicalCPUs int) float64 {
if prev.PID == 0 || prev.PID != cur.PID {
return 0
}
wall := cur.SampledAt.Sub(prev.SampledAt)
if wall <= 0 {
return 0
}
cpuDelta := cur.CPUDuration - prev.CPUDuration
if cpuDelta <= 0 {
return 0
}
if logicalCPUs <= 0 {
logicalCPUs = 1
}
pct := (float64(cpuDelta) / float64(wall)) * 100.0 / float64(logicalCPUs)
if pct < 0 {
return 0
}
if pct > 100 {
return 100
}
return pct
}
// InspectDiskUsage returns actual host bytes consumed and virtual logical capacity
// for a .qcow2 or raw disk image without spawning qemu-img.
func InspectDiskUsage(path string) (DiskUsage, error) {
info, err := os.Stat(path)
if err != nil {
return DiskUsage{}, err
}
actual := fileActualSize(path, uint64(info.Size()))
usage := DiskUsage{
Path: path,
ActualBytes: actual,
VirtualBytes: uint64(info.Size()),
Format: "raw",
}
if vSize, ok := readQCOW2VirtualSize(path); ok {
usage.VirtualBytes = vSize
usage.Format = "qcow2"
}
return usage, nil
}
// readQCOW2VirtualSize reads the 8-byte big-endian virtual size from a QCOW2
// header (magic "QFI\xfb", version 2 or 3, size at byte offset 24).
func readQCOW2VirtualSize(path string) (uint64, bool) {
f, err := os.Open(path)
if err != nil {
return 0, false
}
defer f.Close()
var hdr [32]byte
if _, err := f.ReadAt(hdr[:], 0); err != nil {
return 0, false
}
if hdr[0] != 'Q' || hdr[1] != 'F' || hdr[2] != 'I' || hdr[3] != 0xfb {
return 0, false
}
ver := binary.BigEndian.Uint32(hdr[4:8])
if ver < 2 || ver > 3 {
return 0, false
}
return binary.BigEndian.Uint64(hdr[24:32]), true
}
+13
View File
@@ -0,0 +1,13 @@
//go:build !windows
package host
import "fmt"
func SampleProcessStats(pid int) (ProcessSample, error) {
return ProcessSample{}, fmt.Errorf("process stats sampling is only supported on Windows")
}
func fileActualSize(_ string, fallback uint64) uint64 {
return fallback
}
+92
View File
@@ -0,0 +1,92 @@
//go:build windows
package host
import (
"fmt"
"syscall"
"time"
"unsafe"
)
var (
procK32GetProcessMemoryInfo = kernel32.NewProc("K32GetProcessMemoryInfo")
procGetCompressedFileSizeW = kernel32.NewProc("GetCompressedFileSizeW")
)
const (
invalidFileSize = 0xFFFFFFFF
)
type processMemoryCountersEx struct {
CB uint32
PageFaultCount uint32
PeakWorkingSetSize uintptr
WorkingSetSize uintptr
QuotaPeakPagedPoolUsage uintptr
QuotaPagedPoolUsage uintptr
QuotaPeakNonPagedPoolUsage uintptr
QuotaNonPagedPoolUsage uintptr
PagefileUsage uintptr
PeakPagefileUsage uintptr
PrivateUsage uintptr
}
// SampleProcessStats queries CPU time and memory usage for pid using native Win32 APIs.
func SampleProcessStats(pid int) (ProcessSample, error) {
if pid <= 0 {
return ProcessSample{}, fmt.Errorf("invalid pid %d", pid)
}
h, _, err := procOpenProcess.Call(uintptr(processQueryLimitedInfo), 0, uintptr(pid))
if h == 0 {
return ProcessSample{}, fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
now := time.Now()
sample := ProcessSample{
PID: pid,
SampledAt: now,
}
var createFT, exitFT, kernelFT, userFT syscall.Filetime
if r, _, _ := procGetProcessTimes.Call(
h,
uintptr(unsafe.Pointer(&createFT)),
uintptr(unsafe.Pointer(&exitFT)),
uintptr(unsafe.Pointer(&kernelFT)),
uintptr(unsafe.Pointer(&userFT)),
); r != 0 {
k100ns := int64(kernelFT.HighDateTime)<<32 | int64(kernelFT.LowDateTime)
u100ns := int64(userFT.HighDateTime)<<32 | int64(userFT.LowDateTime)
sample.CPUDuration = time.Duration(k100ns+u100ns) * 100 * time.Nanosecond
if createFT.HighDateTime != 0 || createFT.LowDateTime != 0 {
sample.CreatedAt = time.Unix(0, createFT.Nanoseconds())
}
}
var pmc processMemoryCountersEx
pmc.CB = uint32(unsafe.Sizeof(pmc))
if r, _, _ := procK32GetProcessMemoryInfo.Call(
h,
uintptr(unsafe.Pointer(&pmc)),
uintptr(pmc.CB),
); r != 0 {
sample.WorkingSet = uint64(pmc.WorkingSetSize)
sample.PrivateBytes = uint64(pmc.PrivateUsage)
}
return sample, nil
}
func fileActualSize(path string, fallback uint64) uint64 {
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return fallback
}
var high uint32
low, _, err := procGetCompressedFileSizeW.Call(uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&high)))
if low == invalidFileSize && err != syscall.Errno(0) {
return fallback
}
return (uint64(high) << 32) | uint64(low)
}
+2 -2
View File
@@ -73,7 +73,7 @@ var catalog = map[Locale]map[string]string{
"installer.cached.empty": "还没有下载任何安装包。",
"installer.cached.total": "共 %s,位于 %s",
"installer.partial": "(未下载完)",
"runtime.remote.empty": "当前通道还没有发布运行时(候选版需要加 --candidate)。",
"runtime.remote.empty": "当前通道还没有发布运行时(alpha 版需要加 --alpha)。",
"runtime.remote.downloading": "下载运行时 %s(%s,%s)",
"runtime.remote.paused": "已暂停。再次运行同一命令会从中断处继续。",
},
@@ -112,7 +112,7 @@ var catalog = map[Locale]map[string]string{
"installer.cached.empty": "No installers downloaded yet.",
"installer.cached.total": "%s in %s",
"installer.partial": "(partly downloaded)",
"runtime.remote.empty": "No runtime is published on this channel yet (add --candidate for candidates).",
"runtime.remote.empty": "No runtime is published on this channel yet (add --alpha for alpha builds).",
"runtime.remote.downloading": "Downloading runtime %s (%s, %s)",
"runtime.remote.paused": "Paused. Run the same command again to continue where it stopped.",
},
-1
View File
@@ -285,7 +285,6 @@ type pbzxReader struct {
src io.Reader
started bool
cur io.Reader
curLeft int64
}
func newPBZXReader(src io.Reader) *pbzxReader {
+745
View File
@@ -0,0 +1,745 @@
package opencore
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"unicode/utf16"
)
const (
sectorSize = 512
maxReadBytes = 16 << 20 // 16 MiB safety cap matching upstream reims-ctl
qcow2Mask = 0x00fffffffffffe00
qcow2Copied = uint64(1) << 63
qcow2Compress = uint64(1) << 62
fatEOC = uint32(0x0ffffff8)
)
var (
gptESPTypeGUID = [16]byte{
0x28, 0x73, 0x2a, 0xc1, 0x1f, 0xf8, 0xd2, 0x11,
0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b,
}
errNeedsConvertFallback = errors.New("in-place qcow2 write requires qemu-img convert fallback")
)
type diskIO interface {
Size() uint64
ReadAt(off uint64, buf []byte) error
WriteAt(off uint64, data []byte) error
Close() error
}
type rawDisk struct {
f *os.File
size uint64
}
func (r *rawDisk) Size() uint64 { return r.size }
func (r *rawDisk) ReadAt(off uint64, buf []byte) error {
if off+uint64(len(buf)) > r.size {
return fmt.Errorf("raw read past end (%d + %d > %d)", off, len(buf), r.size)
}
_, err := r.f.ReadAt(buf, int64(off))
return err
}
func (r *rawDisk) WriteAt(off uint64, data []byte) error {
if off+uint64(len(data)) > r.size {
return fmt.Errorf("raw write past end (%d + %d > %d)", off, len(data), r.size)
}
_, err := r.f.WriteAt(data, int64(off))
return err
}
func (r *rawDisk) Close() error { return r.f.Close() }
type qcow2Disk struct {
f *os.File
clusterBits uint32
size uint64
l1 []uint64
}
func openQcow2(f *os.File) (*qcow2Disk, error) {
var h [48]byte
if _, err := f.ReadAt(h[:], 0); err != nil {
return nil, err
}
if string(h[:4]) != "QFI\xfb" {
return nil, fmt.Errorf("not a qcow2 image")
}
if binary.BigEndian.Uint64(h[8:16]) != 0 {
return nil, fmt.Errorf("qcow2 image has a backing file")
}
ver := binary.BigEndian.Uint32(h[4:8])
if ver >= 3 {
var feat [8]byte
if _, err := f.ReadAt(feat[:], 72); err != nil {
return nil, err
}
if binary.BigEndian.Uint64(feat[:])&((1<<2)|(1<<4)) != 0 {
return nil, fmt.Errorf("unsupported qcow2 incompatible features (external data file or extended L2)")
}
}
cbits := binary.BigEndian.Uint32(h[20:24])
if cbits < 9 || cbits > 21 {
return nil, fmt.Errorf("unsupported qcow2 cluster_bits=%d", cbits)
}
l1Size := binary.BigEndian.Uint32(h[36:40])
if l1Size > 1<<20 {
l1Size = 1 << 20
}
l1Off := binary.BigEndian.Uint64(h[40:48])
l1Bytes := make([]byte, int(l1Size)*8)
if _, err := f.ReadAt(l1Bytes, int64(l1Off)); err != nil {
return nil, err
}
l1 := make([]uint64, l1Size)
for i := range l1 {
l1[i] = binary.BigEndian.Uint64(l1Bytes[i*8 : i*8+8])
}
return &qcow2Disk{
f: f,
clusterBits: cbits,
size: binary.BigEndian.Uint64(h[24:32]),
l1: l1,
}, nil
}
func (q *qcow2Disk) Size() uint64 { return q.size }
func (q *qcow2Disk) lookupCluster(idx uint64) (hostOff uint64, allocated bool, writable bool, err error) {
perTable := uint64(1) << (q.clusterBits - 3)
l1Idx := idx / perTable
if l1Idx >= uint64(len(q.l1)) {
return 0, false, false, nil
}
l1e := q.l1[l1Idx]
if l1e&qcow2Mask == 0 {
return 0, false, false, nil
}
var ebuf [8]byte
if _, err := q.f.ReadAt(ebuf[:], int64((l1e&qcow2Mask)+(idx%perTable)*8)); err != nil {
return 0, false, false, err
}
e := binary.BigEndian.Uint64(ebuf[:])
if e&qcow2Compress != 0 {
return 0, false, false, fmt.Errorf("compressed qcow2 cluster: %w", errNeedsConvertFallback)
}
off := e & qcow2Mask
if e&1 != 0 || off == 0 {
return 0, false, false, nil
}
// Only write in-place when both L1 and L2 entries have QCOW_OFLAG_COPIED
// (refcount == 1, no internal snapshot sharing).
canWrite := (l1e&qcow2Copied != 0) && (e&qcow2Copied != 0)
return off, true, canWrite, nil
}
func (q *qcow2Disk) ReadAt(off uint64, buf []byte) error {
if off+uint64(len(buf)) > q.size {
return fmt.Errorf("qcow2 read past end (%d + %d > %d)", off, len(buf), q.size)
}
csize := uint64(1) << q.clusterBits
done := 0
for done < len(buf) {
at := off + uint64(done)
within := at & (csize - 1)
n := int(csize - within)
if rem := len(buf) - done; n > rem {
n = rem
}
hostOff, alloc, _, err := q.lookupCluster(at >> q.clusterBits)
if err != nil {
return err
}
if alloc {
if _, err := q.f.ReadAt(buf[done:done+n], int64(hostOff+within)); err != nil {
return err
}
} else {
clear(buf[done : done+n])
}
done += n
}
return nil
}
func (q *qcow2Disk) WriteAt(off uint64, data []byte) error {
if off+uint64(len(data)) > q.size {
return fmt.Errorf("qcow2 write past end (%d + %d > %d)", off, len(data), q.size)
}
csize := uint64(1) << q.clusterBits
// Pre-validate every touched cluster before writing anything so partial writes never happen.
type span struct {
hostOff int64
slice []byte
}
var spans []span
done := 0
for done < len(data) {
at := off + uint64(done)
within := at & (csize - 1)
n := int(csize - within)
if rem := len(data) - done; n > rem {
n = rem
}
hostOff, alloc, writable, err := q.lookupCluster(at >> q.clusterBits)
if err != nil {
return err
}
if !alloc || !writable {
return fmt.Errorf("qcow2 cluster at 0x%x not directly writable: %w", at, errNeedsConvertFallback)
}
spans = append(spans, span{hostOff: int64(hostOff + within), slice: data[done : done+n]})
done += n
}
for _, s := range spans {
if _, err := q.f.WriteAt(s.slice, s.hostOff); err != nil {
return err
}
}
return nil
}
func (q *qcow2Disk) Close() error { return q.f.Close() }
func openDisk(path string, rw bool) (diskIO, bool, error) {
flag := os.O_RDONLY
if rw {
flag = os.O_RDWR
}
f, err := os.OpenFile(path, flag, 0)
if err != nil {
return nil, false, err
}
var magic [4]byte
if _, err := f.ReadAt(magic[:], 0); err != nil {
_ = f.Close()
return nil, false, err
}
if string(magic[:]) == "QFI\xfb" {
q, err := openQcow2(f)
if err != nil {
_ = f.Close()
return nil, true, err
}
return q, true, nil
}
info, err := f.Stat()
if err != nil {
_ = f.Close()
return nil, false, err
}
return &rawDisk{f: f, size: uint64(info.Size())}, false, nil
}
func findESPStart(d diskIO) (uint64, error) {
var hdr [sectorSize]byte
if err := d.ReadAt(sectorSize, hdr[:]); err != nil {
return 0, err
}
if string(hdr[:8]) != "EFI PART" {
return 0, fmt.Errorf("image has no GPT header")
}
partLBA := binary.LittleEndian.Uint64(hdr[72:80])
partCount := binary.LittleEndian.Uint32(hdr[80:84])
entrySize := binary.LittleEndian.Uint32(hdr[84:88])
if entrySize < 128 || entrySize > 4096 {
return 0, fmt.Errorf("invalid GPT entry size %d", entrySize)
}
if partCount > 128 {
partCount = 128
}
table := make([]byte, uint64(partCount)*uint64(entrySize))
if err := d.ReadAt(partLBA*sectorSize, table); err != nil {
return 0, err
}
for i := uint32(0); i < partCount; i++ {
e := table[uint64(i)*uint64(entrySize) : uint64(i+1)*uint64(entrySize)]
if bytes.Equal(e[:16], gptESPTypeGUID[:]) {
firstLBA := binary.LittleEndian.Uint64(e[32:40])
return firstLBA * sectorSize, nil
}
}
return 0, fmt.Errorf("GPT has no EFI System Partition")
}
type fat32FS struct {
disk diskIO
fatOffset uint64
numFATs uint64
fatBytes uint64
dataOffset uint64
clusterSize uint64
rootCluster uint32
maxCluster uint32
}
type fatEntry struct {
name string
firstCluster uint32
size uint32
dirEntryOff uint64 // byte offset on disk of this 32-byte short directory entry
}
func openFAT32(d diskIO, espStart uint64) (*fat32FS, error) {
var bpb [sectorSize]byte
if err := d.ReadAt(espStart, bpb[:]); err != nil {
return nil, err
}
bps := uint64(binary.LittleEndian.Uint16(bpb[11:13]))
spc := uint64(bpb[13])
reserved := uint64(binary.LittleEndian.Uint16(bpb[14:16]))
numFATs := uint64(bpb[16])
fat16Sectors := binary.LittleEndian.Uint16(bpb[22:24])
fat32Sectors := uint64(binary.LittleEndian.Uint32(bpb[36:40]))
totalSectors := uint64(binary.LittleEndian.Uint32(bpb[32:36]))
if totalSectors == 0 {
totalSectors = uint64(binary.LittleEndian.Uint16(bpb[19:21]))
}
if bpb[510] != 0x55 || bpb[511] != 0xaa || fat16Sectors != 0 || fat32Sectors == 0 {
return nil, fmt.Errorf("EFI System Partition is not FAT32")
}
if bps < 512 || spc == 0 || numFATs == 0 {
return nil, fmt.Errorf("invalid FAT32 geometry")
}
dataSectors := uint64(0)
metaSectors := reserved + numFATs*fat32Sectors
if totalSectors > metaSectors {
dataSectors = totalSectors - metaSectors
}
maxCluster := uint32(2 + dataSectors/spc - 1)
if fatEntries := uint32((fat32Sectors * bps) / 4); fatEntries > 2 && maxCluster >= fatEntries {
maxCluster = fatEntries - 1
}
return &fat32FS{
disk: d,
fatOffset: espStart + reserved*bps,
numFATs: numFATs,
fatBytes: fat32Sectors * bps,
dataOffset: espStart + metaSectors*bps,
clusterSize: spc * bps,
rootCluster: binary.LittleEndian.Uint32(bpb[44:48]),
maxCluster: maxCluster,
}, nil
}
func (f *fat32FS) clusterOffset(c uint32) uint64 {
return f.dataOffset + uint64(c-2)*f.clusterSize
}
func (f *fat32FS) readFAT(c uint32) (uint32, error) {
var b [4]byte
if err := f.disk.ReadAt(f.fatOffset+uint64(c)*4, b[:]); err != nil {
return 0, err
}
return binary.LittleEndian.Uint32(b[:]) & 0x0fffffff, nil
}
func (f *fat32FS) writeFAT(c uint32, val uint32) error {
var cur [4]byte
if err := f.disk.ReadAt(f.fatOffset+uint64(c)*4, cur[:]); err != nil {
return err
}
preservedTop := binary.LittleEndian.Uint32(cur[:]) & 0xf0000000
var out [4]byte
binary.LittleEndian.PutUint32(out[:], preservedTop|(val&0x0fffffff))
for i := uint64(0); i < f.numFATs; i++ {
if err := f.disk.WriteAt(f.fatOffset+i*f.fatBytes+uint64(c)*4, out[:]); err != nil {
return err
}
}
return nil
}
func (f *fat32FS) clusterChain(first uint32) ([]uint32, error) {
var chain []uint32
seen := make(map[uint32]bool)
c := first
maxClusters := int(maxReadBytes/f.clusterSize) + 2
for c >= 2 && c < fatEOC && len(chain) < maxClusters {
if seen[c] {
return nil, fmt.Errorf("FAT32 cluster loop at %d", c)
}
seen[c] = true
chain = append(chain, c)
next, err := f.readFAT(c)
if err != nil {
return nil, err
}
c = next
}
return chain, nil
}
func decodeLFNPart(entry []byte) []uint16 {
u := make([]uint16, 0, 13)
for _, off := range []int{1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30} {
v := binary.LittleEndian.Uint16(entry[off : off+2])
if v == 0x0000 || v == 0xffff {
break
}
u = append(u, v)
}
return u
}
func decodeShortName(entry []byte) string {
base := strings.TrimRight(string(entry[0:8]), " ")
ext := strings.TrimRight(string(entry[8:11]), " ")
if ext != "" {
return base + "." + ext
}
return base
}
func (f *fat32FS) findInDir(dirCluster uint32, want string) (*fatEntry, error) {
chain, err := f.clusterChain(dirCluster)
if err != nil {
return nil, err
}
buf := make([]byte, f.clusterSize)
var lfnParts [][]uint16
for _, c := range chain {
cOff := f.clusterOffset(c)
if err := f.disk.ReadAt(cOff, buf); err != nil {
return nil, err
}
for pos := 0; pos+32 <= len(buf); pos += 32 {
e := buf[pos : pos+32]
if e[0] == 0x00 {
return nil, nil
}
if e[0] == 0xe5 {
lfnParts = nil
continue
}
attr := e[11]
if attr == 0x0f {
lfnParts = append(lfnParts, decodeLFNPart(e))
continue
}
if attr&0x08 != 0 { // volume label
lfnParts = nil
continue
}
shortName := decodeShortName(e)
longName := ""
if len(lfnParts) > 0 {
var all []uint16
for i := len(lfnParts) - 1; i >= 0; i-- {
all = append(all, lfnParts[i]...)
}
longName = string(utf16.Decode(all))
lfnParts = nil
}
if strings.EqualFold(longName, want) || strings.EqualFold(shortName, want) {
cl := (uint32(binary.LittleEndian.Uint16(e[20:22])) << 16) | uint32(binary.LittleEndian.Uint16(e[26:28]))
sz := binary.LittleEndian.Uint32(e[28:32])
name := longName
if name == "" {
name = shortName
}
return &fatEntry{
name: name,
firstCluster: cl,
size: sz,
dirEntryOff: cOff + uint64(pos),
}, nil
}
}
}
return nil, nil
}
func (f *fat32FS) findPath(path string) (*fatEntry, error) {
parts := strings.Split(strings.Trim(path, "/"), "/")
cur := f.rootCluster
for i, part := range parts {
e, err := f.findInDir(cur, part)
if err != nil {
return nil, err
}
if e == nil {
return nil, nil
}
if i == len(parts)-1 {
return e, nil
}
cur = e.firstCluster
}
return nil, nil
}
func (f *fat32FS) readFile(path string) ([]byte, *fatEntry, error) {
e, err := f.findPath(path)
if err != nil {
return nil, nil, err
}
if e == nil {
return nil, nil, fmt.Errorf("%s not found on EFI partition", path)
}
if uint64(e.size) > maxReadBytes {
return nil, nil, fmt.Errorf("%s is too large (%d bytes)", path, e.size)
}
chain, err := f.clusterChain(e.firstCluster)
if err != nil {
return nil, nil, err
}
out := make([]byte, 0, e.size)
buf := make([]byte, f.clusterSize)
rem := uint64(e.size)
for _, c := range chain {
if rem == 0 {
break
}
if err := f.disk.ReadAt(f.clusterOffset(c), buf); err != nil {
return nil, nil, err
}
take := f.clusterSize
if take > rem {
take = rem
}
out = append(out, buf[:take]...)
rem -= take
}
if uint32(len(out)) != e.size {
return nil, nil, fmt.Errorf("%s truncated (%d != %d)", path, len(out), e.size)
}
return out, e, nil
}
func (f *fat32FS) findFreeCluster(after uint32) (uint32, error) {
start := after + 1
if start < 2 || start > f.maxCluster {
start = 2
}
for c := start; c <= f.maxCluster; c++ {
v, err := f.readFAT(c)
if err != nil {
return 0, err
}
if v == 0 {
return c, nil
}
}
for c := uint32(2); c < start; c++ {
v, err := f.readFAT(c)
if err != nil {
return 0, err
}
if v == 0 {
return c, nil
}
}
return 0, fmt.Errorf("no free FAT32 clusters on EFI partition")
}
func (f *fat32FS) writeFile(e *fatEntry, data []byte, allowAlloc bool) error {
chain, err := f.clusterChain(e.firstCluster)
if err != nil {
return err
}
needed := (uint64(len(data)) + f.clusterSize - 1) / f.clusterSize
if needed == 0 {
needed = 1
}
if needed > uint64(len(chain)) {
if !allowAlloc {
return fmt.Errorf("config.plist grew past existing cluster chain (%d > %d clusters): %w", needed, len(chain), errNeedsConvertFallback)
}
last := chain[len(chain)-1]
for uint64(len(chain)) < needed {
nextC, err := f.findFreeCluster(last)
if err != nil {
return err
}
if err := f.writeFAT(last, nextC); err != nil {
return err
}
if err := f.writeFAT(nextC, 0x0fffffff); err != nil {
return err
}
chain = append(chain, nextC)
last = nextC
}
}
// Write payload across clusters, zero-padding the slack in the final cluster.
cBuf := make([]byte, f.clusterSize)
for i := uint64(0); i < needed; i++ {
start := i * f.clusterSize
end := start + f.clusterSize
if end > uint64(len(data)) {
end = uint64(len(data))
}
clear(cBuf)
copy(cBuf, data[start:end])
if err := f.disk.WriteAt(f.clusterOffset(chain[i]), cBuf); err != nil {
return err
}
}
// If the file shrank to fewer clusters, free the trailing clusters when allocating is allowed.
if allowAlloc && uint64(len(chain)) > needed {
if err := f.writeFAT(chain[needed-1], 0x0fffffff); err != nil {
return err
}
for i := needed; i < uint64(len(chain)); i++ {
if err := f.writeFAT(chain[i], 0); err != nil {
return err
}
}
}
// Update 4-byte file size in the 32-byte FAT32 directory entry.
var szBuf [4]byte
binary.LittleEndian.PutUint32(szBuf[:], uint32(len(data)))
return f.disk.WriteAt(e.dirEntryOff+28, szBuf[:])
}
// ReadConfigPlist reads EFI/OC/config.plist from an OpenCore qcow2 or raw image.
func ReadConfigPlist(imagePath string) ([]byte, error) {
d, _, err := openDisk(imagePath, false)
if err != nil {
return nil, err
}
defer d.Close()
esp, err := findESPStart(d)
if err != nil {
return nil, err
}
fs, err := openFAT32(d, esp)
if err != nil {
return nil, err
}
data, _, err := fs.readFile("EFI/OC/config.plist")
return data, err
}
// ReadImagePrevLang reads the current NVRAM prev-lang:kbd from an OpenCore image.
func ReadImagePrevLang(imagePath string) (string, error) {
cfg, err := ReadConfigPlist(imagePath)
if err != nil {
return "", err
}
lang, ok := ReadPrevLang(cfg)
if !ok {
return "", nil
}
return lang, nil
}
func patchImageDirect(imagePath, lang string) (changed bool, err error) {
d, isQcow2, err := openDisk(imagePath, true)
if err != nil {
return false, err
}
defer d.Close()
esp, err := findESPStart(d)
if err != nil {
return false, err
}
fs, err := openFAT32(d, esp)
if err != nil {
return false, err
}
orig, entry, err := fs.readFile("EFI/OC/config.plist")
if err != nil {
return false, err
}
if cur, ok := ReadPrevLang(orig); ok && cur == lang {
return false, nil
}
patched, err := PatchPrevLang(orig, lang)
if err != nil {
return false, err
}
if err := fs.writeFile(entry, patched, !isQcow2); err != nil {
return false, err
}
return true, nil
}
// PatchImagePrevLang updates NVRAM > Add > 7C436110-... > prev-lang:kbd inside
// imagePath (opencore.qcow2 or opencore.img). Fast in-place pure-Go patching is
// used whenever clusters are directly writable; if a qcow2 image needs cluster
// allocation or decompression and qemuImgPath is provided, it safely falls back
// to an atomic qemu-img raw round-trip.
func PatchImagePrevLang(ctx context.Context, imagePath, lang, qemuImgPath string, env []string) (bool, error) {
norm, err := NormalizeGuestLang(lang)
if err != nil {
return false, err
}
if norm == "" {
return false, nil
}
changed, err := patchImageDirect(imagePath, norm)
if err == nil {
return changed, nil
}
if !errors.Is(err, errNeedsConvertFallback) || strings.TrimSpace(qemuImgPath) == "" {
return false, err
}
return patchQcow2ViaRaw(ctx, imagePath, norm, qemuImgPath, env)
}
func patchQcow2ViaRaw(ctx context.Context, qcow2Path, lang, qemuImgPath string, env []string) (bool, error) {
dir := filepath.Dir(qcow2Path)
rawTmp := filepath.Join(dir, ".opencore-lang-patch.raw.tmp")
qcowTmp := filepath.Join(dir, ".opencore-lang-patch.qcow2.tmp")
defer os.Remove(rawTmp)
defer os.Remove(qcowTmp)
if err := runQemuImg(ctx, qemuImgPath, env, "convert", "-f", "qcow2", "-O", "raw", qcow2Path, rawTmp); err != nil {
return false, fmt.Errorf("convert opencore to raw: %w", err)
}
changed, err := patchImageDirect(rawTmp, lang)
if err != nil {
return false, err
}
if !changed {
return false, nil
}
if err := runQemuImg(ctx, qemuImgPath, env, "convert", "-f", "raw", "-O", "qcow2", rawTmp, qcowTmp); err != nil {
return false, fmt.Errorf("convert patched opencore back to qcow2: %w", err)
}
if err := os.Rename(qcowTmp, qcow2Path); err != nil {
// On Windows os.Rename fails if destination already exists; swap via backup.
bak := qcow2Path + ".lang.bak"
_ = os.Remove(bak)
if berr := os.Rename(qcow2Path, bak); berr != nil {
return false, fmt.Errorf("replace opencore image: %w", berr)
}
if rerr := os.Rename(qcowTmp, qcow2Path); rerr != nil {
_ = os.Rename(bak, qcow2Path)
return false, fmt.Errorf("replace opencore image: %w", rerr)
}
_ = os.Remove(bak)
}
return true, nil
}
func runQemuImg(ctx context.Context, qemuImgPath string, env []string, args ...string) error {
cmd := exec.CommandContext(ctx, qemuImgPath, args...)
configureCmd(cmd)
if len(env) > 0 {
cmd.Env = env
}
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("qemu-img %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return nil
}
+112
View File
@@ -0,0 +1,112 @@
package opencore
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
)
const (
// GuestLangSidecarFile stores the user's chosen OpenCore prev-lang:kbd value
// inside the VM directory so `update-opencore` rebuilds can replay it.
GuestLangSidecarFile = ".reims-go-guest-lang"
)
// Preset describes a selectable macOS boot/recovery language (`prev-lang:kbd`).
type Preset struct {
Value string `json:"value"`
LabelZH string `json:"label_zh"`
LabelEN string `json:"label_en"`
}
// Presets returns the built-in macOS prev-lang:kbd choices.
// `:0` pairs the locale with the standard US keyboard layout so terminal
// commands in macOS Recovery / Setup Assistant stay predictable; `:252` uses
// OpenCore's Pinyin layout ID.
func Presets() []Preset {
return []Preset{
{Value: "zh-Hans:0", LabelZH: "简体中文(美式键盘,推荐)", LabelEN: "Simplified Chinese (US Keyboard)"},
{Value: "zh-Hans:252", LabelZH: "简体中文(拼音键盘)", LabelEN: "Simplified Chinese (Pinyin)"},
{Value: "zh-Hant:0", LabelZH: "繁體中文(美式键盘)", LabelEN: "Traditional Chinese (US Keyboard)"},
{Value: "en-US:0", LabelZH: "English (US)", LabelEN: "English (US)"},
{Value: "ja-JP:0", LabelZH: "日本語(美式键盘)", LabelEN: "Japanese (US Keyboard)"},
{Value: "ko-KR:0", LabelZH: "한국어(美式键盘)", LabelEN: "Korean (US Keyboard)"},
}
}
// DefaultGuestLang chooses the default macOS prev-lang:kbd matching the app UI locale.
func DefaultGuestLang(locale i18n.Locale) string {
if locale == i18n.EnUS {
return "en-US:0"
}
return "zh-Hans:0"
}
var reGuestLang = regexp.MustCompile(`^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}:[0-9]{1,6}$`)
// NormalizeGuestLang validates and normalizes a prev-lang:kbd string.
// An empty input returns ("", nil), meaning "unspecified / keep existing".
func NormalizeGuestLang(raw string) (string, error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", nil
}
if !reGuestLang.MatchString(s) {
return "", fmt.Errorf("invalid macOS language code %q (expected format like zh-Hans:0 or en-US:0)", raw)
}
return s, nil
}
// ReadSavedGuestLang reads the persisted prev-lang:kbd preference from vmDir.
func ReadSavedGuestLang(vmDir string) string {
if vmDir == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(vmDir, GuestLangSidecarFile))
if err != nil {
return ""
}
norm, err := NormalizeGuestLang(string(b))
if err != nil {
return ""
}
return norm
}
// WriteSavedGuestLang saves (or clears when empty) the VM's prev-lang:kbd preference.
func WriteSavedGuestLang(vmDir, lang string) error {
if vmDir == "" {
return fmt.Errorf("vm directory is empty")
}
norm, err := NormalizeGuestLang(lang)
if err != nil {
return err
}
p := filepath.Join(vmDir, GuestLangSidecarFile)
if norm == "" {
if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
return os.WriteFile(p, []byte(norm+"\n"), 0o644)
}
// ResolveOpenCorePath returns the OpenCore image path inside vmDir (preferring
// opencore.qcow2, falling back to opencore.img), or "" if neither exists.
func ResolveOpenCorePath(vmDir string) string {
if vmDir == "" {
return ""
}
for _, name := range []string{"opencore.qcow2", "opencore.img"} {
p := filepath.Join(vmDir, name)
if info, err := os.Stat(p); err == nil && !info.IsDir() {
return p
}
}
return ""
}
+417
View File
@@ -0,0 +1,417 @@
package opencore
import (
"bytes"
"context"
"encoding/binary"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/i18n"
)
const sampleConfigPlist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NVRAM</key>
<dict>
<key>Add</key>
<dict>
<key>4D1EDE05-38C7-4A6A-9CC6-4BCCA8B38C14</key>
<dict>
<key>DefaultBackgroundColor</key>
<data>
AAAAAA==
</data>
</dict>
<key>7C436110-AB2A-4BBB-A880-FE41995C9F82</key>
<dict>
<key>#INFO (prev-lang:kbd)</key>
<string>en:252 (ABC), set 656e3a323532</string>
<key>boot-args</key>
<string>keepsyms=1 tlbto_us=0 vti=9</string>
<key>csr-active-config</key>
<data>
AAAAAA==
</data>
<key>prev-lang:kbd</key>
<data>
ZW4tVVM6MA==
</data>
<key>run-efi-updater</key>
<string>No</string>
</dict>
</dict>
<key>Delete</key>
<dict>
<key>7C436110-AB2A-4BBB-A880-FE41995C9F82</key>
<array>
<string>boot-args</string>
<string>csr-active-config</string>
<string>prev-lang:kbd</string>
</array>
</dict>
</dict>
<key>PlatformInfo</key>
<dict>
<key>Generic</key>
<dict>
<key>SystemProductName</key>
<string>iMac20,1</string>
</dict>
</dict>
</dict>
</plist>
`
func TestNormalizeAndDefaultGuestLang(t *testing.T) {
if got := DefaultGuestLang(i18n.ZhCN); got != "zh-Hans:0" {
t.Fatalf("DefaultGuestLang(zh-CN) = %q, want zh-Hans:0", got)
}
if got := DefaultGuestLang(i18n.EnUS); got != "en-US:0" {
t.Fatalf("DefaultGuestLang(en-US) = %q, want en-US:0", got)
}
for _, valid := range []string{"", "zh-Hans:0", "zh-Hans:252", "zh-Hant:0", "en-US:0", "ja-JP:0", " ko-KR:0 "} {
if _, err := NormalizeGuestLang(valid); err != nil {
t.Fatalf("NormalizeGuestLang(%q) unexpected err: %v", valid, err)
}
}
for _, bad := range []string{"zh-Hans", "en_US:0", "zh-Hans:abc", "<script>:0", "a:0"} {
if _, err := NormalizeGuestLang(bad); err == nil {
t.Fatalf("NormalizeGuestLang(%q) expected error", bad)
}
}
}
func TestSidecarReadWrite(t *testing.T) {
dir := t.TempDir()
if got := ReadSavedGuestLang(dir); got != "" {
t.Fatalf("empty dir ReadSavedGuestLang = %q, want empty", got)
}
if err := WriteSavedGuestLang(dir, "zh-Hans:0"); err != nil {
t.Fatalf("WriteSavedGuestLang: %v", err)
}
if got := ReadSavedGuestLang(dir); got != "zh-Hans:0" {
t.Fatalf("ReadSavedGuestLang = %q, want zh-Hans:0", got)
}
if err := WriteSavedGuestLang(dir, ""); err != nil {
t.Fatalf("clear WriteSavedGuestLang: %v", err)
}
if got := ReadSavedGuestLang(dir); got != "" {
t.Fatalf("after clear ReadSavedGuestLang = %q, want empty", got)
}
}
func TestReadAndPatchPrevLang(t *testing.T) {
got, ok := ReadPrevLang([]byte(sampleConfigPlist))
if !ok || got != "en-US:0" {
t.Fatalf("ReadPrevLang = (%q, %v), want (en-US:0, true)", got, ok)
}
patched, err := PatchPrevLang([]byte(sampleConfigPlist), "zh-Hans:0")
if err != nil {
t.Fatalf("PatchPrevLang: %v", err)
}
got2, ok2 := ReadPrevLang(patched)
if !ok2 || got2 != "zh-Hans:0" {
t.Fatalf("after patch ReadPrevLang = (%q, %v), want (zh-Hans:0, true)", got2, ok2)
}
// Comment key and unrelated sections must stay intact.
if !strings.Contains(string(patched), "<key>#INFO (prev-lang:kbd)</key>\n\t\t\t\t<string>en:252 (ABC), set 656e3a323532</string>") {
t.Fatalf("#INFO comment key was unexpectedly altered")
}
if !strings.Contains(string(patched), "<string>iMac20,1</string>") {
t.Fatalf("PlatformInfo was unexpectedly altered")
}
// Patch to a longer code (zh-Hans:252) and back.
patched2, err := PatchPrevLang(patched, "zh-Hans:252")
if err != nil {
t.Fatalf("PatchPrevLang(zh-Hans:252): %v", err)
}
if got3, ok3 := ReadPrevLang(patched2); !ok3 || got3 != "zh-Hans:252" {
t.Fatalf("after second patch ReadPrevLang = (%q, %v), want (zh-Hans:252, true)", got3, ok3)
}
}
func TestPatchPrevLangMissingKeyAndDelete(t *testing.T) {
src := `<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>NVRAM</key>
<dict>
<key>Add</key>
<dict>
<key>7C436110-AB2A-4BBB-A880-FE41995C9F82</key>
<dict>
<key>boot-args</key>
<string>keepsyms=1</string>
</dict>
</dict>
<key>Delete</key>
<dict>
<key>7C436110-AB2A-4BBB-A880-FE41995C9F82</key>
<array>
<string>boot-args</string>
</array>
</dict>
</dict>
</dict>
</plist>
`
patched, err := PatchPrevLang([]byte(src), "zh-Hans:0")
if err != nil {
t.Fatalf("PatchPrevLang missing key: %v", err)
}
if got, ok := ReadPrevLang(patched); !ok || got != "zh-Hans:0" {
t.Fatalf("ReadPrevLang = (%q, %v), want (zh-Hans:0, true)", got, ok)
}
if !strings.Contains(string(patched), "<string>prev-lang:kbd</string>") {
t.Fatalf("expected prev-lang:kbd to be added to NVRAM > Delete array:\n%s", string(patched))
}
}
// buildSyntheticRawOpenCore creates a minimal GPT + FAT32 raw disk image
// containing EFI/OC/config.plist with the provided payload.
func buildSyntheticRawOpenCore(t *testing.T, configPlist []byte) []byte {
t.Helper()
const (
totalSectors = 256
espStartLBA = 34
reservedSec = 2
numFATs = 2
fatSectors = 2
spc = 1 // 512-byte clusters, matching reims-util
rootCluster = 2
efiCluster = 3
ocCluster = 4
cfgCluster = 5
)
img := make([]byte, totalSectors*sectorSize)
// GPT header at LBA 1.
gpt := img[sectorSize : 2*sectorSize]
copy(gpt[:8], "EFI PART")
binary.LittleEndian.PutUint64(gpt[72:80], 2) // partition table LBA
binary.LittleEndian.PutUint32(gpt[80:84], 4) // 4 entries
binary.LittleEndian.PutUint32(gpt[84:88], 128)
// GPT partition entry 0: EFI System Partition at LBA 34.
pe := img[2*sectorSize : 2*sectorSize+128]
copy(pe[:16], gptESPTypeGUID[:])
binary.LittleEndian.PutUint64(pe[32:40], espStartLBA)
binary.LittleEndian.PutUint64(pe[40:48], totalSectors-2)
espOff := espStartLBA * sectorSize
bpb := img[espOff : espOff+sectorSize]
binary.LittleEndian.PutUint16(bpb[11:13], sectorSize)
bpb[13] = spc
binary.LittleEndian.PutUint16(bpb[14:16], reservedSec)
bpb[16] = numFATs
binary.LittleEndian.PutUint32(bpb[32:36], totalSectors-espStartLBA)
binary.LittleEndian.PutUint32(bpb[36:40], fatSectors)
binary.LittleEndian.PutUint32(bpb[44:48], rootCluster)
bpb[510] = 0x55
bpb[511] = 0xaa
fatOff := espOff + reservedSec*sectorSize
dataOff := espOff + (reservedSec+numFATs*fatSectors)*sectorSize
setFAT := func(c, v uint32) {
for f := 0; f < numFATs; f++ {
off := fatOff + f*fatSectors*sectorSize + int(c)*4
binary.LittleEndian.PutUint32(img[off:off+4], v)
}
}
setFAT(0, 0x0ffffff8)
setFAT(1, 0x0fffffff)
setFAT(rootCluster, 0x0fffffff)
setFAT(efiCluster, 0x0fffffff)
setFAT(ocCluster, 0x0fffffff)
clusterOff := func(c uint32) int { return dataOff + int(c-2)*sectorSize }
// Root dir: "EFI" directory entry -> efiCluster.
writeDirEntry := func(dirCluster uint32, slot int, name83 string, attr byte, targetCluster, size uint32) {
e := img[clusterOff(dirCluster)+slot*32 : clusterOff(dirCluster)+(slot+1)*32]
copy(e[:11], name83)
e[11] = attr
binary.LittleEndian.PutUint16(e[20:22], uint16(targetCluster>>16))
binary.LittleEndian.PutUint16(e[26:28], uint16(targetCluster&0xffff))
binary.LittleEndian.PutUint32(e[28:32], size)
}
writeDirEntry(rootCluster, 0, "EFI ", 0x10, efiCluster, 0)
writeDirEntry(efiCluster, 0, "OC ", 0x10, ocCluster, 0)
// Write LFN + short entry for "config.plist" in OC dir.
lfn := img[clusterOff(ocCluster) : clusterOff(ocCluster)+32]
lfn[0] = 0x41 // single LFN entry
lfn[11] = 0x0f
nameRunes := []rune("config.plist")
lfnOffsets := []int{1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30}
for i, off := range lfnOffsets {
var u uint16 = 0xffff
if i < len(nameRunes) {
u = uint16(nameRunes[i])
} else if i == len(nameRunes) {
u = 0x0000
}
binary.LittleEndian.PutUint16(lfn[off:off+2], u)
}
writeDirEntry(ocCluster, 1, "CONFIG~1PLI", 0x20, cfgCluster, uint32(len(configPlist)))
// Write config.plist clusters.
nClusters := (len(configPlist) + sectorSize - 1) / sectorSize
for i := 0; i < nClusters; i++ {
c := uint32(cfgCluster + i)
if i+1 < nClusters {
setFAT(c, c+1)
} else {
setFAT(c, 0x0fffffff)
}
start := i * sectorSize
end := start + sectorSize
if end > len(configPlist) {
end = len(configPlist)
}
copy(img[clusterOff(c):clusterOff(c)+sectorSize], configPlist[start:end])
}
return img
}
// wrapRawAsQcow2 wraps a small raw disk image (<= 1 MiB) into a valid qcow2 v3
// image with 64 KiB uncompressed COPIED clusters for testing in-place qcow2 writes.
func wrapRawAsQcow2(raw []byte) []byte {
const (
cbits = 16
csize = 1 << cbits // 64 KiB
)
numDataClusters := (len(raw) + csize - 1) / csize
// Cluster 0: header; Cluster 1: L1 table; Cluster 2: L2 table; Cluster 3+: data clusters.
out := make([]byte, (3+numDataClusters)*csize)
copy(out[0:4], "QFI\xfb")
binary.BigEndian.PutUint32(out[4:8], 3) // version 3
binary.BigEndian.PutUint32(out[20:24], cbits)
binary.BigEndian.PutUint64(out[24:32], uint64(len(raw)))
binary.BigEndian.PutUint32(out[36:40], 1) // l1_size = 1
binary.BigEndian.PutUint64(out[40:48], csize) // l1_table_offset = cluster 1
binary.BigEndian.PutUint32(out[100:104], 104) // header_length
// L1[0] -> L2 at cluster 2, with COPIED bit set.
binary.BigEndian.PutUint64(out[csize:csize+8], qcow2Copied|uint64(2*csize))
// L2[i] -> data cluster (3 + i), with COPIED bit set.
for i := 0; i < numDataClusters; i++ {
off := 2*csize + i*8
binary.BigEndian.PutUint64(out[off:off+8], qcow2Copied|uint64((3+i)*csize))
start := i * csize
end := start + csize
if end > len(raw) {
end = len(raw)
}
copy(out[(3+i)*csize:(3+i+1)*csize], raw[start:end])
}
return out
}
func TestPatchRawAndQcow2Images(t *testing.T) {
dir := t.TempDir()
rawBytes := buildSyntheticRawOpenCore(t, []byte(sampleConfigPlist))
// 1. Raw image patch (including growing across a 512-byte FAT32 cluster boundary).
rawPath := filepath.Join(dir, "opencore.img")
if err := os.WriteFile(rawPath, rawBytes, 0o644); err != nil {
t.Fatalf("write raw: %v", err)
}
if got, err := ReadImagePrevLang(rawPath); err != nil || got != "en-US:0" {
t.Fatalf("ReadImagePrevLang(raw) = (%q, %v), want (en-US:0, nil)", got, err)
}
changed, err := PatchImagePrevLang(context.Background(), rawPath, "zh-Hans:252", "", nil)
if err != nil || !changed {
t.Fatalf("PatchImagePrevLang(raw) = (%v, %v), want (true, nil)", changed, err)
}
if got, err := ReadImagePrevLang(rawPath); err != nil || got != "zh-Hans:252" {
t.Fatalf("after patch ReadImagePrevLang(raw) = (%q, %v), want (zh-Hans:252, nil)", got, err)
}
// Second patch with same language must be a no-op.
changed2, err := PatchImagePrevLang(context.Background(), rawPath, "zh-Hans:252", "", nil)
if err != nil || changed2 {
t.Fatalf("repeat PatchImagePrevLang(raw) = (%v, %v), want (false, nil)", changed2, err)
}
// 2. Qcow2 v3 in-place patch.
qcowPath := filepath.Join(dir, "opencore.qcow2")
if err := os.WriteFile(qcowPath, wrapRawAsQcow2(rawBytes), 0o644); err != nil {
t.Fatalf("write qcow2: %v", err)
}
if got, err := ReadImagePrevLang(qcowPath); err != nil || got != "en-US:0" {
t.Fatalf("ReadImagePrevLang(qcow2) = (%q, %v), want (en-US:0, nil)", got, err)
}
changedQ, err := PatchImagePrevLang(context.Background(), qcowPath, "zh-Hans:0", "", nil)
if err != nil || !changedQ {
t.Fatalf("PatchImagePrevLang(qcow2) = (%v, %v), want (true, nil)", changedQ, err)
}
if got, err := ReadImagePrevLang(qcowPath); err != nil || got != "zh-Hans:0" {
t.Fatalf("after patch ReadImagePrevLang(qcow2) = (%q, %v), want (zh-Hans:0, nil)", got, err)
}
// Verify raw image grows across cluster boundary cleanly when plist sits near 512B boundary.
padLen := (sectorSize - (len(sampleConfigPlist) % sectorSize)) - 2
if padLen < 0 {
padLen += sectorSize
}
tightPlist := append([]byte(sampleConfigPlist), bytes.Repeat([]byte(" "), padLen)...)
tightPath := filepath.Join(dir, "tight.img")
if err := os.WriteFile(tightPath, buildSyntheticRawOpenCore(t, tightPlist), 0o644); err != nil {
t.Fatalf("write tight raw: %v", err)
}
if changed, err := PatchImagePrevLang(context.Background(), tightPath, "zh-Hans:252", "", nil); err != nil || !changed {
t.Fatalf("PatchImagePrevLang(tight raw growing across cluster) = (%v, %v)", changed, err)
}
if got, err := ReadImagePrevLang(tightPath); err != nil || got != "zh-Hans:252" {
t.Fatalf("after grow ReadImagePrevLang = (%q, %v), want (zh-Hans:252, nil)", got, err)
}
}
func TestPatchRealOpenCoreCopy(t *testing.T) {
src := os.Getenv("REIMS_GO_TEST_OPENCORE")
if src == "" {
t.Skip("set REIMS_GO_TEST_OPENCORE to test against a temporary copy of a real opencore.qcow2")
}
raw, err := os.ReadFile(src)
if err != nil {
t.Fatalf("read %s: %v", src, err)
}
cp := filepath.Join(t.TempDir(), "opencore.qcow2")
if err := os.WriteFile(cp, raw, 0o644); err != nil {
t.Fatalf("write copy: %v", err)
}
origLang, err := ReadImagePrevLang(cp)
if err != nil {
t.Fatalf("ReadImagePrevLang(orig): %v", err)
}
t.Logf("original prev-lang:kbd = %q", origLang)
for _, target := range []string{"zh-Hans:0", "zh-Hans:252", "en-US:0"} {
changed, err := PatchImagePrevLang(context.Background(), cp, target, os.Getenv("REIMS_GO_TEST_QEMU_IMG"), nil)
if err != nil {
t.Fatalf("PatchImagePrevLang(%s): %v", target, err)
}
got, err := ReadImagePrevLang(cp)
if err != nil || got != target {
t.Fatalf("after patch(%s) ReadImagePrevLang = (%q, %v), changed=%v", target, got, err, changed)
}
// Ensure the patched plist still parses as valid XML and preserves PlatformInfo.
cfg, err := ReadConfigPlist(cp)
if err != nil {
t.Fatalf("ReadConfigPlist after %s: %v", target, err)
}
if _, err := parsePlistTree(cfg); err != nil {
t.Fatalf("patched plist invalid XML after %s: %v", target, err)
}
if !strings.Contains(string(cfg), "<key>PlatformInfo</key>") || !strings.Contains(string(cfg), "<key>Kernel</key>") {
t.Fatalf("patched plist missing PlatformInfo/Kernel after %s", target)
}
}
}
+305
View File
@@ -0,0 +1,305 @@
package opencore
import (
"bytes"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"strings"
)
// AppleNVRAMGUID is Apple's boot variable NVRAM GUID where macOS Recovery,
// Setup Assistant, and LoginWindow read `prev-lang:kbd`.
const AppleNVRAMGUID = "7C436110-AB2A-4BBB-A880-FE41995C9F82"
type xmlElem struct {
name string
start int // byte offset of '<name...>'
contentStart int // byte offset right after '>'
contentEnd int // byte offset of '</name>' (or end of self-closing tag)
end int // byte offset right after closing '>'
selfClosing bool
text string
children []*xmlElem
}
// parsePlistTree builds a lightweight byte-offset-preserving tree of XML plist
// elements so we can read and surgically patch specific keys without
// reformatting unrelated sections of OpenCore's config.plist.
func parsePlistTree(src []byte) (*xmlElem, error) {
dec := xml.NewDecoder(bytes.NewReader(src))
var stack []*xmlElem
var root *xmlElem
for {
tokStart := int(dec.InputOffset())
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("parse plist xml: %w", err)
}
tokEnd := int(dec.InputOffset())
switch t := tok.(type) {
case xml.StartElement:
// Advance tokStart past leading whitespace/comments to '<'.
lt := bytes.IndexByte(src[tokStart:tokEnd], '<')
if lt >= 0 {
tokStart += lt
}
el := &xmlElem{
name: t.Name.Local,
start: tokStart,
contentStart: tokEnd,
}
if len(stack) > 0 {
parent := stack[len(stack)-1]
parent.children = append(parent.children, el)
} else {
root = el
}
stack = append(stack, el)
case xml.EndElement:
if len(stack) == 0 {
return nil, fmt.Errorf("unexpected closing tag </%s>", t.Name.Local)
}
el := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// Distinguish self-closing <data/> from <data></data>.
if tokStart == el.contentStart && tokEnd == el.contentStart {
el.selfClosing = true
el.contentEnd = tokEnd
el.end = tokEnd
} else {
closeStart := bytes.LastIndex(src[el.contentStart:tokEnd], []byte("</"))
if closeStart >= 0 {
el.contentEnd = el.contentStart + closeStart
} else {
el.contentEnd = tokStart
}
el.end = tokEnd
}
if el.name == "key" || el.name == "string" || el.name == "data" {
el.text = strings.TrimSpace(string(src[el.contentStart:el.contentEnd]))
}
}
}
if root == nil {
return nil, fmt.Errorf("empty plist")
}
return root, nil
}
func findRootDict(root *xmlElem) *xmlElem {
if root == nil {
return nil
}
if root.name == "dict" {
return root
}
for _, c := range root.children {
if c.name == "dict" {
return c
}
}
return nil
}
func dictLookup(dict *xmlElem, key string) (*xmlElem, *xmlElem) {
if dict == nil || dict.name != "dict" {
return nil, nil
}
for i := 0; i+1 < len(dict.children); i += 2 {
k := dict.children[i]
v := dict.children[i+1]
if k.name == "key" && k.text == key {
return k, v
}
}
return nil, nil
}
func findAppleNVRAMAddDict(root *xmlElem) *xmlElem {
top := findRootDict(root)
_, nvram := dictLookup(top, "NVRAM")
_, add := dictLookup(nvram, "Add")
_, apple := dictLookup(add, AppleNVRAMGUID)
if apple != nil && apple.name == "dict" {
return apple
}
return nil
}
func findAppleNVRAMDeleteArray(root *xmlElem) *xmlElem {
top := findRootDict(root)
_, nvram := dictLookup(top, "NVRAM")
_, del := dictLookup(nvram, "Delete")
_, apple := dictLookup(del, AppleNVRAMGUID)
if apple != nil && apple.name == "array" {
return apple
}
return nil
}
// ReadPrevLang extracts the NVRAM > Add > 7C436110-... > prev-lang:kbd string
// from an OpenCore XML config.plist.
func ReadPrevLang(src []byte) (string, bool) {
root, err := parsePlistTree(src)
if err != nil {
return "", false
}
apple := findAppleNVRAMAddDict(root)
if apple == nil {
return "", false
}
_, val := dictLookup(apple, "prev-lang:kbd")
if val == nil {
return "", false
}
switch val.name {
case "data":
cleaned := strings.Join(strings.Fields(val.text), "")
if cleaned == "" {
return "", false
}
raw, err := base64.StdEncoding.DecodeString(cleaned)
if err != nil {
return "", false
}
return strings.TrimRight(string(raw), "\x00"), true
case "string":
return strings.TrimSpace(val.text), val.text != ""
default:
return "", false
}
}
// lineIndent returns the leading whitespace on the line containing offset.
func lineIndent(src []byte, offset int) string {
if offset > len(src) {
offset = len(src)
}
nl := bytes.LastIndexByte(src[:offset], '\n')
lineStart := nl + 1
i := lineStart
for i < offset && (src[i] == ' ' || src[i] == '\t') {
i++
}
return string(src[lineStart:i])
}
type bytePatch struct {
start int
end int
repl []byte
}
// PatchPrevLang returns a modified copy of an OpenCore XML config.plist with
// NVRAM > Add > 7C436110-... > prev-lang:kbd set to base64(lang) (and ensured
// present in NVRAM > Delete so OpenCore overrides any cached OVMF_VARS value).
func PatchPrevLang(src []byte, lang string) ([]byte, error) {
norm, err := NormalizeGuestLang(lang)
if err != nil {
return nil, err
}
if norm == "" {
return nil, fmt.Errorf("guest language must not be empty")
}
root, err := parsePlistTree(src)
if err != nil {
return nil, err
}
apple := findAppleNVRAMAddDict(root)
if apple == nil {
return nil, fmt.Errorf("config.plist missing NVRAM > Add > %s", AppleNVRAMGUID)
}
b64 := base64.StdEncoding.EncodeToString([]byte(norm))
var patches []bytePatch
if keyEl, valEl := dictLookup(apple, "prev-lang:kbd"); keyEl != nil && valEl != nil {
indent := lineIndent(src, valEl.start)
var repl string
if valEl.name == "data" && bytes.Contains(src[valEl.start:valEl.end], []byte("\n")) {
// Match reims-util's multiline <data>\n\t\t\t\tBASE64\n\t\t\t\t</data> style.
nl := "\n"
if bytes.Contains(src[valEl.start:valEl.end], []byte("\r\n")) {
nl = "\r\n"
}
repl = fmt.Sprintf("<data>%s%s%s%s%s</data>", nl, indent, b64, nl, indent)
} else {
repl = fmt.Sprintf("<data>%s</data>", b64)
}
patches = append(patches, bytePatch{start: valEl.start, end: valEl.end, repl: []byte(repl)})
} else {
// Insert before </dict> of Apple NVRAM Add dict.
closeIndent := lineIndent(src, apple.contentEnd)
entryIndent := closeIndent + "\t"
if len(apple.children) > 0 {
entryIndent = lineIndent(src, apple.children[0].start)
}
nl := "\n"
if bytes.Contains(src, []byte("\r\n")) {
nl = "\r\n"
}
insert := fmt.Sprintf("%s<key>prev-lang:kbd</key>%s%s<data>%s%s%s%s%s</data>%s%s",
entryIndent, nl, entryIndent, nl, entryIndent, b64, nl, entryIndent, nl, closeIndent)
// Insert right at the start of the closing tag line (after the last newline before </dict>).
insertPos := apple.contentEnd
for insertPos > apple.contentStart && (src[insertPos-1] == ' ' || src[insertPos-1] == '\t') {
insertPos--
}
patches = append(patches, bytePatch{start: insertPos, end: apple.contentEnd, repl: []byte(insert)})
}
// Ensure prev-lang:kbd is also in NVRAM > Delete > 7C436110-... so OVMF_VARS
// does not hold onto an old value across boots.
if delArr := findAppleNVRAMDeleteArray(root); delArr != nil {
hasDelete := false
for _, item := range delArr.children {
if item.name == "string" && item.text == "prev-lang:kbd" {
hasDelete = true
break
}
}
if !hasDelete && !delArr.selfClosing {
closeIndent := lineIndent(src, delArr.contentEnd)
entryIndent := closeIndent + "\t"
if len(delArr.children) > 0 {
entryIndent = lineIndent(src, delArr.children[0].start)
}
nl := "\n"
if bytes.Contains(src, []byte("\r\n")) {
nl = "\r\n"
}
insert := fmt.Sprintf("%s<string>prev-lang:kbd</string>%s%s", entryIndent, nl, closeIndent)
insertPos := delArr.contentEnd
for insertPos > delArr.contentStart && (src[insertPos-1] == ' ' || src[insertPos-1] == '\t') {
insertPos--
}
patches = append(patches, bytePatch{start: insertPos, end: delArr.contentEnd, repl: []byte(insert)})
}
}
// Apply patches in reverse byte-offset order so earlier offsets stay valid.
out := append([]byte(nil), src...)
for i := 0; i < len(patches); i++ {
for j := i + 1; j < len(patches); j++ {
if patches[j].start > patches[i].start {
patches[i], patches[j] = patches[j], patches[i]
}
}
}
for _, p := range patches {
buf := make([]byte, 0, len(out)-(p.end-p.start)+len(p.repl))
buf = append(buf, out[:p.start]...)
buf = append(buf, p.repl...)
buf = append(buf, out[p.end:]...)
out = buf
}
return out, nil
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package opencore
import "os/exec"
func configureCmd(_ *exec.Cmd) {}
+12
View File
@@ -0,0 +1,12 @@
//go:build windows
package opencore
import (
"os/exec"
"syscall"
)
func configureCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
+58 -1
View File
@@ -144,11 +144,68 @@ func TypeStrokes(ctx context.Context, q Executor, strokes []Stroke, hold, gap ti
// SocketPath is the QMP socket reims-ctl gives every VM it starts: `-qmp
// unix:<dir>\qmp.sock,server=on,wait=off` (`reims-ctl command`, upstream
// 3731afd). It exists on every host, unlike the Win10 cold-reboot TCP monitor.
// 3731afd). It exists on every host, unlike the Win10 cold-reboot monitor.
func SocketPath(vmDir string) string {
return filepath.Join(vmDir, "qmp.sock")
}
// PressCombo holds modifiers, presses and releases key, then releases modifiers
// in reverse order. Any error or cancellation releases every key still down.
func PressCombo(ctx context.Context, q Executor, hold time.Duration, key string, modifiers ...string) error {
var downMods []string
keyDown := false
defer func() {
if keyDown {
_ = sendKeys(q, false, key)
}
for i := len(downMods) - 1; i >= 0; i-- {
_ = sendKeys(q, false, downMods[i])
}
}()
for _, m := range modifiers {
if err := ctx.Err(); err != nil {
return err
}
if err := sendKeys(q, true, m); err != nil {
return err
}
downMods = append(downMods, m)
sleep(ctx, hold)
}
if err := ctx.Err(); err != nil {
return err
}
if err := sendKeys(q, true, key); err != nil {
return err
}
keyDown = true
sleep(ctx, hold)
if err := sendKeys(q, false, key); err != nil {
return err
}
keyDown = false
sleep(ctx, hold)
for i := len(downMods) - 1; i >= 0; i-- {
m := downMods[i]
downMods = downMods[:i]
if err := sendKeys(q, false, m); err != nil {
return err
}
}
return nil
}
// SendPasteShortcut presses Command+V (meta_l + v) in a running macOS VM over
// its QMP socket. Works in every macOS app without Accessibility permissions.
func SendPasteShortcut(ctx context.Context, vmDir string) error {
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer q.Close()
return PressCombo(ctx, q, 25*time.Millisecond, "v", "meta_l")
}
// TypeIntoVM types text into a running VM through its QMP socket and returns
// how many keys it pressed.
func TypeIntoVM(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
+20
View File
@@ -90,6 +90,26 @@ func TestTypeStrokesReleasesShiftOnError(t *testing.T) {
}
}
func TestPressComboAndCleanup(t *testing.T) {
r := &recorder{}
if err := PressCombo(context.Background(), r, 0, "v", "meta_l"); err != nil {
t.Fatal(err)
}
want := "meta_l down,v down,v up,meta_l up"
if got := strings.Join(r.events, ","); got != want {
t.Fatalf("got %s\nwant %s", got, want)
}
// Failure after meta_l down + v down must release both v and meta_l.
r2 := &recorder{failAt: 2}
if err := PressCombo(context.Background(), r2, 0, "v", "meta_l"); err == nil {
t.Fatal("want error")
}
if got := strings.Join(r2.events, ","); !strings.HasSuffix(got, "v up,meta_l up") {
t.Fatalf("keys left down: %s", got)
}
}
func TestDialAndExecuteAgainstMockQMP(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
+25
View File
@@ -0,0 +1,25 @@
package qmp
import "context"
// Screendump asks QEMU to write the current frame of console 0 to path as a
// binary PPM and returns "ppm". PPM rather than PNG on purpose: QEMU encodes
// the dump on its main loop, and on a 2880×1620 reims-vgpu console PNG took
// ~820 ms there against ~35 ms for PPM (measured 2026-11-28, QEMU 11.1), so
// PNG would stall the guest each time the page refreshes its thumbnail.
func (c *Conn) Screendump(path string) (string, error) {
if err := c.Execute("screendump", map[string]any{"filename": path, "format": "ppm"}); err != nil {
return "", err
}
return "ppm", nil
}
// ScreendumpVM connects to a running VM's QMP socket and writes one frame.
func ScreendumpVM(ctx context.Context, vmDir, path string) (string, error) {
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return "", err
}
defer q.Close()
return q.Screendump(path)
}
+88 -28
View File
@@ -8,8 +8,9 @@ package runtime
// reims-runtime-src-<commit>.tar.zst (matching sources, spec §7)
// SHA256SUMS.txt
//
// A GitHub prerelease is the candidate channel; a full release is stable
// (spec §6). The client lists stable only unless candidate is asked for.
// A GitHub prerelease is the alpha channel (built automatically from upstream
// by CI); a full release is stable (promoted by a person after a real-host
// smoke test, spec §6). The client lists stable only unless alpha is asked for.
import (
"bufio"
@@ -37,10 +38,29 @@ const (
)
const (
ChannelStable = "stable"
ChannelCandidate = "candidate"
ChannelStable = "stable"
ChannelAlpha = "alpha"
// channelLegacyCandidate is what the alpha channel was called before
// 2026-11-28; configs and manifests written then still say it.
channelLegacyCandidate = "candidate"
)
// NormalizeChannel maps a stored or user-given channel name to ChannelStable
// or ChannelAlpha. The pre-2026-11-28 name "candidate" means alpha; anything
// else (including "") means stable.
func NormalizeChannel(s string) string {
switch strings.ToLower(strings.TrimSpace(s)) {
case ChannelAlpha, channelLegacyCandidate:
return ChannelAlpha
}
return ChannelStable
}
// maxReleasePages bounds how far ListRemote follows GitHub's pagination: the
// releases API returns at most 100 per page, and the repository also holds
// app releases and (until pruned) daily alpha runtimes.
const maxReleasePages = 10
// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO
// overrides the repository (for forks and testing).
type Source struct {
@@ -104,29 +124,23 @@ func newRequest(ctx context.Context, url string) (*http.Request, error) {
return req, nil
}
// ListRemote lists published runtime packages, newest first. Candidates are
// included only when includeCandidate is set.
func (s Source) ListRemote(ctx context.Context, includeCandidate bool) ([]Remote, error) {
url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", strings.TrimRight(s.APIBase, "/"), s.Repo)
req, err := newRequest(ctx, url)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := s.client().Do(req)
if err != nil {
return nil, fmt.Errorf("list runtime releases: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
return nil, fmt.Errorf("GitHub API rate limit reached; try again later (HTTP %d)", resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("list runtime releases: HTTP %d", resp.StatusCode)
}
// ListRemote lists published runtime packages, newest first. Alpha runtimes
// are included only when includeAlpha is set.
func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) {
base := strings.TrimRight(s.APIBase, "/")
url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", base, s.Repo)
var rels []ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rels); err != nil {
return nil, fmt.Errorf("read runtime releases: %w", err)
for page := 0; url != "" && page < maxReleasePages; page++ {
batch, next, err := s.releasesPage(ctx, url)
if err != nil {
return nil, err
}
rels = append(rels, batch...)
// Follow only links back to the same API (never another host).
if !strings.HasPrefix(next, base+"/") {
next = ""
}
url = next
}
var out []Remote
for _, r := range rels {
@@ -136,7 +150,7 @@ func (s Source) ListRemote(ctx context.Context, includeCandidate bool) ([]Remote
commit := strings.TrimPrefix(r.TagName, runtimeTagPrefix)
rem := Remote{Commit: commit, Tag: r.TagName, PublishedAt: r.PublishedAt, PageURL: r.HTMLURL, Channel: ChannelStable}
if r.Prerelease {
rem.Channel = ChannelCandidate
rem.Channel = ChannelAlpha
}
for _, a := range r.Assets {
switch {
@@ -152,7 +166,7 @@ func (s Source) ListRemote(ctx context.Context, includeCandidate bool) ([]Remote
if rem.ArchiveURL == "" || rem.SumsURL == "" || rem.SourceURL == "" {
continue
}
if rem.Channel == ChannelCandidate && !includeCandidate {
if rem.Channel == ChannelAlpha && !includeAlpha {
continue
}
out = append(out, rem)
@@ -161,6 +175,52 @@ func (s Source) ListRemote(ctx context.Context, includeCandidate bool) ([]Remote
return out, nil
}
// releasesPage fetches one page of the releases API and returns the URL of
// the next page from the Link header ("" on the last page).
func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, string, error) {
req, err := newRequest(ctx, url)
if err != nil {
return nil, "", err
}
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := s.client().Do(req)
if err != nil {
return nil, "", fmt.Errorf("list runtime releases: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
return nil, "", fmt.Errorf("GitHub API rate limit reached; try again later (HTTP %d)", resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("list runtime releases: HTTP %d", resp.StatusCode)
}
var rels []ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rels); err != nil {
return nil, "", fmt.Errorf("read runtime releases: %w", err)
}
return rels, nextLink(resp.Header.Get("Link")), nil
}
// nextLink returns the rel="next" target of an RFC 8288 Link header.
func nextLink(h string) string {
for _, part := range strings.Split(h, ",") {
seg := strings.Split(part, ";")
if len(seg) < 2 {
continue
}
isNext := false
for _, p := range seg[1:] {
if strings.TrimSpace(p) == `rel="next"` {
isNext = true
}
}
if isNext {
return strings.Trim(strings.TrimSpace(seg[0]), "<>")
}
}
return ""
}
// Pick finds a release by commit prefix, or the newest for "" / "latest".
func Pick(list []Remote, want string) (*Remote, error) {
want = strings.TrimSpace(want)
+52 -2
View File
@@ -79,8 +79,8 @@ func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(all) != 2 || all[0].Commit != "abc1234" || all[0].Channel != ChannelCandidate || all[0].SourceName == "" {
t.Fatalf("with candidate = %+v", all)
if len(all) != 2 || all[0].Commit != "abc1234" || all[0].Channel != ChannelAlpha || all[0].SourceName == "" {
t.Fatalf("with alpha = %+v", all)
}
if r, err := Pick(all, "abc"); err != nil || r.Commit != "abc1234" {
t.Fatalf("pick prefix: %v %v", r, err)
@@ -152,3 +152,53 @@ func TestDownloadRejectsAWrongChecksum(t *testing.T) {
t.Fatalf("bad download kept: %v", entries)
}
}
func TestListRemoteFollowsPagination(t *testing.T) {
mux := http.NewServeMux()
var srv *httptest.Server
release := func(commit string, pre bool) string {
return fmt.Sprintf(`{"tag_name":"runtime-%[1]s","prerelease":%[2]t,"published_at":"2026-11-%[3]sT00:00:00Z","assets":[
{"name":"reims-runtime-win-x64-%[1]s.tar.zst","size":1,"browser_download_url":"x"},
{"name":"reims-runtime-src-%[1]s.tar.zst","size":1,"browser_download_url":"x"},
{"name":"SHA256SUMS.txt","size":1,"browser_download_url":"x"}]}`, commit, pre, commit[:2])
}
mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Query().Get("page") {
case "":
w.Header().Set("Link", fmt.Sprintf(`<%s/repos/o/r/releases?per_page=100&page=2>; rel="next", <%s/repos/o/r/releases?per_page=100&page=2>; rel="last"`, srv.URL, srv.URL))
fmt.Fprint(w, "["+release("20alpha", true)+"]")
case "2":
// The stable runtime sits on the second page, behind newer alphas.
fmt.Fprint(w, "["+release("10stabl", false)+"]")
default:
t.Errorf("unexpected page %q", r.URL.RawQuery)
}
})
srv = httptest.NewServer(mux)
defer srv.Close()
src := Source{APIBase: srv.URL, Repo: "o/r", Client: srv.Client()}
list, err := src.ListRemote(context.Background(), false)
if err != nil {
t.Fatal(err)
}
if len(list) != 1 || list[0].Commit != "10stabl" {
t.Fatalf("stable across pages = %+v", list)
}
}
func TestNextLinkStaysOnAPIHost(t *testing.T) {
if got := nextLink(`<https://api.github.com/x?page=2>; rel="next", <https://api.github.com/x?page=9>; rel="last"`); got != "https://api.github.com/x?page=2" {
t.Fatalf("nextLink = %q", got)
}
if got := nextLink(`<https://api.github.com/x?page=9>; rel="last"`); got != "" {
t.Fatalf("no next: %q", got)
}
}
func TestNormalizeChannel(t *testing.T) {
for in, want := range map[string]string{"": ChannelStable, "stable": ChannelStable, "alpha": ChannelAlpha, "candidate": ChannelAlpha, " Alpha ": ChannelAlpha, "beta": ChannelStable} {
if got := NormalizeChannel(in); got != want {
t.Errorf("NormalizeChannel(%q) = %q, want %q", in, got, want)
}
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ type Manifest struct {
UtilCommit string `json:"util_commit,omitempty"`
MetalCommit string `json:"metal2vulkan_commit,omitempty"`
Patches []Patch `json:"patches,omitempty"`
Channel string `json:"channel,omitempty"` // candidate | stable
Channel string `json:"channel,omitempty"` // channel at build time: alpha (older packages: candidate)
SourcePackage string `json:"source_package,omitempty"` // file name of the matching source archive
}
+160
View File
@@ -0,0 +1,160 @@
// Package thumb turns a QEMU screendump into a small JPEG for the VM page.
package thumb
import (
"bufio"
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"os"
"strconv"
)
// Load decodes a screendump written as "png" or "ppm" (binary P6).
func Load(path, format string) (image.Image, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
if format == "png" {
return png.Decode(bufio.NewReader(f))
}
return decodePPM(bufio.NewReader(f))
}
// decodePPM reads a binary PPM (P6, maxval ≤ 255), the format QEMU's
// screendump writes when no format is given.
func decodePPM(r *bufio.Reader) (image.Image, error) {
tok := func() (string, error) {
var b []byte
for {
c, err := r.ReadByte()
if err != nil {
return "", err
}
switch {
case c == '#':
if _, err := r.ReadString('\n'); err != nil {
return "", err
}
case c == ' ' || c == '\t' || c == '\n' || c == '\r':
if len(b) > 0 {
return string(b), nil
}
default:
b = append(b, c)
}
}
}
magic, err := tok()
if err != nil {
return nil, err
}
if magic != "P6" {
return nil, fmt.Errorf("ppm: unsupported magic %q", magic)
}
var dims [3]int
for i := range dims {
s, err := tok()
if err != nil {
return nil, err
}
if dims[i], err = strconv.Atoi(s); err != nil {
return nil, fmt.Errorf("ppm: bad header: %w", err)
}
}
w, h, maxv := dims[0], dims[1], dims[2]
if w <= 0 || h <= 0 || w > 16384 || h > 16384 || maxv <= 0 || maxv > 255 {
return nil, errors.New("ppm: unsupported size or depth")
}
px := make([]byte, w*h*3)
if _, err := io.ReadFull(r, px); err != nil {
return nil, fmt.Errorf("ppm: %w", err)
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i, j := 0, 0; i < len(px); i, j = i+3, j+4 {
img.Pix[j], img.Pix[j+1], img.Pix[j+2], img.Pix[j+3] = px[i], px[i+1], px[i+2], 255
}
return img, nil
}
// Scale shrinks img to at most maxW pixels wide by averaging each source
// block (box filter), which keeps text and UI edges readable at small sizes.
func Scale(img image.Image, maxW int) image.Image {
b := img.Bounds()
sw, sh := b.Dx(), b.Dy()
if sw <= maxW || sw == 0 {
return img
}
dw := maxW
dh := sh * dw / sw
if dh < 1 {
dh = 1
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < dh; y++ {
y0, y1 := y*sh/dh, (y+1)*sh/dh
for x := 0; x < dw; x++ {
x0, x1 := x*sw/dw, (x+1)*sw/dw
var r, g, bl, n uint32
for sy := y0; sy < y1; sy++ {
for sx := x0; sx < x1; sx++ {
cr, cg, cb, _ := img.At(b.Min.X+sx, b.Min.Y+sy).RGBA()
r, g, bl, n = r+cr>>8, g+cg>>8, bl+cb>>8, n+1
}
}
if n == 0 {
n = 1
}
dst.SetRGBA(x, y, color.RGBA{uint8(r / n), uint8(g / n), uint8(bl / n), 255})
}
}
return dst
}
// Blank reports whether a frame is (almost) one flat colour — a powered-off
// or not-yet-drawn console — so the UI can keep its placeholder instead.
func Blank(img image.Image) bool {
b := img.Bounds()
step := max(1, b.Dx()/64)
var first color.RGBA
firstSet := false
diff := 0
total := 0
for y := b.Min.Y; y < b.Max.Y; y += step {
for x := b.Min.X; x < b.Max.X; x += step {
r, g, bl, _ := img.At(x, y).RGBA()
c := color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), 255}
if !firstSet {
first, firstSet = c, true
}
if absDiff(c.R, first.R)+absDiff(c.G, first.G)+absDiff(c.B, first.B) > 24 {
diff++
}
total++
}
}
return total == 0 || diff*100 < total // under 1% of samples differ
}
func absDiff(a, b uint8) int {
if a > b {
return int(a - b)
}
return int(b - a)
}
// JPEG encodes img at the given quality.
func JPEG(img image.Image, quality int) ([]byte, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
+72
View File
@@ -0,0 +1,72 @@
package thumb
import (
"bufio"
"bytes"
"fmt"
"image"
"image/color"
"testing"
)
func ppm(w, h int, fill func(x, y int) [3]byte) []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "P6\n# qemu\n%d %d\n255\n", w, h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p := fill(x, y)
b.Write(p[:])
}
}
return b.Bytes()
}
func TestDecodePPM(t *testing.T) {
data := ppm(3, 2, func(x, y int) [3]byte { return [3]byte{byte(x * 100), byte(y * 100), 7} })
img, err := decodePPM(bufio.NewReader(bytes.NewReader(data)))
if err != nil {
t.Fatal(err)
}
if img.Bounds().Dx() != 3 || img.Bounds().Dy() != 2 {
t.Fatalf("size %v", img.Bounds())
}
r, g, b, _ := img.At(2, 1).RGBA()
if r>>8 != 200 || g>>8 != 100 || b>>8 != 7 {
t.Fatalf("pixel (2,1) = %d,%d,%d", r>>8, g>>8, b>>8)
}
}
func TestDecodePPMRejectsP3(t *testing.T) {
if _, err := decodePPM(bufio.NewReader(bytes.NewReader([]byte("P3\n1 1\n255\n0 0 0\n")))); err == nil {
t.Fatal("want error for ASCII PPM")
}
}
func TestScaleKeepsAspect(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 1920, 1080))
out := Scale(img, 640)
if out.Bounds().Dx() != 640 || out.Bounds().Dy() != 360 {
t.Fatalf("scaled to %v", out.Bounds())
}
if Scale(img, 4000) != image.Image(img) {
t.Fatal("smaller-than-max image should pass through")
}
}
func TestBlank(t *testing.T) {
flat := image.NewRGBA(image.Rect(0, 0, 200, 100))
if !Blank(flat) {
t.Fatal("all-black frame should be blank")
}
busy := image.NewRGBA(image.Rect(0, 0, 200, 100))
for y := 0; y < 100; y++ {
for x := 0; x < 200; x++ {
if (x/20+y/20)%2 == 0 {
busy.Set(x, y, color.White)
}
}
}
if Blank(busy) {
t.Fatal("checkerboard frame should not be blank")
}
}
+98
View File
@@ -0,0 +1,98 @@
package tray
import (
"bytes"
"image"
"image/draw"
"image/png"
)
// VMItem is a lightweight summary shown inside the system tray menu.
type VMItem struct {
Name string
Running bool
}
// Snapshot holds the live state read each time the user opens the tray menu.
type Snapshot struct {
LocaleZh bool
VMs []VMItem
}
// Callbacks wires tray actions back into the Wails application.
type Callbacks struct {
OnShow func()
OnStartVM func(name string)
OnStopVM func(name string)
OnOpenSharedDir func(name string)
OnQuit func()
GetSnapshot func() Snapshot
}
// resizePNGIcon scales an embedded PNG (e.g. assets/logo.png) to size×size PNG
// bytes suitable for Windows CreateIconFromResourceEx.
func resizePNGIcon(srcPNG []byte, size int) ([]byte, error) {
if len(srcPNG) == 0 || size <= 0 {
return nil, nil
}
img, err := png.Decode(bytes.NewReader(srcPNG))
if err != nil {
return nil, err
}
sb := img.Bounds()
sw, sh := sb.Dx(), sb.Dy()
if sw == size && sh == size {
return srcPNG, nil
}
src := image.NewNRGBA(image.Rect(0, 0, sw, sh))
draw.Draw(src, src.Bounds(), img, sb.Min, draw.Src)
dst := image.NewNRGBA(image.Rect(0, 0, size, size))
// Box-filter downscale for crisp tray icon edges without external dependencies.
for y := 0; y < size; y++ {
y0 := y * sh / size
y1 := (y + 1) * sh / size
if y1 <= y0 {
y1 = y0 + 1
}
if y1 > sh {
y1 = sh
}
for x := 0; x < size; x++ {
x0 := x * sw / size
x1 := (x + 1) * sw / size
if x1 <= x0 {
x1 = x0 + 1
}
if x1 > sw {
x1 = sw
}
var rSum, gSum, bSum, aSum, count uint64
for sy := y0; sy < y1; sy++ {
row := src.Pix[sy*src.Stride:]
for sx := x0; sx < x1; sx++ {
off := sx * 4
a := uint64(row[off+3])
rSum += uint64(row[off+0]) * a
gSum += uint64(row[off+1]) * a
bSum += uint64(row[off+2]) * a
aSum += a
count++
}
}
doff := y*dst.Stride + x*4
if aSum > 0 && count > 0 {
dst.Pix[doff+0] = uint8(rSum / aSum)
dst.Pix[doff+1] = uint8(gSum / aSum)
dst.Pix[doff+2] = uint8(bSum / aSum)
dst.Pix[doff+3] = uint8(aSum / count)
}
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, dst); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
+13
View File
@@ -0,0 +1,13 @@
//go:build !windows
package tray
// Manager is a no-op stub on non-Windows platforms.
type Manager struct{}
func Start(_ []byte, _ string, _ Callbacks) (*Manager, error) {
return &Manager{}, nil
}
func (m *Manager) UpdateTooltip(_ string) {}
func (m *Manager) Close() {}
+33
View File
@@ -0,0 +1,33 @@
package tray
import (
"bytes"
"image"
"image/color"
"image/png"
"testing"
)
func TestResizePNGIcon(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 128, 128))
for y := 0; y < 128; y++ {
for x := 0; x < 128; x++ {
src.SetNRGBA(x, y, color.NRGBA{R: 10, G: 132, B: 255, A: 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, src); err != nil {
t.Fatal(err)
}
out, err := resizePNGIcon(buf.Bytes(), 32)
if err != nil {
t.Fatalf("resizePNGIcon: %v", err)
}
decoded, err := png.Decode(bytes.NewReader(out))
if err != nil {
t.Fatalf("png.Decode: %v", err)
}
if decoded.Bounds().Dx() != 32 || decoded.Bounds().Dy() != 32 {
t.Fatalf("resized icon = %dx%d, want 32x32", decoded.Bounds().Dx(), decoded.Bounds().Dy())
}
}
+489
View File
@@ -0,0 +1,489 @@
//go:build windows
package tray
import (
"fmt"
"runtime"
"sync"
"syscall"
"unsafe"
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procRegisterClassExW = user32.NewProc("RegisterClassExW")
procCreateWindowExW = user32.NewProc("CreateWindowExW")
procDestroyWindow = user32.NewProc("DestroyWindow")
procDefWindowProcW = user32.NewProc("DefWindowProcW")
procGetMessageW = user32.NewProc("GetMessageW")
procTranslateMessage = user32.NewProc("TranslateMessage")
procDispatchMessageW = user32.NewProc("DispatchMessageW")
procPostMessageW = user32.NewProc("PostMessageW")
procPostQuitMessage = user32.NewProc("PostQuitMessage")
procRegisterWindowMessageW = user32.NewProc("RegisterWindowMessageW")
procCreatePopupMenu = user32.NewProc("CreatePopupMenu")
procAppendMenuW = user32.NewProc("AppendMenuW")
procSetMenuDefaultItem = user32.NewProc("SetMenuDefaultItem")
procTrackPopupMenu = user32.NewProc("TrackPopupMenu")
procDestroyMenu = user32.NewProc("DestroyMenu")
procSetForegroundWindow = user32.NewProc("SetForegroundWindow")
procGetCursorPos = user32.NewProc("GetCursorPos")
procLoadIconW = user32.NewProc("LoadIconW")
procDestroyIcon = user32.NewProc("DestroyIcon")
procCreateIconFromResourceEx = user32.NewProc("CreateIconFromResourceEx")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
shell32 = syscall.NewLazyDLL("shell32.dll")
procShellNotifyIconW = shell32.NewProc("Shell_NotifyIconW")
)
const (
wmDestroy = 0x0002
wmClose = 0x0010
wmNull = 0x0000
wmContextMenu = 0x007B
wmCommand = 0x0111
wmLButtonUp = 0x0202
wmLButtonDbl = 0x0203
wmRButtonUp = 0x0205
wmUser = 0x0400
wmTrayIcon = wmUser + 1
nimAdd = 0x00000000
nimModify = 0x00000001
nimDelete = 0x00000002
nifMessage = 0x00000001
nifIcon = 0x00000002
nifTip = 0x00000004
mfString = 0x00000000
mfPopup = 0x00000010
mfSeparator = 0x00000800
tpmRightButton = 0x0002
tpmBottomAlign = 0x0020
tpmReturnCmd = 0x0100
tpmNonotify = 0x0080
idiApplication = 32512
cmdShow = 1001
cmdQuit = 1002
cmdVMBase = 2000 // per-VM slots: base + i*10 + {0: start/stop, 1: shared folder}
maxTrayVMs = 16
trayIconUID = 1
)
type wndClassExW struct {
CbSize uint32
Style uint32
LpfnWndProc uintptr
CbClsExtra int32
CbWndExtra int32
HInstance uintptr
HIcon uintptr
HCursor uintptr
HbrBackground uintptr
LpszMenuName *uint16
LpszClassName *uint16
HIconSm uintptr
}
type winPoint struct {
X, Y int32
}
type winMsg struct {
HWnd uintptr
Message uint32
WParam uintptr
LParam uintptr
Time uint32
Pt winPoint
}
type notifyIconDataW struct {
CbSize uint32
HWnd uintptr
UID uint32
UFlags uint32
UCallbackMessage uint32
HIcon uintptr
SzTip [128]uint16
DwState uint32
DwStateMask uint32
SzInfo [256]uint16
UVersionOrTimeout uint32
SzInfoTitle [64]uint16
DwInfoFlags uint32
GuidItem [16]byte
HBalloonIcon uintptr
}
var (
activeMu sync.RWMutex
activeMgr *Manager
)
// Manager owns the Windows notification area (system tray) icon and context menu.
type Manager struct {
mu sync.Mutex
cb Callbacks
iconPNG []byte
hwnd uintptr
hicon uintptr
customIcon bool
taskbarCreated uint32
tooltip string
closed bool
done chan struct{}
menuVMs []VMItem
}
// Start launches the Windows system tray icon on a dedicated locked OS thread.
func Start(iconPNG []byte, tooltip string, cb Callbacks) (*Manager, error) {
if tooltip == "" {
tooltip = "Reims-Go"
}
m := &Manager{
cb: cb,
iconPNG: iconPNG,
tooltip: tooltip,
done: make(chan struct{}),
}
ready := make(chan error, 1)
go m.runLoop(ready)
if err := <-ready; err != nil {
return nil, err
}
return m, nil
}
// UpdateTooltip refreshes the hover tooltip text of the tray icon.
func (m *Manager) UpdateTooltip(text string) {
if m == nil {
return
}
m.mu.Lock()
if m.closed || m.hwnd == 0 {
m.mu.Unlock()
return
}
m.tooltip = text
nid := m.buildNID(nifTip)
m.mu.Unlock()
_, _, _ = procShellNotifyIconW.Call(nimModify, uintptr(unsafe.Pointer(&nid)))
}
// Close removes the tray icon and stops the hidden window message loop.
func (m *Manager) Close() {
if m == nil {
return
}
m.mu.Lock()
if m.closed {
m.mu.Unlock()
return
}
m.closed = true
hwnd := m.hwnd
m.mu.Unlock()
if hwnd != 0 {
_, _, _ = procPostMessageW.Call(hwnd, wmClose, 0, 0)
<-m.done
}
}
func (m *Manager) buildNID(flags uint32) notifyIconDataW {
var nid notifyIconDataW
nid.CbSize = uint32(unsafe.Sizeof(nid))
nid.HWnd = m.hwnd
nid.UID = trayIconUID
nid.UFlags = flags
nid.UCallbackMessage = wmTrayIcon
nid.HIcon = m.hicon
tipU16, _ := syscall.UTF16FromString(m.tooltip)
for i := 0; i < len(tipU16) && i < len(nid.SzTip)-1; i++ {
nid.SzTip[i] = tipU16[i]
}
return nid
}
func (m *Manager) addTrayIcon() {
nid := m.buildNID(nifMessage | nifIcon | nifTip)
_, _, _ = procShellNotifyIconW.Call(nimAdd, uintptr(unsafe.Pointer(&nid)))
}
func (m *Manager) removeTrayIcon() {
nid := m.buildNID(0)
_, _, _ = procShellNotifyIconW.Call(nimDelete, uintptr(unsafe.Pointer(&nid)))
}
func (m *Manager) loadIcon() (uintptr, bool) {
if scaled, err := resizePNGIcon(m.iconPNG, 32); err == nil && len(scaled) > 0 {
h, _, _ := procCreateIconFromResourceEx.Call(
uintptr(unsafe.Pointer(&scaled[0])),
uintptr(len(scaled)),
1, // fIcon = TRUE
0x00030000,
32,
32,
0,
)
if h != 0 {
return h, true
}
}
h, _, _ := procLoadIconW.Call(0, uintptr(idiApplication))
return h, false
}
func (m *Manager) runLoop(ready chan<- error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(m.done)
hInst, _, _ := procGetModuleHandle.Call(0)
className, _ := syscall.UTF16PtrFromString("ReimsGoTrayWindowClass")
tbMsgName, _ := syscall.UTF16PtrFromString("TaskbarCreated")
tbMsg, _, _ := procRegisterWindowMessageW.Call(uintptr(unsafe.Pointer(tbMsgName)))
m.taskbarCreated = uint32(tbMsg)
activeMu.Lock()
activeMgr = m
activeMu.Unlock()
defer func() {
activeMu.Lock()
if activeMgr == m {
activeMgr = nil
}
activeMu.Unlock()
}()
wc := wndClassExW{
CbSize: uint32(unsafe.Sizeof(wndClassExW{})),
LpfnWndProc: syscall.NewCallback(trayWndProc),
HInstance: hInst,
LpszClassName: className,
}
_, _, _ = procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc)))
winTitle, _ := syscall.UTF16PtrFromString("Reims-Go Tray")
hwnd, _, err := procCreateWindowExW.Call(
0,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(winTitle)),
0,
0, 0, 0, 0,
0, 0, hInst, 0,
)
if hwnd == 0 {
ready <- fmt.Errorf("CreateWindowExW: %w", err)
return
}
hicon, custom := m.loadIcon()
m.mu.Lock()
m.hwnd = hwnd
m.hicon = hicon
m.customIcon = custom
m.mu.Unlock()
m.addTrayIcon()
ready <- nil
var msg winMsg
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) <= 0 {
break
}
_, _, _ = procTranslateMessage.Call(uintptr(unsafe.Pointer(&msg)))
_, _, _ = procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg)))
}
m.removeTrayIcon()
if m.customIcon && m.hicon != 0 {
_, _, _ = procDestroyIcon.Call(m.hicon)
}
}
func appendMenuString(menu uintptr, flags uintptr, id uintptr, label string) {
u16, _ := syscall.UTF16PtrFromString(label)
_, _, _ = procAppendMenuW.Call(menu, flags, id, uintptr(unsafe.Pointer(u16)))
}
func (m *Manager) showContextMenu() {
var snap Snapshot
if m.cb.GetSnapshot != nil {
snap = m.cb.GetSnapshot()
}
zh := snap.LocaleZh
hMenu, _, _ := procCreatePopupMenu.Call()
if hMenu == 0 {
return
}
defer procDestroyMenu.Call(hMenu)
showLabel := "Show Reims-Go"
quitLabel := "Quit Reims-Go"
startLabel := "Start"
stopLabel := "Stop"
sharedLabel := "Open Shared Folder"
runningTag := "Running"
stoppedTag := "Stopped"
if zh {
showLabel = "显示 Reims-Go"
quitLabel = "退出 Reims-Go"
startLabel = "启动"
stopLabel = "停止"
sharedLabel = "打开共享目录"
runningTag = "运行中"
stoppedTag = "已停止"
}
appendMenuString(hMenu, mfString, cmdShow, showLabel)
_, _, _ = procSetMenuDefaultItem.Call(hMenu, cmdShow, 0)
vms := snap.VMs
if len(vms) > maxTrayVMs {
vms = vms[:maxTrayVMs]
}
m.mu.Lock()
m.menuVMs = append([]VMItem(nil), vms...)
m.mu.Unlock()
if len(vms) > 0 {
_, _, _ = procAppendMenuW.Call(hMenu, mfSeparator, 0, 0)
for i, vm := range vms {
sub, _, _ := procCreatePopupMenu.Call()
if sub == 0 {
continue
}
base := uintptr(cmdVMBase + i*10)
if vm.Running {
appendMenuString(sub, mfString, base+0, stopLabel)
} else {
appendMenuString(sub, mfString, base+0, startLabel)
}
appendMenuString(sub, mfString, base+1, sharedLabel)
dot := "○"
stateTag := stoppedTag
if vm.Running {
dot = "●"
stateTag = runningTag
}
appendMenuString(hMenu, mfPopup, sub, fmt.Sprintf("%s %s (%s)", dot, vm.Name, stateTag))
}
}
_, _, _ = procAppendMenuW.Call(hMenu, mfSeparator, 0, 0)
appendMenuString(hMenu, mfString, cmdQuit, quitLabel)
var pt winPoint
_, _, _ = procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
_, _, _ = procSetForegroundWindow.Call(m.hwnd)
cmd, _, _ := procTrackPopupMenu.Call(
hMenu,
tpmRightButton|tpmBottomAlign|tpmReturnCmd|tpmNonotify,
uintptr(pt.X),
uintptr(pt.Y),
0,
m.hwnd,
0,
)
_, _, _ = procPostMessageW.Call(m.hwnd, wmNull, 0, 0)
if cmd != 0 {
m.dispatchCommand(int(cmd))
}
}
func (m *Manager) dispatchCommand(cmd int) {
switch cmd {
case cmdShow:
if m.cb.OnShow != nil {
go m.cb.OnShow()
}
case cmdQuit:
if m.cb.OnQuit != nil {
go m.cb.OnQuit()
}
default:
if cmd >= cmdVMBase {
idx := (cmd - cmdVMBase) / 10
act := (cmd - cmdVMBase) % 10
m.mu.Lock()
var item VMItem
valid := idx >= 0 && idx < len(m.menuVMs)
if valid {
item = m.menuVMs[idx]
}
m.mu.Unlock()
if !valid {
return
}
switch act {
case 0:
if item.Running {
if m.cb.OnStopVM != nil {
go m.cb.OnStopVM(item.Name)
}
} else {
if m.cb.OnStartVM != nil {
go m.cb.OnStartVM(item.Name)
}
}
case 1:
if m.cb.OnOpenSharedDir != nil {
go m.cb.OnOpenSharedDir(item.Name)
}
}
}
}
}
func trayWndProc(hwnd uintptr, msg uint32, wparam, lparam uintptr) uintptr {
activeMu.RLock()
m := activeMgr
activeMu.RUnlock()
if m != nil && m.taskbarCreated != 0 && msg == m.taskbarCreated {
m.addTrayIcon()
return 0
}
switch msg {
case wmTrayIcon:
ev := uint32(lparam & 0xFFFF)
switch ev {
case wmLButtonUp, wmLButtonDbl:
if m != nil && m.cb.OnShow != nil {
go m.cb.OnShow()
}
case wmRButtonUp, wmContextMenu:
if m != nil {
m.showContextMenu()
}
}
return 0
case wmCommand:
if m != nil {
m.dispatchCommand(int(wparam & 0xFFFF))
}
return 0
case wmClose:
_, _, _ = procDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
_, _, _ = procPostQuitMessage.Call(0)
return 0
}
ret, _, _ := procDefWindowProcW.Call(hwnd, uintptr(msg), wparam, lparam)
return ret
}
+2 -2
View File
@@ -13,8 +13,8 @@ import (
// Version is the current Reims-Go release version. Release builds may override
// it at link time with:
//
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.1"
var Version = "v0.2.1"
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.2"
var Version = "v0.2.2"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
+293
View File
@@ -0,0 +1,293 @@
// Package vmstart holds what has to happen around `reims-ctl start` for both
// the GUI and the CLI (docs/architecture.md principle 3): the commit-memory
// check, VM preparation before QEMU launches, the macOS language preset and
// P-core pinning afterwards.
//
// Two start steps stay in the GUI because they need a process that outlives
// the start command: the Guest Tools bridge (guesttools_flow.go) and the Win10
// cold-reboot watcher (app.go).
package vmstart
import (
"bufio"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// Prep runs start preparation against the active runtime. Log receives one
// human-readable line per step; the GUI routes it to the VM's log panel, the
// CLI to stderr.
type Prep struct {
Client *reims.Client
Runtime rt.Installed
cfg config.Config
log func(string)
}
// New resolves the active runtime for cfg. It fails when none is installed.
func New(cfg config.Config, log func(string)) (*Prep, error) {
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
if log == nil {
log = func(string) {}
}
return &Prep{Client: reims.NewClient(&cfg, *active), Runtime: *active, cfg: cfg, log: log}, nil
}
// CheckMemory refuses to start a VM whose guest RAM can't be committed right
// now. Without it QEMU exits with "Cannot set up guest memory 'ram'" (measured
// 2026-11-28, portable-runtime-spec.md §5.1), which says nothing about what to do.
func (p *Prep) CheckMemory(memory string, rep host.Report) error {
avail, ok := host.CommitAvailGB()
if !ok {
return nil
}
memGB, ok := reims.ParseSizeGB(memory)
if !ok || memGB+host.StartMarginGB <= avail {
return nil
}
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.commit_memory", memGB, avail, host.RecommendedMemoryGB(rep)))
}
// Prepare brings a stopped VM's configuration up to date before it starts:
// the offline-install helper disk, the recovery boot picker, the macOS
// language preset and the WHPX nested-virtualization fallback. cur is updated
// to match what was written through `reims-ctl set`.
func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
p.syncOfflineHelper(ctx, name, cur)
p.syncRecoveryBootPicker(ctx, name, cur)
p.ReplayGuestLang(ctx, cur.Directory)
p.applyProbedWHPXCompat(ctx, name, rep, cur)
}
func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error {
return p.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &args}, io.Discard, io.Discard)
}
// syncOfflineHelper attaches the REIMSHELP HFS+ helper disk while an offline
// installer is attached, and strips it once the installer is ejected.
func (p *Prep) syncOfflineHelper(ctx context.Context, name string, cur *reims.VMDetail) {
if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) {
p.log("Preparing offline install helper disk (REIMSHELP)...")
helperPath, err := installer.EnsureOfflineHelperImage(p.cfg.XDGCacheDir(), cur.InstallerPath)
if err != nil {
p.log("Warning: offline install helper disk skipped: " + err.Error())
return
}
merged := reims.MergeOfflineHelperArgs(cur.ExtraArgs, helperPath)
if merged != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, merged); err != nil {
p.log("Warning: could not attach REIMSHELP disk: " + err.Error())
return
}
cur.ExtraArgs = merged
}
return
}
stripped := reims.StripOfflineHelperArgs(cur.ExtraArgs)
if stripped != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, stripped); err == nil {
cur.ExtraArgs = stripped
}
}
}
// syncRecoveryBootPicker applies a recovery-mode switch made while the VM was
// running: update-opencore needs a stopped VM (upstream 3731afd
// opencore.rs:400-402), so the switch is recorded in a marker file and done here.
func (p *Prep) syncRecoveryBootPicker(ctx context.Context, name string, cur *reims.VMDetail) {
var show bool
var done string
switch ReadRecoveryMarker(cur.Directory) {
case "want":
p.log("Enabling OpenCore boot picker for recovery mode...")
show, done = true, "on"
case "restore":
p.log("Restoring OpenCore direct boot after exiting recovery mode...")
show, done = false, ""
default:
return
}
w := LineWriter(p.log)
if err := p.Client.UpdateOpenCore(ctx, name, show, w, w); err != nil {
p.log("Warning: could not update OpenCore boot picker: " + err.Error())
return
}
WriteRecoveryMarker(cur.Directory, done)
p.ReplayGuestLang(ctx, cur.Directory)
}
// applyProbedWHPXCompat pre-applies `-machine kernel-irqchip=off` on Windows 11
// builds where WHvPartitionPropertyCodeNestedVirtualization is probed as
// unsupported (e.g. hr=0x80370302) and the active runtime lacks
// qemu-whpx-nested-virt-nonfatal.patch, avoiding a first-start crash and retry.
func (p *Prep) applyProbedWHPXCompat(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
if rep.NeedsColdRebootWorkaround || !rep.WHPXCaps.KernelIrqchipAvailable || rep.WHPXCaps.NestedVirtProperty {
return
}
if p.RuntimeHasPatch("nested-virt-nonfatal") || reims.HasKernelIrqchipArg(cur.ExtraArgs) {
return
}
merged := reims.MergeKernelIrqchipOffArgs(cur.ExtraArgs)
if err := p.setExtraArgs(ctx, name, merged); err != nil {
return
}
cur.ExtraArgs = merged
code := rep.WHPXCaps.NestedVirtProbeError
if code == "" {
code = "unsupported"
}
if p.cfg.Locale == i18n.ZhCN {
p.log(fmt.Sprintf("[兼容] 当前 Windows 不支持嵌套虚拟化属性(%s),已自动启用 kernel-irqchip=off", code))
} else {
p.log(fmt.Sprintf("[compat] Host rejects nested-virtualization property (%s); enabled kernel-irqchip=off automatically", code))
}
}
// RuntimeHasPatch reports whether the active runtime was built with a patch
// whose name contains substr (case-insensitive).
func (p *Prep) RuntimeHasPatch(substr string) bool {
needle := strings.ToLower(substr)
for _, patch := range p.Runtime.Manifest.Patches {
if strings.Contains(strings.ToLower(patch.Name), needle) {
return true
}
}
return false
}
// ApplyGuestLang saves the VM's macOS prev-lang:kbd preference and, when the
// VM is stopped, writes it into the OpenCore image right away. A running VM
// gets it on its next start (ReplayGuestLang). An empty lang is a no-op.
func (p *Prep) ApplyGuestLang(ctx context.Context, vmDir, lang string, running bool) error {
norm, err := opencore.NormalizeGuestLang(lang)
if err != nil || norm == "" {
return err
}
if err := opencore.WriteSavedGuestLang(vmDir, norm); err != nil {
return err
}
if running {
p.log(fmt.Sprintf("Scheduled macOS boot/recovery language (%s) for next start", norm))
return nil
}
return p.patchGuestLang(ctx, vmDir, norm)
}
// ReplayGuestLang re-applies the saved language after anything that rebuilds
// the OpenCore image (update-opencore, a graphics switch, a clone) and before
// every start. Failures are logged, not returned: the VM still boots.
func (p *Prep) ReplayGuestLang(ctx context.Context, vmDir string) {
saved := opencore.ReadSavedGuestLang(vmDir)
if saved == "" {
return
}
if err := p.patchGuestLang(ctx, vmDir, saved); err != nil {
p.log(fmt.Sprintf("Warning: could not apply macOS language (%s) to OpenCore: %v", saved, err))
}
}
func (p *Prep) patchGuestLang(ctx context.Context, vmDir, lang string) error {
ocPath := opencore.ResolveOpenCorePath(vmDir)
if ocPath == "" {
return nil
}
changed, err := opencore.PatchImagePrevLang(ctx, ocPath, lang, p.Runtime.QemuImgPath(), p.Client.Env)
if err != nil {
return err
}
if changed {
p.log(fmt.Sprintf("Applied macOS boot/recovery language (%s) to OpenCore NVRAM", lang))
}
return nil
}
// PinQEMU sets a running VM's QEMU process affinity per host.SelectSafeAffinity
// and returns the line to log about it.
func PinQEMU(loc i18n.Locale, rep host.Report, pid, vcpus int) string {
plan := host.SelectSafeAffinity(rep, vcpus)
zh := loc == i18n.ZhCN
if plan.Mode == "all" {
if zh {
return fmt.Sprintf("[CPU] 跳过绑核:虚拟机配置了 %d vCPU,超过可用安全绑定线程上限(P 核仅 %d 线程),已使用全部核心避免超售卡顿", vcpus, plan.PThreads)
}
return fmt.Sprintf("[CPU] Skipped CPU pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all host CPUs to avoid spinlock stall", vcpus, plan.PThreads)
}
err := host.PinProcessToPCores(uint32(pid), plan.Mask)
if plan.Mode == "non_lpe" {
if err != nil {
return fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", pid, err)
}
if zh {
return fmt.Sprintf("[CPU] 虚拟机配置了 %d vCPU(超过 %d 个 P 核线程),已自动将 QEMU (PID %d) 绑定到 P+E 核(%d 核 / %d 线程,掩码 %s;仅排除 %d 个慢速 LP-E 核)",
vcpus, plan.PThreads, pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.LPECoreCount)
}
return fmt.Sprintf("[CPU] VM has %d vCPUs (exceeds %d P-core threads); pinned QEMU (PID %d) to P+E cores (%d cores / %d logical CPUs, mask %s; %d slow LP-E cores excluded)",
vcpus, plan.PThreads, pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.LPECoreCount)
}
if err != nil {
return fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", pid, err)
}
if zh {
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 %d 个 P 核(%d 个逻辑线程,掩码 %s;未占用 %d 个 E 核)",
pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.ECoreCount+rep.LPECoreCount)
}
return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to %d P-cores (%d logical CPUs, mask %s; %d E/LP-E cores excluded)",
pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.ECoreCount+rep.LPECoreCount)
}
const recoveryMarkerFile = ".reims-go-recovery-picker"
// ReadRecoveryMarker returns the VM's pending recovery boot-picker state:
// "want" (enable on next start), "on" (enabled), "restore" (disable on next
// start) or "" (none).
func ReadRecoveryMarker(vmDir string) string {
if vmDir == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(vmDir, recoveryMarkerFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// WriteRecoveryMarker records state; "" removes the marker.
func WriteRecoveryMarker(vmDir, state string) {
if vmDir == "" {
return
}
p := filepath.Join(vmDir, recoveryMarkerFile)
if state == "" {
_ = os.Remove(p)
return
}
_ = os.WriteFile(p, []byte(state), 0o644)
}
// LineWriter turns command output into one log call per non-empty line.
type LineWriter func(string)
func (w LineWriter) Write(b []byte) (int, error) {
sc := bufio.NewScanner(strings.NewReader(string(b)))
for sc.Scan() {
if line := strings.TrimSpace(sc.Text()); line != "" {
w(line)
}
}
return len(b), nil
}
+6 -2
View File
@@ -12,6 +12,9 @@ import (
//go:embed all:frontend/dist
var assets embed.FS
//go:embed assets/logo.png
var trayIconPNG []byte
func main() {
app := NewApp()
err := wails.Run(&options.App{
@@ -35,8 +38,9 @@ func main() {
DarkModeBorder: windows.RGB(58, 58, 62),
},
},
OnStartup: app.startup,
OnShutdown: app.shutdown,
OnStartup: app.startup,
OnBeforeClose: app.beforeClose,
OnShutdown: app.shutdown,
Bind: []any{
app,
},
-37
View File
@@ -1,37 +0,0 @@
package main
import (
"fmt"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
// checkStartMemory refuses to start a VM whose guest RAM can't be committed
// right now. Without it QEMU exits with "Cannot set up guest memory 'ram'"
// (measured 2026-11-28, portable-runtime-spec.md §5.1), which says nothing
// about what to do.
func (a *App) checkStartMemory(c *reims.Client, name string) error {
avail, ok := host.CommitAvailGB()
if !ok {
return nil
}
d, err := a.GetVMDetail(name)
if err != nil {
return nil // can't tell; let reims-ctl report its own error
}
memGB, ok := reims.ParseSizeGB(d.Memory)
if !ok {
return nil
}
if memGB+host.StartMarginGB <= avail {
return nil
}
a.mu.Lock()
loc := a.cfg.Locale
root := a.cfg.DataRoot
a.mu.Unlock()
rec := host.RecommendedMemoryGB(host.Inspect(root))
return fmt.Errorf("%s", i18n.T(loc, "err.commit_memory", memGB, avail, rec))
}
+34
View File
@@ -0,0 +1,34 @@
package main
import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted
// sidecar preference, falling back to reading prev-lang:kbd directly from its
// OpenCore image so existing VMs accurately reflect their boot/recovery locale.
func (a *App) populateGuestLangDetail(d *reims.VMDetail) {
if d == nil || d.Directory == "" {
return
}
if saved := opencore.ReadSavedGuestLang(d.Directory); saved != "" {
d.GuestLang = saved
return
}
if ocPath := opencore.ResolveOpenCorePath(d.Directory); ocPath != "" {
if lang, err := opencore.ReadImagePrevLang(ocPath); err == nil && lang != "" {
d.GuestLang = lang
}
}
}
// prep returns the shared start/OpenCore helpers (internal/vmstart) for one VM,
// logging to that VM's log panel.
func (a *App) prep(name string) (*vmstart.Prep, error) {
a.mu.Lock()
cfg := *a.cfg
a.mu.Unlock()
return vmstart.New(cfg, func(line string) { a.emitLog(name, line) })
}
+3 -1
View File
@@ -1,6 +1,6 @@
# 上游临时补丁队列(Upstream Patch Queue)
本目录仅存放**尚未被上游合入的最小兼容性补丁**,由本地打包脚本与 CI 构建流程在编译 `vendor/qemu` 前通过 `git apply` 自动应用。
本目录仅存放**尚未被上游合入的最小兼容性补丁**,由本地打包脚本与 CI 构建流程在编译 `vendor/qemu` 前通过 `git apply` 自动应用。应用顺序和作用对象以 [`series.txt`](series.txt) 为准,CI(`scripts/apply-patch-series.ps1`)与 `scripts/pack-runtime.ps1` 都只读这一份清单。
## 原则
1. **内核/引擎 Bug 优先上游化**:补丁同步提交 PR/Issue 给上游(`steelbrain/qemu-reims-vgpu` / `steelbrain/reims-vgpu`),绝不长期维护独立 fork。
@@ -11,6 +11,8 @@
| 文件 | 目标仓库 / 基准 commit | 解决的问题 | 上游状态 |
| :--- | :--- | :--- | :--- |
| `reims-vgpu-cargo-lock.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `Cargo.lock` | 不改代码:cargo 构建时给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 三个包补上了 `source = "git+…metal2vulkan?rev=0b0ac58…"`。为了让源码包和实际构建逐字节一致,照实声明(2026-11-28 从本机构建目录 `git diff` 取得) | 不需要上游修复;上游 `Cargo.lock` 补齐后即可删除 |
| `reims-vgpu-win32-unicode-input.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `crates/reims-vgpu-window` | Windows 窗口层仅处理 `SDL_EVENT_KEY_DOWN`/`UP` 且丢弃扫描码为 0 的 `VK_PACKET` 及 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,导致远程输入法、宿主机 IME、语音输入注入的文字无法进入客体;通过 `SDL_SetWindowsMessageHook` 在配置 `REIMS_GO_INPUT_URL` 时将非物理按键字符异步转发至本地回环桥,物理键码路径零影响 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时实测验证后提上游 PR |
| `qemu-whpx-win10-compat.patch` | `steelbrain/qemu-reims-vgpu` (`4571bc5`) | 修复 Windows 10 19045 上 WHPX 两处必现崩溃:① `whpx_tsc_deadline_refused()` 在正式 partition 上删建 vCPU 0 导致 `WHvCreateVirtualProcessor` 返回 `0x80070057`;② `whpx_set_registers()` 调用 Win11 新增的 `WHvResetPartition` 未判空导致 `0xc0000005` 崩溃 | 待提交上游 PR |
| `qemu-whpx-win10-startup-ipis.patch` | 同上,须在前一项之后应用 | Win10 开启内核 irqchip 时,将多核客体的 INIT/SIPI 经 `WHvRequestInterrupt` 转发,避免 XNU 启动从核时停住。8 核两次冷启动与 12 核冷启动均验证 x2APIC、FileVault、SSH 和图形登录,默认 8 核启动与正常关机也通过。多核整体性能收益和客体冷重启仍待验证 | 待提交上游 PR |
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上,须在前两项之后应用 | 部分 Windows 11 宿主(如 24H2/Home 或 Core Ultra 200)在 `WHvGetCapability` 报告 `Bank1.NestedVirtSupport=1`,但 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)。原代码将其视为致命错误直接中止启动,迫使退回 `kernel-irqchip=off`;改为 `warn_report` 并清零 `Bank1.NestedVirtSupport`,保留完整的 Hyper-V 内核态 x2APIC / SynIC 加速 | 待真机编译冒烟后提交上游 PR |
| `qemu-win32-coroutine-fiber-commit.patch` | `steelbrain/qemu-reims-vgpu` (`4571bc5`) 的 `util/coroutine-windows.c` | 修复 Windows 下并发磁盘 I/O(如登录 Apple ID 触发 VA-API 解码 + iCloud/AHCI 并发读盘)时 `CreateFiber(1 MiB)` 提前提交整块 1 MiB 栈导致提交内存见底返回 `NULL`,且未判空直接进入 `SwitchToFiber(NULL)` 触发 `0xc0000005`(读 `0x10`)闪退;改为 `CreateFiberEx(64 KiB, 1 MiB, 0, ...)` 将初始提交降为 1/16,同时在 `qemu_coroutine_new()` 与 `qemu_coroutine_self()` 中处理 `IsThreadAFiber()` 并对 `NULL` 报错中止 | 待编译冒烟验证后提交上游 PR |
@@ -0,0 +1,60 @@
diff --git a/util/coroutine-windows.c b/util/coroutine-windows.c
--- a/util/coroutine-windows.c
+++ b/util/coroutine-windows.c
@@ -26,6 +26,8 @@
#include "qemu/coroutine_int.h"
#include "qemu/coroutine-tls.h"
+#define COROUTINE_INITIAL_COMMIT_SIZE (64 * 1024)
+
typedef struct
{
Coroutine base;
@@ -71,11 +73,26 @@
Coroutine *qemu_coroutine_new(void)
{
const size_t stack_size = COROUTINE_STACK_SIZE;
+ const size_t commit_size = MIN(COROUTINE_INITIAL_COMMIT_SIZE, stack_size);
CoroutineWin32 *co;
co = g_malloc0(sizeof(*co));
- co->fiber = CreateFiber(stack_size, coroutine_trampoline, &co->base);
+ /*
+ * CreateFiber(stack_size, ...) commits the full 1 MiB stack up front,
+ * which can exhaust Windows commit charge during burst disk I/O + GPU
+ * workloads and return NULL (later crashing inside SwitchToFiber(NULL)
+ * reading 0x10). Reserve stack_size while committing only 64 KiB upfront.
+ */
+ co->fiber = CreateFiberEx(commit_size, stack_size, 0,
+ coroutine_trampoline, &co->base);
+ if (!co->fiber) {
+ fprintf(stderr,
+ "qemu_coroutine_new: CreateFiberEx(commit=%zu, reserve=%zu) failed: "
+ "GetLastError()=%lu\n",
+ commit_size, stack_size, (unsigned long)GetLastError());
+ abort();
+ }
return &co->base;
}
@@ -96,7 +113,18 @@
current = &leader->base;
set_current(current);
- leader->fiber = ConvertThreadToFiber(NULL);
+ if (IsThreadAFiber()) {
+ leader->fiber = GetCurrentFiber();
+ } else {
+ leader->fiber = ConvertThreadToFiber(NULL);
+ }
+ if (!leader->fiber) {
+ fprintf(stderr,
+ "qemu_coroutine_self: ConvertThreadToFiber failed: "
+ "GetLastError()=%lu\n",
+ (unsigned long)GetLastError());
+ abort();
+ }
}
return current;
}
@@ -0,0 +1,238 @@
diff --git a/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs b/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs
index 6f70e07..074917c 100644
--- a/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs
+++ b/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs
@@ -183,6 +183,8 @@ fn start_video() -> bool {
);
return false;
}
+ #[cfg(target_os = "windows")]
+ super::super::windows::install_unicode_input_hook();
// SAFETY: SDL's video runs.
let kind = unsafe { SDL_RegisterEvents(1) };
WAKE.store(kind, Ordering::Release);
diff --git a/crates/reims-vgpu-window/src/native/windows.rs b/crates/reims-vgpu-window/src/native/windows.rs
index cc456c5..4ce46a6 100644
--- a/crates/reims-vgpu-window/src/native/windows.rs
+++ b/crates/reims-vgpu-window/src/native/windows.rs
@@ -42,12 +42,19 @@
//! taskbar then goes to the bottom of the z-order while the window is active, and that taking
//! the mark away leaves the window to the shell's own detection.
+use std::cell::Cell;
use std::ffi::c_void;
+use std::io::Write;
+use std::net::{SocketAddr, TcpStream};
use std::ptr::{NonNull, null, null_mut};
+use std::sync::OnceLock;
+use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
+use std::time::Duration;
use sdl3_sys::everything::{
- SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
- SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_WINDOW_FULLSCREEN, SDL_Window,
+ MSG as SDL_MSG, SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
+ SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_SetWindowsMessageHook, SDL_WINDOW_FULLSCREEN,
+ SDL_Window,
};
use windows_sys::Win32::Foundation::{FALSE, HWND, RPC_E_CHANGED_MODE, S_FALSE, S_OK, TRUE};
use windows_sys::Win32::System::Com::{
@@ -62,6 +69,198 @@ use crate::capture::HostOs;
/// The OS whose names the title gives the release chord's keys: Ctrl+Alt+Win (the module doc).
pub(super) const HOST_OS: HostOs = HostOs::Windows;
+/// Win32 MSG layout matching winuser.h for SDL_SetWindowsMessageHook.
+#[repr(C)]
+struct Win32Msg {
+ /// Target window handle.
+ _hwnd: HWND,
+ /// Message identifier (WM_*).
+ message: u32,
+ /// WPARAM.
+ w_param: usize,
+ /// LPARAM.
+ _l_param: isize,
+ /// Message timestamp (GetMessageTime).
+ time: u32,
+ /// Cursor position (POINT).
+ _pt: [i32; 2],
+}
+
+/// WM_KEYDOWN.
+const WM_KEYDOWN: u32 = 0x0100;
+/// WM_CHAR.
+const WM_CHAR: u32 = 0x0102;
+/// WM_SYSKEYDOWN.
+const WM_SYSKEYDOWN: u32 = 0x0104;
+/// WM_UNICHAR.
+const WM_UNICHAR: u32 = 0x0109;
+/// WM_IME_CHAR.
+const WM_IME_CHAR: u32 = 0x0286;
+/// UNICODE_NOCHAR.
+const UNICODE_NOCHAR: usize = 0xFFFF;
+/// VK_PROCESSKEY (host IME intercepted key).
+const VK_PROCESSKEY: u16 = 0x00E5;
+/// VK_PACKET (SendInput with KEYEVENTF_UNICODE).
+const VK_PACKET: u16 = 0x00E7;
+
+/// Non-blocking channel carrying UTF-16 code units from the SDL UI thread to the HTTP forwarder.
+static UNICODE_TX: OnceLock<SyncSender<u16>> = OnceLock::new();
+
+thread_local! {
+ /// Whether the most recent WM_KEYDOWN was unmapped (VK_PACKET or VK_PROCESSKEY).
+ static LAST_KEY_UNMAPPED: Cell<bool> = const { Cell::new(false) };
+ /// Timestamp of the most recent normal WM_KEYDOWN that SDL translates to a USB key.
+ static LAST_MAPPED_KEY_TIME: Cell<u32> = const { Cell::new(0) };
+}
+
+/// Parses a loopback http://127.0.0.1:<port><path> endpoint from REIMS_GO_INPUT_URL.
+fn parse_loopback_input_url(raw: &str) -> Option<(SocketAddr, String)> {
+ let rest = raw.trim().strip_prefix("http://127.0.0.1:")?;
+ let (port_str, path) = match rest.find('/') {
+ Some(idx) => (&rest[..idx], &rest[idx..]),
+ None => (rest, "/v1/host-text"),
+ };
+ let port: u16 = port_str.parse().ok()?;
+ if port == 0 || path.contains(['\r', '\n', ' ']) {
+ return None;
+ }
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+ Some((addr, path.to_owned()))
+}
+
+/// Installs a Win32 message hook on SDL's UI thread when REIMS_GO_INPUT_URL and
+/// REIMS_GO_INPUT_TOKEN are set, forwarding non-keyboard WM_CHAR / WM_UNICHAR /
+/// WM_IME_CHAR text (remote IMEs, dictation, host IME commits) to the local host bridge.
+pub(super) fn install_unicode_input_hook() {
+ let Ok(url) = std::env::var("REIMS_GO_INPUT_URL") else {
+ return;
+ };
+ let Ok(token) = std::env::var("REIMS_GO_INPUT_TOKEN") else {
+ return;
+ };
+ if token.is_empty() || token.contains(['\r', '\n']) {
+ return;
+ }
+ let Some((addr, path)) = parse_loopback_input_url(&url) else {
+ log::warn!(target: "reims_vgpu_window", "ignoring non-loopback REIMS_GO_INPUT_URL");
+ return;
+ };
+ let (tx, rx) = mpsc::sync_channel::<u16>(512);
+ if UNICODE_TX.set(tx).is_err() {
+ return;
+ }
+ let _ = std::thread::Builder::new()
+ .name("reims-vgpu.ime".into())
+ .spawn(move || forward_unicode_loop(rx, addr, path, token));
+ // SAFETY: called on SDL's UI thread right after SDL_Init(SDL_INIT_VIDEO).
+ unsafe { SDL_SetWindowsMessageHook(Some(unicode_message_hook), null_mut()) };
+}
+
+/// Enqueues a UTF-16 code unit without blocking the Win32 message loop.
+fn enqueue_utf16(unit: u16) {
+ if unit != 0
+ && let Some(tx) = UNICODE_TX.get()
+ {
+ let _ = tx.try_send(unit);
+ }
+}
+
+/// SDL Win32 message hook: forwards non-physical WM_CHAR / WM_UNICHAR / WM_IME_CHAR
+/// events to the local input bridge while leaving all physical keyboard events untouched.
+unsafe extern "C" fn unicode_message_hook(_userdata: *mut c_void, raw_msg: *mut SDL_MSG) -> bool {
+ if raw_msg.is_null() {
+ return true;
+ }
+ // SAFETY: SDL passes a valid pointer to Win32 MSG for the duration of the callback.
+ let msg = unsafe { &*raw_msg.cast::<Win32Msg>() };
+ match msg.message {
+ WM_KEYDOWN | WM_SYSKEYDOWN => {
+ let vk = (msg.w_param & 0xFFFF) as u16;
+ if vk == VK_PACKET || vk == VK_PROCESSKEY {
+ LAST_KEY_UNMAPPED.set(true);
+ } else {
+ LAST_KEY_UNMAPPED.set(false);
+ LAST_MAPPED_KEY_TIME.set(msg.time);
+ }
+ true
+ }
+ WM_CHAR | WM_IME_CHAR => {
+ let unit = (msg.w_param & 0xFFFF) as u16;
+ let non_physical = unit >= 0x80
+ || LAST_KEY_UNMAPPED.get()
+ || msg.time != LAST_MAPPED_KEY_TIME.get();
+ if non_physical && (unit >= 0x20 || unit == 0x0D || unit == 0x09) {
+ enqueue_utf16(unit);
+ return false;
+ }
+ true
+ }
+ WM_UNICHAR => {
+ if msg.w_param != UNICODE_NOCHAR
+ && let Ok(code) = u32::try_from(msg.w_param)
+ && let Some(ch) = char::from_u32(code)
+ && (ch >= ' ' || ch == '\r' || ch == '\t')
+ {
+ let mut pair = [0u16; 2];
+ for &mut u in ch.encode_utf16(&mut pair) {
+ enqueue_utf16(u);
+ }
+ return false;
+ }
+ true
+ }
+ _ => true,
+ }
+}
+
+/// Decodes UTF-16 code units, coalesces bursts, and POSTs UTF-8 text to the loopback bridge.
+fn forward_unicode_loop(rx: mpsc::Receiver<u16>, addr: SocketAddr, path: String, token: String) {
+ let mut units: Vec<u16> = Vec::with_capacity(64);
+ loop {
+ let first = match rx.recv() {
+ Ok(u) => u,
+ Err(_) => return,
+ };
+ units.clear();
+ units.push(first);
+ if first != 0x0D {
+ while units.len() < 128 {
+ match rx.recv_timeout(Duration::from_millis(35)) {
+ Ok(u) => {
+ units.push(u);
+ if u == 0x0D {
+ break;
+ }
+ }
+ Err(RecvTimeoutError::Timeout) => break,
+ Err(RecvTimeoutError::Disconnected) => break,
+ }
+ }
+ }
+ let text: String = char::decode_utf16(units.iter().copied())
+ .filter_map(Result::ok)
+ .map(|c| if c == '\r' { '\n' } else { c })
+ .collect();
+ if !text.is_empty() {
+ post_loopback_text(addr, &path, &token, &text);
+ }
+ }
+}
+
+/// Sends a minimal HTTP/1.1 POST with UTF-8 ext to the local host bridge.
+fn post_loopback_text(addr: SocketAddr, path: &str, token: &str, text: &str) {
+ let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else {
+ return;
+ };
+ let _ = stream.set_write_timeout(Some(Duration::from_millis(500)));
+ let req = format!(
+ "POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ text.len()
+ );
+ let _ = stream.write_all(req.as_bytes());
+ let _ = stream.write_all(text.as_bytes());
+}
+
/// The GPU the compositor composites SDL's window on: none known on Windows (the module doc).
///
/// # Safety
+11
View File
@@ -0,0 +1,11 @@
# Patch queue, in the order the patches are applied (AGENTS.md rule 4,
# portable-runtime-spec.md section 5). One patch per line: <target> <file>.
# target is "reims-vgpu" (the upstream repository root) or "vendor/qemu".
# CI (build-runtime.yml via scripts/apply-patch-series.ps1) and
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
reims-vgpu reims-vgpu-cargo-lock.patch
reims-vgpu reims-vgpu-win32-unicode-input.patch
vendor/qemu qemu-whpx-win10-compat.patch
vendor/qemu qemu-whpx-win10-startup-ipis.patch
vendor/qemu qemu-whpx-nested-virt-nonfatal.patch
vendor/qemu qemu-win32-coroutine-fiber-commit.patch
+17 -13
View File
@@ -26,10 +26,10 @@ func (a *App) baseCtx() context.Context {
return context.Background()
}
func (a *App) includeCandidate() bool {
func (a *App) includeAlpha() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.RuntimeChannel == rt.ChannelCandidate
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
}
// remoteCache keeps the release list for a while: GitHub allows 60
@@ -37,26 +37,26 @@ func (a *App) includeCandidate() bool {
// the CLI all ask for it.
var remoteCache struct {
sync.Mutex
at time.Time
candidate bool
list []rt.Remote
at time.Time
alpha bool
list []rt.Remote
}
const remoteCacheTTL = 10 * time.Minute
// ListRemoteRuntimes lists published runtimes for the configured channel.
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
cand := a.includeCandidate()
alpha := a.includeAlpha()
remoteCache.Lock()
defer remoteCache.Unlock()
if remoteCache.list != nil && remoteCache.candidate == cand && time.Since(remoteCache.at) < remoteCacheTTL {
if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL {
return remoteCache.list, nil
}
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), cand)
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha)
if err != nil {
return nil, err
}
remoteCache.at, remoteCache.candidate, remoteCache.list = time.Now(), cand, list
remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list
return list, nil
}
@@ -67,9 +67,13 @@ func forgetRemoteRuntimes() {
remoteCache.Unlock()
}
// SetRuntimeChannel picks "stable" or "candidate" for online installs.
// SetRuntimeChannel picks "stable" or "alpha" for online installs
// ("candidate", the old name for alpha, is still accepted).
func (a *App) SetRuntimeChannel(channel string) error {
if channel != rt.ChannelStable && channel != rt.ChannelCandidate {
switch channel {
case rt.ChannelStable, rt.ChannelAlpha, "candidate":
channel = rt.NormalizeChannel(channel)
default:
return fmt.Errorf("unknown channel %q", channel)
}
a.mu.Lock()
@@ -131,9 +135,9 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
}
step("Looking up runtime releases on GitHub")
// An explicit commit may be a candidate even on the stable channel: the
// An explicit commit may be an alpha even on the stable channel: the
// user asked for it by name.
list, err := src.ListRemote(ctx, cfg.RuntimeChannel == rt.ChannelCandidate || (commit != "" && commit != "latest"))
list, err := src.ListRemote(ctx, rt.NormalizeChannel(cfg.RuntimeChannel) == rt.ChannelAlpha || (commit != "" && commit != "latest"))
if err != nil {
return "", err
}
+86
View File
@@ -0,0 +1,86 @@
<#
.SYNOPSIS
Apply the patch queue in patches/series.txt to an upstream reims-vgpu checkout.
.DESCRIPTION
For each patch, in series order:
- applies cleanly -> apply it;
- already in the tree -> skip it (git apply --reverse --check passes: on a
fresh upstream clone this means merged upstream);
- neither -> stop with an error. Patches are never edited
automatically (AGENTS.md rule 4).
Writes the result as JSON to -ResultFile:
{ "applied": ["a.patch", ...], "merged": ["b.patch", ...], "conflict": "c.patch" | null }
so CI can pass the applied list to pack-runtime.ps1 (manifest states only what
was really applied, AGENTS.md rule 5) and report merged or conflicting patches.
.EXAMPLE
pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -ResultFile patches.json
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ReimsRepo,
[string]$ResultFile = ''
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
function Read-PatchSeries {
$series = Join-Path $patchesDir 'series.txt'
foreach ($line in Get-Content -LiteralPath $series) {
$t = $line.Trim()
if (-not $t -or $t.StartsWith('#')) { continue }
$parts = $t -split '\s+'
if ($parts.Count -ne 2 -or $parts[0] -notin @('reims-vgpu', 'vendor/qemu')) {
throw "Bad line in patches/series.txt: '$line'"
}
[pscustomobject]@{ Target = $parts[0]; Name = $parts[1] }
}
}
$result = [ordered]@{ applied = @(); merged = @(); conflict = $null }
function Save-Result {
if ($ResultFile) {
[IO.File]::WriteAllText($ResultFile, ($result | ConvertTo-Json -Depth 3), [Text.UTF8Encoding]::new($false))
}
}
foreach ($p in Read-PatchSeries) {
$file = Join-Path $patchesDir $p.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch listed in series.txt is missing: $file" }
$dir = if ($p.Target -eq 'vendor/qemu') { Join-Path $ReimsRepo 'vendor\qemu' } else { $ReimsRepo }
# git -C into a missing or uninitialised submodule falls back to the outer
# repository, where "git apply" silently skips paths outside the current
# directory and reports success. Require $dir to be its own work tree.
$top = (& git -C $dir rev-parse --show-toplevel 2>$null)
if ($LASTEXITCODE -ne 0 -or -not $top -or
[IO.Path]::GetFullPath($top.Trim()).TrimEnd([char[]]'\/') -ne [IO.Path]::GetFullPath($dir).TrimEnd([char[]]'\/')) {
throw "$dir is not a checked-out git work tree (is the vendor/qemu submodule initialised?)"
}
& git -C $dir apply --check $file 2>$null
if ($LASTEXITCODE -eq 0) {
& git -C $dir apply $file
if ($LASTEXITCODE -ne 0) { throw "git apply $($p.Name) failed after a clean --check" }
Write-Host "applied $($p.Target) $($p.Name)"
$result.applied += $p.Name
continue
}
& git -C $dir apply --reverse --check $file 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "merged $($p.Target) $($p.Name) (already in the tree: merged upstream? retire it per spec section 5 rule 4)"
$result.merged += $p.Name
continue
}
$result.conflict = $p.Name
Save-Result
# Show git's own reason in the log.
& git -C $dir apply --check $file
throw "$($p.Name) neither applies nor is already upstream in $dir. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
$global:LASTEXITCODE = 0
Save-Result
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more