Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48e75ca665 | ||
|
|
9c8a75448d | ||
|
|
3b26f6117f | ||
|
|
f5ec733230 | ||
|
|
7641a7c948 | ||
|
|
1276050569 | ||
|
|
8acc0c3c23 | ||
|
|
172df5c4d5 | ||
|
|
f85e1aba88 | ||
|
|
a7921e998b | ||
|
|
24f29f806f | ||
|
|
33ac322bb2 | ||
|
|
5000e00780 | ||
|
|
d21ee22c80 | ||
|
|
99e189bef2 | ||
|
|
0ad5652ecd | ||
|
|
4cf1e8ea37 | ||
|
|
31a72892de | ||
|
|
12fa25d089 | ||
|
|
181ad64618 | ||
|
|
1017301682 | ||
|
|
470ed2d30a | ||
|
|
2f1e0bb0e4 | ||
|
|
69803355bf | ||
|
|
d30c694e2f |
No files matched your search
@@ -17,6 +17,10 @@ on:
|
||||
description: "Publish as an alpha prerelease (never stable)"
|
||||
type: boolean
|
||||
default: true
|
||||
rebuild:
|
||||
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -36,22 +40,50 @@ jobs:
|
||||
outputs:
|
||||
commit: ${{ steps.r.outputs.commit }}
|
||||
skip: ${{ steps.r.outputs.skip }}
|
||||
suffix: ${{ steps.r.outputs.suffix }}
|
||||
steps:
|
||||
- id: r
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
WANT: ${{ inputs.upstream_commit }}
|
||||
REBUILD: ${{ inputs.rebuild }}
|
||||
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
|
||||
# Already published (alpha or stable) under any short-hash length or -pN revision?
|
||||
max_rev=0
|
||||
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
|
||||
rest="${tag#runtime-}"
|
||||
base="${rest%%-p*}"
|
||||
case "$commit" in
|
||||
"$base"*)
|
||||
rev=1
|
||||
if [ "$rest" != "$base" ]; then
|
||||
num="${rest#"$base"-p}"
|
||||
case "$num" in
|
||||
''|*[!0-9]*) ;;
|
||||
*) rev="$num" ;;
|
||||
esac
|
||||
fi
|
||||
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
|
||||
echo "Upstream $commit is already released as $tag (rev $rev)"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
skip=false
|
||||
suffix=""
|
||||
if [ "$max_rev" -gt 0 ]; then
|
||||
if [ "$REBUILD" = "true" ]; then
|
||||
suffix="-p$((max_rev + 1))"
|
||||
echo "Rebuild requested: will publish with suffix $suffix"
|
||||
else
|
||||
skip=true
|
||||
fi
|
||||
fi
|
||||
echo "skip=$skip" >> "$GITHUB_OUTPUT"
|
||||
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
needs: resolve
|
||||
@@ -60,6 +92,7 @@ jobs:
|
||||
timeout-minutes: 150
|
||||
outputs:
|
||||
short: ${{ steps.patches.outputs.short }}
|
||||
release_id: ${{ steps.patches.outputs.release_id }}
|
||||
applied: ${{ steps.patches.outputs.applied }}
|
||||
merged: ${{ steps.patches.outputs.merged }}
|
||||
conflict: ${{ steps.patches.outputs.conflict }}
|
||||
@@ -99,8 +132,10 @@ jobs:
|
||||
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()
|
||||
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
|
||||
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
|
||||
"short=$short" >> $env:GITHUB_OUTPUT
|
||||
"release_id=$releaseId" >> $env:GITHUB_OUTPUT
|
||||
|
||||
# Applies what applies, skips what upstream already has, stops on a
|
||||
# conflict without touching the patch (AGENTS.md rule 4).
|
||||
@@ -120,6 +155,7 @@ jobs:
|
||||
if (-not $ok) { throw 'patch queue does not apply' }
|
||||
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
|
||||
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
|
||||
"RELEASE_ID=$releaseId" >> $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
|
||||
@@ -151,6 +187,7 @@ jobs:
|
||||
-OutDir $outDir `
|
||||
-TempRoot $env:RUNNER_TEMP `
|
||||
-Channel alpha `
|
||||
-ReleaseId $env:RELEASE_ID `
|
||||
-Patches $applied
|
||||
|
||||
- name: Alpha entry gate
|
||||
@@ -159,14 +196,14 @@ jobs:
|
||||
$ErrorActionPreference = 'Stop'
|
||||
& ./scripts/check-runtime-alpha.ps1 `
|
||||
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
|
||||
-Commit $env:SHORT_COMMIT `
|
||||
-Commit $env:RELEASE_ID `
|
||||
-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 }}-alpha
|
||||
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
|
||||
path: |
|
||||
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
|
||||
${{ runner.temp }}/releases/SHA256SUMS.txt
|
||||
@@ -180,14 +217,15 @@ jobs:
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$c = $env:SHORT_COMMIT
|
||||
$c = $env:RELEASE_ID
|
||||
$short = $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 }}).
|
||||
**Alpha** runtime (``$c``), built automatically from upstream [steelbrain/reims-vgpu@$short](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).
|
||||
|
||||
@@ -199,6 +237,24 @@ jobs:
|
||||
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
|
||||
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
|
||||
- name: Mirror alpha prerelease to GitCode (best-effort)
|
||||
if: github.event_name == 'schedule' || inputs.publish
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
GITHUB_REPO: ${{ github.repository }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
if (-not $env:GITCODE_TOKEN) {
|
||||
Write-Host 'GITCODE_TOKEN not set; skipping GitCode mirror'
|
||||
exit 0
|
||||
}
|
||||
$tag = "runtime-$($env:RELEASE_ID)"
|
||||
git fetch --tags origin
|
||||
git -c credential.helper= push "https://Nwflower:$($env:GITCODE_TOKEN)@gitcode.com/Nwflower/Reims-Go.git" "refs/tags/${tag}:refs/tags/${tag}"
|
||||
python scripts/sync-gitcode-release.py $tag
|
||||
|
||||
- name: Prune old alpha prereleases
|
||||
if: github.event_name == 'schedule' || inputs.publish
|
||||
env:
|
||||
|
||||
@@ -38,9 +38,11 @@ jobs:
|
||||
go test ./...
|
||||
go vet ./...
|
||||
|
||||
- name: Build CLI & GUI binaries
|
||||
- name: Build reims-go.exe (window + command-line mode)
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path build/bin | Out-Null
|
||||
go build -trimpath -o build/bin/reims-go-cli.exe ./cmd/reims-go
|
||||
go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o build/bin/reims-go.exe .
|
||||
# Command-line mode must still answer through a pipe from the GUI-subsystem build.
|
||||
$out = & build/bin/reims-go.exe version | Out-String
|
||||
if ($LASTEXITCODE -ne 0 -or $out -notmatch '^reims-go ') { throw "reims-go.exe version failed: $out" }
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
shell: pwsh
|
||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@v2.17.1
|
||||
|
||||
- name: Build Windows x64 GUI & CLI binaries
|
||||
- name: Build Windows x64 binary
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -64,11 +64,10 @@ jobs:
|
||||
$dist = 'dist-release'
|
||||
New-Item -ItemType Directory -Force -Path $dist | Out-Null
|
||||
$verPkg = 'github.com/Nwflower/reims-go/internal/version'
|
||||
# One executable: the window without arguments, command-line mode with a command.
|
||||
$guiOut = Join-Path $dist "reims-go-$tag-windows-amd64.exe"
|
||||
$cliOut = Join-Path $dist "reims-go-cli-$tag-windows-amd64.exe"
|
||||
wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o "reims-go-$tag-windows-amd64.exe"
|
||||
Copy-Item (Join-Path 'build\bin' "reims-go-$tag-windows-amd64.exe") $guiOut
|
||||
go build -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o $cliOut ./cmd/reims-go
|
||||
$lines = @(Get-ChildItem -LiteralPath $dist -File | Sort-Object Name | ForEach-Object {
|
||||
$h = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()
|
||||
"$h $($_.Name)"
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Sync Mirror to GitCode
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
release:
|
||||
types: [published, released, edited, prereleased]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Specific release tag to sync (empty = latest app release + all runtime-* releases)"
|
||||
required: false
|
||||
default: ""
|
||||
sync_releases:
|
||||
description: "Also sync Release metadata and assets to GitCode"
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
concurrency:
|
||||
group: sync-gitcode
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GITCODE_REPO: Nwflower/Reims-Go
|
||||
GITCODE_USER: Nwflower
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Push main branch and tags to GitCode
|
||||
env:
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$GITCODE_TOKEN" ]; then
|
||||
echo "GITCODE_TOKEN secret is not configured; skipping."
|
||||
exit 0
|
||||
fi
|
||||
git fetch --tags origin
|
||||
# Use GIT_ASKPASS so the token never appears in URLs or process argv.
|
||||
askpass="$(mktemp)"
|
||||
chmod 700 "$askpass"
|
||||
cat > "$askpass" <<'EOF'
|
||||
#!/bin/sh
|
||||
case "$1" in
|
||||
*Username*) printf '%s\n' "$GITCODE_USER" ;;
|
||||
*) printf '%s\n' "$GITCODE_TOKEN" ;;
|
||||
esac
|
||||
EOF
|
||||
trap 'rm -f "$askpass"' EXIT
|
||||
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" HEAD:refs/heads/main
|
||||
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" --tags
|
||||
|
||||
- name: Sync Release and assets to GitCode
|
||||
if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.sync_releases)
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
GITHUB_REPO: ${{ github.repository }}
|
||||
TARGET_TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$GITCODE_TOKEN" ]; then
|
||||
echo "GITCODE_TOKEN secret is not configured; skipping release sync."
|
||||
exit 0
|
||||
fi
|
||||
if [ -n "$TARGET_TAG" ]; then
|
||||
python3 scripts/sync-gitcode-release.py "$TARGET_TAG"
|
||||
else
|
||||
python3 scripts/sync-gitcode-release.py
|
||||
fi
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# 更新日志
|
||||
|
||||
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
|
||||
|
||||
## v0.2.5 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 运行时下载与更新检查新增 GitCode 国内镜像源,默认自动优先 GitHub 并在不可达时自动切换 GitCode。
|
||||
- 桌面外壳视觉与交互升级:精简 VM 主页为 Studio Display 预览、2×3 图标规格卡、单行连接分组与可一键复制的技术信息;支持日志抽屉顶部拖拽调整高度。
|
||||
- 侧栏「宿主与运行时」改称「内核」,将应用配置拆分为独立「设置」标签页(新增浅色 / 深色 / 跟随系统外观切换)。
|
||||
- 底部状态栏空闲时实时展示宿主机内存占用百分比、可用内存、数据盘剩余空间与运行中虚拟机数量。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- 内嵌开源 Inter Variable 字体并按 Windows DirectWrite 特性显式映射多字重中文字体栈,修复默认字重偏轻与中英文混排断层问题。
|
||||
- 修复 GitCode API 将 alpha 运行时预发布返回为 `prerelease=false` 导致稳定通道误报新版本的问题。
|
||||
- 遵循 Windows 系统代理配置并在 GitHub API 触发限流时自动回退网页解析,下载检查失败时提供一键重试。
|
||||
- 按实际图形后端(`reims-vgpu` / `vmware-svga`)显示准确的虚拟机窗口快捷键提示。
|
||||
|
||||
## v0.2.4 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- 分辨率选项新增「全屏」,原来单独的全屏开关并入其中。
|
||||
- HiDPI 分辨率标出实际显示大小,例如「看起来像 1280 × 800」。
|
||||
- 宿主页显示 Windows 处理器计划(程序优先或后台服务),并可一键以管理员身份打开设置。
|
||||
|
||||
### 优化
|
||||
|
||||
- 分辨率推荐按 macOS 实际进入 HiDPI 的条件判断,只列出放得进屏幕的尺寸;进不了 HiDPI 时会说明怎么办。
|
||||
- 虚拟机自己关机或退出后,界面立即显示已停止,不再最多等 5 秒。
|
||||
- 设置页能正确读出已保存的分辨率、显示器数量、VMware SVGA 显卡后端和不限时的关机等待。
|
||||
- 显示器数量改成多块后可以再改回 1。
|
||||
|
||||
## v0.2.3 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 命令行并入 `reims-go.exe`:双击打开界面,带子命令即在终端运行,不再单独提供命令行版。
|
||||
- 从命令行启动的虚拟机交给 Reims-Go 界面托管,界面没开时自动在托盘后台运行,同样有剪贴板、共享目录和 Win10 自动冷重启。
|
||||
- 同时只运行一个 Reims-Go,再次双击会唤出已打开的窗口。
|
||||
- 可把 Windows 本地磁盘只读共享给 macOS,每台虚拟机单独开启,默认关闭。
|
||||
|
||||
### 优化
|
||||
|
||||
- 虚拟机页面在后台查询虚拟机状态的次数减少约八成。
|
||||
- 屏幕缩略图生成更快、改为每 15 秒刷新,虚拟机窗口在前台时暂停截图,减少对虚拟机的打扰。
|
||||
- 命令行启动失败时直接显示原因。
|
||||
|
||||
## v0.2.2 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- Guest Tools 2.0:支持图片剪贴板,共享目录可直接挂载到 macOS。
|
||||
- 可向虚拟机发送中文和 emoji,宿主机输入法也能直接输入到虚拟机。
|
||||
- 系统托盘驻留,关闭窗口后最小化到托盘,可从托盘启停虚拟机。
|
||||
- 一键开关 macOS 防休眠。
|
||||
- 详情页实时显示虚拟机的 CPU、内存、磁盘占用和运行时长。
|
||||
- 详情页显示虚拟机屏幕缩略图。
|
||||
- 按显示器分辨率和缩放推荐 HiDPI 分辨率。
|
||||
- 可预设 macOS 系统语言,恢复模式和设置助理不再总是英文。
|
||||
- 虚拟磁盘支持停机扩容和回收未用空间。
|
||||
- 可切换音频后端,并检查宿主机的播放和录音设备。
|
||||
- 设置面板改版为 macOS 系统设置风格,改动可逐项撤销。
|
||||
- 运行时候选通道改名为 alpha,每天自动从上游构建。
|
||||
|
||||
### 优化
|
||||
|
||||
- 截取缩略图改用更快的格式,截图时虚拟机的卡顿大幅减少。
|
||||
- 运行中虚拟机的状态识别更准确,相关提示和保护恢复正常。
|
||||
|
||||
## v0.2.1 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 离线装机辅助盘自动完成抹盘和安装命令,装机不用手敲长命令。
|
||||
- 一键进入或退出恢复模式,可挂载离线镜像或下载在线恢复镜像。
|
||||
- Guest Tools:宿主机与 macOS 之间双向剪贴板和共享文件夹。
|
||||
- 已关机的虚拟机可秒级派生出独立副本。
|
||||
- 新建虚拟机时可导入 VMDK 或 RAW 磁盘。
|
||||
- 一键导出已脱敏的排障日志包。
|
||||
- 宿主页显示当前版本并检查更新。
|
||||
|
||||
### 优化
|
||||
|
||||
- 新建虚拟机默认使用 NVMe 磁盘,旧虚拟机可一键升级。
|
||||
- 绑核支持三层大小核,虚拟 CPU 多于性能核时自动避开低功耗核。
|
||||
- Win10 冷重启使用的控制通道只在本机可见,虚拟机内无法访问。
|
||||
- 数据目录在外置盘、网络盘或内存负载过高时给出提示。
|
||||
- 临时文件全部放在数据目录里,不再写入 C 盘。
|
||||
|
||||
## v0.2.0 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 默认用离线安装包装机,装机引导精简为三步。
|
||||
- 新增「安装包」页面,可下载、暂停、续传和删除离线安装包。
|
||||
- 按 Windows 实际可用内存推荐内存大小,新建、修改和启动前都会检查。
|
||||
- 首次启动时先检查 WHPX、显卡和内存,再安装运行时。
|
||||
- 新建助手增加确认页,创建改在后台进行。
|
||||
|
||||
### 优化
|
||||
|
||||
- 宿主页去掉重复信息,运行时合并为一个列表。
|
||||
- 新建时虚拟机重名会提前提示。
|
||||
- 运行时版本列表缓存 10 分钟,避免触发 GitHub 访问次数限制。
|
||||
|
||||
## v0.1.0 — 2026-11-28
|
||||
|
||||
### 新功能
|
||||
|
||||
- 首个版本:单文件桌面应用,在 Windows x64 上运行带 GPU 加速的 macOS 虚拟机,无需自己编译。
|
||||
- 虚拟机列表、启动和关机、分类设置面板与分步新建助手。
|
||||
- 离线安装包下载,支持暂停和续传。
|
||||
- 运行时在线安装,分稳定版和候选版两个通道。
|
||||
- 宿主机体检,虚拟机启动后自动绑定到性能核。
|
||||
- Win10 上虚拟机内部重启时自动冷重启。
|
||||
@@ -77,15 +77,17 @@ wails build
|
||||
|
||||
### 命令行
|
||||
|
||||
命令行模式就在同一个 `reims-go.exe` 里:不带参数打开窗口,带子命令就在终端里执行。
|
||||
|
||||
```powershell
|
||||
reims-go doctor # 环境体检
|
||||
reims-go runtime fetch # 在线安装运行时
|
||||
reims-go installer download tahoe # 下载离线安装包(支持续传)
|
||||
reims-go vm create macos-tahoe # 新建虚拟机
|
||||
reims-go vm start macos-tahoe # 启动虚拟机
|
||||
reims-go doctor | Out-Host # 环境体检
|
||||
reims-go runtime fetch | Out-Host # 在线安装运行时
|
||||
reims-go installer download tahoe | Out-Host # 下载离线安装包(支持续传)
|
||||
reims-go vm create macos-tahoe | Out-Host # 新建虚拟机
|
||||
reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘里的 Reims-Go,带剪贴板与共享目录)
|
||||
```
|
||||
|
||||
运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
|
||||
`reims-go.exe` 是窗口程序,交互式 PowerShell / cmd 不会等它结束;加 `| Out-Host`(或任何管道、重定向)就会等命令执行完并给出退出码。脚本和 Agent 通过管道调用,不受影响。运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
|
||||
|
||||
<br />
|
||||
|
||||
@@ -136,3 +138,15 @@ reims-go vm start macos-tahoe # 启动虚拟机
|
||||
## 友情链接
|
||||
|
||||
- [LINUX DO](https://linux.do/) — 新的理想型社区
|
||||
|
||||
<br />
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/#Nwflower/Reims-Go&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Nwflower/Reims-Go&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
@@ -1,49 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
// attachConsole is only needed for Windows GUI-subsystem builds.
|
||||
func attachConsole() {}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procAttachConsole = kernel32.NewProc("AttachConsole")
|
||||
)
|
||||
|
||||
const attachParentProcess = ^uintptr(0) // ATTACH_PARENT_PROCESS, (DWORD)-1
|
||||
|
||||
// attachConsole gives command-line mode somewhere to write. reims-go.exe is
|
||||
// a GUI-subsystem program, so Windows starts it without a console. Handles
|
||||
// the caller passed in (a pipe, a file: how agents and scripts run it) are
|
||||
// kept; only missing ones are pointed at the console of the terminal that
|
||||
// launched it.
|
||||
func attachConsole() {
|
||||
out, errOut, in := usable(os.Stdout), usable(os.Stderr), usable(os.Stdin)
|
||||
if out && errOut && in {
|
||||
return
|
||||
}
|
||||
if r, _, _ := procAttachConsole.Call(attachParentProcess); r == 0 {
|
||||
return // started from Explorer or a shortcut: nowhere to write
|
||||
}
|
||||
if !out || !errOut {
|
||||
if f, err := os.OpenFile("CONOUT$", os.O_RDWR, 0); err == nil {
|
||||
if !out {
|
||||
os.Stdout = f
|
||||
}
|
||||
if !errOut {
|
||||
os.Stderr = f
|
||||
}
|
||||
}
|
||||
}
|
||||
if !in {
|
||||
if f, err := os.OpenFile("CONIN$", os.O_RDWR, 0); err == nil {
|
||||
os.Stdin = f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// usable reports whether f wraps a real handle the caller passed in.
|
||||
func usable(f *os.File) bool {
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
h := syscall.Handle(f.Fd())
|
||||
if h == 0 || h == syscall.InvalidHandle {
|
||||
return false
|
||||
}
|
||||
t, err := syscall.GetFileType(h)
|
||||
return err == nil && t != syscall.FILE_TYPE_UNKNOWN
|
||||
}
|
||||
+15
-9
@@ -6,7 +6,7 @@
|
||||
|
||||
1. **零编译上手**:用户拿到单个 `reims-go.exe`(或便携压缩包),首次启动向导自动检测环境 → 下载/导入便携运行时 → 创建并启动 macOS Tahoe。
|
||||
2. **不重复造 `reims-ctl` 的轮子**:`reims-go` 通过受控子进程包装 `reims-ctl`(及 `qemu-img`),避免像手写 PowerShell 启动脚本那样在每次上游变更参数时失效。
|
||||
3. **GUI 与 CLI 同源**:所有核心能力落在 `internal/` Go 包中;既可双击启动 Wails 桌面界面,也可通过 `reims-go <subcommand>` 在终端或 CI 中自动化调用。
|
||||
3. **GUI 与 CLI 同源、同一个 exe**:所有核心能力落在 `internal/` Go 包中。只发布一个 `reims-go.exe`:双击(无参数)打开 Wails 桌面界面,带子命令(`reims-go <subcommand>`)走命令行模式,供终端、脚本、CI 和 Agent 调用。2026-11-28 起不再单独发布 `reims-go-cli.exe`。
|
||||
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 ./...`。
|
||||
@@ -17,7 +17,7 @@
|
||||
flowchart TB
|
||||
subgraph UI["交互层"]
|
||||
GUI["Wails 桌面界面\n(React / Vite + WebView2)"]
|
||||
CLI["CLI 子命令\n(reims-go doctor/runtime/installer/vm)"]
|
||||
CLI["命令行模式(同一个 exe)\n(reims-go doctor/runtime/installer/vm)"]
|
||||
end
|
||||
|
||||
subgraph Core["Go 核心服务层 (internal/)"]
|
||||
@@ -59,7 +59,7 @@ flowchart TB
|
||||
|
||||
### 3.2 `internal/runtime` — 便携运行时管理
|
||||
- 维护 `<DataRoot>\runtimes\` 下的多版本便携运行时包:
|
||||
- **来源**:本仓库的 GitHub Release(tag `runtime-<commit>`,预发布为 `alpha`(CI 每天自动构建),正式发布为 `stable`),支持断点续传,并对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包。下载端点只有这一个,没有镜像,也不测速选路;
|
||||
- **来源**:本仓库的 GitHub Release(主源,tag `runtime-<commit>`,预发布为 `alpha`,正式发布为 `stable`)与官方镜像仓 [GitCode `Nwflower/Reims-Go`](https://gitcode.com/Nwflower/Reims-Go)(支持 `auto` 自动回退、`github`、`gitcode` 三种模式;自动读取环境变量与 Windows 系统代理;GitHub 限流时自动降级网页解析),均支持 HTTP `Range` 断点续传并强制对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包;
|
||||
- 校验 `manifest.json` 与 SHA256 后解压至 `<commit>.tmp` 再原子重命名,失败不破坏现有版本;
|
||||
- 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖;
|
||||
|
||||
@@ -83,9 +83,15 @@ flowchart TB
|
||||
- **配置写入只用 `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/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`)。
|
||||
- `internal/vmstart` 是 GUI 和 CLI 共用的启动步骤:提交内存预检、离线辅助盘、恢复模式引导菜单、客体语言重放、WHPX 嵌套虚拟化兼容,以及启动后的 P 核绑定。GUI 的 `StartVM`(`app.go`)调用它;CLI 的 `vm start`(`internal/cli/start.go`)通常把启动交给界面进程,只在指定了 `--data-root` 时自己调用它。
|
||||
- 只有界面进程做的两步:Guest Tools 桥接(`guesttools_flow.go`)和 Win10 冷重启监视(`app.go`)。这两步都需要启动后仍在运行的进程,而命令执行完就退出,所以 `vm start` 会把启动交给界面进程:
|
||||
- 界面已在运行:按 Wails 单实例协议(`options.SingleInstanceLock`,WM_COPYDATA)把 `--start-vm=<名称>` 发给它,不弹窗;
|
||||
- 界面没在运行:以 `--background` 拉起一个只在托盘里运行的界面进程(`StartHidden`)。拉起时与调用方的控制台和句柄分离,Agent 读的管道会随命令结束而关闭;
|
||||
- 两种情况都由界面调用 `StartVM`,再把结果写到 `<DataRoot>\tmp\cli-start-*.json`(只接受这个目录下的这类文件名),命令读到后带退出码返回。
|
||||
- 指定了 `--data-root` 的 `vm start` 仍在命令进程里启动,没有剪贴板和共享目录,Win10 上客体重启后不会自动拉起。
|
||||
- 单实例:同一用户只运行一个界面进程。再次双击会把已有窗口调到前台。`wails dev` 构建用另一个锁名(`internal/cli/instance_id_dev.go`),不会和已安装的 Reims-Go 互相抢。
|
||||
- 命令行模式与 Windows 子系统:`reims-go.exe` 是 GUI 子系统程序。命令行模式会保留调用方传入的句柄(管道、文件),缺失的才用 `AttachConsole` 接回父进程控制台(`console_windows.go`)。所以 Agent、脚本、管道调用都能正常拿到输出和退出码;在交互式 PowerShell / cmd 里,提示符会先返回,要等命令结束需加 `| Out-Host`。
|
||||
- GUI 的其余编排在 `internal/app` 的 `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` 转发端口,没有命令执行通道。
|
||||
|
||||
@@ -93,9 +99,10 @@ flowchart TB
|
||||
|
||||
```text
|
||||
reims-go/
|
||||
├── cmd/
|
||||
│ └── reims-go/ # 主入口(无参启动 Wails GUI,带子命令走 CLI 模式)
|
||||
├── main.go # 唯一入口:无参数启动 Wails 界面,带子命令走 internal/cli(附 console_*.go)
|
||||
├── internal/
|
||||
│ ├── app/ # GUI 编排层与 Wails 绑定(App、*_flow.go、tasks.go、vm_monitor.go、window_launch.go)
|
||||
│ ├── cli/ # 命令行模式:子命令、把 vm start 交给界面进程
|
||||
│ ├── config/ # reims-go.json(含 locale: zh-CN|en-US、DataRoot、P-Core 开关)
|
||||
│ ├── i18n/ # Go 端中英双语消息字典与结构化错误码
|
||||
│ ├── host/ # WHPX、提交内存预检、Vulkan ICD、P/E 核拓扑、进程亲和性(*_windows.go + *_other.go)
|
||||
@@ -110,7 +117,6 @@ reims-go/
|
||||
│ ├── thumb/ # 把截屏缩小成 JPEG
|
||||
│ ├── tray/ # 系统托盘
|
||||
│ └── version/ # 版本号与更新检查
|
||||
├── *.go # GUI 的 App 与各 *_flow.go 编排(package main)
|
||||
├── frontend/ # Wails 前端(轻量 React + Vite + TypeScript + zh-CN/en-US i18n)
|
||||
├── patches/ # 上游临时补丁队列(合入即退役)
|
||||
├── scripts/
|
||||
|
||||
@@ -114,6 +114,7 @@ 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` 补齐后删除 |
|
||||
| `reims-ctl-win32-random-bytes.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `crates/reims-ctl/src/vm.rs` | `random_bytes()`(`vm.rs:849-864`)在打不开 `/dev/urandom` 时退回用「纳秒时间 ^ (pid << 64)」当种子。Windows 上永远走这条退路,于是新 VM 的 MAC 后 3 字节(也就是 OpenCore 的 ROM)只剩约 22 位、可预测的时钟熵,第 4 段永远是 4 的倍数。改成用 std `RandomState` 做哈希(它的密钥来自系统随机源 ProcessPrng),不加依赖,不改 Cargo 文件 | 2026-11-29 新增补丁,`git apply --check` 通过;本机没有 Rust 工具链,尚未编译,待编入下一版 alpha 运行时验证后提 PR |
|
||||
| `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 新增补丁,待编入下一版 alpha 运行时并在 Win11 真机冒烟验证后提 PR |
|
||||
|
||||
+6
-4
@@ -62,7 +62,7 @@ flowchart LR
|
||||
- 完整跑完一次离线安装包下载(18.4 GB);
|
||||
- 下载完成时 `done` 事件里是否带 `installer.build` 字段(代码按可选处理)。
|
||||
- [x] **M1.4**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`insert`、`eject`、`update-opencore`、`delete`、`logs`、`downloads` 与 `qemu-img` 转换/CoW 派生,带单元测试。
|
||||
- [x] **M1.5**:`cmd/reims-go` — 提供 `doctor`、`runtime available/fetch/install/list/use`、`installer list/download/cached/delete`、`vm list/create/set/start/stop/eject/type`、`version` 子命令,支持 `--lang zh-CN|en-US` 与中英双语输出。
|
||||
- [x] **M1.5**:命令行模式(2026-11-28 起从 `cmd/reims-go` 移到 `internal/cli`,并入 `reims-go.exe`)— 提供 `doctor`、`runtime available/fetch/install/list/use`、`installer list/download/cached/delete`、`vm list/create/set/start/stop/eject/type`、`version` 子命令,支持 `--lang zh-CN|en-US` 与中英双语输出。
|
||||
|
||||
**DoD**:
|
||||
- 在一个从未 dot-source `reims-env.ps1` 的全新 PowerShell 中,仅运行 `reims-go` CLI 即可完成体检、导入运行时、断点续传下载离线包、启动/查看 VM;
|
||||
@@ -78,7 +78,8 @@ flowchart LR
|
||||
- [x] **M2.2**:**离线安装包下载管理器(核心体验)** — 调用 `reims-util --json` 展示可选 macOS Tahoe 精确版本,在 GUI 内直接触发宿主机直连下载、实时显示进度条 / 速率 / 已下体积 / 自动重试状态、支持「暂停/取消」与「断点续传」,并可视化管理 `<DataRoot>\data\reims-ctl\installers` 缓存。
|
||||
- 2026-11-28(v0.2):侧边栏新增「安装包」页。上半部分是已下载的安装包:可以继续未下载完的、删除(两步确认,删除走 `reims-ctl downloads delete`)。下半部分是 Apple 提供的版本:下载、进度、暂停。下载前检查剩余空间(按安装包大小加 10% 计,因为一开始就会占满整个镜像的空间)。速率显示在进度的悬停提示里。暂停后再次下载会接着下。
|
||||
- [x] **M2.3**:**VM 主面板与创建/装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 实例列表、实时状态、一键启停与串口/图形日志抽屉;新建默认推荐复用本地离线包 + 默认 `NVMe` 磁盘控制器,启动前校验提交内存;离线安装通过纯 Go HFS+ 辅助盘 `REIMSHELP` 自动绕过 macOS 26.7.3 缺 `pkgutil` / `installer -target` 失效,支持空白盘自动 APFS 抹盘 + QMP 一键键入;提供对称的「进入/退出恢复模式」切换与约 1 GB 在线恢复镜像兜底拉取。
|
||||
- [x] **M2.4**:打包为单文件 `reims-go.exe`(~13.3 MB)与命令行版 `reims-go-cli.exe`(~11.5 MB)。无代码签名,冷启动时间待量化实测。
|
||||
- [x] **M2.4**:打包为单文件 `reims-go.exe`(~13.3 MB)。无代码签名,冷启动时间待量化实测。
|
||||
- 2026-11-28:不再单独发布命令行版 `reims-go-cli.exe`,命令行模式并入同一个 exe:带子命令即走命令行;`vm start` 把启动交给界面进程(没在运行就以 `--background` 拉起到托盘),因此命令行启动的 VM 也有剪贴板、共享目录和 Win10 冷重启。细节见 [`architecture.md`](architecture.md) 3.5 节。
|
||||
- [x] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 类别分页;VM 运行中可改并标出生效时机;保存前在 Go 侧校验提交内存与 ICD,写入仅走 `reims-ctl set`。
|
||||
- [x] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改并提供「重启以应用」按钮。
|
||||
- [x] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,分步新建助手并在最后一步预览完整 `reims-ctl` 命令。
|
||||
@@ -116,7 +117,7 @@ flowchart LR
|
||||
- [ ] **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`)已随构建脚本落盘。
|
||||
- [x] **M4.4**:**客户端自动发布与在线更新检查** — 已新增 [.github/workflows/release.yml](../.github/workflows/release.yml)(打 `v*` tag 自动跑测、构建 `reims-go-<tag>-windows-amd64.exe` + `SHA256SUMS.txt`(2026-11-28 前还附带 `reims-go-cli-<tag>-windows-amd64.exe`) 并发布 GitHub Release);客户端与 CLI 接入 `internal/version` 版本号与稳定版在线更新检查(`HostView` 一键检查/跳转下载,运行时支持多版本回滚切换);合规文件(`NOTICE.md`、`LICENSE`、运行时源码包与 `MSYS2-PACKAGES.txt`)已随构建脚本落盘。
|
||||
- [ ] **M4.5**:**补丁上游化(人工提交 PR)** — 已在 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 整理好 4 个 QEMU 补丁的根因、复现步骤与实测证据,待人工向上游提 PR 并合入后从 `patches/` 队列清零。
|
||||
|
||||
**DoD**:
|
||||
@@ -133,7 +134,7 @@ flowchart LR
|
||||
### 核心体验的实现与跟进清单
|
||||
|
||||
- [ ] **M5.1(上游运行时联动)**:**沉浸全屏、无黑边缩放与 GPU 性能升级**
|
||||
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」一键开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与 `Ctrl+Alt+Enter` / `Ctrl+Alt+G` 热切快捷键提示条;
|
||||
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与按显卡后端区分的真实快捷键提示(`reims-vgpu` 捕获时显示 `Ctrl+Alt+Win` 释放输入,`vmware-svga` GTK 窗口显示 `Ctrl+Alt+F` / `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 键位提示;
|
||||
@@ -141,6 +142,7 @@ flowchart LR
|
||||
- [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` 并在不可用时自动回退同步模式;
|
||||
- Windows 盘符只读共享:每台 VM 在「存储与网络」设置中独立开启内部固定盘符,默认全部关闭,系统盘显示敏感信息提示;新增 `/dav/<vm>/drives/<盘符>/`,由服务端同时限制 HTTP 写方法和文件打开标志,持久化并复核 Volume GUID 防止盘符重绑定,限制 `PROPFIND Depth` 避免整盘递归,并验证 Junction / 符号链接解析后的目标仍在授权盘符内。Guest Tools 4 根据 `/v1/config` 自动挂载/卸载 `Windows C` 等 Finder 卷,关闭开关立即拒绝新请求。**(macOS Finder 真机挂载、只读兼容与重连待验证)**
|
||||
- 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`;
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
| 键盘与指针 | 点击窗口时捕获键鼠 | `--capture` | 下次启动 | — |
|
||||
| 串口与日志 | 日志开关、日志级别 | `--logs`、`--log-level` | 下次启动 | 日志在详情页抽屉里实时查看 |
|
||||
| 高级 | 关机等待时间、额外 QEMU 参数、环境变量 | `--stop-timeout`、`--extra-args`、`--env` | 下次启动 | `reims-go` 自己注入的 QMP 参数要和用户填的分开存放、合并写入,不能互相覆盖 |
|
||||
| (VZ 有,上游没有) | 共享目录、剪贴板、vsock | 无 | — | 先不做,界面上也不放占位 |
|
||||
| 宿客协作(Reims-Go 扩展) | ReimsShare、Windows 盘符只读共享、剪贴板 | Guest Tools HTTP/WebDAV,无对应 `reims-ctl` 参数 | 立即生效 | 每台 VM 独立配置;盘符共享默认全部关闭,仅枚举内部固定磁盘,系统盘提示敏感信息风险 |
|
||||
|
||||
## 4. 状态模型
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.5",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,6 +9,7 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.2.1",
|
||||
"@radix-ui/react-dialog": "^1.3.1",
|
||||
"@radix-ui/react-dropdown-menu": "^2.2.1",
|
||||
|
||||
@@ -1 +1 @@
|
||||
7782101f68324d7c033ce75c59399d77
|
||||
64168eba4b0b33765a8a7ffa2b52319b
|
||||
Generated
+8
@@ -8,6 +8,9 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@radix-ui/react-alert-dialog':
|
||||
specifier: ^1.2.1
|
||||
version: 1.2.1(@types/react-dom@19.3.0(@types/react@19.3.3))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
@@ -305,6 +308,9 @@ packages:
|
||||
'@floating-ui/utils@0.2.12':
|
||||
resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}
|
||||
|
||||
'@fontsource-variable/inter@5.3.0':
|
||||
resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==}
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
|
||||
|
||||
@@ -1293,6 +1299,8 @@ snapshots:
|
||||
|
||||
'@floating-ui/utils@0.2.12': {}
|
||||
|
||||
'@fontsource-variable/inter@5.3.0': {}
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
+93
-41
@@ -6,18 +6,19 @@ import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import { HostView } from './components/HostView'
|
||||
import { AppSettingsPage, ThemeMode } from './components/AppSettingsPage'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { SettingsModal } from './components/SettingsModal'
|
||||
import { Setup } from './components/Setup'
|
||||
import { HOST_ID, INSTALLERS_ID, Sidebar } from './components/Sidebar'
|
||||
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
import { InstallersPage } from './components/InstallersPage'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { I18nKey, t } from './i18n'
|
||||
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, VMStats } from './types'
|
||||
import { TooltipProvider } from './ui/controls'
|
||||
import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail, VMStats } from './types'
|
||||
import { Tip, TooltipProvider } from './ui/controls'
|
||||
import { Toaster, useToasts } from './ui/toast'
|
||||
import { api, events } from './wails'
|
||||
import { WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime'
|
||||
@@ -59,15 +60,40 @@ export const App: React.FC = () => {
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>(() => {
|
||||
try { return localStorage.getItem('reims-go-theme') === 'dark' ? 'dark' : 'light' } catch { return 'light' }
|
||||
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch {}
|
||||
return 'system'
|
||||
})
|
||||
const [sysDark, setSysDark] = useState<boolean>(() =>
|
||||
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches,
|
||||
)
|
||||
const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
try { localStorage.setItem('reims-go-theme', theme) } catch {}
|
||||
}, [theme])
|
||||
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.('(prefers-color-scheme: dark)')
|
||||
if (!mq) return
|
||||
const onChange = (e: MediaQueryListEvent) => setSysDark(e.matches)
|
||||
mq.addEventListener('change', onChange)
|
||||
return () => mq.removeEventListener('change', onChange)
|
||||
}, [])
|
||||
|
||||
const setThemeMode = (mode: ThemeMode) => {
|
||||
setThemeModeState(mode)
|
||||
try {
|
||||
if (mode === 'system') localStorage.removeItem('reims-go-theme')
|
||||
else localStorage.setItem('reims-go-theme', mode)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const toggleTheme = () => setThemeMode(theme === 'light' ? 'dark' : 'light')
|
||||
|
||||
const [logsOpen, setLogsOpen] = useState(false)
|
||||
const [logTab, setLogTab] = useState<LogTab>('app')
|
||||
const [logLines, setLogLines] = useState<LogLine[]>([])
|
||||
@@ -89,7 +115,7 @@ export const App: React.FC = () => {
|
||||
setState(s)
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
if (cur === HOST_ID || cur === INSTALLERS_ID) return cur
|
||||
if (cur === HOST_ID || cur === INSTALLERS_ID || cur === SETTINGS_ID) return cur
|
||||
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
|
||||
})
|
||||
@@ -117,11 +143,18 @@ export const App: React.FC = () => {
|
||||
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
|
||||
}).catch(() => {})
|
||||
const offTask = events.onTask((task) => onTaskRef.current(task))
|
||||
return () => { offState(); offLog(); offTask() }
|
||||
// Keep host telemetry (memory load, free disk) fresh while the window is visible.
|
||||
const hostTimer = window.setInterval(() => {
|
||||
if (!document.hidden) void refresh()
|
||||
}, 10000)
|
||||
return () => { offState(); offLog(); offTask(); window.clearInterval(hostTimer) }
|
||||
}, [refresh])
|
||||
|
||||
const vms = state?.vms ?? []
|
||||
const selectedVM = selected !== HOST_ID ? vms.find((v) => v.name === selected) : undefined
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
|
||||
const selectedVM = selected !== HOST_ID && selected !== INSTALLERS_ID && selected !== SETTINGS_ID
|
||||
? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setDetail(null); setVmStats(null); return }
|
||||
@@ -176,6 +209,9 @@ export const App: React.FC = () => {
|
||||
const setChannel = (alpha: boolean) => {
|
||||
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
|
||||
}
|
||||
const setSource = (source: RuntimeSource) => {
|
||||
api.SetRuntimeSource(source).then(refresh).catch((e) => fail(tr('failGeneric'), e))
|
||||
}
|
||||
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
|
||||
const importRuntime = async () => {
|
||||
try {
|
||||
@@ -464,19 +500,20 @@ export const App: React.FC = () => {
|
||||
Reims-Go
|
||||
</div>
|
||||
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
aria-label={theme === 'light' ? 'Dark mode' : 'Light mode'}
|
||||
title={theme === 'light' ? '切换深色外观' : '切换浅色外观'}
|
||||
onClick={() => setTheme((cur) => (cur === 'light' ? 'dark' : 'light'))}
|
||||
>
|
||||
{theme === 'light' ? <Moon size={14} /> : <Sun size={14} />}
|
||||
</button>
|
||||
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
|
||||
<button
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}
|
||||
onClick={toggleTheme}
|
||||
>
|
||||
{theme === 'light' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
|
||||
</button>
|
||||
</Tip>
|
||||
<div className="win-controls">
|
||||
<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>
|
||||
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
|
||||
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
|
||||
<button type="button" className="win-btn close" aria-label={tr('closeWindow')} onClick={() => api.RequestClose()}><X size={15} aria-hidden="true" /></button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -492,6 +529,7 @@ export const App: React.FC = () => {
|
||||
onFinish={() => setSetupStage(null)}
|
||||
onError={fail}
|
||||
onChannel={setChannel}
|
||||
onSource={setSource}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
onImportRuntime={importRuntime}
|
||||
@@ -564,43 +602,57 @@ export const App: React.FC = () => {
|
||||
.catch((e) => fail(tr('failGuestTools'), e))
|
||||
}}
|
||||
/>
|
||||
) : selected === SETTINGS_ID ? (
|
||||
<AppSettingsPage
|
||||
state={state}
|
||||
locale={locale}
|
||||
themeMode={themeMode}
|
||||
onThemeMode={setThemeMode}
|
||||
onSetLocale={setLang}
|
||||
onRefresh={refresh}
|
||||
onError={fail}
|
||||
/>
|
||||
) : (
|
||||
<HostView
|
||||
state={state}
|
||||
locale={locale}
|
||||
onRefresh={refresh}
|
||||
onError={fail}
|
||||
onSetLocale={setLang}
|
||||
runtimeTask={runtimeTask}
|
||||
onChannel={setChannel}
|
||||
onSource={setSource}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<LogPanel
|
||||
locale={locale}
|
||||
open={logsOpen}
|
||||
onToggle={toggleLogs}
|
||||
tab={selectedVM ? logTab : 'app'}
|
||||
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial(); if (tab === 'qemu') loadQemu() }}
|
||||
lines={logLines}
|
||||
unseenErrors={unseenErrors}
|
||||
onClear={() => setLogLines([])}
|
||||
serialText={serialLog}
|
||||
qemuText={qemuLog}
|
||||
showSerial={!!selectedVM}
|
||||
onRefreshSerial={() => loadSerial()}
|
||||
onRefreshQemu={() => loadQemu()}
|
||||
task={activeTask}
|
||||
runningTasks={runningTasks}
|
||||
onCancelTask={cancelTask}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!showSetup && (
|
||||
<LogPanel
|
||||
locale={locale}
|
||||
open={logsOpen}
|
||||
onToggle={toggleLogs}
|
||||
tab={selectedVM ? logTab : 'app'}
|
||||
onTab={(tab) => { setLogTab(tab); if (tab === 'serial') loadSerial(); if (tab === 'qemu') loadQemu() }}
|
||||
lines={logLines}
|
||||
unseenErrors={unseenErrors}
|
||||
onClear={() => setLogLines([])}
|
||||
serialText={serialLog}
|
||||
qemuText={qemuLog}
|
||||
showSerial={!!selectedVM}
|
||||
onRefreshSerial={() => loadSerial()}
|
||||
onRefreshQemu={() => loadQemu()}
|
||||
task={activeTask}
|
||||
runningTasks={runningTasks}
|
||||
onCancelTask={cancelTask}
|
||||
host={state?.host}
|
||||
runningVMs={runningVMCount}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showWizard && state && (
|
||||
<CreateWizard
|
||||
locale={locale}
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { Download } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
themeMode: ThemeMode
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
export const AppSettingsPage: React.FC<Props> = ({
|
||||
state, locale, themeMode, onThemeMode, onSetLocale, onRefresh, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { host, config, optimizations } = state
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
setCheckingUpdate(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
const info = await api.CheckAppUpdate(force)
|
||||
setAppUpdate(info)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setCheckingUpdate(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void runUpdateCheck(false)
|
||||
}, [])
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
await fn()
|
||||
onRefresh()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const pickDataRoot = guard(async () => {
|
||||
const dir = await api.PickDirectory(tr('hostDataRoot'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div className="page-title"><h1>{tr('sidebarSettings')}</h1></div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsGeneral')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostDataRoot')}</div>
|
||||
<div className="row-sub mono">{config.data_root}</div>
|
||||
</div>
|
||||
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('autoPinPCores')}
|
||||
<span className={`badge ${optBadgeClass(pcoreOpt?.status)}`}>
|
||||
{optStatusLabel(locale, pcoreOpt?.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{pcoreOpt?.supported
|
||||
? tr('optPCoreSub', { detail: pcoreOpt.detail ?? `${host.p_core_count}P+${host.e_core_count}E` })
|
||||
: tr('optPCoreUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('autoPinPCores')}
|
||||
disabled={!pcoreOpt?.supported}
|
||||
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
|
||||
onChange={(checked) => guard(() => api.SetAutoPinPCores(checked))()}
|
||||
/>
|
||||
</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">
|
||||
<Switch
|
||||
label={tr('minimizeToTray')}
|
||||
checked={config.minimize_to_tray !== false}
|
||||
onChange={(checked) => guard(() => api.SetMinimizeToTray(checked))()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAppearance')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('themeLabel')}</div></div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight') },
|
||||
{ value: 'dark', label: tr('themeDark') },
|
||||
{ value: 'system', label: tr('themeSystem') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('language')}</div></div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
onChange={onSetLocale}
|
||||
options={[
|
||||
{ value: 'zh-CN', label: '中文' },
|
||||
{ value: 'en-US', label: 'English' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAbout')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{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>
|
||||
)}
|
||||
</div>
|
||||
{appUpdate?.has_update ? (
|
||||
<div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
|
||||
) : updateErr ? (
|
||||
<div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && (appUpdate.page_url || appUpdate.download_url) ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Download size={14} aria-hidden="true" />}
|
||||
onClick={() => guard(() => api.OpenURL(appUpdate.page_url || appUpdate.download_url || ''))()}
|
||||
>
|
||||
{tr('appDownloadUpdate')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>
|
||||
{tr('appCheckUpdate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -24,12 +24,14 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, 'cloneDesc')}
|
||||
</Alert.Description>
|
||||
<div className="field" style={{ marginTop: 10 }}>
|
||||
<div className="field field-spaced">
|
||||
<label className="field-label" htmlFor="clone-name">{t(locale, 'cloneNameLabel')}</label>
|
||||
<input
|
||||
id="clone-name"
|
||||
className="input mono"
|
||||
value={cloneName}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setCloneName(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && trimmed) onConfirm(trimmed) }}
|
||||
autoFocus
|
||||
|
||||
@@ -12,6 +12,9 @@ import {
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
recommendedDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
@@ -444,14 +447,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
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}
|
||||
desc={[hostDisplayDesc(host, tr), hostDisplayAdvice(host, tr)].filter(Boolean).join(' · ') || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-res"
|
||||
@@ -461,7 +457,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
options={recommendedDisplayPresets(host).map((p) => ({
|
||||
value: p.resolution,
|
||||
label: p.label,
|
||||
detail: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
|
||||
detail: [p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
|
||||
}))}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Cpu, Download, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Cpu, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale, Task } from '../types'
|
||||
import { AppState, Locale, RuntimeSource, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
@@ -12,39 +12,19 @@ interface Props {
|
||||
locale: Locale
|
||||
onRefresh: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
runtimeTask: Task | null
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
}
|
||||
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, onSetLocale, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
|
||||
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => {
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const [openingSched, setOpeningSched] = useState(false)
|
||||
const { host, config, runtimes, optimizations } = state
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
|
||||
const runUpdateCheck = async (force: boolean) => {
|
||||
setCheckingUpdate(true)
|
||||
setUpdateErr('')
|
||||
try {
|
||||
const info = await api.CheckAppUpdate(force)
|
||||
setAppUpdate(info)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setCheckingUpdate(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void runUpdateCheck(false)
|
||||
}, [])
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const rebootOpt = findOptimization(optimizations, 'cold_reboot')
|
||||
const gpuOpt = findOptimization(optimizations, 'discrete_gpu')
|
||||
@@ -71,10 +51,13 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
setEnabling(false)
|
||||
}
|
||||
|
||||
const pickDataRoot = guard(async () => {
|
||||
const dir = await api.PickDirectory(tr('hostDataRoot'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
// One UAC prompt, then Windows' own Performance Options; the choice shows
|
||||
// here on the next refresh.
|
||||
const openScheduling = async () => {
|
||||
setOpeningSched(true)
|
||||
await guard(() => api.OpenProcessorScheduling())()
|
||||
setOpeningSched(false)
|
||||
}
|
||||
|
||||
const importRuntime = async () => {
|
||||
setImporting(true)
|
||||
@@ -101,7 +84,10 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
|
||||
<div className="tiles">
|
||||
<div className="tile">
|
||||
<div className="tile-head"><ShieldCheck size={14} /> {tr('whpxTitle')}</div>
|
||||
<div className="tile-head">
|
||||
<span className={`tile-icon ${whpx.tone}`} aria-hidden="true"><ShieldCheck size={13} /></span>
|
||||
{tr('whpxTitle')}
|
||||
</div>
|
||||
<div className={`tile-value ${whpx.tone}`}>{whpx.short}</div>
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" className="tile-action" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
@@ -110,16 +96,28 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
) : null}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><Cpu size={14} /> {tr('hostCPU')}</div>
|
||||
<div className="tile-head">
|
||||
<span className="tile-icon accent" aria-hidden="true"><Cpu size={13} /></span>
|
||||
{tr('hostCPU')}
|
||||
</div>
|
||||
<div className="tile-value">{tr('hostCoresThreads', { c: host.physical_cores, t: host.logical_cpus })}</div>
|
||||
{host.p_core_count > 0 && host.e_core_count > 0 && (
|
||||
<div className="tile-sub">{host.p_core_count}P + {host.e_core_count}E</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><MemoryStick size={14} /> {tr('hostRAM')}</div>
|
||||
<div className="tile-head">
|
||||
<span className="tile-icon accent" aria-hidden="true"><MemoryStick size={13} /></span>
|
||||
{tr('hostRAM')}
|
||||
</div>
|
||||
<div className="tile-value">{tr('hostRAMAvail', { n: host.avail_ram_gb.toFixed(1) })}</div>
|
||||
<div className="tile-sub">{tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}</div>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<div className="tile-head"><HardDrive size={14} /> {tr('hostDisk')}</div>
|
||||
<div className="tile-head">
|
||||
<span className="tile-icon" aria-hidden="true"><HardDrive size={13} /></span>
|
||||
{tr('hostDisk')}
|
||||
</div>
|
||||
<div className="tile-value">{host.free_disk_gb.toFixed(0)} GB</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -135,9 +133,11 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
|
||||
source={config.runtime_source === 'github' || config.runtime_source === 'gitcode' ? config.runtime_source : 'auto'}
|
||||
installed={runtimes ?? []}
|
||||
task={runtimeTask}
|
||||
onChannel={onChannel}
|
||||
onSource={onSource}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
@@ -155,102 +155,6 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settings')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('hostDataRoot')}</div>
|
||||
<div className="row-sub mono">{config.data_root}</div>
|
||||
</div>
|
||||
<div className="row-right"><Button onClick={pickDataRoot}>{tr('choose')}</Button></div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('autoPinPCores')}
|
||||
<span className={`badge ${optBadgeClass(pcoreOpt?.status)}`}>
|
||||
{optStatusLabel(locale, pcoreOpt?.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row-sub">
|
||||
{pcoreOpt?.supported
|
||||
? tr('optPCoreSub', { detail: pcoreOpt.detail ?? `${host.p_core_count}P+${host.e_core_count}E` })
|
||||
: tr('optPCoreUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<label className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={tr('autoPinPCores')}
|
||||
disabled={!pcoreOpt?.supported}
|
||||
checked={!!pcoreOpt?.supported && config.auto_pin_pcores}
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main"><div className="row-title">{tr('language')}</div></div>
|
||||
<div className="row-right">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onSetLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onSetLocale('en-US')}>English</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{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>
|
||||
)}
|
||||
</div>
|
||||
{appUpdate?.has_update ? (
|
||||
<div className="row-sub">{tr('appUpdateAvailable', { v: appUpdate.latest })}</div>
|
||||
) : updateErr ? (
|
||||
<div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && (appUpdate.page_url || appUpdate.download_url) ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Download size={14} />}
|
||||
onClick={() => guard(() => api.OpenURL(appUpdate.page_url || appUpdate.download_url || ''))()}
|
||||
>
|
||||
{tr('appDownloadUpdate')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>
|
||||
{tr('appCheckUpdate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('hostOptimizations')}</div>
|
||||
<div className="list">
|
||||
@@ -289,6 +193,20 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('optSchedTitle')}
|
||||
{host.processor_scheduling && (
|
||||
<span className="badge">{tr(host.processor_scheduling === 'background' ? 'optSchedBackground' : 'optSchedPrograms')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{tr('optSchedSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button busy={openingSched} onClick={openScheduling}>{tr('optSchedOpen')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import { AlertTriangle, Download, LoaderCircle, Package, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
@@ -65,12 +65,30 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
|
||||
const progress = (task: Task) => (
|
||||
<span className="task-inline row-sub">
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
{task.percent >= 0 && <span className="progress"><div style={{ width: `${task.percent}%` }} /></span>}
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
{task.percent >= 0 && (
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
const skeleton = (rows: number, label?: string) => (
|
||||
<div className="skeleton-list" role="status" aria-label={label}>
|
||||
{Array.from({ length: rows }).map((_, i) => (
|
||||
<div className="skeleton-row" key={i} aria-hidden="true">
|
||||
<div className="skeleton-stack">
|
||||
<div className="skeleton-bar w-title" />
|
||||
<div className="skeleton-bar w-sub" />
|
||||
</div>
|
||||
<div className="skeleton-bar w-btn" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
@@ -82,12 +100,16 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersDownloaded')}</div>
|
||||
{cached === null ? (
|
||||
skeleton(2, tr('installersDownloaded'))
|
||||
) : cached.length === 0 ? (
|
||||
<div className="empty-panel">
|
||||
<Package size={22} aria-hidden="true" />
|
||||
<span>{tr('installersEmpty')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="list">
|
||||
{cached === null ? (
|
||||
<div className="row"><span className="row-sub">…</span></div>
|
||||
) : cached.length === 0 ? (
|
||||
<div className="row"><span className="row-sub">{tr('installersEmpty')}</span></div>
|
||||
) : cached.map((c) => {
|
||||
{cached.map((c) => {
|
||||
const task = c.version ? running(c.version) : undefined
|
||||
return (
|
||||
<div className="row" key={c.name}>
|
||||
@@ -126,16 +148,26 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersAvailable')}</div>
|
||||
{releasesErr ? (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('offlineListFailed')}:{releasesErr}</span>
|
||||
</span>
|
||||
</div>
|
||||
) : releases === null ? (
|
||||
<>
|
||||
{skeleton(3, tr('offlineLoading'))}
|
||||
<span className="hint">{tr('offlineLoading')}</span>
|
||||
</>
|
||||
) : (
|
||||
<div className="list">
|
||||
{releasesErr ? (
|
||||
<div className="row"><span className="row-sub">{tr('offlineListFailed')}:{releasesErr}</span></div>
|
||||
) : releases === null ? (
|
||||
<div className="row"><span className="row-sub">{tr('offlineLoading')}</span></div>
|
||||
) : releases.map((r) => {
|
||||
{releases.map((r) => {
|
||||
const task = running(r.version)
|
||||
const done = isDownloaded(r.version)
|
||||
const short = !done && !task && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
|
||||
@@ -166,6 +198,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<span className="hint">{tr('installersHint')}</span>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ArrowDown, ChevronDown, ChevronUp, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import { ArrowDown, ChevronDown, ChevronUp, Eraser, HardDrive, LoaderCircle, MemoryStick, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useLayoutEffect, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { LogLine } from '../lib/logs'
|
||||
import { taskDetail, taskTitle } from '../lib/tasks'
|
||||
import { Locale, Task } from '../types'
|
||||
import { HostReport, Locale, Task } from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
|
||||
export type LogTab = 'app' | 'serial' | 'qemu'
|
||||
@@ -25,6 +25,8 @@ interface Props {
|
||||
task: Task | null
|
||||
runningTasks: number
|
||||
onCancelTask: (id: string) => void
|
||||
host?: HostReport
|
||||
runningVMs?: number
|
||||
}
|
||||
|
||||
/** Sticks to the bottom until the user scrolls up; offers "jump to latest" then. */
|
||||
@@ -50,29 +52,95 @@ function useStickToBottom(dep: unknown, active: boolean) {
|
||||
return { ref, stuck, onScroll, jump }
|
||||
}
|
||||
|
||||
const LOG_HEIGHT_KEY = 'reims-go-log-height'
|
||||
const DEFAULT_LOG_HEIGHT = 240
|
||||
const MIN_LOG_HEIGHT = 120
|
||||
const MAX_LOG_HEIGHT = 520
|
||||
|
||||
export const LogPanel: React.FC<Props> = ({
|
||||
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
|
||||
task, runningTasks, onCancelTask,
|
||||
task, runningTasks, onCancelTask, host, runningVMs = 0,
|
||||
}) => {
|
||||
const tr = (k: Parameters<typeof t>[1]) => t(locale, k)
|
||||
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const content = tab === 'app' ? lines : tab === 'serial' ? serialText : qemuText
|
||||
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
|
||||
|
||||
const memPct = host
|
||||
? Math.max(0, Math.min(100, host.memory_load_pct > 0
|
||||
? host.memory_load_pct
|
||||
: host.total_ram_gb > 0
|
||||
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
|
||||
: 0))
|
||||
: 0
|
||||
const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0
|
||||
const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : ''
|
||||
const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30
|
||||
|
||||
const [height, setHeight] = useState<number>(() => {
|
||||
try {
|
||||
const saved = Number(localStorage.getItem(LOG_HEIGHT_KEY))
|
||||
if (Number.isFinite(saved) && saved >= MIN_LOG_HEIGHT && saved <= MAX_LOG_HEIGHT) return saved
|
||||
} catch {}
|
||||
return DEFAULT_LOG_HEIGHT
|
||||
})
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const dragRef = useRef<{ startY: number; startH: number } | null>(null)
|
||||
|
||||
const onResizeDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.preventDefault()
|
||||
e.currentTarget.setPointerCapture(e.pointerId)
|
||||
dragRef.current = { startY: e.clientY, startH: height }
|
||||
setDragging(true)
|
||||
}
|
||||
const onResizeMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!dragRef.current) return
|
||||
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, Math.round(dragRef.current.startH + (dragRef.current.startY - e.clientY))))
|
||||
setHeight(next)
|
||||
}
|
||||
const onResizeUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!dragRef.current) return
|
||||
dragRef.current = null
|
||||
setDragging(false)
|
||||
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(height)) } catch {}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="logs">
|
||||
{open && (
|
||||
<div
|
||||
className="log-resize-handle"
|
||||
role="separator"
|
||||
aria-orientation="horizontal"
|
||||
aria-label={tr('resizeLogPanel')}
|
||||
data-dragging={dragging}
|
||||
onPointerDown={onResizeDown}
|
||||
onPointerMove={onResizeMove}
|
||||
onPointerUp={onResizeUp}
|
||||
onPointerCancel={onResizeUp}
|
||||
onDoubleClick={() => {
|
||||
setHeight(DEFAULT_LOG_HEIGHT)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
|
||||
}}
|
||||
>
|
||||
<span className="log-resize-pill" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
<div className="logbar">
|
||||
{task && (
|
||||
{task ? (
|
||||
<>
|
||||
<Tip label={[task.step, taskDetail(task)].filter(Boolean).join(' · ') || taskTitle(locale, task)} side="top">
|
||||
<span className="task" tabIndex={0}>
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
<span className="task-label">
|
||||
{runningTasks > 1 ? t(locale, 'tasksRunning', { n: runningTasks }) : taskTitle(locale, task)}
|
||||
</span>
|
||||
{task.percent >= 0 && (
|
||||
<>
|
||||
<span className="progress" aria-hidden="true"><div style={{ width: `${task.percent}%` }} /></span>
|
||||
<span>{Math.floor(task.percent)}%</span>
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
<span className="task-pct">{Math.floor(task.percent)}%</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
@@ -81,7 +149,47 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<IconButton small tipSide="top" label={tr('pauseDownload')} icon={<Pause size={14} />} onClick={() => onCancelTask(task.id)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
) : host ? (
|
||||
<div className="status-telemetry">
|
||||
{host.total_ram_gb > 0 && (
|
||||
<Tip
|
||||
side="top"
|
||||
label={tr('footerMemTip', {
|
||||
used: usedMemGB.toFixed(1),
|
||||
total: host.total_ram_gb.toFixed(1),
|
||||
avail: host.avail_ram_gb.toFixed(1),
|
||||
})}
|
||||
>
|
||||
<span className={`status-metric${memTone}`} tabIndex={0}>
|
||||
<MemoryStick size={12} aria-hidden="true" />
|
||||
<span>{tr('footerMem', { pct: memPct })}</span>
|
||||
<span className="status-mini-bar" aria-hidden="true">
|
||||
<span className={`status-mini-fill${memTone}`} style={{ transform: `scaleX(${memPct / 100})` }} />
|
||||
</span>
|
||||
<span className="status-metric-dim">({tr('footerMemAvail', { avail: host.avail_ram_gb.toFixed(1) })})</span>
|
||||
</span>
|
||||
</Tip>
|
||||
)}
|
||||
{host.free_disk_gb > 0 && (
|
||||
<>
|
||||
<span className="status-sep" aria-hidden="true">·</span>
|
||||
<span className={`status-metric${lowDisk ? ' warn' : ''}`}>
|
||||
<HardDrive size={12} aria-hidden="true" />
|
||||
<span>{tr('footerDisk', { gb: host.free_disk_gb.toFixed(0) })}</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{runningVMs > 0 && (
|
||||
<>
|
||||
<span className="status-sep" aria-hidden="true">·</span>
|
||||
<span className="status-metric ok">
|
||||
<span className="status status-running" aria-hidden="true" />
|
||||
<span>{tr('footerRunningVMs', { n: runningVMs })}</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
<span className="spacer" />
|
||||
{open && (
|
||||
<div className="tabs" role="tablist">
|
||||
@@ -110,20 +218,23 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
|
||||
)}
|
||||
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
<IconButton
|
||||
small
|
||||
tipSide="top"
|
||||
label={open ? tr('collapseLogs') : tr('expandLogs')}
|
||||
shortcut="Ctrl+L"
|
||||
icon={open ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
|
||||
onClick={onToggle}
|
||||
aria-expanded={open}
|
||||
/>
|
||||
<Tip label={open ? tr('collapseLogs') : tr('expandLogs')} shortcut="Ctrl+L" side="top">
|
||||
<button
|
||||
type="button"
|
||||
className="log-toggle-btn"
|
||||
onClick={onToggle}
|
||||
aria-expanded={open}
|
||||
aria-label={open ? tr('collapseLogs') : tr('expandLogs')}
|
||||
>
|
||||
<span>{tr('logButton')}</span>
|
||||
{open ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronUp size={14} aria-hidden="true" />}
|
||||
</button>
|
||||
</Tip>
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<div className="logs-body-wrap">
|
||||
<div className="logs-body" ref={ref} onScroll={onScroll} role="log" aria-live="off">
|
||||
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} role="log" aria-live="off">
|
||||
{tab === 'app'
|
||||
? (lines.length === 0
|
||||
? <span className="muted">{tr('logsEmpty')}</span>
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import { Download, LoaderCircle, Pause } from 'lucide-react'
|
||||
import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, RuntimeSource, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
channel: 'stable' | 'alpha'
|
||||
source: RuntimeSource
|
||||
installed: InstalledRuntime[]
|
||||
task: Task | null
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstall: (commit: string) => void
|
||||
onCancel: (taskId: string) => void
|
||||
}
|
||||
@@ -23,12 +26,13 @@ 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 alpha switch.
|
||||
* none installed, the newest release to install), then download source and alpha switches.
|
||||
*/
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, installed, task, onChannel, onSource, onInstall, onCancel }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [reload, setReload] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
@@ -38,11 +42,16 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
.then((list) => { if (live) setRemote(list ?? []) })
|
||||
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [channel, task?.status === 'done'])
|
||||
}, [channel, source, task?.status === 'done', reload])
|
||||
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latest = remote?.[0]
|
||||
const isInstalled = (c: string) => installed.some((i) => i.commit.startsWith(c) || c.startsWith(i.commit))
|
||||
const sameRuntimeId = (a: string, b: string) => {
|
||||
const [baseA, revA = ''] = a.split('-', 2)
|
||||
const [baseB, revB = ''] = b.split('-', 2)
|
||||
return revA === revB && (baseA.startsWith(baseB) || baseB.startsWith(baseA))
|
||||
}
|
||||
const isInstalled = (c: string) => installed.some((i) => sameRuntimeId(i.commit, c))
|
||||
const running = task?.status === 'running'
|
||||
const updatable = !!latest && !isInstalled(latest.commit)
|
||||
|
||||
@@ -50,24 +59,33 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
if (running && task) {
|
||||
sub = (
|
||||
<div className="row-sub task-inline">
|
||||
<LoaderCircle size={14} className="spin" />
|
||||
{task.percent >= 0 && <span className="progress"><div style={{ width: `${task.percent}%` }} /></span>}
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
{task.percent >= 0 && (
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</div>
|
||||
)
|
||||
} else if (active && !updatable) {
|
||||
sub = <div className="row-sub">{shortQemu(active.manifest.qemu_version)}</div>
|
||||
} else if (error) {
|
||||
sub = <div className="row-sub" title={error}>{tr('runtimeLookupFailed')}</div>
|
||||
const isRateLimit = /rate limit|HTTP 403|HTTP 429/i.test(error)
|
||||
const msg = isRateLimit ? tr('runtimeLookupRateLimit') : `${tr('runtimeLookupFailed')}: ${error}`
|
||||
sub = <div className="row-sub" title={error}>{msg}</div>
|
||||
} else if (!remote) {
|
||||
sub = <div className="row-sub">…</div>
|
||||
} else if (!latest) {
|
||||
sub = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
|
||||
} else {
|
||||
const srcLabel = latest.source === 'gitcode' ? 'GitCode' : latest.source === 'github' ? 'GitHub' : ''
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} · {gb(latest.archive_size)}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
|
||||
{srcLabel ? ` · ${srcLabel}` : ''}
|
||||
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -84,6 +102,10 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<div className="row-right">
|
||||
{running && task?.cancelable ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
|
||||
) : !running && error ? (
|
||||
<Button icon={<RefreshCw size={14} />} onClick={() => setReload((n) => n + 1)}>
|
||||
{tr('runtimeRetry')}
|
||||
</Button>
|
||||
) : !running && updatable ? (
|
||||
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
@@ -93,21 +115,30 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('runtimeSource')}</div>
|
||||
<div className="row-sub">{tr('runtimeSourceHint')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('runtimeSource')}
|
||||
value={source}
|
||||
onChange={onSource}
|
||||
options={(['auto', 'github', 'gitcode'] as RuntimeSource[]).map((s) => ({
|
||||
value: s,
|
||||
label: tr(`runtimeSource_${s}` as I18nKey),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<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('runtimeAlpha')}
|
||||
checked={channel === 'alpha'}
|
||||
onChange={(e) => onChannel(e.target.checked)}
|
||||
/>
|
||||
<span className="slider" />
|
||||
</label>
|
||||
<Switch label={tr('runtimeAlpha')} checked={channel === 'alpha'} onChange={onChannel} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -25,11 +25,10 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
|
||||
<Alert.Description className="dialog-desc">
|
||||
{t(locale, guestToolsConnected ? 'sendTextDesc' : 'sendTextDescNoGT')}
|
||||
</Alert.Description>
|
||||
<div className="field" style={{ marginTop: 10 }}>
|
||||
<div className="field field-spaced">
|
||||
<textarea
|
||||
className="input"
|
||||
className="input textarea"
|
||||
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)}
|
||||
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
recommendedDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
shortGPUName,
|
||||
@@ -22,7 +25,7 @@ import {
|
||||
optStatusLabel,
|
||||
parseKernelIrqchip,
|
||||
} from '../lib/optimizations'
|
||||
import { DiskCompactResult, DiskResizeResult, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
|
||||
@@ -70,6 +73,7 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[]
|
||||
|
||||
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
|
||||
const CUSTOM = '__custom'
|
||||
const FULLSCREEN = '__fullscreen'
|
||||
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
|
||||
|
||||
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
|
||||
@@ -142,6 +146,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | ''>('')
|
||||
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
|
||||
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
|
||||
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
|
||||
const [driveBusy, setDriveBusy] = useState(false)
|
||||
const driveBusyRef = useRef(false)
|
||||
const activeVMNameRef = useRef(detail.name)
|
||||
activeVMNameRef.current = detail.name
|
||||
const [driveErr, setDriveErr] = useState('')
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
const presets = recommendedDisplayPresets(host)
|
||||
@@ -149,7 +159,19 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const [customRes, setCustomRes] = useState(!presetHit)
|
||||
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
|
||||
|
||||
// The detail the panel opened with can be a stale one (reopened right after
|
||||
// a save, before the refreshed detail arrives): follow newer details until
|
||||
// the person changes something.
|
||||
const edited = useRef(false)
|
||||
useEffect(() => {
|
||||
if (edited.current) return
|
||||
setForm(base)
|
||||
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}, [base]) // presets come from host, which base already follows
|
||||
|
||||
const set = (patch: Partial<SetOpts>) => {
|
||||
edited.current = true
|
||||
setForm((f) => ({ ...f, ...patch }))
|
||||
const touched = Object.keys(patch)
|
||||
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
|
||||
@@ -186,6 +208,35 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
|
||||
}, [issues, cat])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setDriveSettings(null)
|
||||
setDriveErr('')
|
||||
api.GetVMDriveShareSettings(detail.name)
|
||||
.then((settings) => { if (active) setDriveSettings(settings) })
|
||||
.catch((e) => { if (active) setDriveErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { active = false }
|
||||
}, [detail.name])
|
||||
|
||||
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
|
||||
if (driveBusyRef.current || !driveSettings) return
|
||||
driveBusyRef.current = true
|
||||
const vmName = detail.name
|
||||
setDriveBusy(true)
|
||||
setDriveErr('')
|
||||
try {
|
||||
const next = await api.SetVMDriveShareSettings(vmName, enabled, selected)
|
||||
if (activeVMNameRef.current === vmName) setDriveSettings(next)
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vmName) setDriveErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
driveBusyRef.current = false
|
||||
setDriveBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive)
|
||||
|
||||
const handleSave = async () => {
|
||||
if (busy || changed.length === 0 || localBlock) return
|
||||
setErr('')
|
||||
@@ -211,6 +262,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
}
|
||||
|
||||
const resetAll = () => {
|
||||
edited.current = false
|
||||
setForm(base)
|
||||
setIssues([])
|
||||
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
|
||||
@@ -333,7 +385,9 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') })
|
||||
}
|
||||
const vgpu = form.graphics !== 'vmware-svga'
|
||||
const resValue = customRes ? CUSTOM : presets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
|
||||
const pd = host.primary_display
|
||||
const hidpiAdvice = hostDisplayAdvice(host, tr)
|
||||
const resValue = form.borderless ? FULLSCREEN : customRes ? CUSTOM : presets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
|
||||
const resArt = (r: string) => {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
|
||||
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
|
||||
@@ -371,37 +425,42 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
<SetGroup title={tr('displayGroup')}>
|
||||
<SetRow
|
||||
{...rowProps('resolution')}
|
||||
// Full screen is one of the sizes here, so the row also owns borderless.
|
||||
dirty={dirty('resolution') || dirty('borderless')}
|
||||
onReset={() => { reset('resolution')(); reset('borderless')() }}
|
||||
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
|
||||
title={tr('resolution')}
|
||||
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}
|
||||
desc={hostDisplayDesc(host, tr)}
|
||||
block={
|
||||
<>
|
||||
<OptionCards
|
||||
label={tr('resolution')}
|
||||
value={resValue}
|
||||
onChange={(v) => {
|
||||
if (v === CUSTOM) { setCustomRes(true); return }
|
||||
if (v === FULLSCREEN) { setCustomRes(false); set({ borderless: true }); return }
|
||||
if (v === CUSTOM) { setCustomRes(true); set({ borderless: false }); return }
|
||||
setCustomRes(false)
|
||||
set({ resolution: v })
|
||||
set({ resolution: v, borderless: false })
|
||||
}}
|
||||
options={[
|
||||
...presets.map((p) => ({
|
||||
value: p.resolution,
|
||||
title: p.label,
|
||||
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
|
||||
art: resArt(p.resolution),
|
||||
badges: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean),
|
||||
})),
|
||||
{
|
||||
value: FULLSCREEN,
|
||||
title: tr('resFullscreen'),
|
||||
sub: pd ? `${pd.width} × ${pd.height}` : undefined,
|
||||
art: pd ? resArt(`${pd.width}x${pd.height}`) : resArt('16x10'),
|
||||
badges: host.fullscreen_hidpi ? [tr('hidpiPresetBadge')] : [],
|
||||
},
|
||||
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
|
||||
]}
|
||||
/>
|
||||
{customRes && (
|
||||
{customRes && !form.borderless && (
|
||||
<input
|
||||
className="input mono res-input"
|
||||
aria-label={tr('resolution')}
|
||||
@@ -411,6 +470,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
onChange={(e) => set({ resolution: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
{hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
@@ -427,12 +487,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
{...rowProps('borderless')}
|
||||
title={tr('fullscreenLaunch')}
|
||||
desc={tr('fullscreenLaunchHint')}
|
||||
control={<Switch label={tr('fullscreenLaunch')} checked={!!form.borderless} onChange={(borderless) => set({ borderless })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
</>
|
||||
)
|
||||
@@ -534,10 +588,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<input
|
||||
className="input mono"
|
||||
style={{ maxWidth: 140 }}
|
||||
className="input mono input-compact"
|
||||
aria-label={tr('diskResizeTitle')}
|
||||
value={resizeInput}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
disabled={running || !!diskOpBusy}
|
||||
onChange={(e) => setResizeInput(e.target.value)}
|
||||
placeholder="+64G / 256G"
|
||||
@@ -554,7 +609,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
{resizeResult && (
|
||||
<div className="notice">
|
||||
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes) })}</div>
|
||||
<div className="cmd-line" style={{ marginTop: 6 }}>
|
||||
<div className="cmd-line cmd-line-spaced">
|
||||
<code>{resizeResult.guest_expand_cmd}</code>
|
||||
{onCopy && (
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(resizeResult.guest_expand_cmd)} />
|
||||
@@ -593,6 +648,52 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
}
|
||||
/>
|
||||
</SetGroup>
|
||||
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
|
||||
<SetRow
|
||||
title={tr('driveShareMaster')}
|
||||
desc={tr('driveShareMasterDesc')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('driveShareMaster')}
|
||||
checked={!!driveSettings?.enabled}
|
||||
disabled={!driveSettings || driveBusy}
|
||||
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
|
||||
{driveSettings?.enabled && selectedDrives().length > 0 &&
|
||||
(detail.guest_tools_agent_version ?? 0) < driveSettings.required_agent_version && (
|
||||
<div className="notice">{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}</div>
|
||||
)}
|
||||
{(driveSettings?.drives ?? []).map((drive) => {
|
||||
const title = `Windows (${drive.drive}:)`
|
||||
return (
|
||||
<SetRow
|
||||
key={drive.drive}
|
||||
title={title}
|
||||
desc={drive.system ? tr('driveShareSystem', { root: drive.root }) : tr('driveShareDrive', { root: drive.root })}
|
||||
disabled={!driveSettings?.enabled || driveBusy}
|
||||
reason={!driveSettings?.enabled ? tr('driveShareMasterOff') : undefined}
|
||||
control={
|
||||
<Switch
|
||||
label={title}
|
||||
checked={drive.selected}
|
||||
disabled={driveBusy}
|
||||
onChange={(enabled) => {
|
||||
const next = selectedDrives().filter((letter) => letter !== drive.drive)
|
||||
if (enabled) next.push(drive.drive)
|
||||
void updateDriveShares(driveSettings?.enabled ?? false, next)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{driveSettings && driveSettings.drives.length === 0 && (
|
||||
<SetValue title={tr('driveShareTitle')} value={tr('driveShareNoDrives')} />
|
||||
)}
|
||||
</SetGroup>
|
||||
<SetGroup title={tr('catNetwork')}>
|
||||
<SetRow
|
||||
{...rowProps('network')}
|
||||
@@ -667,6 +768,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
{ value: 'auto', label: tr('audioBackendAuto') },
|
||||
{ value: 'dsound', label: tr('audioBackendDsound') },
|
||||
{ value: 'none', label: tr('audioBackendNone') },
|
||||
// A backend set elsewhere (`reims-ctl set --audio-backend wav`) still shows as chosen.
|
||||
...(['auto', 'dsound', 'none'].includes(form.audio_backend || 'auto') ? [] : [{ value: form.audio_backend as string, label: form.audio_backend as string }]),
|
||||
]}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { FolderOpen, HardDrive } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, Task } from '../types'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, RuntimeSource, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
@@ -17,6 +18,7 @@ interface Props {
|
||||
onFinish: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onChannel: (alpha: boolean) => void
|
||||
onSource: (source: RuntimeSource) => void
|
||||
onInstallRuntime: (commit: string) => void
|
||||
onCancelTask: (id: string) => void
|
||||
onImportRuntime: () => void
|
||||
@@ -120,6 +122,8 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
aria-label={tr('setupOther')}
|
||||
value={custom}
|
||||
placeholder="D:\VMs\reims-go"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
onFocus={() => custom && setSelected(custom)}
|
||||
onChange={(e) => { setCustom(e.target.value); setSelected(e.target.value.trim()) }}
|
||||
@@ -138,17 +142,22 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
|
||||
<div className="hint">{tr('setupFree', { n: check.free_gb.toFixed(0) })}</div>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<div className="segmented" role="group" aria-label={tr('language')}>
|
||||
<button type="button" aria-pressed={locale === 'zh-CN'} onClick={() => onLocale('zh-CN')}>中文</button>
|
||||
<button type="button" aria-pressed={locale === 'en-US'} onClick={() => onLocale('en-US')}>English</button>
|
||||
</div>
|
||||
<Segmented
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
onChange={onLocale}
|
||||
options={[
|
||||
{ value: 'zh-CN', label: '中文' },
|
||||
{ value: 'en-US', label: 'English' },
|
||||
]}
|
||||
/>
|
||||
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
|
||||
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
|
||||
const ready = !!state.active_runtime
|
||||
const { host } = state
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
@@ -215,9 +224,11 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
<RuntimeOnline
|
||||
locale={locale}
|
||||
channel={state.config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
|
||||
source={state.config.runtime_source === 'github' || state.config.runtime_source === 'gitcode' ? state.config.runtime_source : 'auto'}
|
||||
installed={state.runtimes ?? []}
|
||||
task={runtimeTask}
|
||||
onChannel={onChannel}
|
||||
onSource={onSource}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Cpu, Download, Monitor, Plus } from 'lucide-react'
|
||||
import { Cpu, Download, Monitor, Plus, Settings } from 'lucide-react'
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
@@ -6,6 +6,7 @@ import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
export const SETTINGS_ID = '__settings__'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -21,7 +22,7 @@ interface Props {
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, hostReady, onSelect, onNew, downloading }) => {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID]
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID, SETTINGS_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -80,6 +81,7 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
return item(vm.name, vm.name, <Monitor size={13} />, 'nav-icon-vm', t(locale, `state_${st}` as I18nKey), statusKind(st))
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
<div className="sidebar-section-label" aria-hidden="true">{t(locale, 'sidebarSystem')}</div>
|
||||
{item(
|
||||
INSTALLERS_ID,
|
||||
t(locale, 'sidebarInstallers'),
|
||||
@@ -96,6 +98,14 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
{item(
|
||||
SETTINGS_ID,
|
||||
t(locale, 'sidebarSettings'),
|
||||
<Settings size={13} />,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
null,
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
+294
-175
@@ -1,6 +1,7 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import {
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
Archive,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
@@ -9,10 +10,14 @@ import {
|
||||
Disc,
|
||||
Ellipsis,
|
||||
FolderOpen,
|
||||
Globe,
|
||||
HardDrive,
|
||||
Info,
|
||||
Keyboard,
|
||||
LifeBuoy,
|
||||
MemoryStick,
|
||||
Monitor,
|
||||
Network,
|
||||
Play,
|
||||
Power,
|
||||
RotateCw,
|
||||
@@ -24,11 +29,11 @@ import {
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { controllerLabel, formatBytes, formatMemory, formatUptime, graphicsLabel, guestLangLabel, splitLangLabel, sshCommand } from '../lib/format'
|
||||
import { controllerLabel, formatBytes, formatDiskUsage, 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'
|
||||
import { Switch } from '../ui/settings'
|
||||
|
||||
export type VMAction =
|
||||
| 'start'
|
||||
@@ -83,8 +88,9 @@ export const VMPage: React.FC<Props> = ({
|
||||
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.
|
||||
// Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
|
||||
// runs, otherwise the last frame saved. Skipped while this window is hidden;
|
||||
// the backend also skips it while the VM's own window is in front.
|
||||
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
|
||||
useEffect(() => { setThumb(null) }, [name])
|
||||
useEffect(() => {
|
||||
@@ -94,7 +100,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
api.GetVMThumbnail(name).then((t) => { if (live && t.data_url) setThumb(t) }).catch(() => {})
|
||||
}
|
||||
pull()
|
||||
const timer = running ? window.setInterval(pull, 5000) : undefined
|
||||
const timer = running ? window.setInterval(pull, 15000) : undefined
|
||||
return () => { live = false; if (timer) window.clearInterval(timer) }
|
||||
}, [name, running])
|
||||
|
||||
@@ -180,81 +186,128 @@ export const VMPage: React.FC<Props> = ({
|
||||
// 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
|
||||
const specs: { label: string; value: string; full?: string; icon: React.ReactNode }[] = 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('factCPU'), value: tr('cores', { n: detail.cpus }), icon: <Cpu size={15} aria-hidden="true" /> },
|
||||
{ label: tr('factMemory'), value: formatMemory(detail.memory), icon: <MemoryStick size={15} aria-hidden="true" /> },
|
||||
{ label: tr('factGraphics'), value: graphicsLabel(locale, detail, host) + (detail.displays > 1 ? ` × ${detail.displays}` : ''), icon: <Monitor size={15} aria-hidden="true" /> },
|
||||
{
|
||||
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)} · ${formatDiskUsage(stats.disk_actual_bytes, stats.disk_virtual_bytes)}`
|
||||
: controllerLabel(detail.disk_controller),
|
||||
full: diskUsed && stats
|
||||
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats.disk_actual_bytes), max: formatBytes(stats.disk_virtual_bytes) })
|
||||
: undefined,
|
||||
icon: <HardDrive size={15} aria-hidden="true" />,
|
||||
},
|
||||
{ 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 }] : []),
|
||||
{ label: tr('fieldNetwork'), value: detail.network ? (detail.ssh_port > 0 ? `NAT · SSH ${detail.ssh_port}` : 'NAT') : tr('off'), icon: <Network size={15} aria-hidden="true" /> },
|
||||
...(detail.guest_lang ? [{ label: tr('specLang'), value: splitLangLabel('', guestLangLabel(locale, detail.guest_lang)).label, icon: <Globe size={15} aria-hidden="true" /> }] : []),
|
||||
]
|
||||
: []
|
||||
|
||||
// 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 cpuPct = running && stats ? Math.min(100, Math.max(0, stats.cpu_percent || 0)) : 0
|
||||
const memPct = running && stats && hostBytes > 0 ? Math.min(100, (stats.memory_rss_bytes / hostBytes) * 100) : 0
|
||||
const meterTone = (pct: number) => (pct >= 90 ? ' high' : pct >= 75 ? ' warn' : '')
|
||||
|
||||
const copyTechSummary = () => {
|
||||
if (!detail) return
|
||||
const rows = [
|
||||
`${tr('fieldKind')}: ${detail.kind || '—'}`,
|
||||
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
|
||||
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
|
||||
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
|
||||
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
|
||||
`${tr('fieldController')}: ${detail.disk_controller}`,
|
||||
`${tr('fieldDisk')}: ${detail.disk}`,
|
||||
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
|
||||
`${tr('fieldAudio')}: ${detail.audio_raw || tr('off')}`,
|
||||
...(detail.guest_lang ? [`${tr('guestLang')}: ${detail.guest_lang}`] : []),
|
||||
`${tr('fieldDir')}: ${detail.directory}`,
|
||||
]
|
||||
onCopy(rows.join('\n'))
|
||||
}
|
||||
|
||||
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">
|
||||
<div className={`vm-hero-pill${running ? ' is-running' : state === 'broken' ? ' is-broken' : ''}`}>
|
||||
<StatusShape kind={statusKind(state)} />
|
||||
{tr(`state_${state}` as I18nKey)}
|
||||
{running && stats && stats.uptime_seconds > 0 && <span className="muted">· {formatUptime(stats.uptime_seconds, locale)}</span>}
|
||||
<span>{tr(`state_${state}` as I18nKey)}</span>
|
||||
{running && stats && stats.uptime_seconds > 0 && <span>· {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>
|
||||
<Button icon={<Square size={13} aria-hidden="true" />} 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>
|
||||
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
|
||||
</Tip>
|
||||
{menu}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{specs.length > 0 && (
|
||||
<div className="vm-spec-card" role="list">
|
||||
{specs.map((s) => (
|
||||
<Tip key={s.label} label={s.full ? `${s.label}:${s.full}` : `${s.label}:${s.value}`}>
|
||||
<div className="vm-spec-cell" role="listitem">
|
||||
<span className="vm-spec-icon">{s.icon}</span>
|
||||
<span className="vm-spec-val">{s.value}</span>
|
||||
</div>
|
||||
</Tip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{running && stats && (
|
||||
<div className="vm-meters">
|
||||
<div className="vm-telemetry-card">
|
||||
<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 className="vm-meter-head">
|
||||
<span>{tr('statsCPU')}</span>
|
||||
<span className="muted">·</span>
|
||||
<span>{Math.round(cpuPct)}%</span>
|
||||
</div>
|
||||
<div className="resource-meter" aria-hidden="true">
|
||||
<span className={`meter-fill${meterTone(cpuPct)}`} style={{ transform: `scaleX(${cpuPct / 100})` }} />
|
||||
</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 className="vm-meter-head">
|
||||
<span>{tr('statsMemory')}</span>
|
||||
<span className="muted">·</span>
|
||||
<span>{stats.memory_rss_bytes > 0 ? formatBytes(stats.memory_rss_bytes) : '—'}</span>
|
||||
</div>
|
||||
<div className="resource-meter" aria-hidden="true">
|
||||
<span className={`meter-fill${meterTone(memPct)}`} style={{ transform: `scaleX(${memPct / 100})` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state === 'broken' && <div className="notice notice-error">{tr('brokenHint')}</div>}
|
||||
{state === 'broken' && (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('brokenHint')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pending.length > 0 && (
|
||||
<div className="notice">
|
||||
<span>
|
||||
{tr('pendingTitle')}:
|
||||
<span className="mono">{pending.map((p) => `${p.field} ${p.from}→${p.to}`).join(' · ')}</span>
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>
|
||||
{tr('pendingTitle')}:
|
||||
<span className="mono">{pending.map((p) => `${p.field} ${p.from}→${p.to}`).join(' · ')}</span>
|
||||
</span>
|
||||
</span>
|
||||
{running && (
|
||||
<Button busy={busyAction === 'restart'} disabled={busy} onClick={() => onAction('restart')}>
|
||||
@@ -266,19 +319,28 @@ export const VMPage: React.FC<Props> = ({
|
||||
|
||||
{(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && (
|
||||
<div className="notice">
|
||||
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(host.memory_load_pct ?? 0) >= 85 && (
|
||||
<div className="notice">
|
||||
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail && !detail.has_installer && detail.disk_controller === 'ahci' && (
|
||||
<div className="notice">
|
||||
<span>{tr('diagAhciUpgradeHint')}</span>
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagAhciUpgradeHint')}</span>
|
||||
</span>
|
||||
<Button busy={busyAction === 'upgradeNVMe'} disabled={busy} onClick={() => onAction('upgradeNVMe')}>
|
||||
{tr('upgradeToNVMe')}
|
||||
</Button>
|
||||
@@ -303,15 +365,15 @@ export const VMPage: React.FC<Props> = ({
|
||||
</h2>
|
||||
{!hasInstaller ? (
|
||||
<>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideBuiltIn1')}</li>
|
||||
<li>{tr('guideBuiltIn2')}</li>
|
||||
<li>{tr('guideBuiltIn3')}</li>
|
||||
<ol className="guide-steps">
|
||||
<li className="guide-step"><span className="guide-step-num">1</span><span className="guide-step-body">{tr('guideBuiltIn1')}</span></li>
|
||||
<li className="guide-step"><span className="guide-step-num">2</span><span className="guide-step-body">{tr('guideBuiltIn2')}</span></li>
|
||||
<li className="guide-step"><span className="guide-step-num">3</span><span className="guide-step-body">{tr('guideBuiltIn3')}</span></li>
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Disc size={14} />}
|
||||
icon={<Disc size={14} aria-hidden="true" />}
|
||||
busy={busyAction === 'attachInstaller'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachInstaller')}
|
||||
@@ -330,26 +392,29 @@ export const VMPage: React.FC<Props> = ({
|
||||
</>
|
||||
) : isOffline ? (
|
||||
<>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideOffline1')}</li>
|
||||
<li>
|
||||
{tr('guideOffline2')}
|
||||
<div className="cmd-line guide-cmd">
|
||||
<code>{OFFLINE_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('typeIntoVM')}
|
||||
icon={<Keyboard size={14} />}
|
||||
busy={busyAction === 'type'}
|
||||
disabled={busy}
|
||||
onClick={() => onTypeText(OFFLINE_INSTALL_CMD)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<ol className="guide-steps">
|
||||
<li className="guide-step"><span className="guide-step-num">1</span><span className="guide-step-body">{tr('guideOffline1')}</span></li>
|
||||
<li className="guide-step">
|
||||
<span className="guide-step-num">2</span>
|
||||
<span className="guide-step-body">
|
||||
{tr('guideOffline2')}
|
||||
<div className="cmd-line guide-cmd">
|
||||
<code>{OFFLINE_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('typeIntoVM')}
|
||||
icon={<Keyboard size={14} />}
|
||||
busy={busyAction === 'type'}
|
||||
disabled={busy}
|
||||
onClick={() => onTypeText(OFFLINE_INSTALL_CMD)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
</li>
|
||||
<li>{tr('guideOffline3')}</li>
|
||||
<li className="guide-step"><span className="guide-step-num">3</span><span className="guide-step-body">{tr('guideOffline3')}</span></li>
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
@@ -364,10 +429,10 @@ export const VMPage: React.FC<Props> = ({
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ol className="steps">
|
||||
<li>{tr('guideStep1')}</li>
|
||||
<li>{tr('guideStep2')}</li>
|
||||
<li>{tr('guideStep3')}</li>
|
||||
<ol className="guide-steps">
|
||||
<li className="guide-step"><span className="guide-step-num">1</span><span className="guide-step-body">{tr('guideStep1')}</span></li>
|
||||
<li className="guide-step"><span className="guide-step-num">2</span><span className="guide-step-body">{tr('guideStep2')}</span></li>
|
||||
<li className="guide-step"><span className="guide-step-num">3</span><span className="guide-step-body">{tr('guideStep3')}</span></li>
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
@@ -396,99 +461,133 @@ export const VMPage: React.FC<Props> = ({
|
||||
? [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))} />}
|
||||
/>
|
||||
)}
|
||||
{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)} />
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('connGroup')}</div>
|
||||
<div className="conn-list">
|
||||
{detail.ssh_port > 0 && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">SSH</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<div className="ssh-pill">
|
||||
<code>{sshCommand(detail.ssh_port)}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(sshCommand(detail.ssh_port))} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsTitle')}</span>
|
||||
<span className="conn-dot" aria-hidden="true">·</span>
|
||||
<span className={`conn-meta${needsUpgrade ? ' warn-text' : ''}`} title={needsUpgrade ? tr('guestToolsUpgradeHint') : gtStatus}>
|
||||
{needsUpgrade ? tr('guestToolsUpgradeHint') : gtStatus}
|
||||
</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
{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={13} aria-hidden="true" />}
|
||||
busy={busyAction === 'attachGuestTools'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachGuestTools')}
|
||||
>
|
||||
{tr('attachGuestTools')}
|
||||
</Button>
|
||||
)}
|
||||
</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 && detail.guest_tools_attached && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('gtInstallCmd')}</span>
|
||||
</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>
|
||||
<div className="conn-ctrl">
|
||||
<div className="ssh-pill">
|
||||
<code>{GUEST_TOOLS_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('sharedFolder')}</span>
|
||||
<span className="conn-dot" aria-hidden="true">·</span>
|
||||
<span className="conn-meta mono" title="~/Desktop/ReimsShare">~/Desktop/ReimsShare</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Button icon={<Upload size={13} aria-hidden="true" />} disabled={busy} onClick={onDeliverFile}>{tr('deliverFileShort')}</Button>
|
||||
<Button icon={<FolderOpen size={13} aria-hidden="true" />} disabled={busy} onClick={() => onAction('openSharedFolder')}>{tr('openShort')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsPreventSleep')}</span>
|
||||
{gtSleepActive && (
|
||||
<>
|
||||
<span className="conn-dot" aria-hidden="true">·</span>
|
||||
<span className="conn-meta ok-text"><Activity size={12} aria-hidden="true" /> {tr('guestToolsSleepActive')}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Switch label={tr('guestToolsPreventSleep')} checked={!!detail.guest_tools_prevent_sleep} onChange={onTogglePreventSleep} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
})()}
|
||||
|
||||
{detail && (
|
||||
<details className="tech">
|
||||
<summary><ChevronRight size={14} /> {tr('techInfo')}</summary>
|
||||
<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('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>
|
||||
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
|
||||
<div className="tech-body">
|
||||
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
|
||||
<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('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>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{detail && (
|
||||
{detail && (detail.graphics === 'vmware-svga' ? (
|
||||
<p className="vm-footnote">
|
||||
<kbd>Ctrl+Alt+Enter</kbd> {tr('shortcutBarFullscreen')}
|
||||
{detail.capture && <><span className="sep">·</span><kbd>Ctrl+Alt+G</kbd> {tr('shortcutBarRelease')}</>}
|
||||
<kbd>Ctrl+Alt+F</kbd> {tr('shortcutBarFullscreen')}
|
||||
<span className="sep">·</span>
|
||||
<kbd>Ctrl+Alt+G</kbd> {tr('shortcutBarRelease')}
|
||||
</p>
|
||||
)}
|
||||
) : detail.capture ? (
|
||||
<p className="vm-footnote">
|
||||
<kbd>Ctrl+Alt+Win</kbd> {tr('shortcutBarRelease')}
|
||||
</p>
|
||||
) : null)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -504,16 +603,25 @@ const VMScreen: React.FC<{ thumb: VMThumbnail | null; running: boolean; startLab
|
||||
const shown = thumb?.data_url ?? ''
|
||||
const under = prev.current !== shown ? prev.current : ''
|
||||
useEffect(() => { prev.current = shown }, [shown])
|
||||
if (!shown) return <IMacIcon running={running} />
|
||||
if (!shown) {
|
||||
return (
|
||||
<div className="vm-imac-wrap">
|
||||
<IMacIcon running={running} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
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 className="vm-display-unit">
|
||||
<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={18} fill="currentColor" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="vm-display-stand" aria-hidden="true" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -521,32 +629,43 @@ const VMScreen: React.FC<{ thumb: VMThumbnail | null; running: boolean; startLab
|
||||
const IMacIcon: React.FC<{ running: boolean }> = ({ running }) => (
|
||||
<svg className="vm-imac-svg" viewBox="0 0 120 96" fill="none" aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id="tahoeScreenOn" x1="16" y1="8" x2="104" y2="62" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#4ec2ff" />
|
||||
<stop offset="55%" stopColor="#1e88e5" />
|
||||
<stop offset="100%" stopColor="#0f55b8" />
|
||||
<linearGradient id="tahoeScreenOn" x1="14" y1="8" x2="106" y2="62" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#63d2ff" />
|
||||
<stop offset="52%" stopColor="#1d86f2" />
|
||||
<stop offset="100%" stopColor="#0d4db3" />
|
||||
</linearGradient>
|
||||
<linearGradient id="tahoeScreenOff" x1="16" y1="8" x2="104" y2="62" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#2c2e35" />
|
||||
<stop offset="100%" stopColor="#18191e" />
|
||||
<linearGradient id="tahoeScreenOff" x1="14" y1="8" x2="106" y2="62" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#2e3139" />
|
||||
<stop offset="100%" stopColor="#16181d" />
|
||||
</linearGradient>
|
||||
<linearGradient id="imacChin" x1="12" y1="62" x2="108" y2="74" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#e8eaee" />
|
||||
<stop offset="100%" stopColor="#d4d7dd" />
|
||||
<linearGradient id="screenSheen" x1="14" y1="9" x2="66" y2="54" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="rgba(255,255,255,0.22)" />
|
||||
<stop offset="100%" stopColor="rgba(255,255,255,0)" />
|
||||
</linearGradient>
|
||||
<linearGradient id="imacChin" x1="10" y1="61" x2="110" y2="74" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#eff1f5" />
|
||||
<stop offset="50%" stopColor="#e2e5eb" />
|
||||
<stop offset="100%" stopColor="#d3d7df" />
|
||||
</linearGradient>
|
||||
<linearGradient id="imacStand" x1="50" y1="73" x2="70" y2="90" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stopColor="#c4c8cf" />
|
||||
<stop offset="100%" stopColor="#e2e5ea" />
|
||||
<stop offset="0%" stopColor="#bfc4cd" />
|
||||
<stop offset="55%" stopColor="#dde0e7" />
|
||||
<stop offset="100%" stopColor="#c7ccd5" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M51 73H69L72 88H48L51 73Z" fill="url(#imacStand)" />
|
||||
<rect x="42" y="87" width="36" height="3.5" rx="1.75" fill="#cfd3da" />
|
||||
<rect x="10" y="6" width="100" height="68" rx="6" fill="#1d1e22" />
|
||||
<rect x="42" y="87" width="36" height="3.5" rx="1.75" fill="#cfd4dc" />
|
||||
<rect x="10" y="6" width="100" height="68" rx="6.5" fill="#1b1c21" />
|
||||
<rect x="10.5" y="6.5" width="99" height="67" rx="6" stroke="rgba(255,255,255,0.14)" strokeWidth="1" />
|
||||
<path d="M10 61H110V68C110 71.3137 107.314 74 104 74H16C12.6863 74 10 71.3137 10 68V61Z" fill="url(#imacChin)" />
|
||||
<rect x="13.5" y="9.5" width="93" height="49" rx="2.5" fill={running ? 'url(#tahoeScreenOn)' : 'url(#tahoeScreenOff)'} />
|
||||
{running && (
|
||||
<path d="M13.5 47C34 39 58 49 78 41C92 35.5 100 37 106.5 39V58.5H13.5V47Z" fill="rgba(255,255,255,0.18)" />
|
||||
<>
|
||||
<path d="M13.5 46C34 37 56 49 79 39.5C92 34 100 36 106.5 38.5V58.5H13.5V46Z" fill="rgba(255,255,255,0.20)" />
|
||||
<path d="M13.5 51.5C38 45 64 53 106.5 46.5V58.5H13.5V51.5Z" fill="rgba(255,255,255,0.12)" />
|
||||
</>
|
||||
)}
|
||||
<circle cx="60" cy="67.5" r="1.8" fill="#8e9299" />
|
||||
<path d="M13.5 9.5H68L42 58.5H13.5V9.5Z" fill="url(#screenSheen)" />
|
||||
<circle cx="60" cy="67.5" r="1.7" fill="#8b9099" />
|
||||
</svg>
|
||||
)
|
||||
+98
-8
@@ -6,7 +6,9 @@ const dict = {
|
||||
'zh-CN': {
|
||||
// Shell
|
||||
sidebarVMs: '虚拟机',
|
||||
sidebarHost: '宿主与运行时',
|
||||
sidebarSystem: '系统',
|
||||
sidebarHost: '内核',
|
||||
sidebarSettings: '设置',
|
||||
sidebarInstallers: '安装包',
|
||||
installersTitle: '安装包',
|
||||
installersDownloaded: '已下载',
|
||||
@@ -28,6 +30,23 @@ const dict = {
|
||||
minimize: '最小化',
|
||||
maximize: '最大化',
|
||||
closeWindow: '关闭',
|
||||
themeSwitchDark: '切换深色外观',
|
||||
themeSwitchLight: '切换浅色外观',
|
||||
copyTechInfo: '复制技术信息',
|
||||
resizeLogPanel: '拖动调整日志高度',
|
||||
logButton: '日志',
|
||||
footerMem: '内存 {pct}%',
|
||||
footerMemAvail: '可用 {avail} GB',
|
||||
footerMemTip: '系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)',
|
||||
footerDisk: '磁盘可用 {gb} GB',
|
||||
footerRunningVMs: '{n} 台运行中',
|
||||
settingsGeneral: '常规',
|
||||
settingsAppearance: '外观与语言',
|
||||
settingsAbout: '关于',
|
||||
themeLabel: '外观',
|
||||
themeLight: '浅色',
|
||||
themeDark: '深色',
|
||||
themeSystem: '跟随系统',
|
||||
|
||||
// Actions
|
||||
newVM: '新建虚拟机',
|
||||
@@ -182,7 +201,14 @@ const dict = {
|
||||
runtimeAlphaHint: 'Alpha 版由 CI 每天从上游自动构建,未经真实宿主冒烟测试',
|
||||
runtimeChannel_alpha: 'Alpha 版',
|
||||
runtimeChannel_stable: '稳定版',
|
||||
runtimeLookupFailed: '无法读取 GitHub 上的运行时列表',
|
||||
runtimeLookupFailed: '无法读取运行时列表',
|
||||
runtimeLookupRateLimit: 'GitHub 接口限流(HTTP 403),可切换 GitCode 镜像、稍后重试或手动导入',
|
||||
runtimeRetry: '重试',
|
||||
runtimeSource: '下载源',
|
||||
runtimeSourceHint: '自动模式优先 GitHub,连不上时自动切换 GitCode 国内镜像',
|
||||
runtimeSource_auto: '自动',
|
||||
runtimeSource_github: 'GitHub',
|
||||
runtimeSource_gitcode: 'GitCode',
|
||||
|
||||
// Toasts & dialogs
|
||||
toastStopped: '{name} 已关机',
|
||||
@@ -231,7 +257,7 @@ const dict = {
|
||||
onlineRecoveryTitle: '拉取在线恢复镜像?',
|
||||
onlineRecoveryDesc: '本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?',
|
||||
onlineRecoveryConfirm: '拉取并挂载(约 1 GB)',
|
||||
noRuntimeAlert: '先在「宿主与运行时」导入运行时包',
|
||||
noRuntimeAlert: '先在「内核」导入运行时包',
|
||||
|
||||
// Host
|
||||
hostRuntime: '运行时',
|
||||
@@ -390,7 +416,18 @@ const dict = {
|
||||
displayGroup: '显示器',
|
||||
resCustom: '自定义',
|
||||
resCustomSub: '宽 × 高',
|
||||
resFullscreen: '全屏',
|
||||
resLooksLike: '看起来像 {w} × {h}',
|
||||
resInvalid: '格式为 宽x高,例如 2560x1600',
|
||||
driveShareTitle: 'Windows 盘符共享',
|
||||
driveShareMaster: '共享 Windows 盘符',
|
||||
driveShareMasterDesc: '将所选内部固定磁盘挂载到 macOS Finder,立即生效',
|
||||
driveShareReadOnly: '只读 · macOS 可以打开和复制文件,不能修改 Windows 文件',
|
||||
driveShareSystem: '{root} · 系统盘包含个人文件和凭据,请谨慎共享',
|
||||
driveShareDrive: '{root} · 只读挂载为 Windows 盘符',
|
||||
driveShareNeedsTools: '需要 Guest Tools {version} 或更新版本。运行中的 VM 要先重启以更新 REIMSTOOLS,然后在 macOS 中重新运行安装命令',
|
||||
driveShareMasterOff: '先开启 Windows 盘符共享',
|
||||
driveShareNoDrives: '没有可共享的内部固定磁盘',
|
||||
networkDesc: '通过 NAT 共享宿主的网络连接',
|
||||
sshForward: 'SSH 端口转发',
|
||||
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
|
||||
@@ -438,6 +475,11 @@ const dict = {
|
||||
optDiscreteGpuRec: '已检测到独立显卡({name}),新建时默认优先使用',
|
||||
optDiscreteGpuIntegrated: '仅检测到核显({name}),性能弱于独立显卡',
|
||||
optDiscreteGpuUnavailable: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障',
|
||||
optSchedTitle: 'Windows 处理器计划',
|
||||
optSchedPrograms: '程序优先',
|
||||
optSchedBackground: '后台服务',
|
||||
optSchedSub: '「程序」偏向前台窗口;「后台服务」让各进程平均分配 CPU。虚拟机常在后台跑任务时,选「后台服务」更稳定',
|
||||
optSchedOpen: '以管理员身份打开…',
|
||||
kernelIrqchipLabel: 'WHPX 中断模式',
|
||||
kernelIrqchipAuto: '自动',
|
||||
kernelIrqchipOn: '开启',
|
||||
@@ -451,9 +493,12 @@ const dict = {
|
||||
minimizeToTraySub: '关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机',
|
||||
hostDisplays: '物理显示器',
|
||||
hostDisplayPrimary: '主屏',
|
||||
hostDisplayHint: '主屏 {w}×{h},{scale}% 缩放 · 推荐 {rec}',
|
||||
hostDisplayHint: '主屏 {w}×{h},{scale}% 缩放',
|
||||
multiDisplayHint: '检测到 {n} 块显示器,排列方式在 macOS「系统设置 › 显示器」里调整',
|
||||
hidpiPresetBadge: 'HiDPI',
|
||||
hidpiTipFullscreen: '窗口里的 macOS 只能 1x,文字会发虚;改用全屏可得到 HiDPI',
|
||||
hidpiTipScale: '这块屏幕上 macOS 只能 1x,文字会发虚;把 Windows 缩放调到 150% 或以上可得到 HiDPI',
|
||||
hidpiTipUnavailable: '这块屏幕像素不够,macOS 只能以 1x 显示',
|
||||
recommendedBadge: '推荐',
|
||||
fullscreenLaunch: '无边框全屏启动',
|
||||
fullscreenLaunchHint: '启动后直接进入无边框全屏',
|
||||
@@ -507,7 +552,9 @@ const dict = {
|
||||
},
|
||||
'en-US': {
|
||||
sidebarVMs: 'Virtual machines',
|
||||
sidebarHost: 'Host & runtime',
|
||||
sidebarSystem: 'System',
|
||||
sidebarHost: 'Engine',
|
||||
sidebarSettings: 'Settings',
|
||||
sidebarInstallers: 'Installers',
|
||||
installersTitle: 'Installers',
|
||||
installersDownloaded: 'Downloaded',
|
||||
@@ -529,6 +576,23 @@ const dict = {
|
||||
minimize: 'Minimize',
|
||||
maximize: 'Maximize',
|
||||
closeWindow: 'Close',
|
||||
themeSwitchDark: 'Switch to dark appearance',
|
||||
themeSwitchLight: 'Switch to light appearance',
|
||||
copyTechInfo: 'Copy technical details',
|
||||
resizeLogPanel: 'Drag to resize log panel',
|
||||
logButton: 'Logs',
|
||||
footerMem: 'Memory {pct}%',
|
||||
footerMemAvail: '{avail} GB free',
|
||||
footerMemTip: 'System memory: {used} GB used / {total} GB total ({avail} GB free)',
|
||||
footerDisk: 'Disk {gb} GB free',
|
||||
footerRunningVMs: '{n} running',
|
||||
settingsGeneral: 'General',
|
||||
settingsAppearance: 'Appearance & language',
|
||||
settingsAbout: 'About',
|
||||
themeLabel: 'Appearance',
|
||||
themeLight: 'Light',
|
||||
themeDark: 'Dark',
|
||||
themeSystem: 'System',
|
||||
|
||||
newVM: 'New virtual machine',
|
||||
start: 'Start',
|
||||
@@ -676,7 +740,14 @@ const dict = {
|
||||
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',
|
||||
runtimeLookupFailed: 'Couldn’t read the runtime list',
|
||||
runtimeLookupRateLimit: 'GitHub API rate limit reached (HTTP 403); switch to GitCode mirror, retry later, or import a local bundle',
|
||||
runtimeRetry: 'Retry',
|
||||
runtimeSource: 'Download source',
|
||||
runtimeSourceHint: 'Auto tries GitHub first and falls back to the GitCode mirror if unreachable',
|
||||
runtimeSource_auto: 'Auto',
|
||||
runtimeSource_github: 'GitHub',
|
||||
runtimeSource_gitcode: 'GitCode',
|
||||
|
||||
toastStopped: '{name} shut down',
|
||||
toastEjected: 'Installer ejected',
|
||||
@@ -724,7 +795,7 @@ const dict = {
|
||||
onlineRecoveryTitle: 'Download online recovery image?',
|
||||
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',
|
||||
noRuntimeAlert: 'Import a runtime under Engine first',
|
||||
|
||||
hostRuntime: 'Runtime',
|
||||
hostGPUs: 'Graphics cards',
|
||||
@@ -880,7 +951,18 @@ const dict = {
|
||||
displayGroup: 'Displays',
|
||||
resCustom: 'Custom',
|
||||
resCustomSub: 'Width × height',
|
||||
resFullscreen: 'Full screen',
|
||||
resLooksLike: 'Looks like {w} × {h}',
|
||||
resInvalid: 'Use WIDTHxHEIGHT, e.g. 2560x1600',
|
||||
driveShareTitle: 'Windows drive sharing',
|
||||
driveShareMaster: 'Share Windows drives',
|
||||
driveShareMasterDesc: 'Mounts selected internal fixed disks in macOS Finder; applies immediately',
|
||||
driveShareReadOnly: 'Read-only · macOS can open and copy files, but cannot change Windows files',
|
||||
driveShareSystem: '{root} · The system disk contains personal files and credentials; share with care',
|
||||
driveShareDrive: '{root} · Mounted read-only as a Windows drive',
|
||||
driveShareNeedsTools: 'Requires Guest Tools {version} or newer. Restart a running VM to update REIMSTOOLS, then run the install command in macOS again',
|
||||
driveShareMasterOff: 'Turn on Windows drive sharing first',
|
||||
driveShareNoDrives: 'No internal fixed disks are available to share',
|
||||
networkDesc: 'Shares the host connection through NAT',
|
||||
sshForward: 'SSH port forwarding',
|
||||
sshOffDesc: 'Forwards a host port to port 22 in macOS',
|
||||
@@ -928,6 +1010,11 @@ const dict = {
|
||||
optDiscreteGpuRec: 'Discrete GPU detected ({name}); preferred automatically',
|
||||
optDiscreteGpuIntegrated: 'Integrated GPU only ({name})',
|
||||
optDiscreteGpuUnavailable: 'No Vulkan GPU detected; use vmware-svga for troubleshooting',
|
||||
optSchedTitle: 'Windows processor scheduling',
|
||||
optSchedPrograms: 'Programs',
|
||||
optSchedBackground: 'Background services',
|
||||
optSchedSub: 'Programs favours the window in front; Background services shares the CPU evenly. If the VM often works while you use other apps, Background services keeps it steadier',
|
||||
optSchedOpen: 'Open as administrator…',
|
||||
kernelIrqchipLabel: 'WHPX interrupt mode',
|
||||
kernelIrqchipAuto: 'Auto',
|
||||
kernelIrqchipOn: 'On',
|
||||
@@ -941,9 +1028,12 @@ const dict = {
|
||||
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',
|
||||
hostDisplayHint: 'Main display {w}×{h} at {scale}%',
|
||||
multiDisplayHint: '{n} displays found; arrange them in macOS System Settings › Displays',
|
||||
hidpiPresetBadge: 'HiDPI',
|
||||
hidpiTipFullscreen: 'In a window macOS runs at 1x with rough text; full screen gives HiDPI',
|
||||
hidpiTipScale: 'macOS runs at 1x on this screen, with rough text; Windows scaling at 150% or more gives HiDPI',
|
||||
hidpiTipUnavailable: 'This screen has too few pixels; macOS runs at 1x',
|
||||
recommendedBadge: 'Recommended',
|
||||
fullscreenLaunch: 'Launch borderless fullscreen',
|
||||
fullscreenLaunchHint: 'Opens macOS in borderless full screen',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { t } from '../i18n'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||||
|
||||
// Human-readable values for the main view (docs/ui-redesign.md §4.3).
|
||||
@@ -118,6 +118,19 @@ export function formatBytes(bytes: number): string {
|
||||
return `${v.toFixed(digits)} ${units[i]}`
|
||||
}
|
||||
|
||||
/** Compact "54 / 128 GB" when both are gigabytes, falling back to full units. */
|
||||
export function formatDiskUsage(actual: number, virtual: number): string {
|
||||
const GiB = 1024 ** 3
|
||||
if (actual >= GiB && virtual >= GiB && virtual < 1024 * GiB) {
|
||||
const a = actual / GiB
|
||||
const v = virtual / GiB
|
||||
const aStr = a >= 10 ? Math.round(a).toString() : a.toFixed(1)
|
||||
const vStr = Math.round(v).toString()
|
||||
return `${aStr} / ${vStr} GB`
|
||||
}
|
||||
return `${formatBytes(actual)} / ${formatBytes(virtual)}`
|
||||
}
|
||||
|
||||
export function formatUptime(sec: number, locale: Locale): string {
|
||||
if (!sec || sec <= 0) return '—'
|
||||
const h = Math.floor(sec / 3600)
|
||||
@@ -133,13 +146,41 @@ export function formatUptime(sec: number, locale: Locale): string {
|
||||
return `${s}s`
|
||||
}
|
||||
|
||||
// Used only when the host report has no presets: with nothing known about the
|
||||
// screen, no size can be called HiDPI (internal/host/display.go).
|
||||
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 },
|
||||
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: false },
|
||||
]
|
||||
|
||||
type Tr = (k: I18nKey, v?: Record<string, string | number>) => string
|
||||
|
||||
// The resolution row's description: the main display and its scaling.
|
||||
export function hostDisplayDesc(host: HostReport, tr: Tr): string | undefined {
|
||||
const d = host.primary_display
|
||||
if (!d) return undefined
|
||||
return tr('hostDisplayHint', { w: d.width, h: d.height, scale: d.scale_pct || 100 })
|
||||
}
|
||||
|
||||
// How to get a HiDPI (sharp-text) macOS desktop when no window size gives
|
||||
// one on this screen; undefined when one does.
|
||||
export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined {
|
||||
const tip: Record<string, I18nKey> = {
|
||||
fullscreen: 'hidpiTipFullscreen',
|
||||
scale: 'hidpiTipScale',
|
||||
unavailable: 'hidpiTipUnavailable',
|
||||
}
|
||||
const key = host.hidpi_advice ? tip[host.hidpi_advice] : undefined
|
||||
return key ? tr(key) : undefined
|
||||
}
|
||||
|
||||
// "Looks like" size of a HiDPI preset: macOS draws it at half each way.
|
||||
export function hidpiLooksLike(resolution: string, tr: Tr): string | undefined {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(resolution)
|
||||
return m ? tr('resLooksLike', { w: Math.round(Number(m[1]) / 2), h: Math.round(Number(m[2]) / 2) }) : undefined
|
||||
}
|
||||
|
||||
export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
|
||||
if (host.display_presets && host.display_presets.length > 0) {
|
||||
return host.display_presets
|
||||
|
||||
+581
-322
File diff suppressed because it is too large.
Load diff
+157
-48
@@ -1,25 +1,69 @@
|
||||
/* Design tokens — macOS Tahoe System Settings aesthetic (Light default, Dark optional). */
|
||||
/* Bundled open-source Inter Variable (SIL OFL 1.1, Latin ~47 KB) — optical twin of Apple SF Pro. */
|
||||
@font-face {
|
||||
font-family: "ReimsSans";
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-weight: 100 900;
|
||||
src: url("@fontsource-variable/inter/files/inter-latin-wght-normal.woff2") format("woff2-variations");
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
||||
/* Map installed PingFang SC / HarmonyOS Sans SC / MiSans / Noto Sans SC / Source Han Sans CN
|
||||
explicitly across weights. On Windows DirectWrite, PingFang SC Regular renders overly thin
|
||||
compared to macOS Retina CoreText, so body weights (400–550) map to Medium for balanced ink. */
|
||||
@font-face {
|
||||
font-family: "ReimsCJK";
|
||||
font-style: normal;
|
||||
font-weight: 400 550;
|
||||
src:
|
||||
local("PingFang SC Medium"), local("PingFangSC-Medium"),
|
||||
local("HarmonyOS Sans SC"), local("HarmonyOS_Sans_SC"),
|
||||
local("MiSans Regular"), local("MiSans"),
|
||||
local("Noto Sans SC Medium"), local("NotoSansSC-Medium"),
|
||||
local("Noto Sans SC"), local("NotoSansSC-Regular"),
|
||||
local("Source Han Sans CN Medium"), local("SourceHanSansCN-Medium"),
|
||||
local("Source Han Sans CN Regular"), local("SourceHanSansCN-Regular");
|
||||
unicode-range: U+2E80-9FFF, U+3000-303F, U+FF00-FFEF, U+F900-FAFF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "ReimsCJK";
|
||||
font-style: normal;
|
||||
font-weight: 560 900;
|
||||
src:
|
||||
local("PingFang SC Semibold"), local("PingFangSC-Semibold"),
|
||||
local("PingFang SC Bold"), local("PingFangSC-Bold"),
|
||||
local("HarmonyOS Sans SC Bold"), local("HarmonyOS_Sans_SC_Bold"),
|
||||
local("MiSans Demibold"), local("MiSans Semibold"), local("MiSans Bold"),
|
||||
local("Noto Sans SC SemiBold"), local("NotoSansSC-SemiBold"), local("Noto Sans SC Bold"),
|
||||
local("Source Han Sans CN Bold"), local("SourceHanSansCN-Bold");
|
||||
unicode-range: U+2E80-9FFF, U+3000-303F, U+FF00-FFEF, U+F900-FAFF;
|
||||
}
|
||||
|
||||
/* Design tokens — macOS Tahoe aesthetic with Windows platform craft (Light default, Dark & System supported). */
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
/* Type */
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||
--font-mono: "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace;
|
||||
/* Typography */
|
||||
--font-sans: "ReimsSans", "ReimsCJK", "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", "Noto Sans SC", "Source Han Sans CN", -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
|
||||
--font-mono: "SF Mono", "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||
--fs-11: 11px;
|
||||
--fs-12: 12px;
|
||||
--fs-13: 13px;
|
||||
--fs-14: 14px;
|
||||
--fs-15: 15px;
|
||||
--fs-16: 16px;
|
||||
--fs-20: 20px;
|
||||
--fs-24: 24px;
|
||||
--fw-regular: 400;
|
||||
--fw-medium: 500;
|
||||
--fw-strong: 600;
|
||||
--fw-regular: 450;
|
||||
--fw-medium: 540;
|
||||
--fw-strong: 640;
|
||||
|
||||
/* Spacing (4px grid) */
|
||||
--sp-1: 4px;
|
||||
--sp-2: 8px;
|
||||
--sp-3: 12px;
|
||||
--sp-4: 16px;
|
||||
--sp-5: 20px;
|
||||
--sp-6: 24px;
|
||||
--sp-8: 32px;
|
||||
|
||||
@@ -32,88 +76,112 @@
|
||||
/* Surfaces (macOS Tahoe Light) */
|
||||
--surface-0: #ffffff;
|
||||
--surface-canvas: #ffffff;
|
||||
--surface-sidebar: linear-gradient(180deg, #eff5fc 0%, #eaf2fa 100%);
|
||||
--surface-sidebar-border: rgba(15, 23, 42, 0.07);
|
||||
--surface-sidebar-shadow: 0 2px 14px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
--surface-chrome: rgba(255, 255, 255, 0.88);
|
||||
--surface-sidebar-rail: linear-gradient(180deg, #e7f0fa 0%, #dde8f7 100%);
|
||||
--surface-sidebar: linear-gradient(180deg, rgba(255, 255, 255, 0.80) 0%, rgba(247, 250, 255, 0.72) 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.90);
|
||||
--surface-sidebar-shadow: 0 4px 18px rgba(15, 35, 70, 0.065), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--surface-chrome: linear-gradient(180deg, #eff4fb 0%, #e8f0fa 100%);
|
||||
--surface-statusbar: #eef3fa;
|
||||
--surface-1: #f5f6f8;
|
||||
--surface-card-elevated: #ffffff;
|
||||
--surface-2: rgba(255, 255, 255, 0.96);
|
||||
--surface-2: rgba(255, 255, 255, 0.94);
|
||||
--surface-input: #ffffff;
|
||||
--surface-hover: rgba(15, 23, 42, 0.05);
|
||||
--surface-active: rgba(15, 23, 42, 0.09);
|
||||
--border: rgba(15, 23, 42, 0.075);
|
||||
--surface-hover: rgba(15, 23, 42, 0.048);
|
||||
--surface-active: rgba(15, 23, 42, 0.085);
|
||||
--border: rgba(15, 23, 42, 0.08);
|
||||
--border-strong: rgba(15, 23, 42, 0.14);
|
||||
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.85);
|
||||
--scrim: rgba(15, 23, 42, 0.28);
|
||||
--shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06);
|
||||
--shadow-overlay: 0 20px 56px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.7);
|
||||
--shadow-card: 0 1px 2px rgba(15, 23, 42, 0.025);
|
||||
--shadow-overlay: 0 22px 58px rgba(15, 23, 42, 0.18), 0 4px 14px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(15, 23, 42, 0.06);
|
||||
--blur-chrome: blur(20px) saturate(180%);
|
||||
--blur-overlay: blur(18px) saturate(165%);
|
||||
|
||||
/* Text */
|
||||
--text: #1d1d1f;
|
||||
--text-2: #515154;
|
||||
--text-3: #86868b;
|
||||
--text-2: #424247;
|
||||
--text-3: #6e6e73;
|
||||
--text-code: #2c2c30;
|
||||
|
||||
/* Semantics (Apple System Colours) */
|
||||
--accent: #007aff;
|
||||
--accent-hover: #006be6;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(0, 122, 255, 0.12);
|
||||
--accent-soft: rgba(0, 122, 255, 0.11);
|
||||
--accent-soft-text: #0066d6;
|
||||
--focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.3);
|
||||
--focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.30);
|
||||
|
||||
--status-running: #28cd41;
|
||||
--status-busy: #ff9f0a;
|
||||
--status-error: #ff3b30;
|
||||
--status-idle: #aeaeb2;
|
||||
|
||||
--ok-soft: rgba(40, 205, 65, 0.13);
|
||||
--ok-text: #188c2c;
|
||||
--warn-soft: rgba(255, 159, 10, 0.14);
|
||||
--warn-text: #a86200;
|
||||
|
||||
--danger: #ff3b30;
|
||||
--danger-soft: rgba(255, 59, 48, 0.10);
|
||||
--danger-border: rgba(255, 59, 48, 0.28);
|
||||
--danger-text: #d70015;
|
||||
--notice-soft: rgba(255, 159, 10, 0.11);
|
||||
--notice-border: rgba(255, 159, 10, 0.32);
|
||||
--notice-soft: rgba(255, 159, 10, 0.10);
|
||||
--notice-border: rgba(255, 159, 10, 0.28);
|
||||
|
||||
/* Motion */
|
||||
--dur-fast: 120ms;
|
||||
--dur: 200ms;
|
||||
--seg-thumb: #ffffff;
|
||||
|
||||
/* Motion (emil-design-eng & apple-design curves) */
|
||||
--ease-out: cubic-bezier(0.23, 1, 0.32, 1);
|
||||
--ease-in-out: cubic-bezier(0.77, 0, 0.175, 1);
|
||||
--ease-spring: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
--dur-press: 100ms;
|
||||
--dur-fast: 130ms;
|
||||
--dur: 180ms;
|
||||
--dur-modal: 220ms;
|
||||
--dur-toast: 280ms;
|
||||
|
||||
/* Layout */
|
||||
--titlebar-h: 42px;
|
||||
--logbar-h: 32px;
|
||||
--sidebar-w: 244px;
|
||||
--page-max: 700px;
|
||||
--sidebar-w: 248px;
|
||||
--page-max: 632px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--surface-0: #1e1e22;
|
||||
--surface-canvas: #1e1e22;
|
||||
--surface-sidebar: linear-gradient(180deg, #27282e 0%, #23242a 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.08);
|
||||
--surface-sidebar-shadow: 0 4px 18px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
--surface-chrome: rgba(28, 28, 32, 0.92);
|
||||
--surface-1: rgba(255, 255, 255, 0.05);
|
||||
--surface-card-elevated: rgba(255, 255, 255, 0.07);
|
||||
--surface-2: #2b2c32;
|
||||
--surface-0: #1b1c20;
|
||||
--surface-canvas: #1d1e23;
|
||||
--surface-sidebar-rail: #17181c;
|
||||
--surface-sidebar: linear-gradient(180deg, rgba(40, 41, 48, 0.94) 0%, rgba(34, 35, 41, 0.92) 100%);
|
||||
--surface-sidebar-border: rgba(255, 255, 255, 0.09);
|
||||
--surface-sidebar-shadow: 0 6px 22px rgba(0, 0, 0, 0.36), inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
--surface-chrome: linear-gradient(180deg, #212228 0%, #1c1d22 100%);
|
||||
--surface-statusbar: #18191e;
|
||||
--surface-1: rgba(255, 255, 255, 0.048);
|
||||
--surface-card-elevated: rgba(255, 255, 255, 0.075);
|
||||
--surface-2: rgba(42, 43, 50, 0.94);
|
||||
--surface-input: rgba(0, 0, 0, 0.28);
|
||||
--surface-hover: rgba(255, 255, 255, 0.07);
|
||||
--surface-hover: rgba(255, 255, 255, 0.075);
|
||||
--surface-active: rgba(255, 255, 255, 0.12);
|
||||
--border: rgba(255, 255, 255, 0.09);
|
||||
--border: rgba(255, 255, 255, 0.085);
|
||||
--border-strong: rgba(255, 255, 255, 0.16);
|
||||
--scrim: rgba(0, 0, 0, 0.55);
|
||||
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.28);
|
||||
--shadow-overlay: 0 24px 64px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.08);
|
||||
--highlight-top: inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
--scrim: rgba(0, 0, 0, 0.56);
|
||||
--shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.30), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.18);
|
||||
--shadow-overlay: 0 26px 68px rgba(0, 0, 0, 0.58), 0 0 0 1px rgba(255, 255, 255, 0.09);
|
||||
|
||||
--text: #f5f5f7;
|
||||
--text-2: #b4b4bc;
|
||||
--text-3: #86868e;
|
||||
--text-2: #c2c2ca;
|
||||
--text-3: #92929c;
|
||||
--text-code: #d4d6e0;
|
||||
|
||||
--accent: #0a84ff;
|
||||
--accent-hover: #2492ff;
|
||||
--accent-text: #ffffff;
|
||||
--accent-soft: rgba(10, 132, 255, 0.22);
|
||||
--accent-soft: rgba(10, 132, 255, 0.20);
|
||||
--accent-soft-text: #64b0ff;
|
||||
--focus-ring: 0 0 0 3px rgba(10, 132, 255, 0.45);
|
||||
|
||||
@@ -122,16 +190,57 @@
|
||||
--status-error: #ff453a;
|
||||
--status-idle: #6e6e76;
|
||||
|
||||
--ok-soft: rgba(48, 209, 88, 0.16);
|
||||
--ok-text: #30d158;
|
||||
--warn-soft: rgba(255, 214, 10, 0.15);
|
||||
--warn-text: #ffd60a;
|
||||
|
||||
--danger: #ff453a;
|
||||
--danger-soft: rgba(255, 69, 58, 0.16);
|
||||
--danger-soft: rgba(255, 69, 58, 0.15);
|
||||
--danger-border: rgba(255, 69, 58, 0.34);
|
||||
--danger-text: #ff8b83;
|
||||
--notice-soft: rgba(255, 214, 10, 0.11);
|
||||
--notice-border: rgba(255, 214, 10, 0.30);
|
||||
--notice-soft: rgba(255, 214, 10, 0.10);
|
||||
--notice-border: rgba(255, 214, 10, 0.28);
|
||||
|
||||
--seg-thumb: #555760;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:root {
|
||||
--dur-press: 0ms;
|
||||
--dur-fast: 0ms;
|
||||
--dur: 0ms;
|
||||
--dur-modal: 0ms;
|
||||
--dur-toast: 0ms;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
:root {
|
||||
--surface-chrome: #ffffff;
|
||||
--surface-2: #ffffff;
|
||||
--surface-sidebar: #eef3fa;
|
||||
--blur-chrome: none;
|
||||
--blur-overlay: none;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--surface-chrome: #1b1c20;
|
||||
--surface-2: #2a2b32;
|
||||
--surface-sidebar: #24252b;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-contrast: more) {
|
||||
:root {
|
||||
--border: rgba(15, 23, 42, 0.20);
|
||||
--border-strong: rgba(15, 23, 42, 0.34);
|
||||
--text-2: #3a3a3d;
|
||||
--text-3: #5a5a5f;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--border: rgba(255, 255, 255, 0.20);
|
||||
--border-strong: rgba(255, 255, 255, 0.34);
|
||||
--text-2: #d2d2da;
|
||||
--text-3: #a6a6b0;
|
||||
}
|
||||
}
|
||||
+16
-11
@@ -1,16 +1,19 @@
|
||||
// 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'
|
||||
import { app, config, host, installer, 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 type RuntimeSource = 'auto' | 'github' | 'gitcode'
|
||||
|
||||
export type Config = Model<config.Config> & {
|
||||
locale: Locale
|
||||
runtime_channel?: 'stable' | 'alpha' | ''
|
||||
runtime_source?: RuntimeSource | ''
|
||||
}
|
||||
|
||||
export type DisplayInfo = host.DisplayInfo
|
||||
@@ -40,15 +43,16 @@ export type InstalledRuntime = Model<runtime.Installed>
|
||||
|
||||
export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
channel: 'stable' | 'alpha'
|
||||
source?: 'github' | 'gitcode'
|
||||
}
|
||||
|
||||
export type VMListItem = Model<reims.VMListItem> & {
|
||||
state: 'running' | 'stopped' | 'broken'
|
||||
}
|
||||
|
||||
export type PendingChange = main.PendingChange
|
||||
export type PendingChange = app.PendingChange
|
||||
|
||||
export type AppState = Omit<Model<main.AppState>, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & {
|
||||
export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizations' | 'runtimes' | 'active_runtime' | 'vms'> & {
|
||||
config: Config
|
||||
host: HostReport
|
||||
optimizations?: Optimization[]
|
||||
@@ -59,9 +63,10 @@ export type AppState = Omit<Model<main.AppState>, 'config' | 'host' | 'optimizat
|
||||
|
||||
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 VMStats = app.VMStats
|
||||
export type DriveShareSettings = Model<app.DriveShareSettings>
|
||||
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
|
||||
export type VMThumbnail = app.VMThumbnail
|
||||
export type ValidationIssue = reims.ValidationIssue
|
||||
export type DiskResizeResult = reims.DiskResizeResult
|
||||
export type DiskCompactResult = reims.DiskCompactResult
|
||||
@@ -81,8 +86,8 @@ export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
|
||||
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
|
||||
/** A tracked long-running job pushed as "reims:task" (tasks.go). */
|
||||
export type Task = Model<main.Task> & {
|
||||
/** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */
|
||||
export type Task = Model<app.Task> & {
|
||||
kind: 'installer-download' | 'vm-create' | string
|
||||
status: TaskStatus
|
||||
}
|
||||
@@ -95,10 +100,10 @@ export type CachedInstaller = Model<installer.Cached> & {
|
||||
kind: 'offline' | 'online' | 'ipsw' | 'other'
|
||||
}
|
||||
|
||||
export type DataRootChoice = main.DataRootChoice
|
||||
export type DataRootCheck = main.DataRootCheck
|
||||
export type DataRootChoice = app.DataRootChoice
|
||||
export type DataRootCheck = app.DataRootCheck
|
||||
|
||||
/** A "reims:log" event (app.go emitLog); not a Go struct, so not generated. */
|
||||
/** A "reims:log" event (internal/app/app.go emitLog); not a Go struct, so not generated. */
|
||||
export interface LogEntry {
|
||||
ts: string
|
||||
source: string
|
||||
|
||||
@@ -44,7 +44,7 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
aria-busy={busy || undefined}
|
||||
{...rest}
|
||||
>
|
||||
{busy ? <LoaderCircle size={14} className="spin" /> : icon}
|
||||
{busy ? <LoaderCircle size={14} className="spin" aria-hidden="true" /> : icon}
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
@@ -73,7 +73,7 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
aria-busy={busy || undefined}
|
||||
{...rest}
|
||||
>
|
||||
{busy ? <LoaderCircle size={16} className="spin" /> : icon}
|
||||
{busy ? <LoaderCircle size={16} className="spin" aria-hidden="true" /> : icon}
|
||||
</button>
|
||||
</Tip>
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Backend calls are the Wails-generated bindings (wailsjs/go/main/App). Only
|
||||
// Backend calls are the Wails-generated bindings (wailsjs/go/app/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 * as Go from '../wailsjs/go/app/App'
|
||||
import { EventsOn } from '../wailsjs/runtime/runtime'
|
||||
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task } from './types'
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
import {reims} from '../models';
|
||||
import {version} from '../models';
|
||||
import {main} from '../models';
|
||||
import {app} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
|
||||
@@ -16,7 +16,7 @@ export function CancelTask(arg1:string):Promise<void>;
|
||||
|
||||
export function CheckAppUpdate(arg1:boolean):Promise<version.UpdateInfo>;
|
||||
|
||||
export function CheckDataRoot(arg1:string):Promise<main.DataRootCheck>;
|
||||
export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
|
||||
|
||||
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
@@ -50,15 +50,17 @@ export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function GetState():Promise<main.AppState>;
|
||||
export function GetState():Promise<app.AppState>;
|
||||
|
||||
export function GetTasks():Promise<Array<main.Task>>;
|
||||
export function GetTasks():Promise<Array<app.Task>>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<main.VMStats>;
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<main.VMThumbnail>;
|
||||
export function GetVMStats(arg1:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
|
||||
|
||||
@@ -70,6 +72,8 @@ export function ListOfflineReleases():Promise<Array<installer.Release>>;
|
||||
|
||||
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
@@ -104,13 +108,17 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetRuntimeSource(arg1:string):Promise<void>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
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 SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
|
||||
|
||||
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
// @ts-check
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export function ApplyVMSettings(arg1) {
|
||||
return window['go']['app']['App']['ApplyVMSettings'](arg1);
|
||||
}
|
||||
|
||||
export function AttachGuestTools(arg1) {
|
||||
return window['go']['app']['App']['AttachGuestTools'](arg1);
|
||||
}
|
||||
|
||||
export function AttachInstaller(arg1, arg2) {
|
||||
return window['go']['app']['App']['AttachInstaller'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CancelTask(arg1) {
|
||||
return window['go']['app']['App']['CancelTask'](arg1);
|
||||
}
|
||||
|
||||
export function CheckAppUpdate(arg1) {
|
||||
return window['go']['app']['App']['CheckAppUpdate'](arg1);
|
||||
}
|
||||
|
||||
export function CheckDataRoot(arg1) {
|
||||
return window['go']['app']['App']['CheckDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function CloneVMCoW(arg1, arg2) {
|
||||
return window['go']['app']['App']['CloneVMCoW'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CompactVMDisk(arg1) {
|
||||
return window['go']['app']['App']['CompactVMDisk'](arg1);
|
||||
}
|
||||
|
||||
export function CompleteSetup(arg1) {
|
||||
return window['go']['app']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['app']['App']['CreateVM'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteInstaller(arg1) {
|
||||
return window['go']['app']['App']['DeleteInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeliverFileToGuest(arg1) {
|
||||
return window['go']['app']['App']['DeliverFileToGuest'](arg1);
|
||||
}
|
||||
|
||||
export function DetachGuestTools(arg1) {
|
||||
return window['go']['app']['App']['DetachGuestTools'](arg1);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['app']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
|
||||
return window['go']['app']['App']['DownloadAndAttachOnlineRecovery'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['app']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstaller(arg1) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EnableWHPX() {
|
||||
return window['go']['app']['App']['EnableWHPX']();
|
||||
}
|
||||
|
||||
export function EnterRecovery(arg1) {
|
||||
return window['go']['app']['App']['EnterRecovery'](arg1);
|
||||
}
|
||||
|
||||
export function ExportDiagnostics(arg1) {
|
||||
return window['go']['app']['App']['ExportDiagnostics'](arg1);
|
||||
}
|
||||
|
||||
export function FinishInstall(arg1) {
|
||||
return window['go']['app']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
|
||||
export function GetState() {
|
||||
return window['go']['app']['App']['GetState']();
|
||||
}
|
||||
|
||||
export function GetTasks() {
|
||||
return window['go']['app']['App']['GetTasks']();
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['app']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMStats(arg1) {
|
||||
return window['go']['app']['App']['GetVMStats'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMThumbnail(arg1) {
|
||||
return window['go']['app']['App']['GetVMThumbnail'](arg1);
|
||||
}
|
||||
|
||||
export function InstallRuntimeArchive(arg1) {
|
||||
return window['go']['app']['App']['InstallRuntimeArchive'](arg1);
|
||||
}
|
||||
|
||||
export function InstallRuntimeOnline(arg1) {
|
||||
return window['go']['app']['App']['InstallRuntimeOnline'](arg1);
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['app']['App']['ListInstallers']();
|
||||
}
|
||||
|
||||
export function ListOfflineReleases() {
|
||||
return window['go']['app']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
export function ListRemoteRuntimes() {
|
||||
return window['go']['app']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
return window['go']['app']['App']['OpenSharedFolder'](arg1);
|
||||
}
|
||||
|
||||
export function OpenURL(arg1) {
|
||||
return window['go']['app']['App']['OpenURL'](arg1);
|
||||
}
|
||||
|
||||
export function OpenVMFolder(arg1) {
|
||||
return window['go']['app']['App']['OpenVMFolder'](arg1);
|
||||
}
|
||||
|
||||
export function PickDirectory(arg1) {
|
||||
return window['go']['app']['App']['PickDirectory'](arg1);
|
||||
}
|
||||
|
||||
export function PickFile(arg1, arg2) {
|
||||
return window['go']['app']['App']['PickFile'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function PreviewCreate(arg1) {
|
||||
return window['go']['app']['App']['PreviewCreate'](arg1);
|
||||
}
|
||||
|
||||
export function QuitApp() {
|
||||
return window['go']['app']['App']['QuitApp']();
|
||||
}
|
||||
|
||||
export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RequestClose() {
|
||||
return window['go']['app']['App']['RequestClose']();
|
||||
}
|
||||
|
||||
export function ResizeVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestartVM(arg1) {
|
||||
return window['go']['app']['App']['RestartVM'](arg1);
|
||||
}
|
||||
|
||||
export function SetAutoPinPCores(arg1) {
|
||||
return window['go']['app']['App']['SetAutoPinPCores'](arg1);
|
||||
}
|
||||
|
||||
export function SetDataRoot(arg1) {
|
||||
return window['go']['app']['App']['SetDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function SetGuestPreventSleep(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetGuestPreventSleep'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetLocale(arg1) {
|
||||
return window['go']['app']['App']['SetLocale'](arg1);
|
||||
}
|
||||
|
||||
export function SetMinimizeToTray(arg1) {
|
||||
return window['go']['app']['App']['SetMinimizeToTray'](arg1);
|
||||
}
|
||||
|
||||
export function SetRuntimeChannel(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
|
||||
}
|
||||
|
||||
export function SetRuntimeSource(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeSource'](arg1);
|
||||
}
|
||||
|
||||
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ShowMainWindow() {
|
||||
return window['go']['app']['App']['ShowMainWindow']();
|
||||
}
|
||||
|
||||
export function StartVM(arg1) {
|
||||
return window['go']['app']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SuggestDataRoots() {
|
||||
return window['go']['app']['App']['SuggestDataRoots']();
|
||||
}
|
||||
|
||||
export function ToggleBorderless(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeClipboard(arg1) {
|
||||
return window['go']['app']['App']['TypeClipboard'](arg1);
|
||||
}
|
||||
|
||||
export function TypeText(arg1, arg2) {
|
||||
return window['go']['app']['App']['TypeText'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1) {
|
||||
return window['go']['app']['App']['UpgradeDiskToNVMe'](arg1);
|
||||
}
|
||||
|
||||
export function UseRuntime(arg1) {
|
||||
return window['go']['app']['App']['UseRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateCreate(arg1) {
|
||||
return window['go']['app']['App']['ValidateCreate'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateSet(arg1) {
|
||||
return window['go']['app']['App']['ValidateSet'](arg1);
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
// @ts-check
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export function ApplyVMSettings(arg1) {
|
||||
return window['go']['main']['App']['ApplyVMSettings'](arg1);
|
||||
}
|
||||
|
||||
export function AttachGuestTools(arg1) {
|
||||
return window['go']['main']['App']['AttachGuestTools'](arg1);
|
||||
}
|
||||
|
||||
export function AttachInstaller(arg1, arg2) {
|
||||
return window['go']['main']['App']['AttachInstaller'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CancelTask(arg1) {
|
||||
return window['go']['main']['App']['CancelTask'](arg1);
|
||||
}
|
||||
|
||||
export function CheckAppUpdate(arg1) {
|
||||
return window['go']['main']['App']['CheckAppUpdate'](arg1);
|
||||
}
|
||||
|
||||
export function CheckDataRoot(arg1) {
|
||||
return window['go']['main']['App']['CheckDataRoot'](arg1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['main']['App']['CreateVM'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteInstaller(arg1) {
|
||||
return window['go']['main']['App']['DeleteInstaller'](arg1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['main']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
|
||||
return window['go']['main']['App']['DownloadAndAttachOnlineRecovery'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DownloadInstaller(arg1) {
|
||||
return window['go']['main']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstaller(arg1) {
|
||||
return window['go']['main']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EnableWHPX() {
|
||||
return window['go']['main']['App']['EnableWHPX']();
|
||||
}
|
||||
|
||||
export function EnterRecovery(arg1) {
|
||||
return window['go']['main']['App']['EnterRecovery'](arg1);
|
||||
}
|
||||
|
||||
export function ExportDiagnostics(arg1) {
|
||||
return window['go']['main']['App']['ExportDiagnostics'](arg1);
|
||||
}
|
||||
|
||||
export function FinishInstall(arg1) {
|
||||
return window['go']['main']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
|
||||
export function GetState() {
|
||||
return window['go']['main']['App']['GetState']();
|
||||
}
|
||||
|
||||
export function GetTasks() {
|
||||
return window['go']['main']['App']['GetTasks']();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function InstallRuntimeOnline(arg1) {
|
||||
return window['go']['main']['App']['InstallRuntimeOnline'](arg1);
|
||||
}
|
||||
|
||||
export function ListInstallers() {
|
||||
return window['go']['main']['App']['ListInstallers']();
|
||||
}
|
||||
|
||||
export function ListOfflineReleases() {
|
||||
return window['go']['main']['App']['ListOfflineReleases']();
|
||||
}
|
||||
|
||||
export function ListRemoteRuntimes() {
|
||||
return window['go']['main']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
return window['go']['main']['App']['OpenSharedFolder'](arg1);
|
||||
}
|
||||
|
||||
export function OpenURL(arg1) {
|
||||
return window['go']['main']['App']['OpenURL'](arg1);
|
||||
}
|
||||
|
||||
export function OpenVMFolder(arg1) {
|
||||
return window['go']['main']['App']['OpenVMFolder'](arg1);
|
||||
}
|
||||
|
||||
export function PickDirectory(arg1) {
|
||||
return window['go']['main']['App']['PickDirectory'](arg1);
|
||||
}
|
||||
|
||||
export function PickFile(arg1, arg2) {
|
||||
return window['go']['main']['App']['PickFile'](arg1, arg2);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function SetAutoPinPCores(arg1) {
|
||||
return window['go']['main']['App']['SetAutoPinPCores'](arg1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['main']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function TypeText(arg1, arg2) {
|
||||
return window['go']['main']['App']['TypeText'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1) {
|
||||
return window['go']['main']['App']['UpgradeDiskToNVMe'](arg1);
|
||||
}
|
||||
|
||||
export function UseRuntime(arg1) {
|
||||
return window['go']['main']['App']['UseRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateCreate(arg1) {
|
||||
return window['go']['main']['App']['ValidateCreate'](arg1);
|
||||
}
|
||||
|
||||
export function ValidateSet(arg1) {
|
||||
return window['go']['main']['App']['ValidateSet'](arg1);
|
||||
}
|
||||
+271
-203
@@ -1,3 +1,260 @@
|
||||
export namespace app {
|
||||
|
||||
export class AppState {
|
||||
config?: config.Config;
|
||||
host: host.Report;
|
||||
optimizations: host.Optimization[];
|
||||
runtimes: runtime.Installed[];
|
||||
active_runtime?: runtime.Installed;
|
||||
vms: reims.VMListItem[];
|
||||
transitions: Record<string, string>;
|
||||
pending_changes: Record<string, Array<PendingChange>>;
|
||||
needs_setup: boolean;
|
||||
app_version: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AppState(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.config = this.convertValues(source["config"], config.Config);
|
||||
this.host = this.convertValues(source["host"], host.Report);
|
||||
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
|
||||
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.vms = this.convertValues(source["vms"], reims.VMListItem);
|
||||
this.transitions = source["transitions"];
|
||||
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
|
||||
this.needs_setup = source["needs_setup"];
|
||||
this.app_version = source["app_version"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class DataRootCheck {
|
||||
path: string;
|
||||
free_gb: number;
|
||||
system: boolean;
|
||||
external: boolean;
|
||||
has_config: boolean;
|
||||
error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DataRootCheck(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.free_gb = source["free_gb"];
|
||||
this.system = source["system"];
|
||||
this.external = source["external"];
|
||||
this.has_config = source["has_config"];
|
||||
this.error = source["error"];
|
||||
}
|
||||
}
|
||||
export class DataRootChoice {
|
||||
path: string;
|
||||
free_gb: number;
|
||||
system: boolean;
|
||||
external: boolean;
|
||||
recommended: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DataRootChoice(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.free_gb = source["free_gb"];
|
||||
this.system = source["system"];
|
||||
this.external = source["external"];
|
||||
this.recommended = source["recommended"];
|
||||
}
|
||||
}
|
||||
export class DriveShareInfo {
|
||||
drive: string;
|
||||
root: string;
|
||||
selected: boolean;
|
||||
system: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DriveShareInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.drive = source["drive"];
|
||||
this.root = source["root"];
|
||||
this.selected = source["selected"];
|
||||
this.system = source["system"];
|
||||
}
|
||||
}
|
||||
export class DriveShareSettings {
|
||||
enabled: boolean;
|
||||
read_only: boolean;
|
||||
required_agent_version: number;
|
||||
drives: DriveShareInfo[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DriveShareSettings(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.enabled = source["enabled"];
|
||||
this.read_only = source["read_only"];
|
||||
this.required_agent_version = source["required_agent_version"];
|
||||
this.drives = this.convertValues(source["drives"], DriveShareInfo);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class PendingChange {
|
||||
field: string;
|
||||
from: string;
|
||||
to: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new PendingChange(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.field = source["field"];
|
||||
this.from = source["from"];
|
||||
this.to = source["to"];
|
||||
}
|
||||
}
|
||||
export class Task {
|
||||
id: string;
|
||||
kind: string;
|
||||
subject: string;
|
||||
vm?: string;
|
||||
step: string;
|
||||
done: number;
|
||||
total: number;
|
||||
percent: number;
|
||||
rate: number;
|
||||
status: string;
|
||||
error?: string;
|
||||
result?: string;
|
||||
cancelable: boolean;
|
||||
started_at: number;
|
||||
updated_at: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Task(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.kind = source["kind"];
|
||||
this.subject = source["subject"];
|
||||
this.vm = source["vm"];
|
||||
this.step = source["step"];
|
||||
this.done = source["done"];
|
||||
this.total = source["total"];
|
||||
this.percent = source["percent"];
|
||||
this.rate = source["rate"];
|
||||
this.status = source["status"];
|
||||
this.error = source["error"];
|
||||
this.result = source["result"];
|
||||
this.cancelable = source["cancelable"];
|
||||
this.started_at = source["started_at"];
|
||||
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"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace config {
|
||||
|
||||
export class Config {
|
||||
@@ -7,6 +264,7 @@ export namespace config {
|
||||
auto_pin_pcores: boolean;
|
||||
default_gpu?: string;
|
||||
runtime_channel?: string;
|
||||
runtime_source?: string;
|
||||
minimize_to_tray?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
@@ -21,6 +279,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.runtime_source = source["runtime_source"];
|
||||
this.minimize_to_tray = source["minimize_to_tray"];
|
||||
}
|
||||
}
|
||||
@@ -56,6 +315,8 @@ export namespace host {
|
||||
scale_pct: number;
|
||||
refresh_hz?: number;
|
||||
primary: boolean;
|
||||
work_width?: number;
|
||||
work_height?: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DisplayInfo(source);
|
||||
@@ -69,6 +330,8 @@ export namespace host {
|
||||
this.scale_pct = source["scale_pct"];
|
||||
this.refresh_hz = source["refresh_hz"];
|
||||
this.primary = source["primary"];
|
||||
this.work_width = source["work_width"];
|
||||
this.work_height = source["work_height"];
|
||||
}
|
||||
}
|
||||
export class DisplayPreset {
|
||||
@@ -178,6 +441,9 @@ export namespace host {
|
||||
primary_display?: DisplayInfo;
|
||||
recommended_resolution?: string;
|
||||
display_presets?: DisplayPreset[];
|
||||
hidpi_advice?: string;
|
||||
fullscreen_hidpi: boolean;
|
||||
processor_scheduling?: string;
|
||||
audio: AudioInfo;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
@@ -218,6 +484,9 @@ export namespace host {
|
||||
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.hidpi_advice = source["hidpi_advice"];
|
||||
this.fullscreen_hidpi = source["fullscreen_hidpi"];
|
||||
this.processor_scheduling = source["processor_scheduling"];
|
||||
this.audio = this.convertValues(source["audio"], AudioInfo);
|
||||
}
|
||||
|
||||
@@ -295,209 +564,6 @@ export namespace installer {
|
||||
|
||||
}
|
||||
|
||||
export namespace main {
|
||||
|
||||
export class AppState {
|
||||
config?: config.Config;
|
||||
host: host.Report;
|
||||
optimizations: host.Optimization[];
|
||||
runtimes: runtime.Installed[];
|
||||
active_runtime?: runtime.Installed;
|
||||
vms: reims.VMListItem[];
|
||||
transitions: Record<string, string>;
|
||||
pending_changes: Record<string, Array<PendingChange>>;
|
||||
needs_setup: boolean;
|
||||
app_version: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AppState(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.config = this.convertValues(source["config"], config.Config);
|
||||
this.host = this.convertValues(source["host"], host.Report);
|
||||
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
|
||||
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.vms = this.convertValues(source["vms"], reims.VMListItem);
|
||||
this.transitions = source["transitions"];
|
||||
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
|
||||
this.needs_setup = source["needs_setup"];
|
||||
this.app_version = source["app_version"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class DataRootCheck {
|
||||
path: string;
|
||||
free_gb: number;
|
||||
system: boolean;
|
||||
external: boolean;
|
||||
has_config: boolean;
|
||||
error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DataRootCheck(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.free_gb = source["free_gb"];
|
||||
this.system = source["system"];
|
||||
this.external = source["external"];
|
||||
this.has_config = source["has_config"];
|
||||
this.error = source["error"];
|
||||
}
|
||||
}
|
||||
export class DataRootChoice {
|
||||
path: string;
|
||||
free_gb: number;
|
||||
system: boolean;
|
||||
external: boolean;
|
||||
recommended: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DataRootChoice(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.path = source["path"];
|
||||
this.free_gb = source["free_gb"];
|
||||
this.system = source["system"];
|
||||
this.external = source["external"];
|
||||
this.recommended = source["recommended"];
|
||||
}
|
||||
}
|
||||
export class PendingChange {
|
||||
field: string;
|
||||
from: string;
|
||||
to: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new PendingChange(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.field = source["field"];
|
||||
this.from = source["from"];
|
||||
this.to = source["to"];
|
||||
}
|
||||
}
|
||||
export class Task {
|
||||
id: string;
|
||||
kind: string;
|
||||
subject: string;
|
||||
vm?: string;
|
||||
step: string;
|
||||
done: number;
|
||||
total: number;
|
||||
percent: number;
|
||||
rate: number;
|
||||
status: string;
|
||||
error?: string;
|
||||
result?: string;
|
||||
cancelable: boolean;
|
||||
started_at: number;
|
||||
updated_at: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Task(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.kind = source["kind"];
|
||||
this.subject = source["subject"];
|
||||
this.vm = source["vm"];
|
||||
this.step = source["step"];
|
||||
this.done = source["done"];
|
||||
this.total = source["total"];
|
||||
this.percent = source["percent"];
|
||||
this.rate = source["rate"];
|
||||
this.status = source["status"];
|
||||
this.error = source["error"];
|
||||
this.result = source["result"];
|
||||
this.cancelable = source["cancelable"];
|
||||
this.started_at = source["started_at"];
|
||||
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"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace reims {
|
||||
|
||||
export class CreateOpts {
|
||||
@@ -895,6 +961,7 @@ export namespace runtime {
|
||||
commit: string;
|
||||
tag: string;
|
||||
channel: string;
|
||||
source?: string;
|
||||
published_at: string;
|
||||
page_url: string;
|
||||
archive_name: string;
|
||||
@@ -913,6 +980,7 @@ export namespace runtime {
|
||||
this.commit = source["commit"];
|
||||
this.tag = source["tag"];
|
||||
this.channel = source["channel"];
|
||||
this.source = source["source"];
|
||||
this.published_at = source["published_at"];
|
||||
this.page_url = source["page_url"];
|
||||
this.archive_name = source["archive_name"];
|
||||
|
||||
+247
-73
@@ -1,7 +1,8 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
@@ -20,6 +22,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"github.com/wailsapp/wails/v2/pkg/options"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -62,24 +65,49 @@ type App struct {
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
lastVMs []reims.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
|
||||
// frontend-bound methods on *App.
|
||||
type Lifecycle struct {
|
||||
OnStartup func(context.Context)
|
||||
OnBeforeClose func(context.Context) bool
|
||||
OnShutdown func(context.Context)
|
||||
OnSecondInstanceLaunch func(options.SecondInstanceData)
|
||||
}
|
||||
|
||||
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
}
|
||||
return &App{
|
||||
a := &App{
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
rebootWatchers: make(map[string]rebootWatcherEntry),
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
}
|
||||
return a, Lifecycle{
|
||||
OnStartup: a.startup,
|
||||
OnBeforeClose: a.beforeClose,
|
||||
OnShutdown: a.shutdown,
|
||||
OnSecondInstanceLaunch: a.onSecondInstance,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) startup(ctx context.Context) {
|
||||
@@ -90,6 +118,7 @@ func (a *App) startup(ctx context.Context) {
|
||||
a.startIMEBridge()
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
go a.pollVMs(pollCtx)
|
||||
a.afterStartup()
|
||||
}
|
||||
|
||||
func (a *App) startIMEBridge() {
|
||||
@@ -148,9 +177,20 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
|
||||
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
|
||||
// Start, stop and delete call wakePoll so their result shows up at once.
|
||||
const (
|
||||
pollBusy = 2 * time.Second
|
||||
pollSteady = 5 * time.Second
|
||||
// polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits
|
||||
// above pollSteady so a poll that runs a little late still counts.
|
||||
polledMaxAge = pollSteady + 3*time.Second
|
||||
)
|
||||
|
||||
func (a *App) pollVMs(ctx context.Context) {
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
timer := time.NewTimer(pollBusy)
|
||||
defer timer.Stop()
|
||||
// Cache static hybrid P-core mask once instead of querying host every tick.
|
||||
a.mu.Lock()
|
||||
initRoot := a.cfg.DataRoot
|
||||
@@ -158,86 +198,97 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
cachedHost := host.Inspect(initRoot)
|
||||
var lastSig string
|
||||
pinnedPIDs := make(map[int]bool)
|
||||
exitWatched := make(map[int]bool)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
case <-timer.C:
|
||||
case <-a.pollWake:
|
||||
}
|
||||
a.mu.Lock()
|
||||
next := pollSteady
|
||||
if len(a.transitions) > 0 {
|
||||
next = pollBusy
|
||||
}
|
||||
a.mu.Unlock()
|
||||
timer.Reset(next)
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
watchExits(ctx, vms, exitWatched, a.wakePoll)
|
||||
type pinCandidate struct {
|
||||
name string
|
||||
pid int
|
||||
}
|
||||
var toPin []pinCandidate
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
autoPin := a.cfg.AutoPinPCores
|
||||
a.lastVMs = append([]reims.VMListItem(nil), vms...)
|
||||
a.lastVMsAt = time.Now()
|
||||
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),
|
||||
})
|
||||
}
|
||||
}
|
||||
type pinCandidate struct {
|
||||
name string
|
||||
pid int
|
||||
}
|
||||
var toPin []pinCandidate
|
||||
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)
|
||||
if vm.State == "stopped" {
|
||||
delete(a.pendingChanges, vm.Name)
|
||||
}
|
||||
}
|
||||
if tr, ok := a.transitions[vm.Name]; ok {
|
||||
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
|
||||
delete(a.transitions, vm.Name)
|
||||
if vm.State == "stopped" {
|
||||
delete(a.pendingChanges, vm.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
|
||||
}
|
||||
}
|
||||
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 autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
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("Reims-Go")
|
||||
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 {
|
||||
if det, derr := c.Show(ctx, cand.name); derr == nil {
|
||||
vmCPUs = det.CPUs
|
||||
}
|
||||
}
|
||||
for _, cand := range toPin {
|
||||
vmCPUs := 0
|
||||
if c, cerr := a.client(); cerr == nil {
|
||||
if det, derr := c.Show(ctx, cand.name); derr == nil {
|
||||
vmCPUs = det.CPUs
|
||||
}
|
||||
}
|
||||
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
|
||||
}
|
||||
if sig != lastSig {
|
||||
lastSig = sig
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
|
||||
}
|
||||
if sig != lastSig {
|
||||
lastSig = sig
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,6 +312,109 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
|
||||
return c.List(ctx)
|
||||
}
|
||||
|
||||
// qemuImage is the executable reims-ctl reports as a running VM's PID.
|
||||
const qemuImage = "qemu-system-x86_64.exe"
|
||||
|
||||
// watchExits waits on every running VM's QEMU process not yet watched and
|
||||
// calls onExit the moment one exits, so a VM that stops by itself (macOS shut
|
||||
// down, QEMU quit or crashed) shows as stopped at once instead of at the next
|
||||
// steady poll. watched holds the PIDs being waited on; PIDs no longer running
|
||||
// are dropped so a reused PID is watched again.
|
||||
func watchExits(ctx context.Context, vms []reims.VMListItem, watched map[int]bool, onExit func()) {
|
||||
running := make(map[int]bool, len(vms))
|
||||
for _, vm := range vms {
|
||||
if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
continue
|
||||
}
|
||||
pid := *vm.PID
|
||||
running[pid] = true
|
||||
if watched[pid] {
|
||||
continue
|
||||
}
|
||||
watched[pid] = true
|
||||
go func() {
|
||||
if err := host.WaitProcessExit(ctx, uint32(pid), qemuImage); err == nil {
|
||||
onExit()
|
||||
}
|
||||
}()
|
||||
}
|
||||
for pid := range watched {
|
||||
if !running[pid] {
|
||||
delete(watched, pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge
|
||||
// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn
|
||||
// their own `reims-ctl list`. A stale or missing poll falls back to one.
|
||||
func (a *App) polledVMs(ctx context.Context) ([]reims.VMListItem, error) {
|
||||
a.mu.Lock()
|
||||
if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge {
|
||||
vms := append([]reims.VMListItem(nil), a.lastVMs...)
|
||||
a.mu.Unlock()
|
||||
return vms, nil
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return a.listVMsInternal(ctx)
|
||||
}
|
||||
|
||||
// polledVM looks name up in polledVMs.
|
||||
func (a *App) polledVM(name string) (reims.VMListItem, bool) {
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
return reims.VMListItem{}, false
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
return vm, true
|
||||
}
|
||||
}
|
||||
return reims.VMListItem{}, false
|
||||
}
|
||||
|
||||
// wakePoll marks the polled list stale and runs pollVMs now. Call it after
|
||||
// anything that changes which VMs exist or run.
|
||||
func (a *App) wakePoll() {
|
||||
a.mu.Lock()
|
||||
a.lastVMsAt = time.Time{}
|
||||
a.mu.Unlock()
|
||||
select {
|
||||
case a.pollWake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for
|
||||
// diskPathTTL so GetVMStats doesn't run `show` every few seconds.
|
||||
type cachedDiskPath struct {
|
||||
path string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
const diskPathTTL = time.Minute
|
||||
|
||||
// vmDiskPath resolves name's disk image path, reusing a recent answer. The
|
||||
// path only changes through `reims-ctl set`, so at worst the disk-usage
|
||||
// figure follows such a change a minute late.
|
||||
func (a *App) vmDiskPath(ctx context.Context, c *reims.Client, name string) string {
|
||||
a.mu.Lock()
|
||||
cur, ok := a.diskPaths[name]
|
||||
a.mu.Unlock()
|
||||
if ok && time.Since(cur.at) < diskPathTTL {
|
||||
return cur.path
|
||||
}
|
||||
d, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
path := resolveVMDiskPath(d)
|
||||
a.mu.Lock()
|
||||
a.diskPaths[name] = cachedDiskPath{path: path, at: time.Now()}
|
||||
a.mu.Unlock()
|
||||
return path
|
||||
}
|
||||
|
||||
func (a *App) emitLog(source, line string) {
|
||||
redacted := reims.RedactLogLine(line)
|
||||
ts := time.Now().Format("15:04:05")
|
||||
@@ -269,6 +423,9 @@ func (a *App) emitLog(source, line string) {
|
||||
if len(a.recentLogs) > 1000 {
|
||||
a.recentLogs = a.recentLogs[len(a.recentLogs)-1000:]
|
||||
}
|
||||
for _, c := range a.logCaptures[source] {
|
||||
c.add(redacted)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if a.ctx == nil {
|
||||
return
|
||||
@@ -396,7 +553,7 @@ func (a *App) QuitApp() {
|
||||
}
|
||||
|
||||
func (a *App) startTray() {
|
||||
mgr, err := tray.Start(trayIconPNG, "Reims-Go", tray.Callbacks{
|
||||
mgr, err := tray.Start(a.trayIcon, "Reims-Go", tray.Callbacks{
|
||||
OnShow: func() {
|
||||
a.ShowMainWindow()
|
||||
},
|
||||
@@ -481,6 +638,19 @@ func (a *App) EnableWHPX() error {
|
||||
return host.EnableWHPXElevated()
|
||||
}
|
||||
|
||||
// OpenProcessorScheduling opens Windows' Performance Options as administrator
|
||||
// (one UAC prompt) for the processor scheduling choice. Declining the prompt
|
||||
// is not an error.
|
||||
func (a *App) OpenProcessorScheduling() error {
|
||||
a.emitLog("host", "Requesting Windows UAC to open Performance Options (processor scheduling)...")
|
||||
err := host.OpenPerformanceOptionsElevated()
|
||||
if errors.Is(err, host.ErrElevationDeclined) {
|
||||
a.emitLog("host", "UAC prompt declined; Performance Options not opened")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
@@ -777,6 +947,7 @@ func (a *App) StartVM(name string) error {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
}
|
||||
a.startVMMonitor(name, curDetail, startAt)
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
@@ -810,6 +981,7 @@ func (a *App) StopVM(name string, force bool) error {
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, name)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
@@ -853,7 +1025,9 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, name)
|
||||
delete(a.transitions, name)
|
||||
delete(a.diskPaths, name)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
)
|
||||
|
||||
func TestPolledVMsReusesFreshPoll(t *testing.T) {
|
||||
pid := 42
|
||||
a := &App{pollWake: make(chan struct{}, 1)}
|
||||
a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}}
|
||||
a.lastVMsAt = time.Now()
|
||||
|
||||
vm, ok := a.polledVM("m0")
|
||||
if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 {
|
||||
t.Fatalf("polledVM = %+v, %v", vm, ok)
|
||||
}
|
||||
if _, ok := a.polledVM("missing"); ok {
|
||||
t.Fatal("unknown VM should not be found")
|
||||
}
|
||||
|
||||
vms, _ := a.polledVMs(context.Background())
|
||||
vms[0].State = "stopped"
|
||||
if a.lastVMs[0].State != "running" {
|
||||
t.Fatal("polledVMs must return a copy, not the cached slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchExitsTracksRunningPIDs(t *testing.T) {
|
||||
gone := 999999 // no such process: WaitProcessExit reports it exited at once
|
||||
stopped := reims.VMListItem{Name: "m1", State: "stopped"}
|
||||
running := reims.VMListItem{Name: "m0", State: "running", PID: &gone}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
exits := make(chan struct{}, 4)
|
||||
watched := map[int]bool{}
|
||||
watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() { exits <- struct{}{} })
|
||||
watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() { exits <- struct{}{} })
|
||||
if len(watched) != 1 || !watched[gone] {
|
||||
t.Fatalf("watched = %v, want only %d", watched, gone)
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
select {
|
||||
case <-exits:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("onExit not called for an exited process")
|
||||
}
|
||||
select {
|
||||
case <-exits:
|
||||
t.Fatal("a PID already watched must not get a second waiter")
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
running.State = "stopped"
|
||||
watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() {})
|
||||
if len(watched) != 0 {
|
||||
t.Fatalf("watched = %v, want empty once the VM stopped", watched)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWakePollMarksStaleAndWakesOnce(t *testing.T) {
|
||||
a := &App{pollWake: make(chan struct{}, 1)}
|
||||
a.lastVMsAt = time.Now()
|
||||
a.wakePoll()
|
||||
a.wakePoll() // a second wake while one is pending must not block
|
||||
if !a.lastVMsAt.IsZero() {
|
||||
t.Fatal("wakePoll should mark the polled list stale")
|
||||
}
|
||||
select {
|
||||
case <-a.pollWake:
|
||||
default:
|
||||
t.Fatal("wakePoll should signal pollVMs")
|
||||
}
|
||||
select {
|
||||
case <-a.pollWake:
|
||||
t.Fatal("pending wakes should coalesce into one")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -0,0 +1,187 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// DriveShareInfo describes one currently available internal fixed drive.
|
||||
type DriveShareInfo struct {
|
||||
Drive string `json:"drive"`
|
||||
Root string `json:"root"`
|
||||
Selected bool `json:"selected"`
|
||||
System bool `json:"system"`
|
||||
}
|
||||
|
||||
// DriveShareSettings is the live, per-VM read-only drive sharing configuration.
|
||||
type DriveShareSettings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
RequiredAgentVersion int `json:"required_agent_version"`
|
||||
Drives []DriveShareInfo `json:"drives"`
|
||||
}
|
||||
|
||||
func shareableFixedDrives() []host.Drive {
|
||||
all := host.ListDrives()
|
||||
out := make([]host.Drive, 0, len(all))
|
||||
for _, drive := range all {
|
||||
if drive.External {
|
||||
continue
|
||||
}
|
||||
if _, ok := guesttools.NormalizeDriveLetter(drive.Root); ok && drive.VolumeGUID != "" {
|
||||
out = append(out, drive)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeDriveSelection(available []host.Drive, selected []string) ([]string, error) {
|
||||
allowed := make(map[string]bool, len(available))
|
||||
for _, drive := range available {
|
||||
if letter, ok := guesttools.NormalizeDriveLetter(drive.Root); ok && !drive.External {
|
||||
allowed[letter] = true
|
||||
}
|
||||
}
|
||||
requested := make(map[string]bool, len(selected))
|
||||
for _, raw := range selected {
|
||||
letter, ok := guesttools.NormalizeDriveLetter(raw)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid drive %q", raw)
|
||||
}
|
||||
if !allowed[letter] {
|
||||
return nil, fmt.Errorf("drive %s is not an available internal fixed drive", letter)
|
||||
}
|
||||
requested[letter] = true
|
||||
}
|
||||
out := []string{}
|
||||
for _, drive := range available {
|
||||
letter, _ := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
if requested[letter] {
|
||||
out = append(out, letter)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// validatedDriveConfig derives runtime roots only from currently present fixed volumes
|
||||
// whose stable GUID matches the user's persisted selection. It never saves filtered state.
|
||||
func validatedDriveConfig(cfg guesttools.VMConfig) guesttools.VMConfig {
|
||||
return validatedDriveConfigForVolumes(cfg, shareableFixedDrives())
|
||||
}
|
||||
|
||||
func validatedDriveConfigForVolumes(cfg guesttools.VMConfig, available []host.Drive) guesttools.VMConfig {
|
||||
selected := make(map[string]bool, len(cfg.SharedDrives))
|
||||
for _, raw := range cfg.SharedDrives {
|
||||
if letter, ok := guesttools.NormalizeDriveLetter(raw); ok {
|
||||
selected[letter] = true
|
||||
}
|
||||
}
|
||||
cfg.SharedDrives = []string{}
|
||||
cfg.DriveRoots = make(map[string]string)
|
||||
for _, drive := range available {
|
||||
if drive.External || drive.VolumeGUID == "" {
|
||||
continue
|
||||
}
|
||||
letter, _ := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
expected := cfg.DriveVolumes[letter]
|
||||
if !selected[letter] || expected == "" || !strings.EqualFold(expected, drive.VolumeGUID) {
|
||||
continue
|
||||
}
|
||||
cfg.SharedDrives = append(cfg.SharedDrives, letter)
|
||||
cfg.DriveRoots[letter] = drive.Root
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func selectedVolumeIdentities(available []host.Drive, selected []string) map[string]string {
|
||||
wanted := make(map[string]bool, len(selected))
|
||||
for _, letter := range selected {
|
||||
wanted[letter] = true
|
||||
}
|
||||
out := make(map[string]string)
|
||||
for _, drive := range available {
|
||||
letter, ok := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
if ok && wanted[letter] && drive.VolumeGUID != "" {
|
||||
out[letter] = drive.VolumeGUID
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func makeDriveShareSettings(cfg guesttools.VMConfig, available []host.Drive) DriveShareSettings {
|
||||
selected := make(map[string]bool, len(cfg.SharedDrives))
|
||||
for _, raw := range cfg.SharedDrives {
|
||||
if letter, ok := guesttools.NormalizeDriveLetter(raw); ok {
|
||||
selected[letter] = true
|
||||
}
|
||||
}
|
||||
settings := DriveShareSettings{
|
||||
Enabled: cfg.DriveSharingEnabled, ReadOnly: true,
|
||||
RequiredAgentVersion: guesttools.DriveShareAgentVersion, Drives: []DriveShareInfo{},
|
||||
}
|
||||
for _, drive := range available {
|
||||
if drive.External {
|
||||
continue
|
||||
}
|
||||
letter, ok := guesttools.NormalizeDriveLetter(drive.Root)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
expected := cfg.DriveVolumes[letter]
|
||||
identityMatches := expected != "" && strings.EqualFold(expected, drive.VolumeGUID)
|
||||
settings.Drives = append(settings.Drives, DriveShareInfo{
|
||||
Drive: letter, Root: drive.Root, Selected: selected[letter] && identityMatches, System: drive.System,
|
||||
})
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
// GetVMDriveShareSettings returns per-VM switches without creating Guest Tools config.
|
||||
func (a *App) GetVMDriveShareSettings(name string) (DriveShareSettings, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
cfg, _ := guesttools.ReadVMConfig(detail.Directory)
|
||||
return makeDriveShareSettings(cfg, shareableFixedDrives()), nil
|
||||
}
|
||||
|
||||
// SetVMDriveShareSettings persists selected drive letters and applies access control immediately.
|
||||
func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string) (DriveShareSettings, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
if detail.Directory == "" {
|
||||
return DriveShareSettings{}, fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
available := shareableFixedDrives()
|
||||
normalized, err := normalizeDriveSelection(available, drives)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
cfg, err := guesttools.LoadOrCreateVMConfig(detail.Directory, name, a.vmSharedDir(name), port)
|
||||
if err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
cfg.DriveSharingEnabled = enabled
|
||||
cfg.SharedDrives = normalized
|
||||
cfg.DriveVolumes = selectedVolumeIdentities(available, normalized)
|
||||
if err := guesttools.SaveVMConfig(detail.Directory, cfg); err != nil {
|
||||
return DriveShareSettings{}, err
|
||||
}
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
a.emitLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return makeDriveShareSettings(cfg, available), nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
)
|
||||
|
||||
func TestNormalizeDriveSelectionRejectsUnavailableAndExternalDrives(t *testing.T) {
|
||||
available := []host.Drive{{Root: `C:\`, System: true}, {Root: `D:\`}, {Root: `E:\`, External: true}}
|
||||
got, err := normalizeDriveSelection(available, []string{"d", "D:", `C:\`})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0] != "C" || got[1] != "D" {
|
||||
t.Fatalf("normalized selection = %#v, want [C D]", got)
|
||||
}
|
||||
for _, selected := range [][]string{{"E"}, {"Z"}, {"../C"}, {"C:/"}} {
|
||||
if _, err := normalizeDriveSelection(available, selected); err == nil {
|
||||
t.Fatalf("selection %#v unexpectedly accepted", selected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatedDriveConfigRejectsMissingAndReboundVolumes(t *testing.T) {
|
||||
cfg := guesttools.VMConfig{
|
||||
DriveSharingEnabled: true, SharedDrives: []string{"C", "D", "E"},
|
||||
DriveVolumes: map[string]string{"C": "vol-c", "D": "old-volume-d"},
|
||||
}
|
||||
available := []host.Drive{
|
||||
{Root: `C:\`, VolumeGUID: "vol-c"},
|
||||
{Root: `D:\`, VolumeGUID: "new-volume-d"},
|
||||
{Root: `E:\`, VolumeGUID: "vol-e", External: true},
|
||||
}
|
||||
got := validatedDriveConfigForVolumes(cfg, available)
|
||||
if len(got.SharedDrives) != 1 || got.SharedDrives[0] != "C" || got.DriveRoots["C"] != `C:\` {
|
||||
t.Fatalf("validated config = %#v, want only original C volume", got)
|
||||
}
|
||||
if len(got.DriveVolumes) != 2 {
|
||||
t.Fatalf("runtime validation mutated persisted identities: %#v", got.DriveVolumes)
|
||||
}
|
||||
cfg.SharedDrives = []string{"C"}
|
||||
cfg.DriveVolumes = nil
|
||||
if got := validatedDriveConfigForVolumes(cfg, available); len(got.SharedDrives) != 0 {
|
||||
t.Fatalf("legacy config without volume identity was trusted: %#v", got)
|
||||
}
|
||||
}
|
||||
func TestMakeDriveShareSettingsDefaultsToReadOnlyAndPerDriveSelection(t *testing.T) {
|
||||
available := []host.Drive{{Root: `C:\`, System: true, VolumeGUID: "vol-c"}, {Root: `D:\`, VolumeGUID: "vol-d"}}
|
||||
settings := makeDriveShareSettings(guesttools.VMConfig{}, available)
|
||||
if settings.Enabled || !settings.ReadOnly || settings.RequiredAgentVersion != guesttools.DriveShareAgentVersion {
|
||||
t.Fatalf("unexpected defaults: %#v", settings)
|
||||
}
|
||||
if settings.Drives == nil || len(settings.Drives) != 2 {
|
||||
t.Fatalf("drives = %#v, want two entries", settings.Drives)
|
||||
}
|
||||
settings = makeDriveShareSettings(guesttools.VMConfig{DriveSharingEnabled: true, SharedDrives: []string{"D"}, DriveVolumes: map[string]string{"D": "vol-d"}}, available)
|
||||
if !settings.Enabled || settings.Drives[0].Selected || !settings.Drives[1].Selected || !settings.Drives[0].System {
|
||||
t.Fatalf("unexpected settings: %#v", settings)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -66,7 +66,7 @@ func (a *App) inputBridgeEnv(name, vmDir string) []string {
|
||||
if err != nil || cfg.Token == "" {
|
||||
return nil
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
srv.RegisterVM(validatedDriveConfig(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,
|
||||
@@ -99,7 +99,7 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
|
||||
cfg.Port = port
|
||||
_ = guesttools.SaveVMConfig(det.Directory, cfg)
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,7 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail) {
|
||||
d.SharedDir = cfg.SharedDir
|
||||
}
|
||||
if srv, _, err := a.ensureGuestToolsBridge(); err == nil {
|
||||
srv.RegisterVM(cfg)
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
st := srv.Status(d.Name, 15*time.Second)
|
||||
d.GuestToolsConnected = st.Connected
|
||||
d.GuestToolsMountMode = st.MountMode
|
||||
@@ -149,7 +149,7 @@ func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail)
|
||||
a.emitLog(name, "Warning: could not load Guest Tools config: "+err.Error())
|
||||
return
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
if !attached {
|
||||
return
|
||||
}
|
||||
@@ -193,7 +193,7 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
|
||||
imgPath := a.guestToolsImagePath(name)
|
||||
if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil {
|
||||
@@ -290,7 +290,7 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
|
||||
if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
srv.RegisterVM(validatedDriveConfig(cfg))
|
||||
srv.SetPreventSleep(name, enabled)
|
||||
a.emitLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
|
||||
if a.ctx != nil {
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// Finishing an offline install (roadmap M2.3): take the installer out and turn
|
||||
// the network back on, which an offline install keeps off so its installer
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// Wails bindings for offline installers (roadmap M1.3). The download manager
|
||||
// page (M2.2) builds on these; downloads report through tasks (tasks.go).
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// Online runtime install from GitHub Releases (internal/runtime/remote.go).
|
||||
// Downloads run as "runtime-install" tasks, so progress shows in the status bar.
|
||||
@@ -32,35 +32,43 @@ func (a *App) includeAlpha() bool {
|
||||
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
|
||||
}
|
||||
|
||||
func (a *App) runtimeSource() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return rt.NormalizeSource(a.cfg.RuntimeSource)
|
||||
}
|
||||
|
||||
// remoteCache keeps the release list for a while: GitHub allows 60
|
||||
// unauthenticated API requests an hour, and the host page, first launch and
|
||||
// the CLI all ask for it.
|
||||
var remoteCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
alpha bool
|
||||
list []rt.Remote
|
||||
at time.Time
|
||||
alpha bool
|
||||
source string
|
||||
list []rt.Remote
|
||||
}
|
||||
|
||||
const remoteCacheTTL = 10 * time.Minute
|
||||
|
||||
// ListRemoteRuntimes lists published runtimes for the configured channel.
|
||||
// ListRemoteRuntimes lists published runtimes for the configured channel and source.
|
||||
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
|
||||
alpha := a.includeAlpha()
|
||||
source := a.runtimeSource()
|
||||
remoteCache.Lock()
|
||||
defer remoteCache.Unlock()
|
||||
if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL {
|
||||
if remoteCache.list != nil && remoteCache.alpha == alpha && remoteCache.source == source && time.Since(remoteCache.at) < remoteCacheTTL {
|
||||
return remoteCache.list, nil
|
||||
}
|
||||
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha)
|
||||
list, err := rt.DefaultSourceFor(source).ListRemote(a.baseCtx(), alpha)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list
|
||||
remoteCache.at, remoteCache.alpha, remoteCache.source, remoteCache.list = time.Now(), alpha, source, list
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// forgetRemoteRuntimes drops the cached list (after an install or a channel change).
|
||||
// forgetRemoteRuntimes drops the cached list (after an install or a channel/source change).
|
||||
func forgetRemoteRuntimes() {
|
||||
remoteCache.Lock()
|
||||
remoteCache.list = nil
|
||||
@@ -83,6 +91,25 @@ func (a *App) SetRuntimeChannel(channel string) error {
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// SetRuntimeSource picks "auto", "github", or "gitcode" for online runtime and
|
||||
// app update lookups.
|
||||
func (a *App) SetRuntimeSource(source string) error {
|
||||
switch strings.ToLower(strings.TrimSpace(source)) {
|
||||
case "", rt.SourceAuto, rt.SourceGitHub, rt.SourceGitCode:
|
||||
source = rt.NormalizeSource(source)
|
||||
default:
|
||||
return fmt.Errorf("unknown runtime source %q", source)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.RuntimeSource = source
|
||||
forgetRemoteRuntimes()
|
||||
appUpdateCache.Lock()
|
||||
appUpdateCache.info = nil
|
||||
appUpdateCache.Unlock()
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
// ("" or "latest" for the newest on the channel) and makes it active. It runs
|
||||
// in the background and returns the task ID; CancelTask pauses the download,
|
||||
@@ -129,12 +156,12 @@ func (a *App) InstallRuntimeOnline(commit string) (string, error) {
|
||||
}
|
||||
|
||||
func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) {
|
||||
src := rt.DefaultSource()
|
||||
src := rt.DefaultSourceFor(cfg.RuntimeSource)
|
||||
step := func(msg string) {
|
||||
a.emitLog("runtime", msg)
|
||||
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
|
||||
}
|
||||
step("Looking up runtime releases on GitHub")
|
||||
step("Looking up runtime releases")
|
||||
// An explicit commit may be an alpha even on the stable channel: the
|
||||
// user asked for it by name.
|
||||
list, err := src.ListRemote(ctx, rt.NormalizeChannel(cfg.RuntimeChannel) == rt.ChannelAlpha || (commit != "" && commit != "latest"))
|
||||
@@ -193,12 +220,13 @@ var appUpdateCache struct {
|
||||
// CheckAppUpdate checks GitHub Releases for a newer stable Reims-Go version.
|
||||
// Results are cached for 10 minutes unless force is true.
|
||||
func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
source := a.runtimeSource()
|
||||
appUpdateCache.Lock()
|
||||
defer appUpdateCache.Unlock()
|
||||
if !force && appUpdateCache.info != nil && time.Since(appUpdateCache.at) < remoteCacheTTL {
|
||||
return *appUpdateCache.info, nil
|
||||
}
|
||||
info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version)
|
||||
info, err := version.DefaultSourceFor(source).CheckUpdate(a.baseCtx(), version.Version)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// First launch: the user picks the data folder before anything else is written
|
||||
// (runtimes, VMs, installers and caches all live under it).
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -57,7 +57,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
return stats, err
|
||||
}
|
||||
ctx := context.Background()
|
||||
vms, _ := c.List(ctx)
|
||||
vms, _ := a.polledVMs(ctx)
|
||||
var pid int
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
@@ -70,13 +70,11 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
|
||||
}
|
||||
stats.PID = pid
|
||||
|
||||
if d, err := c.Show(ctx, name); err == nil {
|
||||
if diskPath := resolveVMDiskPath(d); diskPath != "" {
|
||||
if du, err := host.InspectDiskUsage(diskPath); err == nil {
|
||||
stats.DiskActualBytes = du.ActualBytes
|
||||
stats.DiskVirtualBytes = du.VirtualBytes
|
||||
stats.DiskFormat = du.Format
|
||||
}
|
||||
if diskPath := a.vmDiskPath(ctx, c, name); diskPath != "" {
|
||||
if du, err := host.InspectDiskUsage(diskPath); err == nil {
|
||||
stats.DiskActualBytes = du.ActualBytes
|
||||
stats.DiskVirtualBytes = du.VirtualBytes
|
||||
stats.DiskFormat = du.Format
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// Long-running work (installer downloads, VM creation) is tracked as tasks and
|
||||
// pushed to the frontend as "reims:task" events (docs/ui-redesign.md §6 B1), so
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// VM screen thumbnails for the VM page (docs/ui-audit.md): while a VM runs,
|
||||
// grab one frame over its QMP socket (`screendump`), shrink it to a small
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
)
|
||||
@@ -59,8 +60,14 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
if busy {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil || d.State != "running" || d.Directory == "" {
|
||||
vm, ok := a.polledVM(name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
// The user is looking at the VM window itself, not this page: skip the
|
||||
// screendump, which runs on QEMU's main loop and writes a full-size frame
|
||||
// (about 25 MB at 4K) to disk.
|
||||
if vm.PID != nil && *vm.PID > 0 && host.ForegroundPID() == uint32(*vm.PID) {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
a.mu.Lock()
|
||||
@@ -74,7 +81,7 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
format, err := qmp.ScreendumpVM(ctx, d.Directory, raw)
|
||||
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
// "Paste as keystrokes": type the host's clipboard (or a given text) into a
|
||||
// running VM as US-layout key presses over its QMP socket. QEMU here has no
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -187,7 +187,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
}
|
||||
|
||||
func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) {
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
vms, err := a.polledVMs(ctx)
|
||||
if err != nil {
|
||||
return 0, true // keep watching on transient error
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"strings"
|
||||
@@ -0,0 +1,134 @@
|
||||
package app
|
||||
|
||||
// What the desktop window does with cli.WindowArgs: from its own launch
|
||||
// (`reims-go --background --start-vm=…`) or from a later `reims-go` run
|
||||
// (Wails OnSecondInstanceLaunch). See internal/cli/window_args.go.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/wailsapp/wails/v2/pkg/options"
|
||||
)
|
||||
|
||||
// afterStartup runs the launch request once the window's context exists. A
|
||||
// hidden launch with no tray to reopen it from shows the window after all.
|
||||
func (a *App) afterStartup() {
|
||||
a.mu.Lock()
|
||||
launch := a.launch
|
||||
noTray := a.trayMgr == nil
|
||||
a.mu.Unlock()
|
||||
if launch.Background && noTray {
|
||||
a.ShowMainWindow()
|
||||
}
|
||||
a.handleWindowArgs(launch, false)
|
||||
}
|
||||
|
||||
// onSecondInstance handles another `reims-go.exe` started while this one runs.
|
||||
func (a *App) onSecondInstance(data options.SecondInstanceData) {
|
||||
w, ok := cli.ParseWindowArgs(data.Args)
|
||||
if !ok {
|
||||
// Command-line mode never gets here (it does not take the lock), so
|
||||
// this is an argument we don't know: treat it as a plain launch.
|
||||
w = cli.WindowArgs{}
|
||||
}
|
||||
a.handleWindowArgs(w, true)
|
||||
}
|
||||
|
||||
// handleWindowArgs starts the requested VM, or for a plain second launch
|
||||
// (double-click while running in the tray) brings the window forward. A
|
||||
// `vm start` handed over from the command line leaves the window as it is.
|
||||
func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
|
||||
if w.StartVM == "" {
|
||||
if secondLaunch && !w.Background {
|
||||
a.ShowMainWindow()
|
||||
}
|
||||
return
|
||||
}
|
||||
name := w.StartVM
|
||||
result := a.startResultPath(w.StartResult)
|
||||
if w.StartResult != "" && result == "" {
|
||||
a.emitLog(name, "Ignored a start result path outside the Reims-Go temp folder: "+w.StartResult)
|
||||
}
|
||||
a.emitLog(name, "Start requested from the command line")
|
||||
go func() {
|
||||
capture := a.captureLogs(name)
|
||||
err := a.StartVM(name)
|
||||
lines := a.releaseLogs(name, capture)
|
||||
if err != nil && len(lines) > 0 {
|
||||
// StartVM's own error is often just "exit status 1"; the reason is
|
||||
// in what it logged. The command line has no log panel to look at.
|
||||
err = fmt.Errorf("%w\n%s", err, strings.Join(lines, "\n"))
|
||||
}
|
||||
if result != "" {
|
||||
if werr := cli.WriteStartResult(result, err); werr != nil {
|
||||
a.emitLog(name, "Could not report the start result to the command line: "+werr.Error())
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// logCapture keeps the last few log lines one source emits while it is
|
||||
// registered, for reporting a failed start back to the command line.
|
||||
type logCapture struct{ lines []string }
|
||||
|
||||
const logCaptureMax = 8
|
||||
|
||||
func (c *logCapture) add(line string) {
|
||||
c.lines = append(c.lines, line)
|
||||
if len(c.lines) > logCaptureMax {
|
||||
c.lines = c.lines[len(c.lines)-logCaptureMax:]
|
||||
}
|
||||
}
|
||||
|
||||
// captureLogs starts collecting emitLog lines for source.
|
||||
func (a *App) captureLogs(source string) *logCapture {
|
||||
c := &logCapture{}
|
||||
a.mu.Lock()
|
||||
if a.logCaptures == nil {
|
||||
a.logCaptures = make(map[string][]*logCapture)
|
||||
}
|
||||
a.logCaptures[source] = append(a.logCaptures[source], c)
|
||||
a.mu.Unlock()
|
||||
return c
|
||||
}
|
||||
|
||||
// releaseLogs stops c and returns what it collected.
|
||||
func (a *App) releaseLogs(source string, c *logCapture) []string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
list := a.logCaptures[source]
|
||||
for i, cur := range list {
|
||||
if cur == c {
|
||||
list = append(list[:i], list[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(list) == 0 {
|
||||
delete(a.logCaptures, source)
|
||||
} else {
|
||||
a.logCaptures[source] = list
|
||||
}
|
||||
return c.lines
|
||||
}
|
||||
|
||||
// startResultPath accepts only a result file directly in this data root's
|
||||
// temp folder named like the ones `vm start` makes, so a launch argument
|
||||
// can't make Reims-Go overwrite an arbitrary file.
|
||||
func (a *App) startResultPath(p string) string {
|
||||
if p == "" {
|
||||
return ""
|
||||
}
|
||||
a.mu.Lock()
|
||||
tmp := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
clean := filepath.Clean(p)
|
||||
base := filepath.Base(clean)
|
||||
if !strings.EqualFold(filepath.Dir(clean), filepath.Clean(tmp)) ||
|
||||
!strings.HasPrefix(base, "cli-start-") || !strings.HasSuffix(base, ".json") {
|
||||
return ""
|
||||
}
|
||||
return clean
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
)
|
||||
|
||||
func TestLogCaptureKeepsLastLinesOfItsSource(t *testing.T) {
|
||||
a := &App{cfg: config.Default()}
|
||||
c := a.captureLogs("m0")
|
||||
for i := 0; i < logCaptureMax+3; i++ {
|
||||
a.emitLog("m0", fmt.Sprintf("line %d", i))
|
||||
}
|
||||
a.emitLog("other", "not mine")
|
||||
lines := a.releaseLogs("m0", c)
|
||||
if len(lines) != logCaptureMax || lines[0] != "line 3" || lines[len(lines)-1] != fmt.Sprintf("line %d", logCaptureMax+2) {
|
||||
t.Fatalf("captured %q", lines)
|
||||
}
|
||||
a.emitLog("m0", "after release")
|
||||
if len(c.lines) != logCaptureMax || len(a.logCaptures) != 0 {
|
||||
t.Fatal("a released capture must stop collecting")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartResultPathStaysInTempDir(t *testing.T) {
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = `D:\Data\reims-go`
|
||||
a := &App{cfg: cfg}
|
||||
tmp := cfg.TempDir()
|
||||
|
||||
good := filepath.Join(tmp, "cli-start-123.json")
|
||||
if got := a.startResultPath(good); got != good {
|
||||
t.Fatalf("own result file rejected: %q", got)
|
||||
}
|
||||
for _, bad := range []string{
|
||||
filepath.Join(tmp, "..", "reims-go.json"),
|
||||
filepath.Join(tmp, "sub", "cli-start-1.json"),
|
||||
filepath.Join(tmp, "notes.json"),
|
||||
`C:\Windows\cli-start-1.json`,
|
||||
} {
|
||||
if got := a.startResultPath(bad); got != "" {
|
||||
t.Errorf("startResultPath(%q) = %q, want rejected", bad, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -22,11 +22,24 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
// Package cli is reims-go's command-line mode. The single reims-go.exe opens
|
||||
// the desktop window when started without a command and runs this package
|
||||
// when given one (see main.go); both share the internal/ packages.
|
||||
|
||||
// Main runs one command and returns the process exit code.
|
||||
func Main(args []string) int {
|
||||
if err := run(args); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
os.Exit(1)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// IsCommand reports whether args ask for command-line mode rather than the
|
||||
// desktop window: anything except no arguments or the window's own flags.
|
||||
func IsCommand(args []string) bool {
|
||||
_, isWindow := ParseWindowArgs(args)
|
||||
return !isWindow
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
@@ -65,7 +78,7 @@ func run(args []string) error {
|
||||
case "runtime":
|
||||
return cmdRuntime(cfg, loc, rest[1:])
|
||||
case "vm":
|
||||
return cmdVM(cfg, loc, rest[1:])
|
||||
return cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
|
||||
case "installer":
|
||||
return cmdInstaller(cfg, loc, rest[1:])
|
||||
case "version", "-v", "--version":
|
||||
@@ -81,9 +94,11 @@ func run(args []string) error {
|
||||
|
||||
func printUsage(loc i18n.Locale) {
|
||||
if loc == i18n.ZhCN {
|
||||
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器与 CLI")
|
||||
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器")
|
||||
fmt.Println("\n用法:")
|
||||
fmt.Println(" reims-go 打开界面(--background:只在托盘运行,不显示窗口)")
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
|
||||
fmt.Println("\n 在交互式 PowerShell / cmd 中提示符会先返回;要等命令结束并拿到退出码,请加 | Out-Host 或用管道。")
|
||||
fmt.Println("\n命令:")
|
||||
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
|
||||
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)")
|
||||
@@ -96,7 +111,8 @@ func printUsage(loc i18n.Locale) {
|
||||
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 start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动")
|
||||
fmt.Println(" vm stop|eject <name> 停止 / 弹出安装盘")
|
||||
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
|
||||
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
|
||||
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
|
||||
@@ -105,9 +121,12 @@ func printUsage(loc i18n.Locale) {
|
||||
fmt.Println(" version 查看当前版本")
|
||||
return
|
||||
}
|
||||
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher & CLI for Windows")
|
||||
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher for Windows")
|
||||
fmt.Println("\nUsage:")
|
||||
fmt.Println(" reims-go Open the window (--background: tray only, no window)")
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
|
||||
fmt.Println("\n Interactive PowerShell / cmd return to the prompt early; pipe the output (e.g. | Out-Host)")
|
||||
fmt.Println(" to wait for the command and get its exit code.")
|
||||
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 (--alpha includes alpha builds)")
|
||||
@@ -120,7 +139,9 @@ func printUsage(loc i18n.Locale) {
|
||||
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 start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),")
|
||||
fmt.Println(" with clipboard and shared folders; with --data-root it starts in this process")
|
||||
fmt.Println(" vm stop|eject <name> 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)")
|
||||
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
|
||||
@@ -259,7 +280,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
|
||||
}
|
||||
@@ -345,7 +366,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
if err := startVM(ctx, cfg, prep, name); err != nil {
|
||||
if err := startVM(ctx, cfg, prep, name, viaWindow); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -396,7 +417,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm start <name>")
|
||||
}
|
||||
return startVM(ctx, cfg, prep, args[1])
|
||||
return startVM(ctx, cfg, prep, args[1], viaWindow)
|
||||
case "stop":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm stop <name>")
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !windows
|
||||
|
||||
package cli
|
||||
|
||||
import "errors"
|
||||
|
||||
// Off Windows `vm start` always runs in the command itself.
|
||||
const windowHandoffWorks = false
|
||||
|
||||
func findWindow() uintptr { return 0 }
|
||||
|
||||
func sendToWindow(uintptr, []string) error { return errors.ErrUnsupported }
|
||||
|
||||
func spawnWindow([]string) error { return errors.ErrUnsupported }
|
||||
@@ -0,0 +1,97 @@
|
||||
//go:build windows
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/wailsapp/wails/v2/pkg/options"
|
||||
)
|
||||
|
||||
// Handing work to the desktop window speaks Wails v2's own single-instance
|
||||
// protocol (internal/frontend/desktop/windows/single_instance.go, v2.17.1):
|
||||
// the first instance owns a message-only window named
|
||||
// "wails-app-<id>-sic" / "wails-app-<id>-siw" and reads a JSON
|
||||
// options.SecondInstanceData from WM_COPYDATA with dwData 1542. Recheck
|
||||
// these names when upgrading Wails.
|
||||
const (
|
||||
wmCopyData = 0x004A
|
||||
wailsCopyDataID = 1542
|
||||
hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3
|
||||
detachedProcess = 0x00000008
|
||||
windowHandoffWorks = true
|
||||
)
|
||||
|
||||
var (
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
procFindWindowExW = user32.NewProc("FindWindowExW")
|
||||
procSendMessageW = user32.NewProc("SendMessageW")
|
||||
)
|
||||
|
||||
type copyDataStruct struct {
|
||||
dwData uintptr
|
||||
cbData uint32
|
||||
lpData uintptr
|
||||
}
|
||||
|
||||
// findWindow returns the running Reims-Go window's message window, or 0.
|
||||
func findWindow() uintptr {
|
||||
id := "wails-app-" + InstanceID
|
||||
class, err := syscall.UTF16PtrFromString(id + "-sic")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
name, err := syscall.UTF16PtrFromString(id + "-siw")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
h, _, _ := procFindWindowExW.Call(hwndMessage, 0, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(name)))
|
||||
return h
|
||||
}
|
||||
|
||||
// sendToWindow delivers args to the running window as if a second
|
||||
// `reims-go.exe <args>` had been launched.
|
||||
func sendToWindow(hwnd uintptr, args []string) error {
|
||||
wd, _ := os.Getwd()
|
||||
payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buf, err := syscall.UTF16FromString(string(payload)) // NUL-terminated
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cds := copyDataStruct{
|
||||
dwData: wailsCopyDataID,
|
||||
cbData: uint32(len(buf) * 2),
|
||||
lpData: uintptr(unsafe.Pointer(&buf[0])),
|
||||
}
|
||||
procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds)))
|
||||
runtime.KeepAlive(buf)
|
||||
return nil
|
||||
}
|
||||
|
||||
// spawnWindow launches this executable as the desktop window, detached from
|
||||
// the caller's console and Ctrl+C, with no handles of the caller's: a pipe an
|
||||
// agent reads from must close when this command exits, not when Reims-Go does.
|
||||
func spawnWindow(args []string) error {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.Command(exe, args...)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
if cmd.Process == nil {
|
||||
return errors.New("reims-go window did not start")
|
||||
}
|
||||
return cmd.Process.Release()
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !dev
|
||||
|
||||
package cli
|
||||
|
||||
// InstanceID names the desktop window's single-instance lock (Wails
|
||||
// options.SingleInstanceLock). Command-line mode finds a running window by
|
||||
// the same name to hand `vm start` to it.
|
||||
const InstanceID = "reims-go-9d3f6c1e"
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build dev
|
||||
|
||||
package cli
|
||||
|
||||
// InstanceID for `wails dev` builds: separate from release builds so a dev
|
||||
// window neither hands itself to nor blocks an installed Reims-Go.
|
||||
const InstanceID = "reims-go-9d3f6c1e-dev"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -14,14 +14,15 @@ import (
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
// runtime available [--alpha]: published runtimes on GitHub Releases.
|
||||
// runtime available [--alpha] [--source auto|github|gitcode]: published runtimes.
|
||||
func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
fs := flag.NewFlagSet("runtime available", flag.ContinueOnError)
|
||||
alpha := alphaFlag(fs, cfg, "Include alpha runtimes")
|
||||
source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode")
|
||||
if err := fs.Parse(flagsFirst(args)); err != nil {
|
||||
return err
|
||||
}
|
||||
list, err := rt.DefaultSource().ListRemote(context.Background(), *alpha)
|
||||
list, err := rt.DefaultSourceFor(*source).ListRemote(context.Background(), *alpha)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -29,7 +30,7 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
|
||||
fmt.Println(i18n.T(loc, "runtime.remote.empty"))
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("%-9s %-10s %-11s %9s %s\n", "COMMIT", "CHANNEL", "PUBLISHED", "SIZE", "INSTALLED")
|
||||
fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", "COMMIT", "CHANNEL", "SOURCE", "PUBLISHED", "SIZE", "INSTALLED")
|
||||
for _, r := range list {
|
||||
mark := ""
|
||||
if rt.IsInstalled(cfg, r.Commit) {
|
||||
@@ -39,15 +40,16 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
|
||||
if len(date) >= 10 {
|
||||
date = date[:10]
|
||||
}
|
||||
fmt.Printf("%-9s %-10s %-11s %9s %s\n", r.Commit, r.Channel, date, humanBytes(r.ArchiveSize), mark)
|
||||
fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", r.Commit, r.Channel, r.Source, date, humanBytes(r.ArchiveSize), mark)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runtime fetch [commit|latest] [--alpha]: download, verify, install, activate.
|
||||
// runtime fetch [commit|latest] [--alpha] [--source auto|github|gitcode]: download, verify, install, activate.
|
||||
func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError)
|
||||
alpha := alphaFlag(fs, cfg, "Allow alpha runtimes for \"latest\"")
|
||||
source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode")
|
||||
if err := fs.Parse(flagsFirst(args)); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -56,7 +58,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()
|
||||
src := rt.DefaultSourceFor(*source)
|
||||
list, err := src.ListRemote(ctx, *alpha || explicit)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -106,14 +108,20 @@ func alphaFlag(fs *flag.FlagSet, cfg *config.Config, usage string) *bool {
|
||||
return v
|
||||
}
|
||||
|
||||
// flagsFirst moves "-x" arguments before positional ones, so
|
||||
// "fetch latest --alpha" works like "fetch --alpha latest" (the flag
|
||||
// package stops at the first positional argument).
|
||||
// flagsFirst moves "-x" arguments (and their values for value flags like
|
||||
// --source) before positional ones, so "fetch latest --source gitcode --alpha"
|
||||
// works like "fetch --source gitcode --alpha latest" (the flag package stops
|
||||
// at the first positional argument).
|
||||
func flagsFirst(args []string) []string {
|
||||
var flags, rest []string
|
||||
for _, a := range args {
|
||||
for i := 0; i < len(args); i++ {
|
||||
a := args[i]
|
||||
if len(a) > 1 && a[0] == '-' {
|
||||
flags = append(flags, a)
|
||||
if (a == "-source" || a == "--source") && i+1 < len(args) {
|
||||
i++
|
||||
flags = append(flags, args[i])
|
||||
}
|
||||
} else {
|
||||
rest = append(rest, a)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// startHandoffTimeout bounds how long `vm start` waits for the window to
|
||||
// report back. Preparation can rebuild the OpenCore image before QEMU starts.
|
||||
const startHandoffTimeout = 5 * time.Minute
|
||||
|
||||
// startVM checks the VM can start, then hands it to the desktop window: the
|
||||
// one already running, or a new one in the tray (`--background`). The window
|
||||
// runs the GUI's StartVM, so a VM started from the command line gets Guest
|
||||
// Tools and the Win10 cold-reboot watcher too; both need a process that stays
|
||||
// up after this command exits.
|
||||
//
|
||||
// viaWindow is false when --data-root points elsewhere than the window's
|
||||
// data root could; the VM then starts here, without those two.
|
||||
func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string, viaWindow bool) 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
|
||||
}
|
||||
if viaWindow && windowHandoffWorks {
|
||||
return startInWindow(ctx, cfg, name)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
|
||||
zh := cfg.Locale == i18n.ZhCN
|
||||
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
|
||||
w := WindowArgs{StartVM: name, StartResult: result}
|
||||
if hwnd := findWindow(); hwnd != 0 {
|
||||
if zh {
|
||||
fmt.Fprintf(os.Stderr, "交给正在运行的 Reims-Go 启动 %s…\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Handing %s to the running Reims-Go...\n", name)
|
||||
}
|
||||
if err := sendToWindow(hwnd, w.Args()); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
w.Background = true
|
||||
if zh {
|
||||
fmt.Fprintf(os.Stderr, "在后台拉起 Reims-Go(托盘)来启动 %s…\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Starting Reims-Go in the tray to run %s...\n", name)
|
||||
}
|
||||
if err := spawnWindow(w.Args()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
|
||||
defer stop()
|
||||
res, err := waitStartResult(ctx, result, startHandoffTimeout)
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
if zh {
|
||||
return fmt.Errorf("已停止等待;%s 仍由 Reims-Go 继续启动", name)
|
||||
}
|
||||
return fmt.Errorf("stopped waiting; Reims-Go keeps starting %s", name)
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
if zh {
|
||||
return fmt.Errorf("Reims-Go 在 %v 内没有回报 %s 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)", startHandoffTimeout, name)
|
||||
}
|
||||
return fmt.Errorf("Reims-Go did not report starting %s within %v; check its log panel (quit it first if it is an older version)", name, startHandoffTimeout)
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
if !res.OK {
|
||||
return errors.New(res.Error)
|
||||
}
|
||||
// Guest Tools only connects once macOS is up and its agent runs, so say
|
||||
// what this process can know: who now looks after the VM.
|
||||
if zh {
|
||||
fmt.Printf("%s 已启动,由 Reims-Go 界面进程管理;macOS 启动后,已安装 Guest Tools 的客体会接入剪贴板与共享目录\n", name)
|
||||
} else {
|
||||
fmt.Printf("%s is running, looked after by the Reims-Go window process; once macOS is up, a guest with Guest Tools installed gets clipboard and shared folders\n", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitStartResult polls for the window's StartResult file and removes it.
|
||||
// The window writes it with a rename, so any file seen is complete.
|
||||
func waitStartResult(ctx context.Context, path string, timeout time.Duration) (StartResult, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
tick := time.NewTicker(250 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if b, err := os.ReadFile(path); err == nil {
|
||||
_ = os.Remove(path)
|
||||
var res StartResult
|
||||
if err := json.Unmarshal(b, &res); err != nil {
|
||||
return StartResult{}, fmt.Errorf("unreadable start result %s: %w", path, err)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return StartResult{}, ctx.Err()
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WriteStartResult is the window's side of waitStartResult.
|
||||
func WriteStartResult(path string, startErr error) error {
|
||||
res := StartResult{OK: startErr == nil}
|
||||
if startErr != nil {
|
||||
res.Error = startErr.Error()
|
||||
}
|
||||
b, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
part := path + ".part"
|
||||
if err := os.WriteFile(part, b, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(part, path)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package cli
|
||||
|
||||
import "strings"
|
||||
|
||||
// The desktop window's own flags. `vm start` launches the window with them
|
||||
// (or sends them to a window already running), so they are the whole
|
||||
// protocol between command-line mode and the window. Each flag is one
|
||||
// argument (`--name=value`) so a stray value is never taken for a command.
|
||||
const (
|
||||
flagBackground = "--background"
|
||||
flagStartVM = "--start-vm="
|
||||
flagStartResult = "--start-result="
|
||||
)
|
||||
|
||||
// WindowArgs is what the desktop window was asked to do at launch, or by a
|
||||
// later `reims-go` run handing work to it.
|
||||
type WindowArgs struct {
|
||||
// Background keeps the window hidden; Reims-Go lives in the tray.
|
||||
Background bool
|
||||
// StartVM is a VM to start as the GUI's StartVM would (Guest Tools and
|
||||
// the Win10 cold-reboot watcher included).
|
||||
StartVM string
|
||||
// StartResult is a file the window writes a StartResult to once StartVM
|
||||
// has returned, so the command that asked can report it.
|
||||
StartResult string
|
||||
}
|
||||
|
||||
// ParseWindowArgs reads the window flags. ok is false when args hold
|
||||
// anything else, which means command-line mode. No arguments is a plain
|
||||
// window launch.
|
||||
func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
|
||||
for _, a := range args {
|
||||
switch {
|
||||
case a == flagBackground:
|
||||
w.Background = true
|
||||
case strings.HasPrefix(a, flagStartVM):
|
||||
w.StartVM = strings.TrimPrefix(a, flagStartVM)
|
||||
case strings.HasPrefix(a, flagStartResult):
|
||||
w.StartResult = strings.TrimPrefix(a, flagStartResult)
|
||||
default:
|
||||
return WindowArgs{}, false
|
||||
}
|
||||
}
|
||||
return w, true
|
||||
}
|
||||
|
||||
// Args is the inverse of ParseWindowArgs.
|
||||
func (w WindowArgs) Args() []string {
|
||||
var out []string
|
||||
if w.Background {
|
||||
out = append(out, flagBackground)
|
||||
}
|
||||
if w.StartVM != "" {
|
||||
out = append(out, flagStartVM+w.StartVM)
|
||||
}
|
||||
if w.StartResult != "" {
|
||||
out = append(out, flagStartResult+w.StartResult)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// StartResult is the JSON the window writes to WindowArgs.StartResult.
|
||||
type StartResult struct {
|
||||
OK bool `json:"ok"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseWindowArgs(t *testing.T) {
|
||||
cases := []struct {
|
||||
args []string
|
||||
want WindowArgs
|
||||
isPlain bool // window launch, not a command
|
||||
}{
|
||||
{nil, WindowArgs{}, true},
|
||||
{[]string{"--background"}, WindowArgs{Background: true}, true},
|
||||
{[]string{"--background", "--start-vm=m0", `--start-result=D:\tmp\cli-start-1.json`},
|
||||
WindowArgs{Background: true, StartVM: "m0", StartResult: `D:\tmp\cli-start-1.json`}, true},
|
||||
{[]string{"vm", "start", "m0"}, WindowArgs{}, false},
|
||||
{[]string{"--background", "vm", "list"}, WindowArgs{}, false},
|
||||
{[]string{"--help"}, WindowArgs{}, false},
|
||||
{[]string{"--start-vm", "m0"}, WindowArgs{}, false}, // value must be joined with =
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, ok := ParseWindowArgs(c.args)
|
||||
if ok != c.isPlain || !reflect.DeepEqual(got, c.want) {
|
||||
t.Errorf("ParseWindowArgs(%q) = %+v, %v; want %+v, %v", c.args, got, ok, c.want, c.isPlain)
|
||||
}
|
||||
if IsCommand(c.args) == c.isPlain {
|
||||
t.Errorf("IsCommand(%q) = %v", c.args, !c.isPlain)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowArgsRoundTrip(t *testing.T) {
|
||||
w := WindowArgs{Background: true, StartVM: "mac os", StartResult: `D:\Data\tmp\cli-start-9.json`}
|
||||
got, ok := ParseWindowArgs(w.Args())
|
||||
if !ok || got != w {
|
||||
t.Fatalf("round trip = %+v, %v", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartResultRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
okPath := filepath.Join(dir, "cli-start-1.json")
|
||||
if err := WriteStartResult(okPath, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := waitStartResult(context.Background(), okPath, time.Second)
|
||||
if err != nil || !res.OK {
|
||||
t.Fatalf("ok result = %+v, %v", res, err)
|
||||
}
|
||||
if _, err := os.Stat(okPath); !os.IsNotExist(err) {
|
||||
t.Fatal("result file should be removed once read")
|
||||
}
|
||||
|
||||
failPath := filepath.Join(dir, "cli-start-2.json")
|
||||
go func() {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
_ = WriteStartResult(failPath, errors.New("not enough memory"))
|
||||
}()
|
||||
res, err = waitStartResult(context.Background(), failPath, 5*time.Second)
|
||||
if err != nil || res.OK || res.Error != "not enough memory" {
|
||||
t.Fatalf("failed result = %+v, %v", res, err)
|
||||
}
|
||||
|
||||
_, err = waitStartResult(context.Background(), filepath.Join(dir, "never.json"), 300*time.Millisecond)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("missing result err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ type Config struct {
|
||||
// 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"`
|
||||
// RuntimeSource chooses where online runtimes and app updates are fetched:
|
||||
// "auto" (default, also when empty: try GitHub first, fall back to GitCode),
|
||||
// "github", or "gitcode".
|
||||
RuntimeSource string `json:"runtime_source,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"`
|
||||
|
||||
@@ -39,36 +39,36 @@ type VMListItem struct {
|
||||
}
|
||||
|
||||
type VMDetail struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Kind string `json:"kind"`
|
||||
Directory string `json:"directory"`
|
||||
CPUs int `json:"cpus"`
|
||||
Memory string `json:"memory"`
|
||||
Disk string `json:"disk"`
|
||||
DiskController string `json:"disk_controller"`
|
||||
Graphics string `json:"graphics"`
|
||||
Display string `json:"display"`
|
||||
Displays int `json:"displays"`
|
||||
Resolution string `json:"resolution"`
|
||||
GPU string `json:"gpu"`
|
||||
HasOpenCore bool `json:"has_opencore"`
|
||||
HasInstaller bool `json:"has_installer"`
|
||||
RecoveryMode bool `json:"recovery_mode"`
|
||||
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"`
|
||||
SSHPort int `json:"ssh_port"`
|
||||
Logs bool `json:"logs"`
|
||||
LogLevel string `json:"log_level"`
|
||||
StopTimeout int `json:"stop_timeout"`
|
||||
Capture bool `json:"capture"`
|
||||
Borderless bool `json:"borderless"`
|
||||
ExtraArgs string `json:"extra_args"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Kind string `json:"kind"`
|
||||
Directory string `json:"directory"`
|
||||
CPUs int `json:"cpus"`
|
||||
Memory string `json:"memory"`
|
||||
Disk string `json:"disk"`
|
||||
DiskController string `json:"disk_controller"`
|
||||
Graphics string `json:"graphics"`
|
||||
Display string `json:"display"`
|
||||
Displays int `json:"displays"`
|
||||
Resolution string `json:"resolution"`
|
||||
GPU string `json:"gpu"`
|
||||
HasOpenCore bool `json:"has_opencore"`
|
||||
HasInstaller bool `json:"has_installer"`
|
||||
RecoveryMode bool `json:"recovery_mode"`
|
||||
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"`
|
||||
SSHPort int `json:"ssh_port"`
|
||||
Logs bool `json:"logs"`
|
||||
LogLevel string `json:"log_level"`
|
||||
StopTimeout int `json:"stop_timeout"`
|
||||
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"`
|
||||
@@ -94,26 +94,26 @@ type CreateOpts struct {
|
||||
// Offline makes --macos an offline installer of one release (13 to 20 GB)
|
||||
// that installs with no network; upstream advises the VM's network off then
|
||||
// (`reims-ctl create --help`, 3731afd). Network defaults to false with it.
|
||||
Offline bool `json:"offline,omitempty"`
|
||||
Installer string `json:"installer,omitempty"`
|
||||
CPUs int `json:"cpus,omitempty"`
|
||||
Memory string `json:"memory,omitempty"`
|
||||
Offline bool `json:"offline,omitempty"`
|
||||
Installer string `json:"installer,omitempty"`
|
||||
CPUs int `json:"cpus,omitempty"`
|
||||
Memory string `json:"memory,omitempty"`
|
||||
DiskSize string `json:"disk_size,omitempty"`
|
||||
Disk string `json:"disk,omitempty"`
|
||||
DiskMode string `json:"disk_mode,omitempty"`
|
||||
DiskController string `json:"disk_controller,omitempty"`
|
||||
Graphics string `json:"graphics,omitempty"`
|
||||
GPU string `json:"gpu,omitempty"`
|
||||
Resolution string `json:"resolution,omitempty"`
|
||||
Displays int `json:"displays,omitempty"`
|
||||
Borderless *bool `json:"borderless,omitempty"`
|
||||
Capture *bool `json:"capture,omitempty"`
|
||||
Audio *bool `json:"audio,omitempty"`
|
||||
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"`
|
||||
GPU string `json:"gpu,omitempty"`
|
||||
Resolution string `json:"resolution,omitempty"`
|
||||
Displays int `json:"displays,omitempty"`
|
||||
Borderless *bool `json:"borderless,omitempty"`
|
||||
Capture *bool `json:"capture,omitempty"`
|
||||
Audio *bool `json:"audio,omitempty"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type SetOpts struct {
|
||||
@@ -143,7 +143,10 @@ var (
|
||||
reVMName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
|
||||
reSizeG = regexp.MustCompile(`(?i)^(\d+)\s*([GM])$`)
|
||||
reRes = regexp.MustCompile(`^(\d{3,5})x(\d{3,5})$`)
|
||||
reMac = regexp.MustCompile(`(?i),?\s*mac\s+[0-9a-f]{2}(:[0-9a-f]{2}){5}`)
|
||||
// reResIn finds a WIDTHxHEIGHT inside `show`'s display line (reRes is a
|
||||
// whole-value check and never matched there).
|
||||
reResIn = regexp.MustCompile(`\b\d{3,5}x\d{3,5}\b`)
|
||||
reMac = regexp.MustCompile(`(?i),?\s*mac\s+[0-9a-f]{2}(:[0-9a-f]{2}){5}`)
|
||||
)
|
||||
|
||||
// ParseSizeGB parses "16G" or "4096M" into gigabytes.
|
||||
@@ -501,6 +504,26 @@ func showState(v string) string {
|
||||
return v
|
||||
}
|
||||
|
||||
// parseDisplayCount reads the count that starts `show`'s display line: a word
|
||||
// ("one") or a number ("2"); 1 where there is neither.
|
||||
func parseDisplayCount(v string) int {
|
||||
first := strings.ToLower(strings.TrimSpace(strings.SplitN(v, ",", 2)[0]))
|
||||
switch first {
|
||||
case "one":
|
||||
return 1
|
||||
case "two":
|
||||
return 2
|
||||
case "three":
|
||||
return 3
|
||||
case "four":
|
||||
return 4
|
||||
}
|
||||
if n, err := strconv.Atoi(first); err == nil && n >= 1 && n <= 4 {
|
||||
return n
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// ParseShow parses the text output of `reims-ctl show <name>` while redacting MAC addresses.
|
||||
func ParseShow(name, text string) VMDetail {
|
||||
d := VMDetail{
|
||||
@@ -548,29 +571,24 @@ func ParseShow(name, text string) VMDetail {
|
||||
d.DiskController = "ahci"
|
||||
}
|
||||
case "graphics":
|
||||
if strings.HasPrefix(v, "vmware-svga") {
|
||||
// "VMware SVGA, no GPU acceleration, in QEMU's window" (3731afd
|
||||
// cli.rs describe); older builds printed "vmware-svga".
|
||||
if low := strings.ToLower(v); strings.HasPrefix(low, "vmware svga") || strings.HasPrefix(low, "vmware-svga") {
|
||||
d.Graphics = "vmware-svga"
|
||||
} else {
|
||||
d.Graphics = "reims-vgpu"
|
||||
}
|
||||
case "display":
|
||||
case "display", "displays":
|
||||
// One display: "display one, in a window opening at 1920x1080, ...";
|
||||
// more: "displays 2, in 2 windows opening at 1920x1080, ..." (3731afd).
|
||||
d.Display = v
|
||||
if m := reRes.FindString(v); m != "" {
|
||||
if m := reResIn.FindString(v); m != "" {
|
||||
d.Resolution = m
|
||||
}
|
||||
if strings.Contains(strings.ToLower(v), "borderless") {
|
||||
d.Borderless = true
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(v, "two"):
|
||||
d.Displays = 2
|
||||
case strings.HasPrefix(v, "three"):
|
||||
d.Displays = 3
|
||||
case strings.HasPrefix(v, "four"):
|
||||
d.Displays = 4
|
||||
default:
|
||||
d.Displays = 1
|
||||
}
|
||||
d.Displays = parseDisplayCount(v)
|
||||
case "gpu":
|
||||
if strings.HasPrefix(strings.ToLower(v), "automatic") {
|
||||
d.GPU = "auto"
|
||||
@@ -612,8 +630,11 @@ func ParseShow(name, text string) VMDetail {
|
||||
d.LogLevel = m[1]
|
||||
}
|
||||
case "stop timeout":
|
||||
// "90 s", or "none: stop waits until the guest shuts down" for 0.
|
||||
if m := regexp.MustCompile(`(\d+)`).FindString(v); m != "" {
|
||||
d.StopTimeout, _ = strconv.Atoi(m)
|
||||
} else if strings.HasPrefix(strings.ToLower(v), "none") {
|
||||
d.StopTimeout = 0
|
||||
}
|
||||
case "capture":
|
||||
low := strings.ToLower(strings.TrimSpace(v))
|
||||
|
||||
@@ -114,3 +114,62 @@ func TestParseShowStateDropsPID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reims-ctl 3731afd prints one display as "display one, ..." and several as
|
||||
// "displays 2, in 2 windows ..."; both must read back.
|
||||
func TestParseShowDisplayCount(t *testing.T) {
|
||||
cases := []struct {
|
||||
line string
|
||||
want int
|
||||
wantRes string
|
||||
borderle bool
|
||||
}{
|
||||
{" display one, in a window opening at 1920x1080, whose size the guest follows", 1, "1920x1080", false},
|
||||
{" displays 2, in 2 windows opening at 1920x1080, whose sizes the guest follows", 2, "1920x1080", false},
|
||||
{" displays 4, in 4 windows opening at 2560x1600, whose sizes the guest follows", 4, "2560x1600", false},
|
||||
// Borderless lines name no size; Resolution keeps its default.
|
||||
{" displays 2, in 2 borderless windows, each filling its screen", 2, "1920x1080", true},
|
||||
{" display one, filling its screen, borderless", 1, "1920x1080", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
d := ParseShow("m0", "m0\n state stopped\n"+c.line+"\n")
|
||||
if d.Displays != c.want || d.Resolution != c.wantRes || d.Borderless != c.borderle {
|
||||
t.Errorf("%q: displays=%d res=%q borderless=%v, want %d %q %v", c.line, d.Displays, d.Resolution, d.Borderless, c.want, c.wantRes, c.borderle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Lines as reims-ctl 3731afd's describe (crates/reims-ctl/src/cli.rs) prints
|
||||
// non-default settings.
|
||||
func TestParseShowNonDefaultLines(t *testing.T) {
|
||||
text := "m0\n" +
|
||||
" state stopped\n" +
|
||||
" disk disk.qcow2 (qcow2, SATA)\n" +
|
||||
" graphics VMware SVGA, no GPU acceleration, in QEMU's window\n" +
|
||||
" audio none\n" +
|
||||
" network user, mac 52:54:00:12:34:56\n" +
|
||||
" logs on (trace)\n" +
|
||||
" stop timeout none: stop waits until the guest shuts down\n"
|
||||
d := ParseShow("m0", text)
|
||||
if d.Graphics != "vmware-svga" {
|
||||
t.Errorf("graphics = %q, want vmware-svga", d.Graphics)
|
||||
}
|
||||
if d.StopTimeout != 0 {
|
||||
t.Errorf("stop timeout = %d, want 0 (no limit)", d.StopTimeout)
|
||||
}
|
||||
if d.DiskController != "ahci" {
|
||||
t.Errorf("disk controller = %q, want ahci", d.DiskController)
|
||||
}
|
||||
if !d.Audio || d.AudioBackend != "none" {
|
||||
t.Errorf("audio = %v/%q, want on with backend none", d.Audio, d.AudioBackend)
|
||||
}
|
||||
if !d.Network || d.SSHPort != 0 {
|
||||
t.Errorf("network = %v ssh %d, want on with no ssh port", d.Network, d.SSHPort)
|
||||
}
|
||||
if !d.Logs || d.LogLevel != "trace" {
|
||||
t.Errorf("logs = %v/%q, want on (trace)", d.Logs, d.LogLevel)
|
||||
}
|
||||
if d := ParseShow("m0", "m0\n graphics reims-vgpu, its own GPU device and macOS drivers\n stop timeout 30 s\n"); d.Graphics != "reims-vgpu" || d.StopTimeout != 30 {
|
||||
t.Errorf("reims-vgpu / 30 s parsed as %q / %d", d.Graphics, d.StopTimeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/webdav"
|
||||
)
|
||||
|
||||
// DriveShareAgentVersion is the first macOS agent that applies dynamic drive mounts.
|
||||
const DriveShareAgentVersion = 4
|
||||
|
||||
// NormalizeDriveLetter accepts C, C:, or C:\ and returns the canonical letter C.
|
||||
func NormalizeDriveLetter(raw string) (string, bool) {
|
||||
s := strings.ToUpper(strings.TrimSpace(raw))
|
||||
s = strings.TrimSuffix(s, `\`)
|
||||
s = strings.TrimSuffix(s, ":")
|
||||
if len(s) != 1 || s[0] < 'A' || s[0] > 'Z' {
|
||||
return "", false
|
||||
}
|
||||
return s, true
|
||||
}
|
||||
|
||||
func configuredDriveRoots(cfg VMConfig) map[string]string {
|
||||
roots := make(map[string]string)
|
||||
for _, raw := range cfg.SharedDrives {
|
||||
drive, ok := NormalizeDriveLetter(raw)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
root := cfg.DriveRoots[drive]
|
||||
if root == "" {
|
||||
continue
|
||||
}
|
||||
roots[drive] = root
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
func cloneStringMap(src map[string]string) map[string]string {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
dst := make(map[string]string, len(src))
|
||||
for k, v := range src {
|
||||
dst[k] = v
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
func enabledDriveLetters(vm *registeredVM) []string {
|
||||
out := []string{}
|
||||
if vm == nil || !vm.driveSharingEnabled {
|
||||
return out
|
||||
}
|
||||
for drive := range vm.sharedDriveRoots {
|
||||
out = append(out, drive)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// readOnlyDriveFS exposes an existing fixed-drive root without ever creating it.
|
||||
// Every read resolves junctions/symlinks and verifies that the final target stays
|
||||
// inside the authorized root. All mutating filesystem operations are denied.
|
||||
type readOnlyDriveFS struct {
|
||||
rootAbs string
|
||||
inner webdav.Dir
|
||||
}
|
||||
|
||||
func newReadOnlyDriveFS(root string) (*readOnlyDriveFS, error) {
|
||||
abs, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(abs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &readOnlyDriveFS{rootAbs: resolved, inner: webdav.Dir(resolved)}, nil
|
||||
}
|
||||
|
||||
func pathWithinRoot(root, target string) bool {
|
||||
rel, err := filepath.Rel(root, target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) && !filepath.IsAbs(rel))
|
||||
}
|
||||
|
||||
func (f *readOnlyDriveFS) validate(name string) error {
|
||||
if strings.ContainsRune(name, 0) || strings.Contains(name, `\`) {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
clean := path.Clean("/" + name)
|
||||
full := filepath.Join(f.rootAbs, filepath.FromSlash(strings.TrimPrefix(clean, "/")))
|
||||
if !pathWithinRoot(f.rootAbs, full) {
|
||||
return os.ErrPermission
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(full)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pathWithinRoot(f.rootAbs, resolved) {
|
||||
return os.ErrPermission
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *readOnlyDriveFS) Mkdir(context.Context, string, os.FileMode) error {
|
||||
return os.ErrPermission
|
||||
}
|
||||
|
||||
func (f *readOnlyDriveFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
|
||||
const writeFlags = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_TRUNC
|
||||
if flag&writeFlags != 0 {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
if err := f.validate(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.inner.OpenFile(ctx, name, os.O_RDONLY, perm)
|
||||
}
|
||||
|
||||
func (f *readOnlyDriveFS) RemoveAll(context.Context, string) error {
|
||||
return os.ErrPermission
|
||||
}
|
||||
|
||||
func (f *readOnlyDriveFS) Rename(context.Context, string, string) error {
|
||||
return os.ErrPermission
|
||||
}
|
||||
|
||||
func (f *readOnlyDriveFS) 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)
|
||||
}
|
||||
|
||||
func allowReadOnlyDAV(w http.ResponseWriter, r *http.Request) bool {
|
||||
switch r.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions, "PROPFIND":
|
||||
return true
|
||||
default:
|
||||
w.Header().Set("Allow", "OPTIONS, GET, HEAD, PROPFIND")
|
||||
http.Error(w, "read-only drive share", http.StatusMethodNotAllowed)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeDriveLetter(t *testing.T) {
|
||||
for _, tc := range []struct{ in, want string }{{"c", "C"}, {"C:", "C"}, {"d:\\", "D"}, {" e: ", "E"}} {
|
||||
got, ok := NormalizeDriveLetter(tc.in)
|
||||
if !ok || got != tc.want {
|
||||
t.Fatalf("NormalizeDriveLetter(%q) = %q, %v; want %q", tc.in, got, ok, tc.want)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{"", "CC", "1", "C:/", "../C", `\\server\share`} {
|
||||
if got, ok := NormalizeDriveLetter(raw); ok {
|
||||
t.Fatalf("NormalizeDriveLetter(%q) unexpectedly accepted as %q", raw, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyDriveSharesEnforceSelectionAndIsolation(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
rootC := filepath.Join(tmp, "drive-c")
|
||||
rootD := filepath.Join(tmp, "drive-d")
|
||||
if err := os.MkdirAll(rootC, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(rootD, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(rootC, "hello.txt"), []byte("from-c"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(rootD, "hello.txt"), []byte("from-d"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := NewServer(&memClipboard{})
|
||||
port, err := srv.Start(-1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close(context.Background())
|
||||
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
cfg := VMConfig{
|
||||
VMName: "mac", Token: strings.Repeat("ab", 32), Port: port,
|
||||
SharedDir: filepath.Join(tmp, "shared"), DriveSharingEnabled: true,
|
||||
SharedDrives: []string{"C"}, DriveRoots: map[string]string{"C": rootC, "D": rootD},
|
||||
}
|
||||
srv.RegisterVM(cfg)
|
||||
other := VMConfig{
|
||||
VMName: "other", Token: strings.Repeat("cd", 32), Port: port,
|
||||
DriveSharingEnabled: true, SharedDrives: []string{"C"},
|
||||
DriveRoots: map[string]string{"C": rootD},
|
||||
}
|
||||
srv.RegisterVM(other)
|
||||
|
||||
do := func(method, reqPath, token string, body io.Reader) (int, string, http.Header) {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(method, base+reqPath, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
if method == "PROPFIND" {
|
||||
req.Header.Set("Depth", "1")
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp.StatusCode, string(b), resp.Header
|
||||
}
|
||||
readC := "/dav/mac/drives/C/hello.txt"
|
||||
if code, body, _ := do(http.MethodGet, readC, cfg.Token, nil); code != http.StatusOK || body != "from-c" {
|
||||
t.Fatalf("read shared C: code=%d body=%q", code, body)
|
||||
}
|
||||
if code, body, _ := do("PROPFIND", "/dav/mac/drives/C/", cfg.Token, nil); code != http.StatusMultiStatus || !strings.Contains(body, "hello.txt") {
|
||||
t.Fatalf("PROPFIND shared C: code=%d body=%s", code, body)
|
||||
}
|
||||
reqMissing, err := http.NewRequest("PROPFIND", base+"/dav/mac/drives/C/", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reqMissing.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
respMissing, err := http.DefaultClient.Do(reqMissing)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
respMissing.Body.Close()
|
||||
if respMissing.StatusCode != http.StatusMultiStatus {
|
||||
t.Fatalf("PROPFIND without Depth: code=%d, want 207", respMissing.StatusCode)
|
||||
}
|
||||
for _, depth := range []string{"infinity", "2"} {
|
||||
req, err := http.NewRequest("PROPFIND", base+"/dav/mac/drives/C/", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
if depth != "" {
|
||||
req.Header.Set("Depth", depth)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("PROPFIND Depth %q: code=%d, want 400", depth, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
if code, _, _ := do(http.MethodPut, "/dav/mac/drives/C/new.txt", cfg.Token, strings.NewReader("bad")); code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("PUT read-only C: code=%d, want 405", code)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(rootC, "new.txt")); !os.IsNotExist(err) {
|
||||
t.Fatalf("read-only PUT created a host file: %v", err)
|
||||
}
|
||||
for _, method := range []string{http.MethodDelete, "MKCOL", "MOVE", "COPY", "PROPPATCH", "LOCK"} {
|
||||
if code, _, _ := do(method, readC, cfg.Token, nil); code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("%s read-only C: code=%d, want 405", method, code)
|
||||
}
|
||||
}
|
||||
if body, err := os.ReadFile(filepath.Join(rootC, "hello.txt")); err != nil || string(body) != "from-c" {
|
||||
t.Fatalf("read-only DELETE changed host file: %q, %v", body, err)
|
||||
}
|
||||
if code, _, _ := do(http.MethodGet, "/dav/mac/drives/D/hello.txt", cfg.Token, nil); code != http.StatusForbidden {
|
||||
t.Fatalf("unselected D: code=%d, want 403", code)
|
||||
}
|
||||
if code, _, _ := do(http.MethodGet, readC, "", nil); code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated drive read: code=%d, want 401", code)
|
||||
}
|
||||
if code, body, _ := do(http.MethodGet, "/dav/other/drives/C/hello.txt", other.Token, nil); code != http.StatusOK || body != "from-d" {
|
||||
t.Fatalf("per-VM drive root isolation: code=%d body=%q", code, body)
|
||||
}
|
||||
if code, _, _ := do(http.MethodGet, "/dav/other/drives/C/hello.txt", cfg.Token, nil); code != http.StatusForbidden {
|
||||
t.Fatalf("cross-VM drive read: code=%d, want 403", code)
|
||||
}
|
||||
if _, body, _ := do(http.MethodGet, "/v1/config", cfg.Token, nil); !strings.Contains(body, `"shared_drives":["C"]`) {
|
||||
t.Fatalf("enabled config shared_drives missing C: %s", body)
|
||||
}
|
||||
|
||||
cfg.SharedDrives = []string{"C", "D"}
|
||||
srv.RegisterVM(cfg)
|
||||
if code, body, _ := do(http.MethodGet, "/dav/mac/drives/D/hello.txt", cfg.Token, nil); code != http.StatusOK || body != "from-d" {
|
||||
t.Fatalf("newly selected D: code=%d body=%q", code, body)
|
||||
}
|
||||
cfg.DriveSharingEnabled = false
|
||||
srv.RegisterVM(cfg)
|
||||
if code, _, _ := do(http.MethodGet, readC, cfg.Token, nil); code != http.StatusForbidden {
|
||||
t.Fatalf("disabled master switch: code=%d, want 403", code)
|
||||
}
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/v1/config", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var live struct {
|
||||
SharedDrives []string `json:"shared_drives"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&live); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if live.SharedDrives == nil || len(live.SharedDrives) != 0 {
|
||||
t.Fatalf("disabled config shared_drives = %#v, want empty JSON array", live.SharedDrives)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveShareConfigPersistsLettersButNotRuntimeRoots(t *testing.T) {
|
||||
vmDir := filepath.Join(t.TempDir(), "vm")
|
||||
cfg := VMConfig{VMName: "mac", Token: strings.Repeat("ab", 32), DriveSharingEnabled: true, SharedDrives: []string{"C"}, DriveVolumes: map[string]string{"C": "vol-c"}, DriveRoots: map[string]string{"C": `C:\secret-root`}}
|
||||
if err := SaveVMConfig(vmDir, cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(vmDir, ConfigFileName))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(raw)
|
||||
if !strings.Contains(text, `"shared_drives": [`) || !strings.Contains(text, `"C"`) || strings.Contains(text, "secret-root") || strings.Contains(text, "DriveRoots") {
|
||||
t.Fatalf("persisted drive config leaks runtime roots or omits letters: %s", text)
|
||||
}
|
||||
loaded, ok := ReadVMConfig(vmDir)
|
||||
if !ok || !loaded.DriveSharingEnabled || len(loaded.SharedDrives) != 1 || loaded.SharedDrives[0] != "C" || loaded.DriveVolumes["C"] != "vol-c" || loaded.DriveRoots != nil {
|
||||
t.Fatalf("loaded drive config = %#v", loaded)
|
||||
}
|
||||
}
|
||||
func TestReadOnlyDriveFSRejectsWritesAndEscapingSymlink(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
root := filepath.Join(tmp, "root")
|
||||
outside := filepath.Join(tmp, "outside")
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(outside, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
victim := filepath.Join(root, "victim.txt")
|
||||
if err := os.WriteFile(victim, []byte("safe"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fsys, err := newReadOnlyDriveFS(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, flag := range []int{os.O_WRONLY, os.O_RDWR, os.O_APPEND, os.O_CREATE, os.O_EXCL, os.O_TRUNC} {
|
||||
if _, err := fsys.OpenFile(context.Background(), "victim.txt", flag, 0); err == nil {
|
||||
t.Fatalf("write OpenFile flag %d unexpectedly succeeded", flag)
|
||||
}
|
||||
}
|
||||
if err := fsys.Mkdir(context.Background(), "new-dir", 0o755); err == nil {
|
||||
t.Fatal("Mkdir unexpectedly succeeded")
|
||||
}
|
||||
if err := fsys.RemoveAll(context.Background(), "victim.txt"); err == nil {
|
||||
t.Fatal("RemoveAll unexpectedly succeeded")
|
||||
}
|
||||
if err := fsys.Rename(context.Background(), "victim.txt", "renamed.txt"); err == nil {
|
||||
t.Fatal("Rename unexpectedly succeeded")
|
||||
}
|
||||
if body, err := os.ReadFile(victim); err != nil || string(body) != "safe" {
|
||||
t.Fatalf("write attempt changed file: %q, %v", body, err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(root, "escape")); err != nil {
|
||||
t.Skipf("symlink creation unavailable on this host: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fsys.OpenFile(context.Background(), "escape/secret.txt", os.O_RDONLY, 0); err == nil {
|
||||
t.Fatal("directory symlink escape unexpectedly succeeded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//go:build windows
|
||||
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadOnlyDriveFSRejectsWindowsJunctionEscape(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
root := filepath.Join(tmp, "root")
|
||||
outside := filepath.Join(tmp, "outside")
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(outside, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret := filepath.Join(outside, "secret.txt")
|
||||
if err := os.WriteFile(secret, []byte("outside"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(root, "junction")
|
||||
if output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput(); err != nil {
|
||||
t.Fatalf("create test junction: %v: %s", err, output)
|
||||
}
|
||||
if body, err := os.ReadFile(filepath.Join(link, "secret.txt")); err != nil || string(body) != "outside" {
|
||||
t.Fatalf("test junction is not usable: %q, %v", body, err)
|
||||
}
|
||||
fsys, err := newReadOnlyDriveFS(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fsys.OpenFile(context.Background(), "junction/secret.txt", os.O_RDONLY, 0); err == nil {
|
||||
t.Fatal("junction escape unexpectedly succeeded")
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ const (
|
||||
)
|
||||
|
||||
// BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS")
|
||||
// containing the per-VM Bearer token config, Guest Tools 2.0 POSIX agent script
|
||||
// containing the per-VM Bearer token config, Guest Tools 4 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 {
|
||||
@@ -65,14 +65,15 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
|
||||
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
|
||||
}
|
||||
|
||||
// GuestAgentScript returns the Guest Tools 2.0 stock-macOS POSIX shell daemon
|
||||
// GuestAgentScript returns the Guest Tools 4 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
|
||||
// - Host-controlled read-only Windows fixed-drive mounts with automatic unmount
|
||||
// - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required)
|
||||
func GuestAgentScript() []byte {
|
||||
return []byte(`#!/bin/sh
|
||||
# Reims Guest Tools 2.0: text+PNG clipboard (long-poll), WebDAV shared folder, prevent-sleep.
|
||||
# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep.
|
||||
set -u
|
||||
|
||||
# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified
|
||||
@@ -86,10 +87,11 @@ APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
|
||||
CONF="$APP_DIR/config"
|
||||
SHARE_SYNC="$HOME/ReimsShare"
|
||||
SHARE_MOUNT="$HOME/ReimsShareMount"
|
||||
DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives"
|
||||
DESKTOP_LINK="$HOME/Desktop/ReimsShare"
|
||||
TMP_DIR="$APP_DIR/tmp"
|
||||
INJECT_LOCK="$TMP_DIR/injecting"
|
||||
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$TMP_DIR"
|
||||
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR"
|
||||
rm -f "$INJECT_LOCK" 2>/dev/null || true
|
||||
|
||||
CAFFEINATE_PID=""
|
||||
@@ -193,10 +195,89 @@ ensure_webdav_mount() {
|
||||
|
||||
sleep_active="false"
|
||||
|
||||
apply_prevent_sleep() {
|
||||
is_drive_mounted() {
|
||||
mount 2>/dev/null | grep -F "on $1 (" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
update_drive_link() {
|
||||
letter="$1"
|
||||
mount_point="$DRIVE_MOUNT_ROOT/$letter"
|
||||
link="$HOME/Desktop/Windows $letter"
|
||||
if [ -L "$link" ]; then
|
||||
[ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ] && return 0
|
||||
rm -f "$link" 2>/dev/null || true
|
||||
elif [ -e "$link" ]; then
|
||||
return 0
|
||||
fi
|
||||
ln -s "$mount_point" "$link" 2>/dev/null || true
|
||||
}
|
||||
|
||||
remove_drive_link() {
|
||||
letter="$1"
|
||||
mount_point="$DRIVE_MOUNT_ROOT/$letter"
|
||||
link="$HOME/Desktop/Windows $letter"
|
||||
if [ -L "$link" ] && [ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ]; then
|
||||
rm -f "$link" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
unmount_drive() {
|
||||
letter="$1"
|
||||
mount_point="$DRIVE_MOUNT_ROOT/$letter"
|
||||
if is_drive_mounted "$mount_point"; then
|
||||
umount "$mount_point" >/dev/null 2>&1 || true
|
||||
fi
|
||||
remove_drive_link "$letter"
|
||||
if ! is_drive_mounted "$mount_point"; then
|
||||
rmdir "$mount_point" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
mount_drive() {
|
||||
letter="$1"
|
||||
mount_point="$DRIVE_MOUNT_ROOT/$letter"
|
||||
if is_drive_mounted "$mount_point"; then
|
||||
update_drive_link "$letter"
|
||||
return 0
|
||||
fi
|
||||
command -v mount_webdav >/dev/null 2>&1 || return 0
|
||||
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}/drives/${letter}/"
|
||||
mkdir -p "$mount_point"
|
||||
# Prefer a client read-only mount where supported; the host remains the authority.
|
||||
if mount_webdav -o ro -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \
|
||||
mount_webdav -o ro "$dav_url" "$mount_point" >/dev/null 2>&1 || \
|
||||
mount_webdav -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \
|
||||
mount_webdav "$dav_url" "$mount_point" >/dev/null 2>&1; then
|
||||
update_drive_link "$letter"
|
||||
fi
|
||||
}
|
||||
|
||||
sync_drive_mounts() {
|
||||
cfg_json="$1"
|
||||
desired=$(printf '%s\n' "$cfg_json" | \
|
||||
sed -n 's/.*"shared_drives"[[:space:]]*:[[:space:]]*\[\([^]]*\)\].*/\1/p' | \
|
||||
tr ',' '\n' | sed -n 's/^[[:space:]]*"\([A-Z]\)"[[:space:]]*$/\1/p' | tr '\n' ' ')
|
||||
for mount_point in "$DRIVE_MOUNT_ROOT"/*; do
|
||||
[ -d "$mount_point" ] || continue
|
||||
letter=${mount_point##*/}
|
||||
case " $desired " in
|
||||
*" $letter "*) ;;
|
||||
*) unmount_drive "$letter" ;;
|
||||
esac
|
||||
done
|
||||
for letter in $desired; do
|
||||
mount_drive "$letter"
|
||||
done
|
||||
}
|
||||
|
||||
apply_host_config() {
|
||||
[ -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
|
||||
sync_drive_mounts "$cfg_json"
|
||||
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
|
||||
@@ -223,7 +304,7 @@ report_status() {
|
||||
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}" \
|
||||
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":4}" \
|
||||
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
@@ -431,7 +512,7 @@ while :; do
|
||||
if [ $((tick % 5)) -eq 0 ]; then
|
||||
load_conf
|
||||
ensure_webdav_mount
|
||||
apply_prevent_sleep
|
||||
apply_host_config
|
||||
report_status
|
||||
fi
|
||||
sync_clipboard
|
||||
@@ -509,12 +590,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 2.0 installed and connected!"
|
||||
echo "Reims Guest Tools 4 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 2.0 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
|
||||
echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
|
||||
fi
|
||||
`)
|
||||
}
|
||||
@@ -526,9 +607,17 @@ set -e
|
||||
APP_DIR="$HOME/Library/Application Support/ReimsGuestTools"
|
||||
PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist"
|
||||
SHARE_MOUNT="$HOME/ReimsShareMount"
|
||||
DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives"
|
||||
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
|
||||
for mount_point in "$DRIVE_MOUNT_ROOT"/*; do
|
||||
[ -d "$mount_point" ] || continue
|
||||
letter=${mount_point##*/}
|
||||
umount "$mount_point" 2>/dev/null || true
|
||||
link="$HOME/Desktop/Windows $letter"
|
||||
[ -L "$link" ] && rm -f "$link" 2>/dev/null || true
|
||||
done
|
||||
rm -f "$PLIST"
|
||||
rm -rf "$APP_DIR"
|
||||
echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept."
|
||||
|
||||
@@ -69,14 +69,20 @@ type Clipboard interface {
|
||||
// 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"`
|
||||
PreventSleep bool `json:"prevent_sleep"`
|
||||
VMName string `json:"vm_name"`
|
||||
Token string `json:"token"`
|
||||
Port int `json:"port"`
|
||||
SharedDir string `json:"shared_dir"`
|
||||
PreventSleep bool `json:"prevent_sleep"`
|
||||
DriveSharingEnabled bool `json:"drive_sharing_enabled"`
|
||||
SharedDrives []string `json:"shared_drives,omitempty"`
|
||||
DriveVolumes map[string]string `json:"drive_volumes,omitempty"`
|
||||
// DriveRoots is a runtime-only test/platform override keyed by NormalizeDriveLetter.
|
||||
// Persisted configuration stores drive letters only, never arbitrary host roots.
|
||||
DriveRoots map[string]string `json:"-"`
|
||||
}
|
||||
|
||||
// GuestStatus summarizes live Guest Tools 2.0 connection and capability state.
|
||||
// GuestStatus summarizes live Guest Tools connection and capability state.
|
||||
type GuestStatus struct {
|
||||
Connected bool `json:"connected"`
|
||||
MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync"
|
||||
@@ -166,14 +172,16 @@ type pendingClipOverride struct {
|
||||
}
|
||||
|
||||
type registeredVM struct {
|
||||
name string
|
||||
token string
|
||||
sharedDir string
|
||||
preventSleep bool
|
||||
mountMode string
|
||||
sleepActive bool
|
||||
agentVersion int
|
||||
lastSeen time.Time
|
||||
name string
|
||||
token string
|
||||
sharedDir string
|
||||
preventSleep bool
|
||||
driveSharingEnabled bool
|
||||
sharedDriveRoots map[string]string
|
||||
mountMode string
|
||||
sleepActive bool
|
||||
agentVersion int
|
||||
lastSeen time.Time
|
||||
|
||||
injectMu sync.Mutex
|
||||
textSeq uint64
|
||||
@@ -188,17 +196,17 @@ type registeredVM struct {
|
||||
// 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
|
||||
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)
|
||||
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
|
||||
@@ -341,7 +349,7 @@ func (s *Server) Close(ctx context.Context) error {
|
||||
return srv.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// RegisterVM registers or updates a VM's Bearer token and shared directory.
|
||||
// RegisterVM registers or updates a VM's token, shared directory, and read-only drive selection.
|
||||
func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
if cfg.VMName == "" || cfg.Token == "" {
|
||||
return
|
||||
@@ -349,21 +357,26 @@ func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
if cfg.SharedDir != "" {
|
||||
_ = os.MkdirAll(cfg.SharedDir, 0o755)
|
||||
}
|
||||
driveRoots := configuredDriveRoots(cfg)
|
||||
s.mu.Lock()
|
||||
if cur := s.vms[cfg.VMName]; cur != nil {
|
||||
cur.token = cfg.Token
|
||||
cur.sharedDir = cfg.SharedDir
|
||||
cur.preventSleep = cfg.PreventSleep
|
||||
cur.driveSharingEnabled = cfg.DriveSharingEnabled
|
||||
cur.sharedDriveRoots = driveRoots
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.vms[cfg.VMName] = ®isteredVM{
|
||||
name: cfg.VMName,
|
||||
token: cfg.Token,
|
||||
sharedDir: cfg.SharedDir,
|
||||
preventSleep: cfg.PreventSleep,
|
||||
textActive: make(map[string]*pendingTextInput),
|
||||
textNotify: make(chan struct{}),
|
||||
name: cfg.VMName,
|
||||
token: cfg.Token,
|
||||
sharedDir: cfg.SharedDir,
|
||||
preventSleep: cfg.PreventSleep,
|
||||
driveSharingEnabled: cfg.DriveSharingEnabled,
|
||||
sharedDriveRoots: driveRoots,
|
||||
textActive: make(map[string]*pendingTextInput),
|
||||
textNotify: make(chan struct{}),
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
@@ -575,14 +588,16 @@ func (s *Server) authenticate(r *http.Request) *registeredVM {
|
||||
// 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,
|
||||
name: vm.name,
|
||||
token: vm.token,
|
||||
sharedDir: vm.sharedDir,
|
||||
preventSleep: vm.preventSleep,
|
||||
driveSharingEnabled: vm.driveSharingEnabled,
|
||||
sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots),
|
||||
mountMode: vm.mountMode,
|
||||
sleepActive: vm.sleepActive,
|
||||
agentVersion: vm.agentVersion,
|
||||
lastSeen: vm.lastSeen,
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
@@ -619,8 +634,8 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
|
||||
_ = 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"},
|
||||
"version": DriveShareAgentVersion,
|
||||
"capabilities": []string{"clipboard-text", "clipboard-png", "clipboard-longpoll", "webdav", "prevent-sleep", "text-input", "drive-shares-readonly"},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -639,6 +654,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
"vm": vm.name,
|
||||
"prevent_sleep": vm.preventSleep,
|
||||
"webdav_path": "/dav/" + vm.name + "/",
|
||||
"shared_drives": enabledDriveLetters(vm),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -112,6 +112,11 @@ func (s *Server) handleWebDAV(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
drivePrefix := vm.name + "/drives/"
|
||||
if strings.HasPrefix(trimmed, drivePrefix) {
|
||||
s.handleDriveWebDAV(w, r, vm, strings.TrimPrefix(trimmed, drivePrefix))
|
||||
return
|
||||
}
|
||||
if vm.sharedDir == "" {
|
||||
http.Error(w, "shared directory not configured", http.StatusNotFound)
|
||||
return
|
||||
@@ -125,6 +130,68 @@ func (s *Server) handleWebDAV(w http.ResponseWriter, r *http.Request) {
|
||||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) handleDriveWebDAV(w http.ResponseWriter, r *http.Request, vm *registeredVM, drivePath string) {
|
||||
if !vm.driveSharingEnabled {
|
||||
http.Error(w, "drive sharing disabled", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if r.Method == "PROPFIND" {
|
||||
depth := strings.TrimSpace(r.Header.Get("Depth"))
|
||||
if depth == "" {
|
||||
depth = "1"
|
||||
r.Header.Set("Depth", depth)
|
||||
}
|
||||
if depth != "0" && depth != "1" {
|
||||
http.Error(w, "drive PROPFIND requires Depth: 0 or 1", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
if !allowReadOnlyDAV(w, r) {
|
||||
return
|
||||
}
|
||||
driveSegment := drivePath
|
||||
if idx := strings.IndexByte(driveSegment, '/'); idx >= 0 {
|
||||
driveSegment = driveSegment[:idx]
|
||||
}
|
||||
drive, ok := NormalizeDriveLetter(driveSegment)
|
||||
if !ok || driveSegment != drive {
|
||||
http.Error(w, "invalid drive", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
root, ok := vm.sharedDriveRoots[drive]
|
||||
if !ok {
|
||||
http.Error(w, "drive not shared", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
handler, err := s.getOrCreateDriveDAVHandler(vm.name, drive, root)
|
||||
if err != nil {
|
||||
http.Error(w, "drive unavailable", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) getOrCreateDriveDAVHandler(vmName, drive, root string) (*webdav.Handler, error) {
|
||||
key := vmName + "/drives/" + drive
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if cur := s.davHandlers[key]; cur != nil && s.davRoots[key] == root {
|
||||
return cur, nil
|
||||
}
|
||||
fsys, err := newReadOnlyDriveFS(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := &webdav.Handler{
|
||||
Prefix: "/dav/" + vmName + "/drives/" + drive,
|
||||
FileSystem: fsys,
|
||||
LockSystem: webdav.NewMemLS(),
|
||||
}
|
||||
s.davHandlers[key] = h
|
||||
s.davRoots[key] = root
|
||||
return h, nil
|
||||
}
|
||||
|
||||
func (s *Server) getOrCreateDAVHandler(vmName, sharedDir string) (*webdav.Handler, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
+134
-120
@@ -13,14 +13,19 @@ type DisplayInfo struct {
|
||||
ScalePct int `json:"scale_pct"` // Windows DPI scaling percentage, e.g. 100, 125, 150, 200
|
||||
RefreshHz int `json:"refresh_hz,omitempty"`
|
||||
Primary bool `json:"primary"`
|
||||
// WorkWidth and WorkHeight are the work area (the screen less the taskbar) in
|
||||
// pixels; 0 where unknown.
|
||||
WorkWidth int `json:"work_width,omitempty"`
|
||||
WorkHeight int `json:"work_height,omitempty"`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
Resolution string `json:"resolution"`
|
||||
Label string `json:"label"`
|
||||
// HiDPI: macOS starts this window size HiDPI on the primary screen (GuestStartsHiDPI).
|
||||
HiDPI bool `json:"hidpi"`
|
||||
Recommended bool `json:"recommended,omitempty"`
|
||||
}
|
||||
|
||||
// PrimaryDisplayOf picks the primary monitor (or the first detected monitor).
|
||||
@@ -38,139 +43,148 @@ func PrimaryDisplayOf(displays []DisplayInfo) *DisplayInfo {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecommendDisplayPresets computes crisp 1x / 2x HiDPI resolution presets
|
||||
// based on the host primary monitor's physical pixel dimensions and Windows DPI scaling.
|
||||
// When an x86-64 macOS guest on reims-vgpu starts its desktop HiDPI. Upstream
|
||||
// steelbrain/reims-vgpu 3731afd, guest/kext/src/RgfxDisplayIdentity.hpp:33-41
|
||||
// and 68-79, crates/reims-vgpu-window/features.md:138-150:
|
||||
// - the display has 110 pixels per inch a point at the host screen's scale;
|
||||
// - it starts HiDPI from a window of 2048 x 1536 pixels above 160 pixels per
|
||||
// inch, which is a screen at 150% or more (145% gives exactly 160);
|
||||
// - and from 3840 x 2160 pixels at any scale.
|
||||
//
|
||||
// On Windows the window's points are the screen's pixels
|
||||
// (crates/reims-vgpu-window/src/geometry.rs:68-73), so --resolution is the
|
||||
// window's size in pixels and a borderless window is the screen's.
|
||||
const (
|
||||
guestPointsPerInch = 110
|
||||
guestHiDPIMinPPI = 160
|
||||
guestHiDPIMinWidth = 2048
|
||||
guestHiDPIMinHeight = 1536
|
||||
guestHiDPIAnyWidth = 3840
|
||||
guestHiDPIAnyHeight = 2160
|
||||
windowTitleBarPoints = 32 // a window's title bar and frame, in Windows points
|
||||
defaultTaskbarPoints = 48 // used where the work area is unknown
|
||||
maxDisplayPresetCount = 4
|
||||
)
|
||||
|
||||
// guestPixelsPerInch mirrors rgfxDisplayPixelsPerInch for a screen at scalePct.
|
||||
func guestPixelsPerInch(scalePct int) int {
|
||||
if scalePct <= 0 {
|
||||
return guestPointsPerInch
|
||||
}
|
||||
scale120ths := (scalePct*120 + 50) / 100
|
||||
return (guestPointsPerInch*scale120ths + 60) / 120
|
||||
}
|
||||
|
||||
// GuestStartsHiDPI reports whether macOS starts HiDPI in a reims-vgpu window of
|
||||
// w x h pixels on a host screen at scalePct.
|
||||
func GuestStartsHiDPI(w, h, scalePct int) bool {
|
||||
if w >= guestHiDPIAnyWidth && h >= guestHiDPIAnyHeight {
|
||||
return true
|
||||
}
|
||||
return guestPixelsPerInch(scalePct) > guestHiDPIMinPPI && w >= guestHiDPIMinWidth && h >= guestHiDPIMinHeight
|
||||
}
|
||||
|
||||
// FullscreenStartsHiDPI reports whether a borderless window, which fills the
|
||||
// screen, starts macOS HiDPI on d.
|
||||
func FullscreenStartsHiDPI(d *DisplayInfo) bool {
|
||||
if d == nil || d.Width <= 0 || d.Height <= 0 {
|
||||
return false
|
||||
}
|
||||
return GuestStartsHiDPI(d.Width, d.Height, d.ScalePct)
|
||||
}
|
||||
|
||||
// What HiDPIAdvice returns.
|
||||
const (
|
||||
HiDPIAdviceFullscreen = "fullscreen" // a borderless window is HiDPI
|
||||
HiDPIAdviceScale = "scale" // the screen would be at 150% Windows scaling
|
||||
HiDPIAdviceUnavailable = "unavailable" // too few pixels at any scale
|
||||
)
|
||||
|
||||
// HiDPIAdvice says how to get a HiDPI desktop on d when none of presets is
|
||||
// one, and "" when one is or nothing is known about d.
|
||||
func HiDPIAdvice(d *DisplayInfo, presets []DisplayPreset) string {
|
||||
if d == nil || d.Width <= 0 || d.Height <= 0 {
|
||||
return ""
|
||||
}
|
||||
for _, p := range presets {
|
||||
if p.HiDPI {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case FullscreenStartsHiDPI(d):
|
||||
return HiDPIAdviceFullscreen
|
||||
case d.ScalePct < 150 && GuestStartsHiDPI(d.Width, d.Height, 150):
|
||||
return HiDPIAdviceScale
|
||||
default:
|
||||
return HiDPIAdviceUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
presetSizes16x9 = [][2]int{{1280, 720}, {1600, 900}, {1920, 1080}, {2560, 1440}, {2880, 1620}, {3200, 1800}, {3840, 2160}}
|
||||
presetSizes16x10 = [][2]int{{1280, 800}, {1680, 1050}, {1920, 1200}, {2560, 1600}, {2880, 1800}, {3840, 2400}}
|
||||
)
|
||||
|
||||
// RecommendDisplayPresets lists window sizes that fit the primary screen's
|
||||
// work area below a title bar, largest first, each marked HiDPI where macOS
|
||||
// starts it so there. The recommended one is the largest HiDPI size, else the
|
||||
// largest size: text on a 1x macOS desktop is visibly rough, as macOS has no
|
||||
// subpixel antialiasing.
|
||||
func RecommendDisplayPresets(primary *DisplayInfo) ([]DisplayPreset, string) {
|
||||
if primary == nil || primary.Width <= 0 || primary.Height <= 0 {
|
||||
presets := []DisplayPreset{
|
||||
// Nothing known about the screen: no size can be called HiDPI.
|
||||
return []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"
|
||||
{Resolution: "2880x1800", Label: "2880 × 1800"},
|
||||
}, "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
|
||||
usableW, usableH := primary.WorkWidth, primary.WorkHeight
|
||||
if usableW <= 0 || usableH <= 0 {
|
||||
usableW = primary.Width
|
||||
usableH = primary.Height - defaultTaskbarPoints*scale/100
|
||||
}
|
||||
usableH -= windowTitleBarPoints * scale / 100
|
||||
|
||||
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})
|
||||
sizes := presetSizes16x9
|
||||
if math.Abs(float64(primary.Width)/float64(primary.Height)-1.6) < 0.08 {
|
||||
sizes = presetSizes16x10
|
||||
}
|
||||
|
||||
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})
|
||||
var fit [][2]int
|
||||
for i := len(sizes) - 1; i >= 0; i-- {
|
||||
if sizes[i][0] <= usableW && sizes[i][1] <= usableH {
|
||||
fit = append(fit, sizes[i])
|
||||
}
|
||||
}
|
||||
if len(fit) == 0 {
|
||||
fit = [][2]int{sizes[0]} // a screen smaller than every size: the window shrinks to fit
|
||||
}
|
||||
if len(fit) > maxDisplayPresetCount {
|
||||
fit = fit[:maxDisplayPresetCount]
|
||||
}
|
||||
|
||||
out := make([]DisplayPreset, 0, len(list))
|
||||
for _, c := range list {
|
||||
out := make([]DisplayPreset, 0, len(fit))
|
||||
rec := -1
|
||||
for i, sz := range fit {
|
||||
hidpi := GuestStartsHiDPI(sz[0], sz[1], scale)
|
||||
if hidpi && rec < 0 {
|
||||
rec = i
|
||||
}
|
||||
out = append(out, DisplayPreset{
|
||||
Resolution: c.res,
|
||||
Label: c.label,
|
||||
HiDPI: c.hidpi,
|
||||
Recommended: c.res == rec,
|
||||
Resolution: fmt.Sprintf("%dx%d", sz[0], sz[1]),
|
||||
Label: fmt.Sprintf("%d × %d", sz[0], sz[1]),
|
||||
HiDPI: hidpi,
|
||||
})
|
||||
}
|
||||
return out, rec
|
||||
if rec < 0 {
|
||||
rec = 0
|
||||
}
|
||||
out[rec].Recommended = true
|
||||
return out, out[rec].Resolution
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package host
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -9,42 +10,93 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGuestStartsHiDPI(t *testing.T) {
|
||||
cases := []struct {
|
||||
w, h, scale int
|
||||
want bool
|
||||
}{
|
||||
{1920, 1080, 200, false}, // too small at any scale: the case of a 1x desktop on a 200% screen
|
||||
{2048, 1536, 150, true}, // smallest HiDPI window above 160 ppi
|
||||
{2047, 1536, 200, false},
|
||||
{2560, 1440, 200, false}, // 1440 high is under 1536
|
||||
{2560, 1600, 150, true},
|
||||
{2880, 1800, 145, false}, // 145% is exactly 160 ppi, not above
|
||||
{2880, 1800, 125, false},
|
||||
{3200, 1800, 100, false},
|
||||
{3840, 2160, 100, true}, // any density from 3840 x 2160
|
||||
{3840, 2152, 100, false},
|
||||
{2880, 1800, 0, false}, // unknown scale counts as 1x
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := GuestStartsHiDPI(c.w, c.h, c.scale); got != c.want {
|
||||
t.Errorf("GuestStartsHiDPI(%d, %d, %d%%) = %v, want %v", c.w, c.h, c.scale, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecommendDisplayPresets(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
primary *DisplayInfo
|
||||
wantRec string
|
||||
wantHi bool
|
||||
name string
|
||||
primary *DisplayInfo
|
||||
wantRec string
|
||||
wantHi bool
|
||||
wantSizes []string
|
||||
advice string
|
||||
}{
|
||||
{
|
||||
name: "4K at 150%",
|
||||
primary: &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, Primary: true},
|
||||
wantRec: "3840x2160",
|
||||
wantHi: true,
|
||||
name: "3072x1920 at 200%, as a Retina remote display",
|
||||
primary: &DisplayInfo{Width: 3072, Height: 1920, ScalePct: 200, WorkWidth: 3072, WorkHeight: 1824},
|
||||
wantRec: "2560x1600",
|
||||
wantHi: true,
|
||||
wantSizes: []string{"2560x1600", "1920x1200", "1680x1050", "1280x800"},
|
||||
},
|
||||
{
|
||||
name: "2K 16:9 at 125%",
|
||||
primary: &DisplayInfo{Width: 2560, Height: 1440, ScalePct: 125, Primary: true},
|
||||
wantRec: "2560x1440",
|
||||
wantHi: false,
|
||||
name: "4K at 150%",
|
||||
primary: &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, WorkWidth: 3840, WorkHeight: 2088},
|
||||
wantRec: "3200x1800",
|
||||
wantHi: true,
|
||||
wantSizes: []string{"3200x1800", "2880x1620", "2560x1440", "1920x1080"},
|
||||
},
|
||||
{
|
||||
name: "2.5K 16:10 at 150%",
|
||||
primary: &DisplayInfo{Width: 2560, Height: 1600, ScalePct: 150, Primary: true},
|
||||
wantRec: "2560x1600",
|
||||
wantHi: true,
|
||||
// No window fits 3840 x 2160, the one size HiDPI at 100%; full screen is.
|
||||
name: "4K at 100%",
|
||||
primary: &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 100, WorkWidth: 3840, WorkHeight: 2112},
|
||||
wantRec: "3200x1800",
|
||||
wantHi: false,
|
||||
wantSizes: []string{"3200x1800", "2880x1620", "2560x1440", "1920x1080"},
|
||||
advice: HiDPIAdviceFullscreen,
|
||||
},
|
||||
{
|
||||
name: "1080p at 100%",
|
||||
primary: &DisplayInfo{Width: 1920, Height: 1080, ScalePct: 100, Primary: true},
|
||||
wantRec: "1920x1080",
|
||||
wantHi: false,
|
||||
name: "2.5K 16:10 laptop at 150%",
|
||||
primary: &DisplayInfo{Width: 2560, Height: 1600, ScalePct: 150, WorkWidth: 2560, WorkHeight: 1528},
|
||||
wantRec: "1920x1200",
|
||||
wantHi: false,
|
||||
wantSizes: []string{"1920x1200", "1680x1050", "1280x800"},
|
||||
// The whole 2560 x 1600 screen is HiDPI at 150%.
|
||||
advice: HiDPIAdviceFullscreen,
|
||||
},
|
||||
{
|
||||
name: "nil fallback",
|
||||
primary: nil,
|
||||
wantRec: "1920x1080",
|
||||
wantHi: false,
|
||||
name: "1080p at 100%, work area unknown",
|
||||
primary: &DisplayInfo{Width: 1920, Height: 1080, ScalePct: 100},
|
||||
wantRec: "1600x900",
|
||||
wantHi: false,
|
||||
wantSizes: []string{"1600x900", "1280x720"},
|
||||
advice: HiDPIAdviceUnavailable,
|
||||
},
|
||||
{
|
||||
name: "2880x1800 laptop at 100%",
|
||||
primary: &DisplayInfo{Width: 2880, Height: 1800, ScalePct: 100, WorkWidth: 2880, WorkHeight: 1752},
|
||||
wantRec: "2560x1600",
|
||||
wantHi: false,
|
||||
wantSizes: []string{"2560x1600", "1920x1200", "1680x1050", "1280x800"},
|
||||
advice: HiDPIAdviceScale,
|
||||
},
|
||||
{
|
||||
name: "nil fallback",
|
||||
primary: nil,
|
||||
wantRec: "1920x1080",
|
||||
wantHi: false,
|
||||
wantSizes: []string{"1920x1080", "2560x1440", "2880x1800"},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -54,23 +106,34 @@ func TestRecommendDisplayPresets(t *testing.T) {
|
||||
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
|
||||
var sizes []string
|
||||
recs := 0
|
||||
for _, p := range presets {
|
||||
sizes = append(sizes, p.Resolution)
|
||||
var w, h int
|
||||
_, _ = fmt.Sscanf(p.Resolution, "%dx%d", &w, &h)
|
||||
scale := 0
|
||||
if tc.primary != nil {
|
||||
scale = tc.primary.ScalePct
|
||||
}
|
||||
if p.HiDPI != (tc.primary != nil && GuestStartsHiDPI(w, h, scale)) {
|
||||
t.Errorf("%s HiDPI = %v disagrees with GuestStartsHiDPI", p.Resolution, p.HiDPI)
|
||||
}
|
||||
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)
|
||||
recs++
|
||||
if p.Resolution != tc.wantRec || p.HiDPI != tc.wantHi {
|
||||
t.Errorf("recommended %s HiDPI=%v, want %s HiDPI=%v", p.Resolution, p.HiDPI, tc.wantRec, tc.wantHi)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !foundRec {
|
||||
t.Fatalf("no preset marked recommended")
|
||||
if recs != 1 {
|
||||
t.Errorf("%d presets recommended, want 1", recs)
|
||||
}
|
||||
if fmt.Sprint(sizes) != fmt.Sprint(tc.wantSizes) {
|
||||
t.Errorf("sizes = %v, want %v", sizes, tc.wantSizes)
|
||||
}
|
||||
if got := HiDPIAdvice(tc.primary, presets); got != tc.advice {
|
||||
t.Errorf("HiDPIAdvice = %q, want %q", got, tc.advice)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ var (
|
||||
procGetDC = user32.NewProc("GetDC")
|
||||
procReleaseDC = user32.NewProc("ReleaseDC")
|
||||
|
||||
gdi32 = syscall.NewLazyDLL("gdi32.dll")
|
||||
gdi32 = syscall.NewLazyDLL("gdi32.dll")
|
||||
procGetDeviceCaps = gdi32.NewProc("GetDeviceCaps")
|
||||
|
||||
shcore = syscall.NewLazyDLL("shcore.dll")
|
||||
@@ -34,11 +34,11 @@ type winRect struct {
|
||||
}
|
||||
|
||||
type monitorInfoExW struct {
|
||||
Size uint32
|
||||
Monitor winRect
|
||||
Work winRect
|
||||
Flags uint32
|
||||
Device [32]uint16
|
||||
Size uint32
|
||||
Monitor winRect
|
||||
Work winRect
|
||||
Flags uint32
|
||||
Device [32]uint16
|
||||
}
|
||||
|
||||
type devModeW struct {
|
||||
@@ -116,13 +116,22 @@ func probeDisplays() []DisplayInfo {
|
||||
}
|
||||
|
||||
if w > 0 && h > 0 {
|
||||
// The work area in the same units as the monitor rectangle (pixels for a
|
||||
// DPI-aware process, scaled points otherwise), carried over to w x h.
|
||||
var workW, workH int
|
||||
if monW, monH := int(mi.Monitor.Right-mi.Monitor.Left), int(mi.Monitor.Bottom-mi.Monitor.Top); monW > 0 && monH > 0 {
|
||||
workW = int(mi.Work.Right-mi.Work.Left) * w / monW
|
||||
workH = int(mi.Work.Bottom-mi.Work.Top) * h / monH
|
||||
}
|
||||
displays = append(displays, DisplayInfo{
|
||||
Name: name,
|
||||
Width: w,
|
||||
Height: h,
|
||||
ScalePct: scalePct,
|
||||
RefreshHz: refresh,
|
||||
Primary: mi.Flags&monitorInfoPrimary != 0,
|
||||
Name: name,
|
||||
Width: w,
|
||||
Height: h,
|
||||
ScalePct: scalePct,
|
||||
RefreshHz: refresh,
|
||||
Primary: mi.Flags&monitorInfoPrimary != 0,
|
||||
WorkWidth: workW,
|
||||
WorkHeight: workH,
|
||||
})
|
||||
}
|
||||
return 1
|
||||
|
||||
@@ -9,10 +9,11 @@ import (
|
||||
|
||||
// Drive is a disk a data folder could go on.
|
||||
type Drive struct {
|
||||
Root string `json:"root"`
|
||||
FreeGB float64 `json:"free_gb"`
|
||||
System bool `json:"system"`
|
||||
External bool `json:"external"`
|
||||
Root string `json:"root"`
|
||||
FreeGB float64 `json:"free_gb"`
|
||||
System bool `json:"system"`
|
||||
External bool `json:"external"`
|
||||
VolumeGUID string `json:"volume_guid,omitempty"`
|
||||
}
|
||||
|
||||
// ListDrives returns the home directory's volume on dev/preview hosts.
|
||||
|
||||
@@ -13,18 +13,20 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
procGetLogicalDrives = kernel32.NewProc("GetLogicalDrives")
|
||||
procGetDriveTypeW = kernel32.NewProc("GetDriveTypeW")
|
||||
procGetLogicalDrives = kernel32.NewProc("GetLogicalDrives")
|
||||
procGetDriveTypeW = kernel32.NewProc("GetDriveTypeW")
|
||||
procGetVolumeNameForVolumeMountPointW = kernel32.NewProc("GetVolumeNameForVolumeMountPointW")
|
||||
)
|
||||
|
||||
const driveFixed = 3 // DRIVE_FIXED
|
||||
|
||||
// Drive is a local fixed disk a data folder could go on.
|
||||
type Drive struct {
|
||||
Root string `json:"root"` // `D:\`
|
||||
FreeGB float64 `json:"free_gb"` // bytes available to this user
|
||||
System bool `json:"system"` // holds Windows
|
||||
External bool `json:"external"` // on a USB bus (Windows still calls USB disks "fixed")
|
||||
Root string `json:"root"` // `D:\`
|
||||
FreeGB float64 `json:"free_gb"` // bytes available to this user
|
||||
System bool `json:"system"` // holds Windows
|
||||
External bool `json:"external"` // on a USB bus (Windows still calls USB disks "fixed")
|
||||
VolumeGUID string `json:"volume_guid,omitempty"` // stable volume identity; letters can be reassigned
|
||||
}
|
||||
|
||||
// ListDrives returns local fixed drives (no removable, network or optical).
|
||||
@@ -53,15 +55,31 @@ func ListDrives() []Drive {
|
||||
continue
|
||||
}
|
||||
out = append(out, Drive{
|
||||
Root: root,
|
||||
FreeGB: free,
|
||||
System: strings.EqualFold(root[:2], sys),
|
||||
External: isUSB(root[:2]),
|
||||
Root: root,
|
||||
FreeGB: free,
|
||||
System: strings.EqualFold(root[:2], sys),
|
||||
External: isUSB(root[:2]),
|
||||
VolumeGUID: volumeGUID(root),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func volumeGUID(root string) string {
|
||||
p, err := syscall.UTF16PtrFromString(root)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
buf := make([]uint16, 50)
|
||||
r, _, _ := procGetVolumeNameForVolumeMountPointW.Call(
|
||||
uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)),
|
||||
)
|
||||
if r == 0 {
|
||||
return ""
|
||||
}
|
||||
return syscall.UTF16ToString(buf)
|
||||
}
|
||||
|
||||
// isUSB asks the volume's storage device for its bus type
|
||||
// (IOCTL_STORAGE_QUERY_PROPERTY, StorageDeviceProperty). Opening with no
|
||||
// access rights needs no elevation.
|
||||
|
||||
@@ -13,6 +13,9 @@ func TestListDrivesFindsTheSystemDrive(t *testing.T) {
|
||||
if d.External {
|
||||
t.Error("system drive reported as USB")
|
||||
}
|
||||
if d.VolumeGUID == "" {
|
||||
t.Error("system drive has no volume GUID")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sys {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
// ForegroundPID is not implemented off Windows and always reports no owner.
|
||||
func ForegroundPID() uint32 { return 0 }
|
||||
@@ -0,0 +1,17 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import "unsafe"
|
||||
|
||||
// ForegroundPID returns the process that owns the foreground window, or 0
|
||||
// when there is none (locked screen, desktop focused).
|
||||
func ForegroundPID() uint32 {
|
||||
hwnd, _, _ := procGetForegroundWindow.Call()
|
||||
if hwnd == 0 {
|
||||
return 0
|
||||
}
|
||||
var pid uint32
|
||||
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
|
||||
return pid
|
||||
}
|
||||
+11
-8
@@ -35,11 +35,11 @@ type WHPXCapabilities struct {
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
LogicalCPUs int `json:"logical_cpus"`
|
||||
PhysicalCores int `json:"physical_cores"`
|
||||
HasHybridCores bool `json:"has_hybrid_cores"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
LogicalCPUs int `json:"logical_cpus"`
|
||||
PhysicalCores int `json:"physical_cores"`
|
||||
HasHybridCores bool `json:"has_hybrid_cores"`
|
||||
PCoreCount int `json:"p_core_count"`
|
||||
ECoreCount int `json:"e_core_count"`
|
||||
LPECoreCount int `json:"lpe_core_count,omitempty"`
|
||||
@@ -50,9 +50,9 @@ type Report struct {
|
||||
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
|
||||
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
|
||||
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
|
||||
TotalRAMGB float64 `json:"total_ram_gb"`
|
||||
AvailRAMGB float64 `json:"avail_ram_gb"`
|
||||
MemoryLoadPct int `json:"memory_load_pct"`
|
||||
TotalRAMGB float64 `json:"total_ram_gb"`
|
||||
AvailRAMGB float64 `json:"avail_ram_gb"`
|
||||
MemoryLoadPct int `json:"memory_load_pct"`
|
||||
// Commit memory: QEMU commits all guest RAM at start (CreateFileMapping), so
|
||||
// a VM needs its memory free in the commit charge, not just in physical RAM.
|
||||
// Measured 2026-11-28: 14.7 GiB commit free with 17.3 GiB physical free, and a
|
||||
@@ -71,6 +71,9 @@ type Report struct {
|
||||
PrimaryDisplay *DisplayInfo `json:"primary_display,omitempty"`
|
||||
RecommendedResolution string `json:"recommended_resolution,omitempty"`
|
||||
DisplayPresets []DisplayPreset `json:"display_presets,omitempty"`
|
||||
HiDPIAdvice string `json:"hidpi_advice,omitempty"` // how to reach HiDPI when no preset does (display.go)
|
||||
FullscreenHiDPI bool `json:"fullscreen_hidpi"` // a borderless window on the primary screen is HiDPI
|
||||
ProcessorScheduling string `json:"processor_scheduling,omitempty"` // "programs" or "background" (scheduling.go)
|
||||
Audio AudioInfo `json:"audio"`
|
||||
}
|
||||
|
||||
|
||||
@@ -103,6 +103,9 @@ func Inspect(dataRoot string) Report {
|
||||
rep.Displays = probeDisplays()
|
||||
rep.PrimaryDisplay = PrimaryDisplayOf(rep.Displays)
|
||||
rep.DisplayPresets, rep.RecommendedResolution = RecommendDisplayPresets(rep.PrimaryDisplay)
|
||||
rep.HiDPIAdvice = HiDPIAdvice(rep.PrimaryDisplay, rep.DisplayPresets)
|
||||
rep.FullscreenHiDPI = FullscreenStartsHiDPI(rep.PrimaryDisplay)
|
||||
rep.ProcessorScheduling = probeProcessorScheduling()
|
||||
rep.Audio = ProbeAudio()
|
||||
return rep
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrOtherProcess: the PID now names a process other than the one expected.
|
||||
var ErrOtherProcess = errors.New("pid belongs to another process")
|
||||
|
||||
// WaitProcessExit is not implemented off Windows; callers fall back to polling.
|
||||
func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error {
|
||||
return errors.ErrUnsupported
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
procWaitForSingleObject = kernel32.NewProc("WaitForSingleObject")
|
||||
procQueryFullProcessImageNameW = kernel32.NewProc("QueryFullProcessImageNameW")
|
||||
)
|
||||
|
||||
const (
|
||||
processSynchronize = 0x00100000
|
||||
errorInvalidParameter syscall.Errno = 87 // ERROR_INVALID_PARAMETER: no process with that PID
|
||||
waitObject0 = 0x00000000
|
||||
waitTimeoutCode = 0x00000102
|
||||
// waitSliceMs is how long one wait blocks before checking ctx; the exit
|
||||
// itself is reported the moment it happens.
|
||||
waitSliceMs = 1000
|
||||
)
|
||||
|
||||
// ErrOtherProcess: the PID now names a process other than the one expected.
|
||||
var ErrOtherProcess = errors.New("pid belongs to another process")
|
||||
|
||||
// WaitProcessExit blocks until process pid exits and returns nil, or returns
|
||||
// ctx.Err() once ctx ends. A process already gone counts as exited. When
|
||||
// imageSuffix is set the process's image path must end with it (case
|
||||
// insensitive), else ErrOtherProcess: a guard against a reused PID.
|
||||
func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error {
|
||||
if pid == 0 {
|
||||
return errors.New("no pid")
|
||||
}
|
||||
h, _, err := procOpenProcess.Call(uintptr(processSynchronize|processQueryLimitedInfo), 0, uintptr(pid))
|
||||
if h == 0 {
|
||||
if errno, ok := err.(syscall.Errno); ok && errno == errorInvalidParameter {
|
||||
return nil // no such process: it has exited
|
||||
}
|
||||
return fmt.Errorf("open process %d: %w", pid, err)
|
||||
}
|
||||
defer procCloseHandle.Call(h)
|
||||
|
||||
// An exited process another handle keeps alive opens fine but has no
|
||||
// image name to read: settle that first.
|
||||
if r, _, _ := procWaitForSingleObject.Call(h, 0); r == waitObject0 {
|
||||
return nil
|
||||
}
|
||||
if imageSuffix != "" {
|
||||
var buf [syscall.MAX_PATH * 2]uint16
|
||||
size := uint32(len(buf))
|
||||
if r, _, err := procQueryFullProcessImageNameW.Call(h, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size))); r == 0 {
|
||||
return fmt.Errorf("image name of process %d: %w", pid, err)
|
||||
}
|
||||
if !strings.HasSuffix(strings.ToLower(syscall.UTF16ToString(buf[:size])), strings.ToLower(imageSuffix)) {
|
||||
return ErrOtherProcess
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
r, _, err := procWaitForSingleObject.Call(h, waitSliceMs)
|
||||
switch r {
|
||||
case waitObject0:
|
||||
return nil
|
||||
case waitTimeoutCode:
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("wait for process %d: %w", pid, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func startPing(t *testing.T, pings string) *exec.Cmd {
|
||||
t.Helper()
|
||||
cmd := exec.Command("ping", "-n", pings, "127.0.0.1")
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() })
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestWaitProcessExitReturnsWhenTheProcessEnds(t *testing.T) {
|
||||
cmd := startPing(t, "30")
|
||||
pid := uint32(cmd.Process.Pid)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- WaitProcessExit(context.Background(), pid, "ping.exe") }()
|
||||
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
killedAt := time.Now()
|
||||
if err := cmd.Process.Kill(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("WaitProcessExit = %v", err)
|
||||
}
|
||||
// The exit is signalled, not found by the next wait slice.
|
||||
if d := time.Since(killedAt); d > 500*time.Millisecond {
|
||||
t.Fatalf("noticed the exit after %v", d)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("WaitProcessExit did not return after the process was killed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitProcessExitStopsWithContext(t *testing.T) {
|
||||
cmd := startPing(t, "30")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
err := WaitProcessExit(ctx, uint32(cmd.Process.Pid), "")
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("err = %v, want deadline exceeded", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitProcessExitChecksTheImage(t *testing.T) {
|
||||
cmd := startPing(t, "30")
|
||||
err := WaitProcessExit(context.Background(), uint32(cmd.Process.Pid), "qemu-system-x86_64.exe")
|
||||
if !errors.Is(err, ErrOtherProcess) {
|
||||
t.Fatalf("err = %v, want ErrOtherProcess", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitProcessExitOnAGoneProcess(t *testing.T) {
|
||||
cmd := exec.Command("cmd", "/c", "exit")
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
// Its PID is free (or, rarely, reused by something that is not ping).
|
||||
if err := WaitProcessExit(ctx, uint32(cmd.Process.Pid), "ping.exe"); err != nil && !errors.Is(err, ErrOtherProcess) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package host
|
||||
|
||||
// Windows "Processor scheduling" (System Properties > Advanced > Performance >
|
||||
// Advanced): Programs gives the foreground window's process longer CPU
|
||||
// quanta, Background services gives every process the same fixed quanta.
|
||||
const (
|
||||
SchedulingPrograms = "programs"
|
||||
SchedulingBackground = "background"
|
||||
)
|
||||
|
||||
// SchedulingFromPrioritySeparation reads the setting from the registry's
|
||||
// Win32PrioritySeparation value: its low two bits are the foreground quantum
|
||||
// boost, which Programs sets (0x26 from that dialog, 0x2 on a fresh install)
|
||||
// and Background services clears (0x18).
|
||||
func SchedulingFromPrioritySeparation(v uint32) string {
|
||||
if v&0x3 != 0 {
|
||||
return SchedulingPrograms
|
||||
}
|
||||
return SchedulingBackground
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// ErrElevationDeclined: the person said no at the UAC prompt.
|
||||
var ErrElevationDeclined = errors.New("UAC prompt declined")
|
||||
|
||||
func probeProcessorScheduling() string { return "" }
|
||||
|
||||
func OpenPerformanceOptionsElevated() error {
|
||||
return fmt.Errorf("processor scheduling is a Windows setting (current OS: %s)", runtime.GOOS)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package host
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSchedulingFromPrioritySeparation(t *testing.T) {
|
||||
cases := map[uint32]string{
|
||||
0x26: SchedulingPrograms, // Programs, as the dialog writes it
|
||||
0x02: SchedulingPrograms, // a fresh client install
|
||||
0x18: SchedulingBackground, // Background services
|
||||
0x00: SchedulingBackground,
|
||||
}
|
||||
for v, want := range cases {
|
||||
if got := SchedulingFromPrioritySeparation(v); got != want {
|
||||
t.Errorf("0x%02x: %q, want %q", v, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
regDWORD = 4
|
||||
priorityControlKey = `SYSTEM\CurrentControlSet\Control\PriorityControl`
|
||||
prioritySeparationValue = "Win32PrioritySeparation"
|
||||
// ShellExecuteW's result when the person declines the UAC prompt.
|
||||
seErrAccessDenied = 5
|
||||
)
|
||||
|
||||
// ErrElevationDeclined: the person said no at the UAC prompt.
|
||||
var ErrElevationDeclined = errors.New("UAC prompt declined")
|
||||
|
||||
// probeProcessorScheduling returns SchedulingPrograms or SchedulingBackground,
|
||||
// or "" where the value cannot be read. Reading needs no elevation.
|
||||
func probeProcessorScheduling() string {
|
||||
v, ok := regReadDWORD(hkeyLocalMachine, priorityControlKey, prioritySeparationValue)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return SchedulingFromPrioritySeparation(v)
|
||||
}
|
||||
|
||||
// OpenPerformanceOptionsElevated opens System Properties' Performance Options
|
||||
// through a UAC prompt, so the processor scheduling choice saves without a
|
||||
// second prompt. It returns once the dialog is launched.
|
||||
func OpenPerformanceOptionsElevated() error {
|
||||
verb, _ := syscall.UTF16PtrFromString("runas")
|
||||
file, _ := syscall.UTF16PtrFromString("SystemPropertiesPerformance.exe")
|
||||
r, _, err := procShellExecuteW.Call(0, uintptr(unsafe.Pointer(verb)), uintptr(unsafe.Pointer(file)), 0, 0, 1 /* SW_SHOWNORMAL */)
|
||||
switch {
|
||||
case r == seErrAccessDenied:
|
||||
return ErrElevationDeclined
|
||||
case r <= 32:
|
||||
return fmt.Errorf("ShellExecuteW runas SystemPropertiesPerformance failed (code %d): %w", r, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func regReadDWORD(root uintptr, subKey, valueName string) (uint32, bool) {
|
||||
sk, err := syscall.UTF16PtrFromString(subKey)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
var hKey uintptr
|
||||
if r, _, _ := procRegOpenKeyExW.Call(root, uintptr(unsafe.Pointer(sk)), 0, keyRead, uintptr(unsafe.Pointer(&hKey))); r != 0 {
|
||||
return 0, false
|
||||
}
|
||||
defer procRegCloseKey.Call(hKey)
|
||||
vn, err := syscall.UTF16PtrFromString(valueName)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
var typ uint32
|
||||
var v uint32
|
||||
size := uint32(unsafe.Sizeof(v))
|
||||
r, _, _ := procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&v)), uintptr(unsafe.Pointer(&size)))
|
||||
if r != 0 || typ != regDWORD {
|
||||
return 0, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user