Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6367d17216 | ||
|
|
460de66ac4 | ||
|
|
338a9ee220 | ||
|
|
eb2b102bd5 | ||
|
|
7697374132 | ||
|
|
b839242716 | ||
|
|
181d952388 | ||
|
|
7abcc64e6f | ||
|
|
0934d9d206 | ||
|
|
003e4a08e7 | ||
|
|
704f68cdce | ||
|
|
ab49d79a71 | ||
|
|
c0f08be124 | ||
|
|
dac10a52bc | ||
|
|
b007f6b445 | ||
|
|
48e75ca665 | ||
|
|
9c8a75448d | ||
|
|
3b26f6117f | ||
|
|
f5ec733230 | ||
|
|
7641a7c948 | ||
|
|
1276050569 | ||
|
|
8acc0c3c23 | ||
|
|
172df5c4d5 | ||
|
|
f85e1aba88 | ||
|
|
a7921e998b | ||
|
|
24f29f806f | ||
|
|
33ac322bb2 | ||
|
|
5000e00780 | ||
|
|
d21ee22c80 | ||
|
|
99e189bef2 | ||
|
|
0ad5652ecd | ||
|
|
4cf1e8ea37 | ||
|
|
31a72892de | ||
|
|
12fa25d089 | ||
|
|
181ad64618 | ||
|
|
1017301682 |
No files matched your search
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 41 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 39 KiB |
@@ -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 -RequireSlim `
|
||||
-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,25 +217,46 @@ 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') |
|
||||
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$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).
|
||||
|
||||
Local patches applied (sources and patches are in the attached source packages):
|
||||
$applied$merged
|
||||
|
||||
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
|
||||
|
||||
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
|
||||
"@
|
||||
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
|
||||
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
|
||||
- name: 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:
|
||||
|
||||
@@ -26,6 +26,19 @@ jobs:
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Verify CHANGELOG.md matches current version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go'
|
||||
if ($verFile -notmatch 'var\s+Version\s*=\s*"(v[^"]+)"') {
|
||||
throw 'Could not parse Version from internal/version/version.go'
|
||||
}
|
||||
$ver = $Matches[1]
|
||||
$tmp = Join-Path $env:RUNNER_TEMP "release-notes-$ver.md"
|
||||
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
|
||||
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
|
||||
|
||||
- name: Frontend build
|
||||
shell: pwsh
|
||||
run: |
|
||||
|
||||
@@ -18,6 +18,8 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
@@ -40,6 +42,39 @@ jobs:
|
||||
if (-not $tag.StartsWith('v')) { throw "Release tag must start with 'v', got: $tag" }
|
||||
"RELEASE_TAG=$tag" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Generate release notes from CHANGELOG.md
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$runtimeTag = ''
|
||||
$runtimeTitle = ''
|
||||
try {
|
||||
$rels = gh release list -R $env:GITHUB_REPOSITORY --limit 100 --json tagName,name,isPrerelease,isDraft,createdAt | ConvertFrom-Json
|
||||
$stable = $rels |
|
||||
Where-Object { $_.tagName -like 'runtime-*' -and -not $_.isPrerelease -and -not $_.isDraft } |
|
||||
Sort-Object createdAt -Descending |
|
||||
Select-Object -First 1
|
||||
if ($stable) {
|
||||
$runtimeTag = $stable.tagName
|
||||
$runtimeTitle = if ($stable.name) { $stable.name } else { $stable.tagName }
|
||||
}
|
||||
} catch {
|
||||
Write-Warning "Could not query latest stable runtime release: $_"
|
||||
}
|
||||
$notesFile = Join-Path $env:RUNNER_TEMP "release-notes-$tag.md"
|
||||
& ./scripts/build-release-notes.ps1 `
|
||||
-Tag $tag `
|
||||
-ChangelogPath 'CHANGELOG.md' `
|
||||
-Repo $env:GITHUB_REPOSITORY `
|
||||
-StableRuntimeTag $runtimeTag `
|
||||
-StableRuntimeTitle $runtimeTitle `
|
||||
-OutFile $notesFile
|
||||
"RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
Write-Host "Generated release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag"
|
||||
|
||||
- name: Build frontend
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -67,8 +102,11 @@ jobs:
|
||||
# One executable: the window without arguments, command-line mode with a command.
|
||||
$guiOut = Join-Path $dist "reims-go-$tag-windows-amd64.exe"
|
||||
wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$tag" -o "reims-go-$tag-windows-amd64.exe"
|
||||
if ($LASTEXITCODE) { throw "wails build failed ($LASTEXITCODE)" }
|
||||
Copy-Item (Join-Path 'build\bin' "reims-go-$tag-windows-amd64.exe") $guiOut
|
||||
$lines = @(Get-ChildItem -LiteralPath $dist -File | Sort-Object Name | ForEach-Object {
|
||||
$zipOut = [IO.Path]::ChangeExtension($guiOut, '.zip')
|
||||
Compress-Archive -LiteralPath $guiOut -DestinationPath $zipOut -CompressionLevel Optimal -Force
|
||||
$lines = @(Get-Item -LiteralPath $guiOut, $zipOut | ForEach-Object {
|
||||
$h = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()
|
||||
"$h $($_.Name)"
|
||||
})
|
||||
@@ -82,18 +120,35 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$notesFile = $env:RELEASE_NOTES_FILE
|
||||
if (-not (Test-Path -LiteralPath $notesFile) -or (Get-Item -LiteralPath $notesFile).Length -eq 0) {
|
||||
throw "Release notes file is missing or empty: $notesFile"
|
||||
}
|
||||
$files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName)
|
||||
$exists = $true
|
||||
$existingBody = ''
|
||||
try {
|
||||
gh release view $tag *> $null
|
||||
if ($LASTEXITCODE -ne 0) { $exists = $false }
|
||||
$relJson = gh release view $tag --json body 2>$null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
$exists = $false
|
||||
} else {
|
||||
$existingBody = (($relJson | ConvertFrom-Json).body | Out-String).Trim()
|
||||
}
|
||||
} catch {
|
||||
$exists = $false
|
||||
}
|
||||
if ($exists) {
|
||||
gh release upload $tag @files --clobber
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release upload failed ($LASTEXITCODE)" }
|
||||
# Backfill notes if the existing release body is empty or only GitHub's auto-generated compare link.
|
||||
$isAutoOnly = [string]::IsNullOrWhiteSpace($existingBody) -or ($existingBody -match '^\*\*Full Changelog\*\*:\s*https://\S+$')
|
||||
if ($isAutoOnly) {
|
||||
gh release edit $tag --notes-file $notesFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" }
|
||||
}
|
||||
} else {
|
||||
gh release create $tag @files `
|
||||
--title "Reims-Go $tag" `
|
||||
--generate-notes
|
||||
--notes-file $notesFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
}
|
||||
@@ -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
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
## 开源合规边界
|
||||
|
||||
- `reims-go` 自身代码(Go 后端 + 前端外壳)采用 **MIT** 协议,见 [`LICENSE`](LICENSE)。
|
||||
- `reims-go` 自身代码(Go 后端 + 前端外壳)采用 **Apache-2.0** 协议,见 [`LICENSE`](LICENSE)。
|
||||
- 运行时组件(`qemu-system-x86_64.exe` 为 GPLv2,`reims-ctl` / `reims-vgpu` / `metal2vulkan` 为 `GPL-2.0-or-later OR LGPL-3.0-or-later`,以及 CLANG64/libva 动态库)以**独立子进程与独立运行时压缩包**形态集成。发布二进制时必须同时提供**对应源码包**(含本地补丁,只给上游链接不够)和完整许可证文本(`NOTICE.md` / `licenses/`),见 `docs/portable-runtime-spec.md` 第 7 节。
|
||||
- 不打包、不托管任何 Apple 系统文件;macOS 恢复镜像一律由用户端运行 `reims-util` 直连 Apple 服务器拉取或本地导入。
|
||||
- macOS 的软件许可只允许在 Apple 硬件上虚拟化。上游也处在同样的位置,但一键工具公开发布会放大风险。**是否公开发布由人决定**,在此之前 Release 保持私有。
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# 更新日志
|
||||
|
||||
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
|
||||
|
||||
## v0.2.6 — 2026-11-29
|
||||
|
||||
### 新功能
|
||||
|
||||
- **独立 CPU 绑核**:每台虚拟机可单独选择自动、全部核心、性能核、避开低功耗核或自定义核心组合,运行中修改立即生效,派生副本时自动继承。
|
||||
- **离线恢复点**:支持在关机状态下为虚拟磁盘创建、回滚与删除恢复点。
|
||||
- **SSH 快捷工具**:支持记住 SSH 用户名,一键打开终端、写入 `~/.ssh/config` 或通过 VS Code Remote-SSH 连接。
|
||||
- **窗口控制、截图与文件拖放**:支持一键前置虚拟机窗口、复制全分辨率屏幕截图到剪贴板,以及把文件直接拖进应用窗口传到共享文件夹。
|
||||
- **虚拟机显示名称与页面改版**:支持点击标题就地修改显示名称(保留底层标识名),宽窗口下预览与规格摘要并排呈现;围绕当前状态突出主操作,整合 Guest Tools 与磁盘/网络/实时负载摘要。
|
||||
- **标题栏菜单与可折叠侧栏**:新增标题栏菜单(虚拟机 / 视图 / 帮助,带快捷键)和 `Ctrl+B` 侧栏折叠,支持侧栏虚拟机右键菜单,状态栏信息更加精简。
|
||||
- **系统托盘菜单改版**:每台虚拟机拥有独立子菜单与状态圆点,自动跟随 Windows 系统浅/深色主题,后台操作失败或复制截图时通过系统通知提示。
|
||||
- **macOS 版本图标与「安装包」页改版**:记录虚拟机创建时的 macOS 版本并在侧栏和未截屏预览中展示对应版本数字图标;「安装包」页按大版本归组卡片、折叠旧小版本并新增重试按钮。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- **内存与资源回收优化**:删除虚拟机或退出时及时释放缩略图锁、Guest Tools 注册与 WebDAV 处理器、远程键入队列、监控协程和绑核记录;4K 屏幕预览改用按行流式缩放,大幅降低内存分配;串口与 QEMU 日志监控限制单行缓存上限。
|
||||
- **前端渲染与包体优化**:次级页面与弹窗改为按需懒加载,单机统计轮询下沉至虚拟机页以减少整页重绘,定期清理过期任务记录,并移除不透明区域的冗余毛玻璃合成层。
|
||||
- **修复空间分布统计**:修正虚拟机目录路径(`reims-ctl/vms`),并将数据目录内其余文件一并归入 Reims-Go 空间分布。
|
||||
- **开源协议与发行包调整**:Reims-Go 本体协议由 MIT 变更为 Apache-2.0;Release 同时提供 `.zip` 压缩包与独立 `.exe`,并自动依据 `CHANGELOG.md` 生成发布说明。
|
||||
|
||||
## 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 上虚拟机内部重启时自动冷重启。
|
||||
@@ -1,21 +1,200 @@
|
||||
MIT License
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Copyright (c) 2026 Reims-Go contributors
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
1. Definitions.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate acts) or agreed
|
||||
to in writing, shall any Contributor be liable to You for damages,
|
||||
including any direct, indirect, special, incidental, or consequential
|
||||
damages of any character arising as a result of this License or out of
|
||||
the use or inability to use the Work (including but not limited to damages
|
||||
for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Reims-Go contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,9 +1,9 @@
|
||||
# Third-Party Notices
|
||||
|
||||
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the MIT
|
||||
License (see `LICENSE`). That license applies to Reims-Go's own code only and
|
||||
is separate from the portable runtime bundle it invokes as an external child
|
||||
process.
|
||||
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the Apache
|
||||
License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own code
|
||||
only and is separate from the portable runtime bundle it invokes as an external
|
||||
child process.
|
||||
|
||||
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
|
||||
precompiled binaries built from the following upstream open-source projects.
|
||||
|
||||
@@ -20,12 +20,12 @@
|
||||
<br />
|
||||
|
||||
<p align="center">
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机详情页与深色外观下的宿主与运行时页" />
|
||||
<img src="./.github/readme/hero.webp" width="100%" alt="Reims-Go 主窗口:浅色外观下的虚拟机页与深色外观下的内核页" />
|
||||
</p>
|
||||
|
||||
<br />
|
||||
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。环境体检、运行时安装、下载 macOS 到创建并管理虚拟机,都在一个窗口里完成。
|
||||
Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows 桌面应用。从检查电脑、安装运行时、下载 macOS,到创建和日常使用虚拟机,都在一个窗口里完成。
|
||||
|
||||
> 早期迭代中,功能与界面仍在持续打磨。
|
||||
|
||||
@@ -33,11 +33,43 @@ Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows
|
||||
|
||||
## 特性
|
||||
|
||||
- **开箱即用** — 预编译便携运行时一键在线安装,无需配置 MSYS2、Rust 或本地编译。
|
||||
- **体检与调优** — 一键启用 WHPX、启动前校验提交内存、混合架构智能绑核(P-Core / 避开 LP-E 核),新建默认 NVMe。
|
||||
- **离线装机** — 宿主机直连 Apple 断点续传下载;内置离线辅助盘与「粘贴为键入」,装机无需手敲长命令。
|
||||
- **随时调整** — 运行中即可修改配置并标明生效时机,支持一键进出恢复模式;全部数据留在指定目录,不占 C 盘。
|
||||
- **双端一致** — 浅色 / 深色外观与中英双语,GUI 与命令行共用同一套内核。
|
||||
### 开箱即用
|
||||
|
||||
- **不用编译** — 运行时在应用里一键下载安装,不用装 MSYS2、Rust,也不用自己编译。GitHub 连不上时自动改从 GitCode 国内镜像下载,并沿用 Windows 的系统代理设置。
|
||||
- **先检查再开工** — 首次打开会检查虚拟化、显卡和内存;虚拟化没开的话可以一键开启。
|
||||
- **不占 C 盘** — 运行时、安装包、虚拟磁盘和临时文件都放在你选的数据目录里。
|
||||
|
||||
### 装机
|
||||
|
||||
- **安装包直接从 Apple 下载** — 在 Windows 上下载完整安装包,可以暂停和续传;装机过程不用联网。
|
||||
- **不用手敲命令** — 装机命令点一下就自动键入到 macOS 的恢复终端,抹盘和安装都会自动完成。
|
||||
- **按本机配置推荐** — 内存大小按电脑的空闲内存推荐,分辨率按显示器和缩放推荐清晰的 HiDPI 档位。
|
||||
- **装机界面用中文** — 可以提前选好 macOS 系统语言,恢复模式和设置助理不再只有英文。
|
||||
- **导入已有磁盘** — 新建时可以直接用现成的 VMDK 或 RAW 磁盘。
|
||||
|
||||
### 日常使用
|
||||
|
||||
- **和 Windows 互通** — 双向剪贴板(包括图片)和共享文件夹,把文件拖到窗口里就能传进 macOS;还可以把 Windows 磁盘以只读方式共享给 macOS。
|
||||
- **直接打中文** — 中文、emoji 和 Windows 输入法都能直接输入到虚拟机。
|
||||
- **一眼看清状态** — 页面上有屏幕预览,以及 CPU、内存、磁盘的实时占用;一键截屏并复制。
|
||||
- **常驻托盘** — 关掉窗口后剪贴板和共享照常工作,可以从托盘启动或关闭虚拟机,也可以让 macOS 保持唤醒。
|
||||
- **随时修改设置** — 虚拟机运行时也能改设置,界面会说明改动是立即生效还是下次启动生效;一键进入或退出恢复模式。
|
||||
- **浅色、深色外观,中英双语**。
|
||||
|
||||
### 性能
|
||||
|
||||
- **显卡加速** — 用 Windows 上的独立显卡加速 macOS 的图形显示。
|
||||
- **自动挑选性能核** — 在大小核处理器上,虚拟机自动跑在性能核上,减少卡顿;也可以给每台虚拟机单独指定用哪些核,运行中修改立即生效。
|
||||
- **启动前检查内存** — 内存不够时会先提示,避免启动到一半失败。
|
||||
|
||||
### 进阶
|
||||
|
||||
- **秒级派生副本** — 已关机的虚拟机可以秒级派生出一台独立副本,副本只记录与原机的差异,刚派生时几乎不占额外空间。
|
||||
- **恢复点** — 升级系统或大改环境前留一个恢复点,出问题时一键回滚。
|
||||
- **磁盘管理** — 关机后可以给虚拟磁盘扩容,或回收没有用到的空间。
|
||||
- **SSH** — 端口转发,一键打开终端、写入 `~/.ssh/config` 或用 VS Code 远程连接。
|
||||
- **命令行** — 检查环境、安装运行时、下载安装包,以及新建、修改、启动和关闭虚拟机,都能在命令行里完成,方便写脚本。
|
||||
- **排障** — 一键导出已去掉隐私信息的日志包;Windows 10 上 macOS 自己重启时也能正常回到系统。
|
||||
|
||||
<br />
|
||||
|
||||
@@ -45,9 +77,10 @@ Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Windows 10 / 11(64 位),支持 WHPX 虚拟化
|
||||
- Windows 10 / 11(64 位),处理器支持虚拟化,并已在 BIOS 里开启 Intel VT-x / AMD-V
|
||||
- 支持 Vulkan 的独立显卡(推荐 NVIDIA RTX 系列)
|
||||
- 150 GB 以上可用磁盘空间(建议非 C 盘)
|
||||
- 内存建议 16 GB 以上
|
||||
- 可用磁盘空间建议 150 GB 以上,至少 60 GB(一个安装包约 20 GB,虚拟磁盘会随使用增长);最好不要放在系统盘或外置盘
|
||||
|
||||
### 安装
|
||||
|
||||
@@ -70,24 +103,26 @@ wails build
|
||||
|
||||
### 上手步骤
|
||||
|
||||
1. **初始化** — 首次打开按引导选好数据目录、完成宿主机体检(未开 WHPX 可一键启用并重启),在线安装运行时。
|
||||
2. **新建虚拟机** — 点侧边栏 **+**,选择「离线安装包(推荐)」或先在「安装包」页下载镜像,设定 CPU、内存与磁盘。
|
||||
3. **安装 macOS** — 启动后在恢复终端点右侧键盘图标一键键入安装命令,脚本会自动抹盘并完成离线安装;看到「设置助理」后点「退出恢复模式」。
|
||||
4. **日常管理** — 点齿轮图标随时调整设置,或在「更多」菜单中使用「粘贴为键入」与「进入恢复模式」。
|
||||
1. **初始化** — 首次打开时按引导选好数据目录,完成电脑检查(虚拟化没开可以一键开启,之后需要重启 Windows),再在线安装运行时。
|
||||
2. **新建虚拟机** — 点侧边栏的 **+**,安装来源选「离线安装包」(也可以先到「安装包」页下载好),再设好 CPU、内存和磁盘。
|
||||
3. **安装 macOS** — 启动虚拟机,按页面上的装机引导操作:在恢复终端里点键盘图标,装机命令会自动键入,抹盘和安装随即开始;看到「设置助理」后点「退出恢复模式」。
|
||||
4. **安装 Guest Tools** — 进入 macOS 桌面后,在虚拟机页 Guest Tools 一行点「安装…」,再到 macOS 终端里运行页面给出的命令。装好后剪贴板、共享文件夹和中文输入就能用了。
|
||||
5. **日常管理** — 设置、恢复点和 SSH 都在虚拟机页上;「更多」菜单里还有发送文本、进入恢复模式、派生副本、导出排障日志等操作。
|
||||
|
||||
### 命令行
|
||||
|
||||
命令行模式就在同一个 `reims-go.exe` 里:不带参数打开窗口,带子命令就在终端里执行。
|
||||
命令行就在同一个 `reims-go.exe` 里:不带参数会打开窗口,带上子命令就在终端里执行。
|
||||
|
||||
```powershell
|
||||
reims-go doctor | Out-Host # 环境体检
|
||||
reims-go doctor | Out-Host # 检查电脑环境
|
||||
reims-go runtime fetch | Out-Host # 在线安装运行时
|
||||
reims-go installer download tahoe | 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 vm start macos-tahoe | Out-Host # 启动虚拟机
|
||||
reims-go vm stop macos-tahoe | Out-Host # 关闭虚拟机
|
||||
```
|
||||
|
||||
`reims-go.exe` 是窗口程序,交互式 PowerShell / cmd 不会等它结束;加 `| Out-Host`(或任何管道、重定向)就会等命令执行完并给出退出码。脚本和 Agent 通过管道调用,不受影响。运行 `reims-go help` 查看全部子命令,加 `--lang en-US` 切换英文输出。
|
||||
在 PowerShell 或 cmd 里直接输入命令时,要加上 `| Out-Host`,终端才会等命令执行完再返回。运行 `reims-go help` 可以查看全部子命令,加 `--lang en-US` 会改成英文输出。
|
||||
|
||||
<br />
|
||||
|
||||
@@ -98,16 +133,16 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/host-dark.webp" />
|
||||
<img src="./.github/readme/host-light.webp" alt="宿主与运行时页" />
|
||||
<img src="./.github/readme/host-light.webp" alt="内核页" />
|
||||
</picture>
|
||||
<p align="center"><sub>宿主与运行时</sub></p>
|
||||
<p align="center"><sub>内核</sub></p>
|
||||
</td>
|
||||
<td width="50%">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./.github/readme/vm-dark.webp" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="关于此虚拟机页" />
|
||||
<img src="./.github/readme/vm-light.webp" alt="虚拟机页" />
|
||||
</picture>
|
||||
<p align="center"><sub>关于此虚拟机</sub></p>
|
||||
<p align="center"><sub>虚拟机</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -132,9 +167,21 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机(交给托盘
|
||||
|
||||
## 许可与声明
|
||||
|
||||
- **开源协议**:Reims-Go 本体采用 [MIT](./LICENSE) 协议;独立调用的便携运行时组件及其许可证见 [`NOTICE.md`](./NOTICE.md),每个运行时 Release 均附带对应源码包。
|
||||
- **开源协议**:Reims-Go 本身采用 [Apache-2.0](./LICENSE) 协议。运行时里的 QEMU 等组件作为独立程序随附,各自的许可证见 [`NOTICE.md`](./NOTICE.md);每个运行时 Release 都附带对应的源码包。
|
||||
- **关于 macOS**:Reims-Go 不包含、不分发任何 Apple 系统文件,安装包由本机直连 Apple 服务器获取。**macOS 软件许可协议仅允许在 Apple 硬件上虚拟化**,在非 Apple 硬件上使用请自行评估合规责任。本项目与 Apple Inc. 无关,macOS 为 Apple Inc. 注册商标。
|
||||
|
||||
## 友情链接
|
||||
|
||||
- [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,50 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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 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:
|
||||
}
|
||||
}
|
||||
@@ -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 盘的依赖;
|
||||
|
||||
@@ -91,7 +91,7 @@ flowchart TB
|
||||
- 指定了 `--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 的其余编排仍在根目录的 `App`(`app.go`)和各个 `*_flow.go` 里:CoW 派生(`clone_flow.go`)、磁盘扩容与回收(`disk_flow.go`)、运行监视与里程碑日志(`vm_monitor.go`)。
|
||||
- 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` 转发端口,没有命令执行通道。
|
||||
|
||||
@@ -99,9 +99,9 @@ flowchart TB
|
||||
|
||||
```text
|
||||
reims-go/
|
||||
├── main.go # 唯一入口:无参数启动 Wails 界面,带子命令走 internal/cli
|
||||
├── window_launch.go # 界面处理 --background / --start-vm 与第二次启动
|
||||
├── 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 端中英双语消息字典与结构化错误码
|
||||
@@ -117,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/
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# 内存占用审计(2026-11-29)
|
||||
|
||||
## 范围与结论
|
||||
|
||||
本轮检查了 Reims-Go 的 Go 后端、React 前端、Guest Tools、QMP 截图和 VM 启停链路,并采样已运行的桌面应用,使用无磁盘 WHPX 虚拟机和 4K 图像分别测量 QEMU 启动占用与预览开销。用户的 macOS 虚拟机处于关机状态。
|
||||
|
||||
已确认并修复 Reims-Go 按 VM 生命周期无界保留的状态:缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、磁盘路径、绑核 PID、远程文本队列及其 worker。删除 VM 时立即回收;通过 CLI 或外部工具删除时,由 VM 轮询回收。日志和任务列表也有上限或过期清理。
|
||||
|
||||
本机 macOS VM 的配置与上次启动日志均记录了 8 GiB 客体内存。检查时 Windows 可用提交内存约 7.2 GiB,低于启动器对该 VM 要求的 9 GiB(含 1 GiB 余量)。QEMU 和 vGPU 在固定 macOS 图形负载下是否会持续增长,待验证。
|
||||
|
||||
## 测量与修复
|
||||
|
||||
- 在 macOS VM 关机时,每 15 秒采样一次,共 11 次。Reims-Go 主进程的私有提交为 59.9–60.5 MiB,其进程树中的 6 个 WebView2 进程合计 282.6–286.3 MiB。数值来自修复前已在运行的桌面程序。
|
||||
- 用本机便携运行时(`3731afd`)启动无磁盘、无网络的 WHPX 测试机,依次配置 512、1024、512 MiB 内存。各轮第 10 秒的 QEMU 私有提交为 537.2、1049.9、537.3 MiB,工作集为 46.8、46.8、46.9 MiB,三次 QMP 退出的进程退出码均为 0。此测试覆盖固件空载阶段。
|
||||
- 后台监视串口和 QEMU 日志时,旧实现遇到一直没有换行的输出会持续拼接并保留整行。现在每行暂存上限为 64 KiB,过长行跳到下一个换行,原始日志文件完整保留。
|
||||
- 前端会在已结束任务超过 10 分钟后清理任务记录及通知去重标记,与后端保留时间一致。运行中的任务持续显示。
|
||||
- 用相同的 3840×2160 PPM 文件生成宽 640 像素的 JPEG,各测 8 帧。`BenchmarkPreview4K` 在原版本(`704f68c`)每帧分配 56.4 MiB,按行缩放后为 1.04 MiB,下降约 98%。这是单帧累计 Go 分配量。手动复制截图仍保留全分辨率,并按行将 RGB 转为 RGBA。
|
||||
- VM 详情原先随每次宿主状态刷新重新调用 `reims-ctl show`,包含窗口可见时每 10 秒一次的轮询。现在只随选择、运行/过渡状态和显式 `reims:state-changed` 事件重取,配置保存后的刷新语义保持不变。
|
||||
- Go 的 RSS 在 GC 后不必然立即下降;只有保留对象持续增长才证明泄漏。不要为了压低任务管理器数字在热路径加入 `debug.FreeOSMemory`。
|
||||
|
||||
## 实机复测建议
|
||||
|
||||
使用同一 VM、固定客体负载和同一分辨率,在启动稳定后、1 小时、4 小时分别记录 QEMU 与 Reims-Go 进程树的 Private Bytes、Working Set 和句柄数。期间分别覆盖打开/隐藏 Reims-Go 窗口、切换 VM、截图、复制大图片和客体睡眠唤醒。
|
||||
|
||||
若 QEMU Private Bytes 在固定负载下持续线性增长,再按运行时 manifest 中的 commit 和补丁进行上游定位。既有 `qemu-win32-coroutine-fiber-commit.patch` 将每个协程栈初始提交从 1 MiB 降为 64 KiB,但仍是待真机验证的补丁,且不会改变 Guest RAM 的基础占用。
|
||||
|
||||
## 验证
|
||||
|
||||
- `go test ./...`:通过。
|
||||
- `pnpm --dir frontend run build`:通过;仅有既存的 Vite 大 chunk 提示。
|
||||
- 临时启用 CGO 并使用本机 MSYS2 CLANG64,`go test -race ./...` 通过。
|
||||
@@ -41,7 +41,14 @@
|
||||
|
||||
## 3. 便携运行时体积与目录规范
|
||||
|
||||
本机实测未压缩体积:**917.8 MB**(`qemu/` 828.5 MB + `reims-ctl.exe` 58.0 MB + `reims-util.exe` 31.3 MB);2026-11-28 实测使用 `zstd -T0 -15` 打包 `reims-runtime-win-x64-3731afd.tar.zst` 后仅 **`160.4 MB`**(压缩率 **17.5%**,不到同类 PySide6 打包方案 1.68 GB 的十分之一)。
|
||||
已发布的 `runtime-3731afd` 是未裁剪、保留调试符号的历史基线:本机实测未压缩体积 **917.8 MB**,`zstd -T0 -15` 压缩包 **160.4 MB**。下文的新布局不改变这个既有 Release 的内容。
|
||||
|
||||
2026-11-29 起,新打包流程采用以下两项可复现的体积优化:
|
||||
|
||||
1. 只删除 Windows x64 启动器不会调用的通用工具 `qemu-system-x86_64.exe`、`elf2dmp.exe`、`qemu-edid.exe`、`qemu-io.exe`、`qemu-nbd.exe`、`qemu-storage-daemon.exe`,以及 ARM64、RISC-V、LoongArch64 的 EDK2 固件及其描述文件。x64 固件、BIOS、ROM、keymaps、动态加载的 `libva` 视频驱动和全部 DLL 均保留。
|
||||
2. 对五个主要可执行文件使用 MSYS2 CLANG64 的 `llvm-objcopy` 提取调试符号、剥离 `.debug_*` 节并写入 GNU debug link。对应的 `.debug` 文件单独发布,不丢失崩溃定位能力。通用 DLL 的符号仍保留。
|
||||
|
||||
同一上游 `3731afd` 和相同两项本地补丁的暂存实验结果为:删除上述工具和异架构固件后 **425.3 MiB** 解压 / **98.3 MiB** 压缩;再剥离主要程序调试符号后 **166.4 MiB** 解压 / **48.0 MiB** 压缩。前者与旧包的目录统计口径略有差异,最终以实际归档解压结果为准。
|
||||
|
||||
### 3.1 运行时发布包结构(`reims-runtime-win-x64-<commit>.tar.zst`)
|
||||
|
||||
@@ -60,9 +67,11 @@ reims-runtime-<commit>/
|
||||
│ ├── qemu-img.exe
|
||||
│ ├── reims-vgpu-compile.exe
|
||||
│ └── *.dll # 71 个自包含 CLANG64 + libva/vaon12 DLL
|
||||
└── share/ # QEMU pc-bios / edk2 / keymaps 等数据文件
|
||||
└── share/ # x64 pc-bios / edk2 / keymaps 等数据文件
|
||||
```
|
||||
|
||||
同一 Release 另有 `reims-runtime-symbols-<commit>.tar.zst`,按运行时相同路径保存五个 `*.exe.debug` 文件。`manifest.json` 的 `symbols_package` 指向该附件,`sha256` 记录最终已剥离程序的哈希。GNU 调试器可通过程序内的 debug link 和符号包目录定位对应文件。调试符号包不参与客户端下载。
|
||||
|
||||
> **版本耦合约束**:`reims-ctl.exe`、`reims-util.exe` 与 `qemu/` 必须来自**同一个上游 commit**,作为单一版本目录原子安装与回滚,避免协议或内嵌 kext 版本错配。
|
||||
|
||||
### 3.2 用户数据目录结构(由用户在向导中选择,默认非系统盘如 `D:\Data\reims-go\`)
|
||||
@@ -89,17 +98,17 @@ reims-runtime-<commit>/
|
||||
## 4. 打包与发布流水线(M0 / M4)
|
||||
|
||||
- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。
|
||||
- **本地打包与发布(2026-11-28 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出三个文件:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、覆盖两者的 `SHA256SUMS.txt`。补丁按 `patches/series.txt` 的顺序取,`-Patches` 可以只列实际打上的那几个。
|
||||
- **本地打包与发布(2026-11-29 起)**:`pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出四个压缩包及 `SHA256SUMS.txt`:运行时包、对应源码包 `reims-runtime-src-<commit>.tar.zst`、MSYS2 源码包和可选调试符号包。补丁按 `patches/series.txt` 的顺序取,`-Patches` 可以只列实际打上的那几个。
|
||||
- **打包前的检查**:脚本先核对每个补丁是否与构建目录里的 diff 完全一致;不一致、或者构建目录里有补丁没涉及的文件被改动,就直接停止,不会自动修改补丁。允许改动的文件从补丁本身读出(2026-11-28 前写死为 `whpx-all.c`,带上 fiber 补丁就会误报)。
|
||||
- **manifest 版本 2**:比版本 1 多记录 `vendor_qemu_commit`、`util_commit`、`metal2vulkan_commit`、`patches`(名称、作用对象、SHA256)、`channel`、`source_package`。`dll_count` 改为按实际文件统计;版本 1 的统计有误,记为 0。
|
||||
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件就是上面三个文件。GitHub 的预发布对应 `alpha`(2026-11-28 前叫 `candidate`),正式发布对应 `stable`。三个附件缺任何一个,客户端就不会列出这个版本。
|
||||
- **发布位置**:运行时发布在 [`Nwflower/reims-go`](https://github.com/Nwflower/reims-go/releases) 的 GitHub Release。tag 为 `runtime-<commit>`,附件包含上述四个压缩包和校验清单。GitHub 的预发布对应 `alpha`(2026-11-28 前叫 `candidate`),正式发布对应 `stable`。客户端下载仍只需要运行时包与校验清单,因此旧客户端也可安装新布局。
|
||||
- **客户端安装**(`internal/runtime/remote.go`):从 GitHub API 列出版本 → 下载运行时包,支持续传 → 对照 `SHA256SUMS.txt` 校验,不一致就丢弃 → 用原有的导入流程解压并激活 → 删除下载的压缩包。
|
||||
- **已发布**:`runtime-3731afd`,先以候选版(即现在的 alpha)发布,同日升为稳定版。实测从 GitHub 下载 169 MB、校验、解压、激活,全程约 75 秒。
|
||||
- **自动化 CI(M4,2026-11-28 改为每日自动构建)**:[`build-runtime.yml`](../.github/workflows/build-runtime.yml) 每天 03:23 UTC 运行,也可手动触发并指定上游 commit。流程:
|
||||
1. 取上游默认分支的 HEAD。已有 `runtime-<commit>` 的 Release(alpha 或 stable)就跳过,所以上游不动时不消耗构建时间。
|
||||
2. 在 `windows-latest` 上用 MSYS2 CLANG64,由 `scripts/apply-patch-series.ps1` 按 `patches/series.txt` 逐个处理补丁:能打上就打;反向检查通过(上游已经包含)就跳过并提醒退役;两者都不行就停止,不改补丁(AGENTS.md 规则 4)。
|
||||
3. 执行上游 `scripts/install-ctl.sh --yes`,再用 `pack-runtime.ps1 -Channel alpha -Patches <实际打上的补丁>` 打包,manifest 只写实际打上的补丁(规则 5)。
|
||||
4. `scripts/check-runtime-alpha.ps1` 做 alpha 准入检查(第 6 节),通过后发布为 GitHub 预发布,附件四个缺一不可。
|
||||
4. `scripts/check-runtime-alpha.ps1` 做 alpha 准入检查(第 6 节),通过后发布为 GitHub 预发布,五个附件缺一不可。
|
||||
5. 只保留最近 7 个未升级的 alpha 预发布,更早的连同 tag 删除;正式发布不受影响。
|
||||
6. 构建失败、或有补丁已被上游合并时,在本仓库开一个 issue(已有同名的未关闭 issue 就追加评论)。
|
||||
|
||||
@@ -114,6 +123,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 |
|
||||
@@ -144,7 +154,7 @@ reims-runtime-<commit>/
|
||||
|
||||
| 通道 | 来源 | 进入条件 |
|
||||
| :--- | :--- | :--- |
|
||||
| `alpha` | CI 每天从上游最新 commit 自动构建并打补丁(2026-11-28 前叫 `candidate`,当时是人工指定 commit) | 由 `scripts/check-runtime-alpha.ps1` 自动检查:能构建;四个附件齐全;`SHA256SUMS.txt` 覆盖三个压缩包且校验一致;manifest 的 commit、通道、补丁与实际一致;在不含 MSYS2 的 PATH 下 `qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci` |
|
||||
| `alpha` | CI 每天从上游最新 commit 自动构建并打补丁(2026-11-28 前叫 `candidate`,当时是人工指定 commit) | 由 `scripts/check-runtime-alpha.ps1` 自动检查:能构建;新布局的五个附件齐全;`SHA256SUMS.txt` 覆盖四个压缩包且校验一致;manifest 的 commit、通道、补丁、五个最终可执行文件哈希及符号包一致;视频驱动和许可证文件齐全;在不含 MSYS2 的 PATH 下列出 `reims-graphics-pci`,执行 CLI 版本检查及 qcow2 创建、读取。`-RequireSlim` 用于强制新布局,省略时仍可检查历史包 |
|
||||
| `stable` | 从 `alpha` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 |
|
||||
|
||||
`reims-go` 客户端默认只拉 `stable`,`alpha` 要用户主动打开(界面开关「接收 Alpha 版」,CLI `--alpha`)。旧配置里的 `runtime_channel: "candidate"` 读作 `alpha`,CLI 的 `--candidate` 保留为 `--alpha` 的别名。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。
|
||||
@@ -172,4 +182,4 @@ reims-runtime-<commit>/
|
||||
- **内容**:`repo.msys2.org/mingw/sources/` 上原样的 `<base>-<version>.src.tar.zst`,内含 PKGBUILD、上游源码和 MSYS2 的补丁。每个都附 `.sig` 签名文件;打包时用 `gpgv` 和 MSYS2 密钥逐个校验,校验不过就停止。同时附一份 README,列出全部 55 个包的许可证,以及哪些附了源码。
|
||||
- **`runtime-3731afd` 的结果**:22 个源码包,110 MB,签名全部通过。下载的源码缓存在 `D:\Data\reims-go\releases\msys2-sources-cache`,下次打包会复用。
|
||||
|
||||
`reims-go` 外壳用 MIT,前提是它和这些组件只通过独立进程交互,不链接它们。
|
||||
`reims-go` 外壳用 Apache-2.0,前提是它和这些组件只通过独立进程交互,不链接它们。
|
||||
@@ -134,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 键位提示;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.2.3",
|
||||
"version": "0.2.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,7 +9,9 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.2.1",
|
||||
"@radix-ui/react-context-menu": "^2.4.1",
|
||||
"@radix-ui/react-dialog": "^1.3.1",
|
||||
"@radix-ui/react-dropdown-menu": "^2.2.1",
|
||||
"@radix-ui/react-toast": "^1.3.1",
|
||||
|
||||
@@ -1 +1 @@
|
||||
f71dbd21d10dd124677343ad731d7f59
|
||||
f38f2bbc623190aed99c112f7b10c276
|
||||
@@ -8,9 +8,15 @@ 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)
|
||||
'@radix-ui/react-context-menu':
|
||||
specifier: ^2.4.1
|
||||
version: 2.4.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)
|
||||
'@radix-ui/react-dialog':
|
||||
specifier: ^1.3.1
|
||||
version: 1.3.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 +311,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==}
|
||||
|
||||
@@ -372,6 +381,19 @@ packages:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-context-menu@2.4.1':
|
||||
resolution: {integrity: sha512-Pddn3Z8lio3/ChxyXaEP3jHTTo1LTHCWwF8+mG1chQlWijP+ttVHBKwezrQTiV6Mj670ojvumqvuGh+mdv33iQ==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
'@types/react-dom': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-context@1.3.0':
|
||||
resolution: {integrity: sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==}
|
||||
peerDependencies:
|
||||
@@ -1293,6 +1315,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
|
||||
@@ -1355,6 +1379,19 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
|
||||
'@radix-ui/react-context-menu@2.4.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)':
|
||||
dependencies:
|
||||
'@radix-ui/primitive': 1.2.0
|
||||
'@radix-ui/react-context': 1.3.0(@types/react@19.3.3)(react@19.3.1)
|
||||
'@radix-ui/react-menu': 2.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)
|
||||
'@radix-ui/react-primitive': 2.2.0(@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)
|
||||
'@radix-ui/react-use-controllable-state': 1.3.0(@types/react@19.3.3)(react@19.3.1)
|
||||
react: 19.3.1
|
||||
react-dom: 19.3.1(react@19.3.1)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react-dom': 19.3.0(@types/react@19.3.3)
|
||||
|
||||
'@radix-ui/react-context@1.3.0(@types/react@19.3.3)(react@19.3.1)':
|
||||
dependencies:
|
||||
react: 19.3.1
|
||||
|
||||
@@ -1,31 +1,44 @@
|
||||
import { Minus, Moon, Square, Sun, X } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { CreateWizard, WizardDraft } from './components/CreateWizard'
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { WizardDraft } from './components/CreateWizard'
|
||||
import { DeleteDialog } from './components/DeleteDialog'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import { HostView } from './components/HostView'
|
||||
import type { 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 { InstallersPage } from './components/InstallersPage'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
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 { macOSMajor } from './lib/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { latestVMStats } from './lib/vmStats'
|
||||
import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail } 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'
|
||||
import { OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime'
|
||||
|
||||
// Opened on demand, so each is its own chunk and stays out of the startup
|
||||
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
|
||||
// the Engine / Installers / Settings pages.
|
||||
const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard })))
|
||||
const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })))
|
||||
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
|
||||
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
|
||||
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
|
||||
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
|
||||
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
|
||||
const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '')
|
||||
|
||||
const failKey: Record<VMAction, I18nKey> = {
|
||||
start: 'failStart',
|
||||
focus: 'failFocus',
|
||||
screenshot: 'failScreenshot',
|
||||
stop: 'failStop',
|
||||
forceStop: 'failStop',
|
||||
restart: 'failRestart',
|
||||
@@ -49,25 +62,62 @@ export const App: React.FC = () => {
|
||||
const [state, setState] = useState<AppState | null>(null)
|
||||
const [selected, setSelected] = useState<string>(HOST_ID)
|
||||
const [detail, setDetail] = useState<VMDetail | null>(null)
|
||||
const [vmStats, setVmStats] = useState<VMStats | null>(null)
|
||||
const [detailRevision, setDetailRevision] = useState(0)
|
||||
const [showWizard, setShowWizard] = useState(false)
|
||||
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
|
||||
const [affinityVersion, setAffinityVersion] = useState(0)
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
|
||||
const [cloneSource, setCloneSource] = useState<string | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
const [dropping, setDropping] = useState(false)
|
||||
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')
|
||||
|
||||
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
|
||||
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
|
||||
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
|
||||
})
|
||||
const toggleSidebar = () => setSidebarOpen((open) => {
|
||||
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch {}
|
||||
return !open
|
||||
})
|
||||
|
||||
const [logsOpen, setLogsOpen] = useState(false)
|
||||
const [logTab, setLogTab] = useState<LogTab>('app')
|
||||
const [logLines, setLogLines] = useState<LogLine[]>([])
|
||||
@@ -78,21 +128,22 @@ export const App: React.FC = () => {
|
||||
logsOpenRef.current = logsOpen
|
||||
const [taskMap, setTaskMap] = useState<Record<string, Task>>({})
|
||||
const onTaskRef = useRef<(task: Task) => void>(() => {})
|
||||
const notifiedTasks = useRef(new Set<string>())
|
||||
const notifiedTasks = useRef(new Map<string, number>())
|
||||
const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null)
|
||||
|
||||
const toasts = useToasts()
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const refresh = useCallback(async (reloadDetail = false) => {
|
||||
try {
|
||||
const s = await api.GetState()
|
||||
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
|
||||
})
|
||||
if (reloadDetail) setDetailRevision((revision) => revision + 1)
|
||||
} catch (e) {
|
||||
setLoadError(errText(e))
|
||||
}
|
||||
@@ -100,7 +151,7 @@ export const App: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
const offState = events.onStateChanged(() => { refresh() })
|
||||
const offState = events.onStateChanged(() => { refresh(true) })
|
||||
// Logs never pop the panel open (docs/ui-redesign.md §5.2); errors only bump a badge.
|
||||
const offLog = events.onLog((entry) => {
|
||||
setLogLines((prev) => {
|
||||
@@ -117,28 +168,62 @@ 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()
|
||||
const cutoff = Date.now() - finishedTaskTTL
|
||||
setTaskMap((prev) => pruneFinishedTasks(prev, cutoff))
|
||||
for (const [id, updatedAt] of notifiedTasks.current) {
|
||||
if (updatedAt < cutoff) notifiedTasks.current.delete(id)
|
||||
}
|
||||
}, 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 }
|
||||
if (!selectedVM) { setDetail(null); return }
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [selectedVM?.name, state])
|
||||
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision])
|
||||
|
||||
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
|
||||
// name in the sidebar and page title; the name itself stays the identifier.
|
||||
const [displayNames, setDisplayNames] = useState<Record<string, string>>({})
|
||||
const vmNamesKey = vms.map((v) => v.name).join('|')
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setVmStats(null); return }
|
||||
let live = true
|
||||
const vmName = selectedVM.name
|
||||
const sample = () => {
|
||||
api.GetVMStats(vmName).then((st) => { if (live) setVmStats(st) }).catch(() => {})
|
||||
for (const vm of vms) {
|
||||
api.GetVMNote(vm.name)
|
||||
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) })
|
||||
.catch(() => {})
|
||||
}
|
||||
sample()
|
||||
const timer = window.setInterval(sample, 3000)
|
||||
return () => { live = false; window.clearInterval(timer) }
|
||||
}, [selectedVM?.name, selectedVM?.state])
|
||||
return () => { live = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [vmNamesKey])
|
||||
|
||||
// Each VM's macOS major version for its icon: the release recorded at
|
||||
// creation (.reims-go-macos), else a guess from its name or display name.
|
||||
const [releases, setReleases] = useState<Record<string, string>>({})
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
for (const vm of vms) {
|
||||
api.GetVMMacOS(vm.name)
|
||||
.then((r) => { if (live) setReleases((m) => ({ ...m, [vm.name]: (r ?? '').trim() })) })
|
||||
.catch(() => {})
|
||||
}
|
||||
return () => { live = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [vmNamesKey])
|
||||
const macosMajors: Record<string, number | null> = {}
|
||||
for (const vm of vms) macosMajors[vm.name] = macOSMajor(releases[vm.name], vm.name, displayNames[vm.name])
|
||||
|
||||
// Live VM stats are polled by lib/vmStats.ts and read where they are shown
|
||||
// (VMPage), so a 3-second tick no longer re-renders the whole App.
|
||||
|
||||
const locale: Locale = state?.config.locale ?? 'zh-CN'
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
@@ -150,7 +235,7 @@ export const App: React.FC = () => {
|
||||
// Toast once per finished download; only live events reach here, not the seed list.
|
||||
const notify = task.kind === 'installer-download' || task.kind === 'recovery-download' || task.kind === 'runtime-install'
|
||||
if (task.status !== 'running' && notify && !notifiedTasks.current.has(task.id)) {
|
||||
notifiedTasks.current.add(task.id)
|
||||
notifiedTasks.current.set(task.id, task.updated_at)
|
||||
const isRuntime = task.kind === 'runtime-install'
|
||||
const isRecovery = task.kind === 'recovery-download'
|
||||
if (task.status === 'done') {
|
||||
@@ -174,7 +259,10 @@ export const App: React.FC = () => {
|
||||
api.InstallRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e))
|
||||
}
|
||||
const setChannel = (alpha: boolean) => {
|
||||
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
|
||||
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 () => {
|
||||
@@ -293,12 +381,11 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
const name = selectedVM.name
|
||||
const isRunning = selectedVM.state === 'running'
|
||||
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(name, action, () => api.StartVM(name))
|
||||
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(name, action, () => api.RestartVM(name))
|
||||
@@ -324,6 +411,32 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
|
||||
}
|
||||
|
||||
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
|
||||
if (action === 'settings') {
|
||||
setSelected(name)
|
||||
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
return
|
||||
}
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
|
||||
onVMActionFor(name, action, st === 'running')
|
||||
}
|
||||
|
||||
// The state's own main action (Start, or Show Window while running), shared by
|
||||
// Ctrl+Enter and a double-click in the sidebar.
|
||||
const primaryAction = (name: string) => {
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
if (!vm || busy[name]) return
|
||||
const st = state?.transitions[name] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(name, 'start', false)
|
||||
else if (st === 'running') onVMActionFor(name, 'focus', true)
|
||||
}
|
||||
|
||||
const confirmDelete = (keepFiles: boolean) => {
|
||||
const name = deleteTarget
|
||||
setDeleteTarget(null)
|
||||
@@ -443,11 +556,13 @@ export const App: React.FC = () => {
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (showWizard || showSettings || deleteTarget || sendTextTarget) return
|
||||
if (showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget) return
|
||||
const k = e.key.toLowerCase()
|
||||
if (k === 'n') { e.preventDefault(); openWizard() }
|
||||
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
|
||||
else if (k === 'l') { e.preventDefault(); toggleLogs() }
|
||||
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
|
||||
}
|
||||
useEffect(() => {
|
||||
const h = (e: KeyboardEvent) => shortcutRef.current(e)
|
||||
@@ -455,33 +570,106 @@ export const App: React.FC = () => {
|
||||
return () => window.removeEventListener('keydown', h)
|
||||
}, [])
|
||||
|
||||
// Tray menu: "Show in Reims-Go" selects that VM; "New VM…" opens the wizard.
|
||||
// The backend has already brought the window to the front.
|
||||
const openWizardRef = useRef(openWizard)
|
||||
openWizardRef.current = openWizard
|
||||
useEffect(() => {
|
||||
const offSelect = events.onTraySelectVM((name) => { setSelected(name) })
|
||||
const offNew = events.onTrayNewVM(() => { openWizardRef.current() })
|
||||
return () => { offSelect(); offNew() }
|
||||
}, [])
|
||||
|
||||
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
|
||||
const dropTargetRef = useRef<{ name: string; ready: boolean }>({ name: '', ready: false })
|
||||
dropTargetRef.current = {
|
||||
name: selectedVM?.name ?? '',
|
||||
ready: !!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode,
|
||||
}
|
||||
useEffect(() => {
|
||||
let depth = 0
|
||||
const onEnter = (e: DragEvent) => {
|
||||
if (!dropTargetRef.current.ready) return
|
||||
if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) }
|
||||
}
|
||||
const onLeave = () => {
|
||||
depth = Math.max(0, depth - 1)
|
||||
if (depth === 0) setDropping(false)
|
||||
}
|
||||
const onDropEnd = () => { depth = 0; setDropping(false) }
|
||||
window.addEventListener('dragenter', onEnter)
|
||||
window.addEventListener('dragleave', onLeave)
|
||||
window.addEventListener('drop', onDropEnd)
|
||||
OnFileDrop((_x, _y, paths) => {
|
||||
depth = 0
|
||||
setDropping(false)
|
||||
const cur = dropTargetRef.current
|
||||
if (!cur.ready || !cur.name || !paths || paths.length === 0) return
|
||||
api.DeliverPathsToGuest(cur.name, paths)
|
||||
.then((delivered) => {
|
||||
if (!delivered || delivered.length === 0) return
|
||||
if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) })
|
||||
else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) })
|
||||
})
|
||||
.catch((e) => fail(tr('failGuestTools'), e))
|
||||
}, true)
|
||||
return () => {
|
||||
window.removeEventListener('dragenter', onEnter)
|
||||
window.removeEventListener('dragleave', onLeave)
|
||||
window.removeEventListener('drop', onDropEnd)
|
||||
OnFileDropOff()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="app-shell">
|
||||
<header className="titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
<div className="brand">
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
Reims-Go
|
||||
</div>
|
||||
{showSetup || !state ? (
|
||||
<div className="brand">
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
Reims-Go
|
||||
</div>
|
||||
) : (
|
||||
<TitleMenus
|
||||
locale={locale}
|
||||
sidebarOpen={sidebarOpen}
|
||||
onToggleSidebar={toggleSidebar}
|
||||
logsOpen={logsOpen}
|
||||
onToggleLogs={toggleLogs}
|
||||
themeMode={themeMode}
|
||||
onThemeMode={setThemeMode}
|
||||
vm={selectedVM ? { name: selectedVM.name, state: effectiveState, busy: !!busy[selectedVM.name] } : null}
|
||||
onNewVM={openWizard}
|
||||
onVMAction={onVMAction}
|
||||
onVMSettings={() => { if (detail) setShowSettings(true) }}
|
||||
onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }}
|
||||
onNavigate={setSelected}
|
||||
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
|
||||
appVersion={state.app_version}
|
||||
/>
|
||||
)}
|
||||
<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>
|
||||
|
||||
{showSetup && state ? (
|
||||
<Suspense fallback={null}>
|
||||
<Setup
|
||||
locale={locale}
|
||||
state={state}
|
||||
@@ -492,12 +680,14 @@ export const App: React.FC = () => {
|
||||
onFinish={() => setSetupStage(null)}
|
||||
onError={fail}
|
||||
onChannel={setChannel}
|
||||
onSource={setSource}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
onImportRuntime={importRuntime}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<div className="workspace">
|
||||
<div className={`workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
|
||||
<Sidebar
|
||||
locale={locale}
|
||||
vms={vms}
|
||||
@@ -505,12 +695,17 @@ export const App: React.FC = () => {
|
||||
selected={selected}
|
||||
hostReady={hostReady}
|
||||
onSelect={setSelected}
|
||||
displayNames={displayNames}
|
||||
macosMajors={macosMajors}
|
||||
onActivate={primaryAction}
|
||||
onNew={openWizard}
|
||||
onVMContextAction={onSidebarContextAction}
|
||||
downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')}
|
||||
/>
|
||||
|
||||
<main className="main">
|
||||
<div className="scroll">
|
||||
<Suspense fallback={null}>
|
||||
{!state ? (
|
||||
<div className="page">
|
||||
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
|
||||
@@ -528,14 +723,17 @@ export const App: React.FC = () => {
|
||||
<VMPage
|
||||
locale={locale}
|
||||
name={selectedVM.name}
|
||||
displayName={displayNames[selectedVM.name] ?? ''}
|
||||
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
|
||||
macosMajor={macosMajors[selectedVM.name] ?? null}
|
||||
state={effectiveState}
|
||||
detail={detail}
|
||||
stats={vmStats}
|
||||
host={state.host}
|
||||
pending={pending}
|
||||
busyAction={busy[selectedVM.name]}
|
||||
onAction={onVMAction}
|
||||
onSettings={() => setShowSettings(true)}
|
||||
onOpenAffinity={() => setAffinityTarget(selectedVM.name)}
|
||||
onDelete={() => setDeleteTarget(selectedVM.name)}
|
||||
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
||||
onCopy={copy}
|
||||
@@ -563,45 +761,68 @@ export const App: React.FC = () => {
|
||||
})
|
||||
.catch((e) => fail(tr('failGuestTools'), e))
|
||||
}}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
onError={fail}
|
||||
dropping={dropping}
|
||||
/>
|
||||
) : 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}
|
||||
onNewVM={openWizard}
|
||||
onError={fail}
|
||||
onSetLocale={setLang}
|
||||
runtimeTask={runtimeTask}
|
||||
onChannel={setChannel}
|
||||
onSource={setSource}
|
||||
onInstallRuntime={installRuntime}
|
||||
onCancelTask={cancelTask}
|
||||
/>
|
||||
)}
|
||||
</Suspense>
|
||||
</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}
|
||||
onCopy={copy}
|
||||
hostReady={hostReady}
|
||||
onOpenHost={() => setSelected(HOST_ID)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showWizard && state && (
|
||||
<Suspense fallback={null}>
|
||||
<CreateWizard
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
@@ -609,18 +830,22 @@ export const App: React.FC = () => {
|
||||
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
onSubmit={submitCreate}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{showSettings && state && detail && (
|
||||
<Suspense fallback={null}>
|
||||
<SettingsModal
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
stats={vmStats}
|
||||
stats={latestVMStats(detail.name)}
|
||||
host={state.host}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onCopy={copy}
|
||||
onDiskChanged={refresh}
|
||||
onOpenAffinity={() => setAffinityTarget(detail.name)}
|
||||
affinityVersion={affinityVersion}
|
||||
onClose={() => setShowSettings(false)}
|
||||
onSaved={() => {
|
||||
setShowSettings(false)
|
||||
@@ -628,6 +853,33 @@ export const App: React.FC = () => {
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{affinityTarget && state && (
|
||||
<Suspense fallback={null}>
|
||||
<AffinityDialog
|
||||
locale={locale}
|
||||
vmName={affinityTarget}
|
||||
vcpus={detail?.name === affinityTarget ? detail.cpus : 4}
|
||||
host={state.host}
|
||||
globalAutoPin={state.config.auto_pin_pcores}
|
||||
onClose={() => setAffinityTarget(null)}
|
||||
onApplied={(st) => {
|
||||
setAffinityTarget(null)
|
||||
setAffinityVersion((v) => v + 1)
|
||||
const count = st.effective_cpus?.length ?? 0
|
||||
const mask = st.live_mask_hex || st.effective_mask_hex || '0x0'
|
||||
toasts.push({
|
||||
kind: 'ok',
|
||||
title: st.running
|
||||
? tr('toastAffinityApplied', { count, mask })
|
||||
: tr('toastAffinitySaved'),
|
||||
})
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{deleteTarget && (
|
||||
@@ -657,7 +909,7 @@ export const App: React.FC = () => {
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendTextTarget}
|
||||
guestToolsConnected={Boolean(vmStats?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendTextTarget)?.guest_tools_connected ?? detail?.guest_tools_connected)}
|
||||
onCancel={() => setSendTextTarget(null)}
|
||||
onConfirm={(text) => {
|
||||
const target = sendTextTarget
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
import { AlertTriangle, Check, Cpu } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { HostReport, Locale, LogicalCPUInfo, VMAffinityMode, VMAffinityStatus } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
vmName: string
|
||||
vcpus: number
|
||||
host: HostReport
|
||||
globalAutoPin: boolean
|
||||
onClose: () => void
|
||||
onApplied: (status: VMAffinityStatus) => void
|
||||
}
|
||||
|
||||
function buildTopology(host: HostReport): LogicalCPUInfo[] {
|
||||
if (host.cpu_topology && host.cpu_topology.length > 0) {
|
||||
return host.cpu_topology
|
||||
}
|
||||
const n = Math.min(Math.max(host.logical_cpus || 1, 1), 64)
|
||||
return Array.from({ length: n }, (_, i) => ({
|
||||
index: i,
|
||||
core_index: i,
|
||||
tier: 'standard',
|
||||
smt: false,
|
||||
}))
|
||||
}
|
||||
|
||||
function maskHexFromCPUs(cpus: number[]): string {
|
||||
let mask = 0n
|
||||
for (const idx of cpus) {
|
||||
if (idx >= 0 && idx < 64) {
|
||||
mask |= 1n << BigInt(idx)
|
||||
}
|
||||
}
|
||||
return '0x' + mask.toString(16).toUpperCase()
|
||||
}
|
||||
|
||||
function resolveAutoPreview(topology: LogicalCPUInfo[], host: HostReport, globalAutoPin: boolean, vcpus: number): number[] {
|
||||
const all = topology.map((c) => c.index)
|
||||
if (!globalAutoPin || !host.has_hybrid_cores) return all
|
||||
const pCPUs = topology.filter((c) => c.tier === 'p').map((c) => c.index)
|
||||
if (pCPUs.length >= vcpus + 1 && pCPUs.length > 0) return pCPUs
|
||||
if ((host.lpe_core_count ?? 0) > 0) {
|
||||
const nonLPE = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index)
|
||||
if (nonLPE.length >= vcpus + 1 && nonLPE.length > 0) return nonLPE
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus | null): string {
|
||||
if (!status) return '—'
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const count = status.effective_cpus?.length ?? 0
|
||||
const mask = status.effective_mask_hex || '0x0'
|
||||
switch (status.mode) {
|
||||
case 'all':
|
||||
return tr('affinitySummaryAll', { count })
|
||||
case 'pcores':
|
||||
return tr('affinitySummaryPCores', { count, mask })
|
||||
case 'non_lpe':
|
||||
return tr('affinitySummaryNonLPE', { count, mask })
|
||||
case 'custom':
|
||||
return tr('affinitySummaryCustom', { count, mask })
|
||||
default: {
|
||||
const effLabel = status.effective_mode === 'pcores'
|
||||
? tr('affinityModePCores')
|
||||
: status.effective_mode === 'non_lpe'
|
||||
? tr('affinityModeNonLPE')
|
||||
: tr('affinityModeAll')
|
||||
return tr('affinitySummaryAuto', { eff: effLabel, count })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const AffinityDialog: React.FC<Props> = ({
|
||||
locale, vmName, vcpus, host, globalAutoPin, onClose, onApplied,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const topology = useMemo(() => buildTopology(host), [host])
|
||||
const allIndices = useMemo(() => topology.map((c) => c.index), [topology])
|
||||
const hasSMT = useMemo(() => topology.some((c) => c.smt), [topology])
|
||||
|
||||
const [status, setStatus] = useState<VMAffinityStatus | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
|
||||
const [mode, setMode] = useState<VMAffinityMode>('auto')
|
||||
const [selected, setSelected] = useState<number[]>(allIndices)
|
||||
const [disableEcoQoS, setDisableEcoQoS] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api.GetVMAffinity(vmName)
|
||||
.then((st) => {
|
||||
if (!live) return
|
||||
setStatus(st)
|
||||
setMode(st.mode || 'auto')
|
||||
const initial = st.mode === 'custom' && st.cpus?.length > 0
|
||||
? st.cpus
|
||||
: (st.effective_cpus?.length > 0 ? st.effective_cpus : allIndices)
|
||||
setSelected([...initial].sort((a, b) => a - b))
|
||||
setDisableEcoQoS(st.disable_eco_qos)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (live) setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
})
|
||||
.finally(() => {
|
||||
if (live) setLoading(false)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [vmName, allIndices])
|
||||
|
||||
const selectedSet = useMemo(() => new Set(selected), [selected])
|
||||
const effectiveVCPUs = status?.vcpus || vcpus
|
||||
const maskHex = useMemo(() => maskHexFromCPUs(selected), [selected])
|
||||
|
||||
const applyPreset = (nextMode: VMAffinityMode) => {
|
||||
setMode(nextMode)
|
||||
setErr('')
|
||||
switch (nextMode) {
|
||||
case 'all':
|
||||
setSelected(allIndices)
|
||||
break
|
||||
case 'pcores': {
|
||||
const list = topology.filter((c) => c.tier === 'p').map((c) => c.index)
|
||||
setSelected(list.length > 0 ? list : allIndices)
|
||||
break
|
||||
}
|
||||
case 'non_lpe': {
|
||||
const list = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index)
|
||||
setSelected(list.length > 0 ? list : allIndices)
|
||||
break
|
||||
}
|
||||
case 'auto':
|
||||
setSelected(resolveAutoPreview(topology, host, globalAutoPin, effectiveVCPUs))
|
||||
break
|
||||
case 'custom':
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const toggleCPU = (idx: number) => {
|
||||
setMode('custom')
|
||||
setErr('')
|
||||
setSelected((prev) => {
|
||||
const s = new Set(prev)
|
||||
if (s.has(idx)) s.delete(idx)
|
||||
else s.add(idx)
|
||||
return Array.from(s).sort((a, b) => a - b)
|
||||
})
|
||||
}
|
||||
|
||||
const pickCustomList = (list: number[]) => {
|
||||
setMode('custom')
|
||||
setErr('')
|
||||
setSelected([...new Set(list)].sort((a, b) => a - b))
|
||||
}
|
||||
|
||||
const physicalOnlyList = useMemo(() => {
|
||||
const seen = new Set<number>()
|
||||
const out: number[] = []
|
||||
for (const c of topology) {
|
||||
if (!seen.has(c.core_index)) {
|
||||
seen.add(c.core_index)
|
||||
out.push(c.index)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}, [topology])
|
||||
|
||||
const modeOptions: { value: VMAffinityMode; label: string }[] = [
|
||||
{ value: 'auto', label: tr('affinityModeAuto') },
|
||||
{ value: 'all', label: tr('affinityModeAll') },
|
||||
...(host.has_hybrid_cores ? [{ value: 'pcores' as const, label: tr('affinityModePCores') }] : []),
|
||||
...((host.lpe_core_count ?? 0) > 0 ? [{ value: 'non_lpe' as const, label: tr('affinityModeNonLPE') }] : []),
|
||||
{ value: 'custom', label: tr('affinityModeCustom') },
|
||||
]
|
||||
|
||||
const modeHintKey: Record<VMAffinityMode, I18nKey> = {
|
||||
auto: 'affinityModeAutoHint',
|
||||
all: 'affinityModeAllHint',
|
||||
pcores: 'affinityModePCoresHint',
|
||||
non_lpe: 'affinityModeNonLPEHint',
|
||||
custom: 'affinityModeCustomHint',
|
||||
}
|
||||
|
||||
const emptyCustom = mode === 'custom' && selected.length === 0
|
||||
const oversubscribed = effectiveVCPUs > 0 && selected.length > 0 && selected.length < effectiveVCPUs
|
||||
const allSelected = selected.length === allIndices.length && allIndices.length > 0
|
||||
|
||||
const handleSave = async () => {
|
||||
if (emptyCustom) {
|
||||
setErr(tr('affinityNeedOne'))
|
||||
return
|
||||
}
|
||||
setSaving(true)
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api.SetVMAffinity(vmName, {
|
||||
mode,
|
||||
cpus: mode === 'custom' ? selected : [],
|
||||
disable_eco_qos: disableEcoQoS,
|
||||
})
|
||||
onApplied(updated)
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const subtitle = status?.running && status.pid
|
||||
? tr('affinitySubtitleRunning', { pid: status.pid, vcpus: effectiveVCPUs })
|
||||
: tr('affinitySubtitleStopped', { vcpus: effectiveVCPUs })
|
||||
|
||||
const tierLabel = (tier: string) => {
|
||||
if (tier === 'p') return 'P'
|
||||
if (tier === 'e') return 'E'
|
||||
if (tier === 'lpe') return 'LP-E'
|
||||
return ''
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={`${tr('affinityTitle')} — ${vmName}`}
|
||||
subtitle={subtitle}
|
||||
closeLabel={tr('close')}
|
||||
dismissable={!saving}
|
||||
onClose={onClose}
|
||||
className="affinity-dialog"
|
||||
>
|
||||
<div className="dialog-body affinity-body">
|
||||
<div className="affinity-mode-bar">
|
||||
<Segmented
|
||||
label={tr('affinityTitle')}
|
||||
value={mode}
|
||||
onChange={(m) => applyPreset(m as VMAffinityMode)}
|
||||
options={modeOptions}
|
||||
/>
|
||||
<p className="affinity-hint">{tr(modeHintKey[mode])}</p>
|
||||
</div>
|
||||
|
||||
<div className="affinity-quick-bar">
|
||||
<button
|
||||
type="button"
|
||||
className={`affinity-chip${allSelected ? ' is-active' : ''}`}
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(allSelected ? [allIndices[0]] : allIndices)}
|
||||
>
|
||||
{tr('affinitySelectAll')}
|
||||
</button>
|
||||
{hasSMT && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(physicalOnlyList)}
|
||||
>
|
||||
{tr('affinityPhysicalOnly')}
|
||||
</button>
|
||||
)}
|
||||
{allIndices.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(allIndices.filter((i) => i !== 0))}
|
||||
>
|
||||
{tr('affinityExcludeCPU0')}
|
||||
</button>
|
||||
)}
|
||||
{host.has_hybrid_cores && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(topology.filter((c) => c.tier === 'p').map((c) => c.index))}
|
||||
>
|
||||
{tr('affinityOnlyPCores')}
|
||||
</button>
|
||||
)}
|
||||
{(host.lpe_core_count ?? 0) > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
onClick={() => pickCustomList(topology.filter((c) => c.tier !== 'lpe').map((c) => c.index))}
|
||||
>
|
||||
{tr('affinityAvoidLPE')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="affinity-grid" role="group" aria-label={tr('affinityTitle')}>
|
||||
{topology.map((cpu) => {
|
||||
const checked = selectedSet.has(cpu.index)
|
||||
const tLabel = tierLabel(cpu.tier)
|
||||
return (
|
||||
<button
|
||||
key={cpu.index}
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
disabled={loading || saving}
|
||||
className={`affinity-cpu${checked ? ' is-checked' : ''}${cpu.tier === 'lpe' ? ' is-lpe' : ''}`}
|
||||
onClick={() => toggleCPU(cpu.index)}
|
||||
>
|
||||
<span className="affinity-check" aria-hidden="true">
|
||||
{checked && <Check size={12} strokeWidth={3} />}
|
||||
</span>
|
||||
<span className="affinity-cpu-name tnum">CPU {cpu.index}</span>
|
||||
<span className="affinity-cpu-meta">
|
||||
{cpu.smt && <span className="affinity-core-tag tnum">C{cpu.core_index}</span>}
|
||||
{tLabel && <span className={`affinity-tier tier-${cpu.tier}`}>{tLabel}</span>}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="affinity-summary">
|
||||
<span className="mono tnum">
|
||||
<Cpu size={13} aria-hidden="true" />{' '}
|
||||
{tr('affinitySelectedSummary', { selected: selected.length, total: topology.length, mask: maskHex })}
|
||||
</span>
|
||||
{status?.running && status.live_mask_hex && (
|
||||
<span className="affinity-live mono tnum">
|
||||
{tr('affinityLiveMask', { mask: status.live_mask_hex, count: status.live_cpus?.length ?? 0 })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{oversubscribed && (
|
||||
<div className="notice" role="status">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('affinityOversubWarn', { selected: selected.length, vcpus: effectiveVCPUs })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="affinity-eco-row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('affinityEcoQoS')}</div>
|
||||
<div className="row-sub">{tr('affinityEcoQoSDesc')}</div>
|
||||
</div>
|
||||
<Switch
|
||||
label={tr('affinityEcoQoS')}
|
||||
checked={disableEcoQoS}
|
||||
disabled={loading || saving}
|
||||
onChange={setDisableEcoQoS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{err && <div className="notice notice-error" role="alert">{err}</div>}
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
<Button onClick={onClose} disabled={saving}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={saving}
|
||||
disabled={loading || emptyCustom}
|
||||
onClick={() => void handleSave()}
|
||||
>
|
||||
{status?.running ? tr('affinityApplyNow') : tr('affinitySave')}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -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,9 @@
|
||||
import { Cpu, Download, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatBytes } from '../lib/format'
|
||||
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, AppUpdateInfo, Locale, Task } from '../types'
|
||||
import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
@@ -11,40 +12,28 @@ interface Props {
|
||||
state: AppState
|
||||
locale: Locale
|
||||
onRefresh: () => void
|
||||
onNewVM?: () => 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, onNewVM, 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 [storage, setStorage] = useState<StorageBreakdown | null>(null)
|
||||
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')
|
||||
let live = true
|
||||
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch(() => {})
|
||||
return () => { live = false }
|
||||
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const rebootOpt = findOptimization(optimizations, 'cold_reboot')
|
||||
const gpuOpt = findOptimization(optimizations, 'discrete_gpu')
|
||||
@@ -71,10 +60,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)
|
||||
@@ -99,9 +91,22 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
|
||||
<section className="welcome-card">
|
||||
<h1>{tr('welcomeTitle')}</h1>
|
||||
<p>{tr('welcomeSub')}</p>
|
||||
<Button variant="primary" icon={<Plus size={14} aria-hidden="true" />} onClick={onNewVM}>
|
||||
{tr('newVM')}
|
||||
</Button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<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,20 +115,67 @@ 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>
|
||||
|
||||
{storage && storage.total_bytes > 0 && (() => {
|
||||
const tot = Math.max(storage.total_bytes, 1)
|
||||
const vmsPct = (storage.vms_bytes / tot) * 100
|
||||
const instPct = (storage.installers_bytes / tot) * 100
|
||||
const rtPct = (storage.runtimes_bytes / tot) * 100
|
||||
return (
|
||||
<section className="card">
|
||||
<div className="card-title">
|
||||
<span>{tr('storageBreakdownTitle')}</span>
|
||||
<span className="spacer" />
|
||||
<span className="muted tnum" style={{ fontSize: 12, fontWeight: 500 }}>{formatBytes(storage.total_bytes)}</span>
|
||||
</div>
|
||||
<div className="storage-bar" aria-hidden="true">
|
||||
{vmsPct > 0 && <div className="storage-seg-vms" style={{ width: `${vmsPct}%` }} />}
|
||||
{instPct > 0 && <div className="storage-seg-inst" style={{ width: `${instPct}%` }} />}
|
||||
{rtPct > 0 && <div className="storage-seg-rt" style={{ width: `${rtPct}%` }} />}
|
||||
</div>
|
||||
<div className="storage-legend">
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-vms" aria-hidden="true" />
|
||||
{tr('storageVMs')} · {formatBytes(storage.vms_bytes)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-inst" aria-hidden="true" />
|
||||
{tr('storageInstallers')} · {formatBytes(storage.installers_bytes)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-rt" aria-hidden="true" />
|
||||
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes)}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
})()}
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
{tr('hostRuntime')}
|
||||
@@ -135,9 +187,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 +209,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 +247,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,10 +1,12 @@
|
||||
import { Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import { AlertTriangle, Check, ChevronDown, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { macOSMajor } from '../lib/macosRelease'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { CachedInstaller, HostReport, Locale, Release, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { VersionArt } from './VersionArt'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -21,6 +23,23 @@ const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.max
|
||||
// 18.4 GB release, measured 2026-11-28): reserve 10% over the release size.
|
||||
const needBytes = (r: Release) => r.size * 1.1
|
||||
|
||||
type ReleaseGroup = { key: string; title: string; major: number | null; releases: Release[] }
|
||||
|
||||
/** Newest point release first, one card per macOS major version. */
|
||||
function groupReleases(releases: Release[]): ReleaseGroup[] {
|
||||
const groups = new Map<string, ReleaseGroup>()
|
||||
for (const release of releases) {
|
||||
const major = macOSMajor(release.version, release.title)
|
||||
const key = major === null ? release.title : String(major)
|
||||
const group = groups.get(key) ?? { key, title: release.title, major, releases: [] }
|
||||
group.releases.push(release)
|
||||
groups.set(key, group)
|
||||
}
|
||||
return [...groups.values()]
|
||||
.map((group) => ({ ...group, releases: group.releases.sort((a, b) => b.version.localeCompare(a.version, undefined, { numeric: true })) }))
|
||||
.sort((a, b) => (b.major ?? -1) - (a.major ?? -1) || a.title.localeCompare(b.title))
|
||||
}
|
||||
|
||||
/** Offline installers (roadmap M2.2): what is downloaded, and Apple's releases to download. */
|
||||
export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateWithInstaller, onError, onToast }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
@@ -45,7 +64,8 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
// Refresh the downloaded list whenever a download starts or ends.
|
||||
useEffect(() => { loadCached() }, [finishedCount, downloads.length])
|
||||
|
||||
const isDownloaded = (v: string) => (cached ?? []).some((c) => c.kind === 'offline' && !c.partial && c.version === v)
|
||||
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
|
||||
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
|
||||
|
||||
const download = (version: string) => {
|
||||
api.DownloadInstaller(version).catch((e) => onError(tr('failDownload'), e))
|
||||
@@ -65,109 +85,199 @@ 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>
|
||||
)
|
||||
|
||||
const spaceShort = (r: Release) => !downloaded(r.version) && !running(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
|
||||
|
||||
const releaseAction = (r: Release) => {
|
||||
const task = running(r.version)
|
||||
if (task) return <IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
|
||||
const item = downloaded(r.version)
|
||||
if (item) {
|
||||
return (
|
||||
<Button variant="primary" icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(item)}>
|
||||
{tr('installersCreateVM')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Button icon={<Download size={14} />} disabled={spaceShort(r)} onClick={() => download(r.version)}>
|
||||
{partial(r.version) ? tr('installersResume') : tr('installersDownload')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
const releaseMeta = (r: Release) => (
|
||||
<div className="row-sub">
|
||||
{r.posted} · {gb(r.size)}
|
||||
{spaceShort(r) && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
|
||||
</div>
|
||||
)
|
||||
|
||||
const groups = groupReleases(releases ?? [])
|
||||
const showDownloaded = cached === null || cached.length > 0 || downloads.length > 0
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page installers-page">
|
||||
<header className="page-head">
|
||||
<div className="page-title"><h1>{tr('installersTitle')}</h1></div>
|
||||
<div className="page-title installers-page-title">
|
||||
<h1>{tr('installersTitle')}</h1>
|
||||
<span>{tr('installersHint')}</span>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => { loadCached(); loadReleases() }} />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersDownloaded')}</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) => {
|
||||
const task = c.version ? running(c.version) : undefined
|
||||
return (
|
||||
<div className="row" key={c.name}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{c.title ?? c.name} {c.version}
|
||||
{c.build && <span className="muted">({c.build})</span>}
|
||||
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
|
||||
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
|
||||
</div>
|
||||
{task ? progress(task) : <div className="row-sub mono">{c.name} · {gb(c.bytes)}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
|
||||
) : (
|
||||
<>
|
||||
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
|
||||
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
|
||||
{tr('installersCreateVM')}
|
||||
</Button>
|
||||
{showDownloaded && (
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span>{tr('installersDownloaded')}</span>
|
||||
{cached && cached.length > 0 && <span className="section-count">{cached.length}</span>}
|
||||
</div>
|
||||
{cached === null || (cached.length === 0 && downloads.length > 0) ? (
|
||||
skeleton(1, tr('installersDownloaded'))
|
||||
) : (
|
||||
<div className="list installer-list">
|
||||
{cached.map((c) => {
|
||||
const task = c.version ? running(c.version) : undefined
|
||||
const title = c.title ?? c.name
|
||||
return (
|
||||
<div className="row installer-row" key={c.name} title={c.name}>
|
||||
<span className="installer-art">
|
||||
<VersionArt shape="tile" major={macOSMajor(c.version, title)} name={title} />
|
||||
</span>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span>{title} {c.version}</span>
|
||||
{c.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{c.kind === 'online' && !c.partial && <span className="badge">{tr('installersKindOnline')}</span>}
|
||||
{c.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
|
||||
</div>
|
||||
{task ? progress(task) : (
|
||||
<div className="row-sub">{gb(c.bytes)}{c.build ? ` · ${c.build}` : ''}</div>
|
||||
)}
|
||||
{c.partial && c.kind === 'offline' && c.version && (
|
||||
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
|
||||
)}
|
||||
{confirmDelete === c.name ? (
|
||||
<Button variant="danger" onClick={() => remove(c.name)}>{tr('installersDeleteConfirm')}</Button>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
|
||||
) : (
|
||||
<IconButton label={tr('installersDelete')} icon={<Trash size={15} />} onClick={() => remove(c.name)} />
|
||||
<>
|
||||
{!c.partial && (c.kind === 'offline' || c.kind === 'online') && (
|
||||
<Button variant={c.kind === 'offline' ? 'primary' : 'secondary'} icon={<Plus size={14} />} onClick={() => onCreateWithInstaller(c)}>
|
||||
{tr('installersCreateVM')}
|
||||
</Button>
|
||||
)}
|
||||
{c.partial && c.kind === 'offline' && c.version && (
|
||||
<Button icon={<Download size={14} />} onClick={() => download(c.version!)}>{tr('installersResume')}</Button>
|
||||
)}
|
||||
{confirmDelete === c.name ? (
|
||||
<Button variant="danger" onClick={() => remove(c.name)}>{tr('installersDeleteConfirm')}</Button>
|
||||
) : (
|
||||
<IconButton label={tr('installersDelete')} icon={<Trash size={15} />} onClick={() => remove(c.name)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('installersAvailable')}</div>
|
||||
<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) => {
|
||||
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)
|
||||
return (
|
||||
<div className="row" key={r.product}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{r.title} {r.version}
|
||||
<span className="muted">({r.build})</span>
|
||||
</div>
|
||||
{task ? progress(task) : (
|
||||
<div className="row-sub">
|
||||
{r.posted} · {gb(r.size)}
|
||||
{short && <span className="warn-text"> · {tr('installersNoSpace', { need: Math.ceil(needBytes(r) / 1e9), free: host.free_disk_gb.toFixed(0) })}</span>}
|
||||
{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>
|
||||
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
|
||||
</div>
|
||||
) : releases === null ? (
|
||||
<>
|
||||
{skeleton(2, tr('offlineLoading'))}
|
||||
<span className="hint">{tr('offlineLoading')}</span>
|
||||
</>
|
||||
) : (
|
||||
<div className="release-list">
|
||||
{groups.map((group, groupIndex) => {
|
||||
const [latest, ...older] = group.releases
|
||||
const task = running(latest.version)
|
||||
return (
|
||||
<article className="release-card" key={group.key}>
|
||||
<div className="release-latest">
|
||||
<span className="release-art">
|
||||
<VersionArt shape="tile" major={group.major} name={group.title} />
|
||||
</span>
|
||||
<div className="release-copy">
|
||||
<div className="row-title release-title">
|
||||
<span>{latest.title}</span>
|
||||
<strong>{latest.version}</strong>
|
||||
{groupIndex === 0 && <span className="badge badge-accent">{tr('installersLatest')}</span>}
|
||||
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
|
||||
</div>
|
||||
{task ? progress(task) : releaseMeta(latest)}
|
||||
</div>
|
||||
<div className="row-right">{releaseAction(latest)}</div>
|
||||
</div>
|
||||
{older.length > 0 && (
|
||||
<details className="release-history">
|
||||
<summary>
|
||||
<span>{tr('installersOlder', { count: older.length })}</span>
|
||||
<ChevronDown size={14} aria-hidden="true" />
|
||||
</summary>
|
||||
<div className="release-history-list">
|
||||
{older.map((r) => {
|
||||
const oldTask = running(r.version)
|
||||
return (
|
||||
<div className="release-history-row" key={r.product}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span>{r.version}</span>
|
||||
<span className="muted">{r.build}</span>
|
||||
{downloaded(r.version) && <span className="badge badge-ok">{tr('offlineCached')}</span>}
|
||||
</div>
|
||||
{oldTask ? progress(oldTask) : releaseMeta(r)}
|
||||
</div>
|
||||
<div className="row-right">{releaseAction(r)}</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{task ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => api.CancelTask(task.id)} />
|
||||
) : done ? (
|
||||
<span className="badge badge-ok">{tr('offlineCached')}</span>
|
||||
) : (
|
||||
<Button icon={<Download size={14} />} disabled={short} onClick={() => download(r.version)}>{tr('installersDownload')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<span className="hint">{tr('installersHint')}</span>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ArrowDown, ChevronDown, ChevronUp, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useLayoutEffect, useRef, useState } from 'react'
|
||||
import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useLayoutEffect, useMemo, 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,12 @@ interface Props {
|
||||
task: Task | null
|
||||
runningTasks: number
|
||||
onCancelTask: (id: string) => void
|
||||
host?: HostReport
|
||||
runningVMs?: number
|
||||
onCopy?: (text: string) => void
|
||||
/** False when WHPX or the runtime needs attention; the bar then leads with a link to the host page. */
|
||||
hostReady?: boolean
|
||||
onOpenHost?: () => void
|
||||
}
|
||||
|
||||
/** Sticks to the bottom until the user scrolls up; offers "jump to latest" then. */
|
||||
@@ -50,29 +56,138 @@ function useStickToBottom(dep: unknown, active: boolean) {
|
||||
return { ref, stuck, onScroll, jump }
|
||||
}
|
||||
|
||||
const LogRow = React.memo(({ line }: { line: LogLine }) => (
|
||||
<div className={`log-line ${line.level}`}>
|
||||
<span className="log-ts">{line.ts}</span>
|
||||
<span className="log-src">{line.source}</span>
|
||||
<span className="log-msg">{line.line}</span>
|
||||
</div>
|
||||
))
|
||||
LogRow.displayName = 'LogRow'
|
||||
|
||||
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, onCopy, hostReady = true, onOpenHost,
|
||||
}) => {
|
||||
const tr = (k: Parameters<typeof t>[1]) => t(locale, k)
|
||||
const content = tab === 'app' ? lines : tab === 'serial' ? serialText : qemuText
|
||||
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [query, setQuery] = useState('')
|
||||
const [errorsOnly, setErrorsOnly] = useState(false)
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const filteredLines = useMemo(() => {
|
||||
return lines.filter((l) => {
|
||||
if (errorsOnly && l.level !== 'error' && l.level !== 'warn') return false
|
||||
if (q && !l.line.toLowerCase().includes(q) && !l.source.toLowerCase().includes(q)) return false
|
||||
return true
|
||||
})
|
||||
}, [lines, errorsOnly, q])
|
||||
// Same element list while the lines are unchanged, so an App re-render for
|
||||
// something else doesn't rebuild up to MAX_LOG_LINES rows; a new line renders
|
||||
// just its own row (LogRow is memoised on the line object).
|
||||
const rows = useMemo(() => filteredLines.map((l) => <LogRow key={l.id} line={l} />), [filteredLines])
|
||||
|
||||
const filteredText = useMemo(() => {
|
||||
const raw = tab === 'serial' ? serialText : qemuText
|
||||
if (!q || !raw) return raw
|
||||
return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n')
|
||||
}, [tab, serialText, qemuText, q])
|
||||
|
||||
const copyVisible = () => {
|
||||
if (!onCopy) return
|
||||
if (tab === 'app') {
|
||||
const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n')
|
||||
if (txt) onCopy(txt)
|
||||
} else if (filteredText) {
|
||||
onCopy(filteredText)
|
||||
}
|
||||
}
|
||||
|
||||
const content = tab === 'app' ? filteredLines : filteredText
|
||||
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
|
||||
|
||||
const memPct = host
|
||||
? Math.max(0, Math.min(100, host.memory_load_pct > 0
|
||||
? host.memory_load_pct
|
||||
: host.total_ram_gb > 0
|
||||
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
|
||||
: 0))
|
||||
: 0
|
||||
const 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
|
||||
// "D:\Data\reims-go" → "D:": the drive VM disks and snapshots grow on.
|
||||
const dataDrive = /^([A-Za-z]:)/.exec(host?.data_root ?? '')?.[1]?.toUpperCase() ?? ''
|
||||
|
||||
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,24 +196,94 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<IconButton small tipSide="top" label={tr('pauseDownload')} icon={<Pause size={14} />} onClick={() => onCancelTask(task.id)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<span className="spacer" />
|
||||
{open && (
|
||||
<div className="tabs" role="tablist">
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
) : host ? (
|
||||
// Host at a glance: a problem first (only when there is one), then
|
||||
// memory, the data drive and running VMs. "Label value" pairs with
|
||||
// thin rules between them; exact figures live in the tooltips.
|
||||
<div className="status-telemetry">
|
||||
{!hostReady && onOpenHost && (
|
||||
<Tip side="top" label={tr('footerHostIssueTip')}>
|
||||
<button type="button" className="status-metric status-issue" onClick={onOpenHost}>
|
||||
<AlertTriangle size={12} aria-hidden="true" />
|
||||
<span>{tr('footerHostIssue')}</span>
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
</Tip>
|
||||
)}
|
||||
{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}>
|
||||
<span className="status-label">{tr('footerMemLabel')}</span>
|
||||
<span className="status-value">{tr('footerMemValue', { used: usedMemGB.toFixed(1), total: host.total_ram_gb.toFixed(0) })}</span>
|
||||
<span className="status-mini-bar" aria-hidden="true">
|
||||
<span className={`status-mini-fill${memTone}`} style={{ transform: `scaleX(${memPct / 100})` }} />
|
||||
</span>
|
||||
</span>
|
||||
</Tip>
|
||||
)}
|
||||
{host.free_disk_gb > 0 && (
|
||||
<Tip side="top" label={tr('footerDiskTip', { dir: host.data_root })}>
|
||||
<span className={`status-metric${lowDisk ? ' warn' : ''}`} tabIndex={0}>
|
||||
<span className="status-label">{dataDrive || tr('footerDiskLabel')}</span>
|
||||
<span className="status-value">{tr('footerDiskValue', { gb: host.free_disk_gb.toFixed(0) })}</span>
|
||||
</span>
|
||||
</Tip>
|
||||
)}
|
||||
{runningVMs > 0 && (
|
||||
<span className="status-metric ok">
|
||||
<span className="status status-running" aria-hidden="true" />
|
||||
<span className="status-value">{tr('footerRunningVMs', { n: runningVMs })}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
<span className="spacer" />
|
||||
{open && (
|
||||
<>
|
||||
<input
|
||||
type="search"
|
||||
className="log-filter-input"
|
||||
value={query}
|
||||
placeholder={tr('logSearchPlaceholder')}
|
||||
aria-label={tr('logSearchPlaceholder')}
|
||||
spellCheck={false}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
{tab === 'app' && (
|
||||
<button
|
||||
type="button"
|
||||
className="log-filter-pill"
|
||||
aria-pressed={errorsOnly}
|
||||
onClick={() => setErrorsOnly((v) => !v)}
|
||||
>
|
||||
{tr('logErrorsOnly')}
|
||||
</button>
|
||||
)}
|
||||
<div className="tabs" role="tablist">
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{open && onCopy && (
|
||||
<IconButton small tipSide="top" label={tr('logCopy')} icon={<Copy size={14} />} onClick={copyVisible} />
|
||||
)}
|
||||
{open && tab === 'app' && lines.length > 0 && (
|
||||
<IconButton small tipSide="top" label={tr('clear')} icon={<Eraser size={14} />} onClick={onClear} />
|
||||
@@ -110,33 +295,28 @@ 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
|
||||
? (filteredLines.length === 0
|
||||
? <span className="muted">{tr('logsEmpty')}</span>
|
||||
: lines.map((l) => (
|
||||
<div key={l.id} className={`log-line ${l.level}`}>
|
||||
<span className="log-ts">{l.ts}</span>
|
||||
<span className="log-src">{l.source}</span>
|
||||
<span className="log-msg">{l.line}</span>
|
||||
</div>
|
||||
)))
|
||||
: tab === 'serial'
|
||||
? (serialText || <span className="muted">{tr('logsEmpty')}</span>)
|
||||
: (qemuText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
: rows)
|
||||
: (filteredText || <span className="muted">{tr('logsEmpty')}</span>)}
|
||||
</div>
|
||||
{!stuck && (
|
||||
<Button className="jump-latest" icon={<ArrowDown size={14} />} onClick={jump}>
|
||||
|
||||
@@ -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,11 +25,12 @@ import {
|
||||
optStatusLabel,
|
||||
parseKernelIrqchip,
|
||||
} from '../lib/optimizations'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail, VMStats } from '../types'
|
||||
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { formatAffinitySummary } from './AffinityDialog'
|
||||
|
||||
// VM settings (docs/shell-design.md §4): edits are staged here and written in
|
||||
// one `reims-ctl set` on Save, because upstream applies every change on the
|
||||
@@ -70,6 +74,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()
|
||||
@@ -124,11 +129,13 @@ interface Props {
|
||||
running: boolean
|
||||
onCopy?: (text: string) => void
|
||||
onDiskChanged?: () => void
|
||||
onOpenAffinity?: () => void
|
||||
affinityVersion?: number
|
||||
onClose: () => void
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onClose, onSaved }) => {
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onClose, onSaved }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const base = useMemo(() => baseline(detail, host), [detail, host])
|
||||
@@ -148,6 +155,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const activeVMNameRef = useRef(detail.name)
|
||||
activeVMNameRef.current = detail.name
|
||||
const [driveErr, setDriveErr] = useState('')
|
||||
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
const presets = recommendedDisplayPresets(host)
|
||||
@@ -155,7 +163,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)))
|
||||
@@ -202,6 +222,14 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
return () => { active = false }
|
||||
}, [detail.name])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
api.GetVMAffinity(detail.name)
|
||||
.then((st) => { if (active) setAffinityStatus(st) })
|
||||
.catch(() => {})
|
||||
return () => { active = false }
|
||||
}, [detail.name, running, affinityVersion])
|
||||
|
||||
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
|
||||
if (driveBusyRef.current || !driveSettings) return
|
||||
driveBusyRef.current = true
|
||||
@@ -246,6 +274,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)))
|
||||
@@ -324,6 +353,17 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{onOpenAffinity && (
|
||||
<SetRow
|
||||
title={tr('affinityTitle')}
|
||||
desc={affinityStatus ? `${formatAffinitySummary(locale, affinityStatus)} · ${tr('affinityRowDesc')}` : tr('affinityRowDesc')}
|
||||
control={
|
||||
<Button variant="secondary" icon={<Cpu size={13} aria-hidden="true" />} onClick={onOpenAffinity}>
|
||||
{tr('affinityConfigure')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</SetGroup>
|
||||
<SetGroup title={tr('factMemory')}>
|
||||
<SetRow
|
||||
@@ -368,7 +408,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} />
|
||||
@@ -406,37 +448,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')}
|
||||
@@ -446,6 +493,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>}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
@@ -462,12 +510,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>
|
||||
</>
|
||||
)
|
||||
@@ -569,10 +611,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"
|
||||
@@ -589,7 +632,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)} />
|
||||
@@ -748,6 +791,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,11 +1,15 @@
|
||||
import { Cpu, Download, Monitor, Plus } from 'lucide-react'
|
||||
import * as Ctx from '@radix-ui/react-context-menu'
|
||||
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Play, Plus, Power, RotateCw, Settings, Square, Trash } from 'lucide-react'
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from './VersionArt'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
export const SETTINGS_ID = '__settings__'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -14,14 +18,24 @@ interface Props {
|
||||
selected: string
|
||||
hostReady: boolean
|
||||
onSelect: (id: string) => void
|
||||
/** VM name → display name (its note); empty or missing shows the name. */
|
||||
displayNames?: Record<string, string>
|
||||
/** VM name → macOS major version for its icon; null shows the name's initial. */
|
||||
macosMajors?: Record<string, number | null>
|
||||
/** Double-click on a VM: its main action (start, or show its window). */
|
||||
onActivate?: (name: string) => void
|
||||
onNew: () => void
|
||||
onVMContextAction?: (name: string, action: VMAction | 'settings') => void
|
||||
/** An installer download is running (busy dot on the Installers entry). */
|
||||
downloading?: boolean
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, hostReady, onSelect, onNew, downloading }) => {
|
||||
export const Sidebar: React.FC<Props> = ({
|
||||
locale, vms, transitions, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading,
|
||||
}) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
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) => {
|
||||
@@ -37,13 +51,14 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
listRef.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(ids[next])}"]`)?.focus()
|
||||
}
|
||||
|
||||
const item = (
|
||||
const navBtn = (
|
||||
id: string,
|
||||
label: string,
|
||||
icon: React.ReactNode,
|
||||
badgeClass: string,
|
||||
stateLabel: string,
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
onDoubleClick?: () => void,
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
@@ -55,6 +70,7 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
aria-label={stateLabel ? `${label},${stateLabel}` : label}
|
||||
tabIndex={selected === id ? 0 : -1}
|
||||
onClick={() => onSelect(id)}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
@@ -70,32 +86,108 @@ export const Sidebar: React.FC<Props> = ({ locale, vms, transitions, selected, h
|
||||
<div className="sidebar-wrap">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-head">
|
||||
<span>{t(locale, 'sidebarVMs')}</span>
|
||||
<IconButton small label={t(locale, 'newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
<span>{tr('sidebarVMs')}</span>
|
||||
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
</div>
|
||||
<div className="nav" role="listbox" aria-label={t(locale, 'sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
{vms.length === 0 && <div className="nav-empty">{t(locale, 'emptyVMs')}</div>}
|
||||
<div className="nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
{vms.length === 0 && <div className="nav-empty">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vm.name] ?? vm.state
|
||||
return item(vm.name, vm.name, <Monitor size={13} />, 'nav-icon-vm', t(locale, `state_${st}` as I18nKey), statusKind(st))
|
||||
const running = st === 'running'
|
||||
const stopped = st === 'stopped'
|
||||
const transitioning = st === 'starting' || st === 'stopping'
|
||||
const label = displayNames[vm.name] || vm.name
|
||||
const trigger = navBtn(
|
||||
vm.name,
|
||||
label,
|
||||
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
|
||||
'nav-icon-art',
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vm.name) : undefined,
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vm.name}>
|
||||
<Ctx.Trigger asChild>{trigger}</Ctx.Trigger>
|
||||
<Ctx.Portal>
|
||||
<Ctx.Content className="menu">
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
</Ctx.Portal>
|
||||
</Ctx.Root>
|
||||
)
|
||||
})}
|
||||
<div className="sidebar-sep" role="presentation" />
|
||||
{item(
|
||||
<div className="sidebar-section-label" aria-hidden="true">{tr('sidebarSystem')}</div>
|
||||
{navBtn(
|
||||
INSTALLERS_ID,
|
||||
t(locale, 'sidebarInstallers'),
|
||||
tr('sidebarInstallers'),
|
||||
<Download size={13} />,
|
||||
'nav-icon-installers',
|
||||
downloading ? t(locale, 'state_starting') : '',
|
||||
downloading ? tr('state_starting') : '',
|
||||
downloading ? 'busy' : null,
|
||||
)}
|
||||
{item(
|
||||
{navBtn(
|
||||
HOST_ID,
|
||||
t(locale, 'sidebarHost'),
|
||||
tr('sidebarHost'),
|
||||
<Cpu size={13} />,
|
||||
'nav-icon-host',
|
||||
t(locale, hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
tr(hostReady ? 'hostReady' : 'hostNeedsAction'),
|
||||
hostReady ? 'running' : 'warn',
|
||||
)}
|
||||
{navBtn(
|
||||
SETTINGS_ID,
|
||||
tr('sidebarSettings'),
|
||||
<Settings size={13} />,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
null,
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Check, PanelLeft } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
import type { ThemeMode } from './AppSettingsPage'
|
||||
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID } from './Sidebar'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
sidebarOpen: boolean
|
||||
onToggleSidebar: () => void
|
||||
logsOpen: boolean
|
||||
onToggleLogs: () => void
|
||||
themeMode: ThemeMode
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
/** The selected VM and its current state, or null on the system pages. */
|
||||
vm: { name: string; state: string; busy: boolean } | null
|
||||
onNewVM: () => void
|
||||
onVMAction: (action: VMAction) => void
|
||||
onVMSettings: () => void
|
||||
onVMDelete: () => void
|
||||
onNavigate: (id: string) => void
|
||||
onOpenURL: (url: string) => void
|
||||
appVersion: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The title bar's left side: a sidebar toggle and a small menu bar (VM / View /
|
||||
* Help) that lists every command with its shortcut, so the keyboard paths are
|
||||
* discoverable and still reachable with the sidebar hidden. Once one menu is
|
||||
* open, hovering the next title switches to it, as in a native menu bar.
|
||||
*/
|
||||
export const TitleMenus: React.FC<Props> = ({
|
||||
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, onThemeMode,
|
||||
vm, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [open, setOpen] = useState<string | null>(null)
|
||||
|
||||
const running = vm?.state === 'running'
|
||||
const stopped = vm?.state === 'stopped'
|
||||
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping'
|
||||
const vmBusy = !vm || vm.busy
|
||||
|
||||
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
|
||||
<Menu.Item className={`menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
|
||||
<span className="menu-label">{label}</span>
|
||||
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
|
||||
</Menu.Item>
|
||||
)
|
||||
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
|
||||
<Menu.CheckboxItem className="menu-item menu-item-check" checked={checked} onSelect={onSelect}>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="menu-label">{label}</span>
|
||||
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
|
||||
</Menu.CheckboxItem>
|
||||
)
|
||||
|
||||
// `indented`: the menu has check marks, so every row shares their indent.
|
||||
const menu = (id: string, label: string, content: React.ReactNode, indented = false) => (
|
||||
<Menu.Root modal={false} open={open === id} onOpenChange={(o) => setOpen(o ? id : null)}>
|
||||
<Menu.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="titlebar-menu"
|
||||
onPointerEnter={() => { if (open && open !== id) setOpen(id) }}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`} align="start" sideOffset={4} collisionPadding={8}>
|
||||
{content}
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="titlebar-left" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<Tip label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')} shortcut="Ctrl+B">
|
||||
<button
|
||||
type="button"
|
||||
className="titlebar-icon"
|
||||
aria-label={tr(sidebarOpen ? 'hideSidebar' : 'showSidebar')}
|
||||
aria-pressed={sidebarOpen}
|
||||
onClick={onToggleSidebar}
|
||||
>
|
||||
<PanelLeft size={16} aria-hidden="true" />
|
||||
</button>
|
||||
</Tip>
|
||||
<nav className="titlebar-menus" aria-label={tr('menuBar')}>
|
||||
{menu('vm', tr('menuVM'), (
|
||||
<>
|
||||
{item(tr('newVMEllipsis'), onNewVM, { shortcut: 'Ctrl+N' })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{running
|
||||
? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy })
|
||||
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
|
||||
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
|
||||
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
|
||||
{item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })}
|
||||
{item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
|
||||
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })}
|
||||
</>
|
||||
))}
|
||||
{menu('view', tr('menuView'), (
|
||||
<>
|
||||
{check(tr('sidebarLabel'), sidebarOpen, onToggleSidebar, 'Ctrl+B')}
|
||||
{check(tr('logButton'), logsOpen, onToggleLogs, 'Ctrl+L')}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Label className="menu-group-label">{tr('appearance')}</Menu.Label>
|
||||
<Menu.RadioGroup value={themeMode} onValueChange={(v) => onThemeMode(v as ThemeMode)}>
|
||||
{(['light', 'dark', 'system'] as const).map((m) => (
|
||||
<Menu.RadioItem key={m} className="menu-item menu-item-check" value={m}>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="menu-label">{tr(m === 'light' ? 'themeLight' : m === 'dark' ? 'themeDark' : 'themeSystem')}</span>
|
||||
</Menu.RadioItem>
|
||||
))}
|
||||
</Menu.RadioGroup>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{item(tr('sidebarInstallers'), () => onNavigate(INSTALLERS_ID))}
|
||||
{item(tr('sidebarHost'), () => onNavigate(HOST_ID))}
|
||||
{item(tr('sidebarSettings'), () => onNavigate(SETTINGS_ID))}
|
||||
</>
|
||||
), true)}
|
||||
{menu('help', tr('menuHelp'), (
|
||||
<>
|
||||
{item(tr('helpProjectPage'), () => onOpenURL(REPO_URL))}
|
||||
{item(tr('helpReportIssue'), () => onOpenURL(`${REPO_URL}/issues`))}
|
||||
{item(tr('helpCheckUpdate'), () => onNavigate(SETTINGS_ID))}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Label className="menu-group-label">Reims-Go {appVersion}</Menu.Label>
|
||||
</>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import React, { useId } from 'react'
|
||||
|
||||
/**
|
||||
* A VM's icon: its macOS major version as frosted-glass digits over soft
|
||||
* folds of colour. Drawn here, with our own palettes; no Apple artwork.
|
||||
* The glass is the background itself, blurred and brightened inside the
|
||||
* digits' outline. Without a known version it shows the name's first letter.
|
||||
*/
|
||||
|
||||
type Palette = [string, string, string, string]
|
||||
|
||||
const PALETTES: Record<number, Palette> = {
|
||||
26: ['#f6e8cf', '#ebc8b4', '#a597d8', '#5450b4'], // sand → rose → lavender
|
||||
15: ['#ddf2e8', '#86ccb8', '#3f8ea3', '#22446e'], // mint → teal
|
||||
14: ['#ffe5d2', '#f5a48d', '#d6688f', '#6a3f8e'], // peach → coral → plum
|
||||
13: ['#fff1cc', '#f7b95e', '#df7140', '#83372b'], // cream → amber
|
||||
12: ['#e4ecff', '#91b1f4', '#5b70df', '#2f3592'], // ice → blue
|
||||
11: ['#e5f5ff', '#88c9ee', '#3f86d0', '#233f88'], // sky → ocean
|
||||
}
|
||||
const FUTURE: Palette[] = [
|
||||
['#f3e9ff', '#c6a8f0', '#7d6ad8', '#3c348f'],
|
||||
['#e8f7f0', '#9fd8c0', '#4f9fa6', '#2a4f73'],
|
||||
['#fff0e0', '#f3b98d', '#d77a74', '#6e3f72'],
|
||||
]
|
||||
const NEUTRAL: Palette = ['#eef0f4', '#c9ceda', '#8d95a9', '#4b5266']
|
||||
|
||||
function paletteFor(major: number | null): Palette {
|
||||
if (major === null) return NEUTRAL
|
||||
if (PALETTES[major]) return PALETTES[major]
|
||||
if (major > 26) return FUTURE[(major - 27) % FUTURE.length]
|
||||
return PALETTES[11]
|
||||
}
|
||||
|
||||
function initial(name: string): string {
|
||||
const ch = Array.from(name.trim().replace(/^macos[\s_-]*/i, ''))[0] ?? '?'
|
||||
return ch.toUpperCase()
|
||||
}
|
||||
|
||||
const SHAPES = {
|
||||
// width, height, font size, weight, glass blur, rim width, shadow blur;
|
||||
// glass: how much white the digits add; shade: how dark the drop under them.
|
||||
tile: { w: 64, h: 64, size: 38, weight: 700, blur: 2.4, rim: 2.2, shadow: 1.6, glass: 1.6, shade: 0.7 },
|
||||
screen: { w: 160, h: 100, size: 76, weight: 600, blur: 3.6, rim: 1.1, shadow: 2.4, glass: 1, shade: 0.36 },
|
||||
}
|
||||
|
||||
export const VersionArt: React.FC<{
|
||||
major: number | null
|
||||
name: string
|
||||
shape: 'tile' | 'screen'
|
||||
className?: string
|
||||
}> = ({ major, name, shape, className }) => {
|
||||
const id = useId().replace(/[^a-zA-Z0-9_-]/g, '')
|
||||
const p = paletteFor(major)
|
||||
const s = SHAPES[shape]
|
||||
const label = major !== null ? String(major) : initial(name)
|
||||
const size = label.length > 2 ? s.size * 0.72 : label.length === 1 ? s.size * 1.08 : s.size
|
||||
const text = {
|
||||
x: s.w / 2,
|
||||
y: s.h / 2 + size * 0.04,
|
||||
textAnchor: 'middle' as const,
|
||||
dominantBaseline: 'central' as const,
|
||||
fontSize: size,
|
||||
fontWeight: s.weight,
|
||||
letterSpacing: label.length > 1 ? -size * 0.04 : 0,
|
||||
style: { fontFamily: 'var(--font-sans)', fontVariantNumeric: 'tabular-nums' as const },
|
||||
}
|
||||
const sx = s.w / 100
|
||||
const sy = s.h / 100
|
||||
|
||||
return (
|
||||
<svg className={className} viewBox={`0 0 ${s.w} ${s.h}`} preserveAspectRatio="xMidYMid slice" aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id={`${id}bg`} x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor={p[0]} />
|
||||
<stop offset="0.38" stopColor={p[1]} />
|
||||
<stop offset="0.72" stopColor={p[2]} />
|
||||
<stop offset="1" stopColor={p[3]} />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}hi`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#ffffff" stopOpacity="0.62" />
|
||||
<stop offset="1" stopColor="#ffffff" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}sh`} x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor={p[3]} stopOpacity="0" />
|
||||
<stop offset="1" stopColor={p[3]} stopOpacity="0.6" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0.4" y2="1">
|
||||
<stop offset="0" stopColor="#ffffff" stopOpacity={Math.min(1, 0.62 * s.glass)} />
|
||||
<stop offset="0.55" stopColor="#ffffff" stopOpacity={Math.min(1, 0.22 * s.glass)} />
|
||||
<stop offset="1" stopColor="#ffffff" stopOpacity={Math.min(1, 0.34 * s.glass)} />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}rim`} x1="0" y1="0" x2="0.3" y2="1">
|
||||
<stop offset="0" stopColor="#ffffff" stopOpacity="0.98" />
|
||||
<stop offset="0.6" stopColor="#ffffff" stopOpacity="0.45" />
|
||||
<stop offset="1" stopColor="#ffffff" stopOpacity="0.8" />
|
||||
</linearGradient>
|
||||
<filter id={`${id}blur`} x="-20%" y="-20%" width="140%" height="140%">
|
||||
<feGaussianBlur stdDeviation={s.blur} />
|
||||
</filter>
|
||||
<filter id={`${id}soft`} x="-30%" y="-30%" width="160%" height="160%">
|
||||
<feGaussianBlur stdDeviation={s.shadow} />
|
||||
</filter>
|
||||
<clipPath id={`${id}clip`}>
|
||||
<text {...text}>{label}</text>
|
||||
</clipPath>
|
||||
<g id={`${id}scene`}>
|
||||
<rect width={s.w} height={s.h} fill={`url(#${id}bg)`} />
|
||||
<g transform={`scale(${sx} ${sy})`}>
|
||||
<path d="M-5 40 C16 14 40 60 70 32 S104 8 105 6 L105 -5 L-5 -5 Z" fill={`url(#${id}hi)`} />
|
||||
<path d="M-5 58 C24 30 54 80 105 36 L105 50 C56 90 26 46 -5 72 Z" fill="#ffffff" fillOpacity="0.2" />
|
||||
<path d="M-5 74 C22 50 52 94 80 64 S104 46 105 46 L105 105 L-5 105 Z" fill={`url(#${id}sh)`} />
|
||||
<path d="M-5 58 C24 30 54 80 105 36" fill="none" stroke="#ffffff" strokeOpacity="0.55" strokeWidth="0.7" vectorEffect="non-scaling-stroke" />
|
||||
</g>
|
||||
</g>
|
||||
</defs>
|
||||
|
||||
<use href={`#${id}scene`} />
|
||||
{/* A soft shade under the digits so they lift off the background. */}
|
||||
<text {...text} y={text.y + size * 0.05} fill={p[3]} fillOpacity={s.shade} filter={`url(#${id}soft)`}>{label}</text>
|
||||
{/* The glass: the scene blurred and brightened, seen through the digits. */}
|
||||
<g clipPath={`url(#${id}clip)`}>
|
||||
<use href={`#${id}scene`} filter={`url(#${id}blur)`} />
|
||||
<rect width={s.w} height={s.h} fill={`url(#${id}gl)`} />
|
||||
</g>
|
||||
<text {...text} fill="none" stroke={`url(#${id}rim)`} strokeWidth={s.rim} />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -6,11 +6,16 @@ const dict = {
|
||||
'zh-CN': {
|
||||
// Shell
|
||||
sidebarVMs: '虚拟机',
|
||||
sidebarHost: '宿主与运行时',
|
||||
sidebarSystem: '系统',
|
||||
sidebarHost: '内核',
|
||||
sidebarSettings: '设置',
|
||||
sidebarInstallers: '安装包',
|
||||
installersTitle: '安装包',
|
||||
installersDownloaded: '已下载',
|
||||
installersAvailable: 'Apple 提供的版本',
|
||||
installersLatest: '最新',
|
||||
installersOlder: '{count} 个旧版本',
|
||||
installersRetry: '重试',
|
||||
installersEmpty: '还没有下载任何安装包',
|
||||
installersPartial: '未下载完',
|
||||
installersResume: '继续下载',
|
||||
@@ -28,6 +33,91 @@ 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} 台运行中',
|
||||
footerMemLabel: '内存',
|
||||
footerMemValue: '{used} / {total} GB',
|
||||
footerDiskLabel: '磁盘',
|
||||
footerDiskValue: '可用 {gb} GB',
|
||||
footerDiskTip: '虚拟机数据目录:{dir}',
|
||||
footerHostIssue: '虚拟化未就绪',
|
||||
footerHostIssueTip: '打开「内核」页查看需要处理的项',
|
||||
// Title-bar menus
|
||||
menuBar: '菜单栏',
|
||||
menuVM: '虚拟机',
|
||||
menuView: '视图',
|
||||
menuHelp: '帮助',
|
||||
newVMEllipsis: '新建虚拟机…',
|
||||
deleteEllipsis: '删除…',
|
||||
sidebarLabel: '侧边栏',
|
||||
showSidebar: '显示侧边栏',
|
||||
hideSidebar: '隐藏侧边栏',
|
||||
appearance: '外观',
|
||||
helpProjectPage: '项目主页',
|
||||
helpReportIssue: '报告问题',
|
||||
helpCheckUpdate: '检查更新…',
|
||||
settingsGeneral: '常规',
|
||||
settingsAppearance: '外观与语言',
|
||||
settingsAbout: '关于',
|
||||
themeLabel: '外观',
|
||||
themeLight: '浅色',
|
||||
themeDark: '深色',
|
||||
themeSystem: '跟随系统',
|
||||
showWindow: '显示窗口',
|
||||
copyScreenshot: '截屏并复制',
|
||||
toastScreenshotCopied: '已复制虚拟机画面',
|
||||
failFocus: '无法定位虚拟机窗口',
|
||||
failScreenshot: '截屏失败',
|
||||
dropFilesHint: '松开以投递到 macOS 共享目录',
|
||||
toastFilesDelivered: '已投递 {n} 个文件到共享目录',
|
||||
sshOpenTerminal: '终端',
|
||||
sshMore: 'SSH 工具',
|
||||
sshWriteConfig: '写入 ~/.ssh/config',
|
||||
sshOpenVSCode: '用 VS Code 打开',
|
||||
sshSetUser: '设置 SSH 用户名…',
|
||||
sshUserTitle: 'SSH 登录用户名',
|
||||
sshUserDesc: '用于打开终端、写入 ~/.ssh/config 和 VS Code 直连(留空则连接时不带用户名)',
|
||||
sshUserPlaceholder: '例如 admin',
|
||||
toastSSHConfigWritten: '已写入 Host {alias}',
|
||||
toastSSHUserSaved: '已保存 SSH 用户名',
|
||||
failSSH: 'SSH 操作失败',
|
||||
snapshotsTitle: '恢复点',
|
||||
snapshotCreate: '创建恢复点',
|
||||
snapshotEmpty: '尚未创建恢复点,升级系统或大改环境前可先留档',
|
||||
snapshotHint: '停机快照 · 非异地备份',
|
||||
snapshotNamePlaceholder: '例如:升级 macOS 前',
|
||||
snapshotRestore: '回滚',
|
||||
snapshotRestoreTitle: '回滚到「{name}」?',
|
||||
snapshotRestoreDesc: '当前磁盘在此恢复点之后的改动将被覆盖,且无法撤销。',
|
||||
snapshotDelete: '删除恢复点',
|
||||
snapshotStopFirst: '停止虚拟机后才可管理恢复点',
|
||||
toastSnapshotCreated: '已创建恢复点 {name}',
|
||||
toastSnapshotRestored: '已回滚到 {name}',
|
||||
toastSnapshotDeleted: '已删除恢复点 {name}',
|
||||
failSnapshot: '恢复点操作失败',
|
||||
displayNameEdit: '点按以修改显示名称',
|
||||
displayNameLabel: '显示名称',
|
||||
displayNameEditEllipsis: '修改显示名称…',
|
||||
displayNameTip: '显示名称 · 虚拟机名称为 {name}(点按修改)',
|
||||
fieldVMName: '虚拟机名称',
|
||||
logSearchPlaceholder: '筛选日志…',
|
||||
logErrorsOnly: '仅错误/警告',
|
||||
logCopy: '复制日志',
|
||||
storageBreakdownTitle: '空间分布',
|
||||
storageVMs: '虚拟机文件',
|
||||
storageInstallers: '安装包',
|
||||
storageRuntimes: 'Reims-Go',
|
||||
welcomeTitle: '创建第一台 macOS 虚拟机',
|
||||
welcomeSub: '选择系统来源、分配核数与显卡,几步完成配置',
|
||||
welcomeCheckHost: '先完成内核环境配置 →',
|
||||
|
||||
// Actions
|
||||
newVM: '新建虚拟机',
|
||||
@@ -182,7 +272,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 +328,7 @@ const dict = {
|
||||
onlineRecoveryTitle: '拉取在线恢复镜像?',
|
||||
onlineRecoveryDesc: '本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?',
|
||||
onlineRecoveryConfirm: '拉取并挂载(约 1 GB)',
|
||||
noRuntimeAlert: '先在「宿主与运行时」导入运行时包',
|
||||
noRuntimeAlert: '先在「内核」导入运行时包',
|
||||
|
||||
// Host
|
||||
hostRuntime: '运行时',
|
||||
@@ -390,6 +487,8 @@ const dict = {
|
||||
displayGroup: '显示器',
|
||||
resCustom: '自定义',
|
||||
resCustomSub: '宽 × 高',
|
||||
resFullscreen: '全屏',
|
||||
resLooksLike: '看起来像 {w} × {h}',
|
||||
resInvalid: '格式为 宽x高,例如 2560x1600',
|
||||
driveShareTitle: 'Windows 盘符共享',
|
||||
driveShareMaster: '共享 Windows 盘符',
|
||||
@@ -400,6 +499,43 @@ const dict = {
|
||||
driveShareNeedsTools: '需要 Guest Tools {version} 或更新版本。运行中的 VM 要先重启以更新 REIMSTOOLS,然后在 macOS 中重新运行安装命令',
|
||||
driveShareMasterOff: '先开启 Windows 盘符共享',
|
||||
driveShareNoDrives: '没有可共享的内部固定磁盘',
|
||||
affinityTitle: '处理器相关性',
|
||||
affinityMenu: '处理器相关性…',
|
||||
affinityConfigure: '配置…',
|
||||
affinityRowDesc: '控制 QEMU 进程在哪些宿主机逻辑处理器上运行(实时生效,无需重启)',
|
||||
affinitySubtitleRunning: '运行中(PID {pid})· {vcpus} vCPU · 修改后立即生效',
|
||||
affinitySubtitleStopped: '已停止 · {vcpus} vCPU · 下次启动时自动生效',
|
||||
affinityModeAuto: '自动',
|
||||
affinityModeAll: '所有处理器',
|
||||
affinityModePCores: '仅 P 核',
|
||||
affinityModeNonLPE: 'P + E 核',
|
||||
affinityModeCustom: '自定义',
|
||||
affinityModeAutoHint: '跟随全局策略,在混合大小核处理器上自动避开超售与低功耗核。',
|
||||
affinityModeAllHint: '允许 Windows 将 QEMU 调度到全部宿主机逻辑处理器。',
|
||||
affinityModePCoresHint: '仅在性能核(P-Core)上运行,减少大小核混调引起的抖动。',
|
||||
affinityModeNonLPEHint: '在性能核与能效核(P + E)上运行,仅排除慢速低功耗核(LP-E)。',
|
||||
affinityModeCustomHint: '勾选允许运行 QEMU 的逻辑处理器,等价于 Windows 任务管理器的处理器相关性。',
|
||||
affinitySelectAll: '所有处理器',
|
||||
affinityPhysicalOnly: '仅物理核',
|
||||
affinityExcludeCPU0: '排除 CPU 0',
|
||||
affinityOnlyPCores: '仅 P 核',
|
||||
affinityAvoidLPE: '避开 LP-E',
|
||||
affinitySelectedSummary: '已选 {selected} / {total} 个逻辑处理器 · 掩码 {mask}',
|
||||
affinityLiveMask: 'Windows 当前生效:{mask}({count} 线程)',
|
||||
affinityOversubWarn: '当前只勾选了 {selected} 个逻辑处理器,少于虚拟机分配的 {vcpus} 个 vCPU,可能导致明显卡顿。',
|
||||
affinityNeedOne: '请至少勾选 1 个逻辑处理器',
|
||||
affinityEcoQoS: '禁用 Windows 效率模式节流 (EcoQoS)',
|
||||
affinityEcoQoSDesc: '防止 Windows 11 在窗口失焦或后台运行时把 QEMU 线程压缩到 2 个低功耗核心',
|
||||
affinityApplyNow: '立即应用',
|
||||
affinitySave: '保存',
|
||||
affinitySummaryAuto: '自动({eff} · {count} 线程)',
|
||||
affinitySummaryAll: '所有处理器({count} 线程)',
|
||||
affinitySummaryPCores: '仅 P 核({count} 线程 · {mask})',
|
||||
affinitySummaryNonLPE: 'P + E 核({count} 线程 · {mask})',
|
||||
affinitySummaryCustom: '自定义({count} 线程 · {mask})',
|
||||
toastAffinityApplied: '处理器相关性已应用({count} 个逻辑处理器 · {mask})',
|
||||
toastAffinitySaved: '处理器相关性已保存,下次启动时生效',
|
||||
failAffinity: '设置处理器相关性失败',
|
||||
networkDesc: '通过 NAT 共享宿主的网络连接',
|
||||
sshForward: 'SSH 端口转发',
|
||||
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
|
||||
@@ -447,6 +583,11 @@ const dict = {
|
||||
optDiscreteGpuRec: '已检测到独立显卡({name}),新建时默认优先使用',
|
||||
optDiscreteGpuIntegrated: '仅检测到核显({name}),性能弱于独立显卡',
|
||||
optDiscreteGpuUnavailable: '未检测到可用 Vulkan 显卡,可先切换 vmware-svga 排障',
|
||||
optSchedTitle: 'Windows 处理器计划',
|
||||
optSchedPrograms: '程序优先',
|
||||
optSchedBackground: '后台服务',
|
||||
optSchedSub: '「程序」偏向前台窗口;「后台服务」让各进程平均分配 CPU。虚拟机常在后台跑任务时,选「后台服务」更稳定',
|
||||
optSchedOpen: '以管理员身份打开…',
|
||||
kernelIrqchipLabel: 'WHPX 中断模式',
|
||||
kernelIrqchipAuto: '自动',
|
||||
kernelIrqchipOn: '开启',
|
||||
@@ -460,9 +601,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: '启动后直接进入无边框全屏',
|
||||
@@ -513,14 +657,40 @@ const dict = {
|
||||
statsDisk: '磁盘占用',
|
||||
statsUptime: '运行时长',
|
||||
statsDiskSub: '实际 {actual} / 上限 {virtual}',
|
||||
// VM page (2026-11-29 redesign)
|
||||
on: '开启',
|
||||
netShared: '共享网络',
|
||||
netOff: '无网络',
|
||||
specCPUTip: '处理器 {n} 核',
|
||||
specCPULiveTip: '处理器 {n} 核,当前占用 {pct}%',
|
||||
specMemTip: '内存 {mem}',
|
||||
specMemLiveTip: '内存 {mem},虚拟机在宿主上占用 {used}',
|
||||
specNetTip: '与宿主共享网络连接',
|
||||
specNetSSHTip: '与宿主共享网络连接,SSH 端口 {port}',
|
||||
specNetOffTip: '虚拟机没有网络',
|
||||
gtStatusConnected: '已连接',
|
||||
gtStatusWaiting: '未连接',
|
||||
gtStatusWaitingTip: '在 macOS 里运行安装命令后会自动连接',
|
||||
gtStatusEnabled: '已启用',
|
||||
gtStatusNone: '未安装',
|
||||
gtStatusUpgrade: '需要更新',
|
||||
gtInstall: '安装…',
|
||||
gtUpdate: '更新…',
|
||||
gtInstallSub: '在 macOS 终端里运行',
|
||||
pendingRestartHint: '重启虚拟机后生效',
|
||||
},
|
||||
'en-US': {
|
||||
sidebarVMs: 'Virtual machines',
|
||||
sidebarHost: 'Host & runtime',
|
||||
sidebarSystem: 'System',
|
||||
sidebarHost: 'Engine',
|
||||
sidebarSettings: 'Settings',
|
||||
sidebarInstallers: 'Installers',
|
||||
installersTitle: 'Installers',
|
||||
installersDownloaded: 'Downloaded',
|
||||
installersAvailable: 'Releases from Apple',
|
||||
installersLatest: 'Latest',
|
||||
installersOlder: '{count} older versions',
|
||||
installersRetry: 'Retry',
|
||||
installersEmpty: 'No installers downloaded yet',
|
||||
installersPartial: 'Partly downloaded',
|
||||
installersResume: 'Resume',
|
||||
@@ -538,6 +708,90 @@ 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',
|
||||
footerMemLabel: 'Memory',
|
||||
footerMemValue: '{used} / {total} GB',
|
||||
footerDiskLabel: 'Disk',
|
||||
footerDiskValue: '{gb} GB free',
|
||||
footerDiskTip: 'VM data folder: {dir}',
|
||||
footerHostIssue: 'Virtualization not ready',
|
||||
footerHostIssueTip: 'Open the Engine page to see what needs attention',
|
||||
menuBar: 'Menu bar',
|
||||
menuVM: 'VM',
|
||||
menuView: 'View',
|
||||
menuHelp: 'Help',
|
||||
newVMEllipsis: 'New Virtual Machine…',
|
||||
deleteEllipsis: 'Delete…',
|
||||
sidebarLabel: 'Sidebar',
|
||||
showSidebar: 'Show sidebar',
|
||||
hideSidebar: 'Hide sidebar',
|
||||
appearance: 'Appearance',
|
||||
helpProjectPage: 'Project Page',
|
||||
helpReportIssue: 'Report an Issue',
|
||||
helpCheckUpdate: 'Check for Updates…',
|
||||
settingsGeneral: 'General',
|
||||
settingsAppearance: 'Appearance & language',
|
||||
settingsAbout: 'About',
|
||||
themeLabel: 'Appearance',
|
||||
themeLight: 'Light',
|
||||
themeDark: 'Dark',
|
||||
themeSystem: 'System',
|
||||
showWindow: 'Show window',
|
||||
copyScreenshot: 'Copy screenshot',
|
||||
toastScreenshotCopied: 'VM screenshot copied',
|
||||
failFocus: 'Could not focus VM window',
|
||||
failScreenshot: 'Screenshot failed',
|
||||
dropFilesHint: 'Drop files to send to macOS shared folder',
|
||||
toastFilesDelivered: 'Sent {n} files to shared folder',
|
||||
sshOpenTerminal: 'Terminal',
|
||||
sshMore: 'SSH tools',
|
||||
sshWriteConfig: 'Write ~/.ssh/config',
|
||||
sshOpenVSCode: 'Open in VS Code',
|
||||
sshSetUser: 'Set SSH username…',
|
||||
sshUserTitle: 'SSH login username',
|
||||
sshUserDesc: 'Used for Terminal, ~/.ssh/config, and VS Code Remote-SSH (leave empty to omit user)',
|
||||
sshUserPlaceholder: 'e.g. admin',
|
||||
toastSSHConfigWritten: 'Wrote Host {alias}',
|
||||
toastSSHUserSaved: 'Saved SSH username',
|
||||
failSSH: 'SSH action failed',
|
||||
snapshotsTitle: 'Restore points',
|
||||
snapshotCreate: 'New restore point',
|
||||
snapshotEmpty: 'No restore points yet — save one before OS updates or major changes',
|
||||
snapshotHint: 'Offline snapshots · Not a backup',
|
||||
snapshotNamePlaceholder: 'e.g. before-macos-update',
|
||||
snapshotRestore: 'Restore',
|
||||
snapshotRestoreTitle: 'Restore "{name}"?',
|
||||
snapshotRestoreDesc: 'Disk changes made after this restore point will be overwritten and cannot be undone.',
|
||||
snapshotDelete: 'Delete restore point',
|
||||
snapshotStopFirst: 'Stop the VM before managing restore points',
|
||||
toastSnapshotCreated: 'Created restore point {name}',
|
||||
toastSnapshotRestored: 'Restored to {name}',
|
||||
toastSnapshotDeleted: 'Deleted restore point {name}',
|
||||
failSnapshot: 'Restore point failed',
|
||||
displayNameEdit: 'Click to change the display name',
|
||||
displayNameLabel: 'Display name',
|
||||
displayNameEditEllipsis: 'Change Display Name…',
|
||||
displayNameTip: 'Display name · VM name is {name} (click to change)',
|
||||
fieldVMName: 'VM name',
|
||||
logSearchPlaceholder: 'Filter logs…',
|
||||
logErrorsOnly: 'Errors & warnings',
|
||||
logCopy: 'Copy logs',
|
||||
storageBreakdownTitle: 'Storage breakdown',
|
||||
storageVMs: 'VM files',
|
||||
storageInstallers: 'Installers',
|
||||
storageRuntimes: 'Reims-Go',
|
||||
welcomeTitle: 'Create your first macOS VM',
|
||||
welcomeSub: 'Pick an installer, assign cores and GPU, and launch in minutes',
|
||||
welcomeCheckHost: 'Set up Engine first →',
|
||||
|
||||
newVM: 'New virtual machine',
|
||||
start: 'Start',
|
||||
@@ -685,7 +939,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',
|
||||
@@ -733,7 +994,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',
|
||||
@@ -889,6 +1150,8 @@ 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',
|
||||
@@ -899,6 +1162,43 @@ const dict = {
|
||||
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',
|
||||
affinityTitle: 'Processor Affinity',
|
||||
affinityMenu: 'Processor Affinity…',
|
||||
affinityConfigure: 'Configure…',
|
||||
affinityRowDesc: 'Choose which host logical CPUs QEMU can run on (applies live without restarting)',
|
||||
affinitySubtitleRunning: 'Running (PID {pid}) · {vcpus} vCPU · Applies immediately',
|
||||
affinitySubtitleStopped: 'Stopped · {vcpus} vCPU · Applied on next start',
|
||||
affinityModeAuto: 'Auto',
|
||||
affinityModeAll: 'All CPUs',
|
||||
affinityModePCores: 'P-Cores',
|
||||
affinityModeNonLPE: 'P + E',
|
||||
affinityModeCustom: 'Custom',
|
||||
affinityModeAutoHint: 'Follows global policy and avoids oversubscription and slow LP-E cores on hybrid CPUs.',
|
||||
affinityModeAllHint: 'Allows Windows to schedule QEMU across all host logical processors.',
|
||||
affinityModePCoresHint: 'Restricts QEMU to performance cores (P-cores) to minimize scheduling jitter.',
|
||||
affinityModeNonLPEHint: 'Runs QEMU on P + E cores while excluding slow SoC LP-E cores.',
|
||||
affinityModeCustomHint: 'Check the host logical CPUs allowed to run QEMU — identical to Windows Task Manager affinity.',
|
||||
affinitySelectAll: 'All CPUs',
|
||||
affinityPhysicalOnly: 'Physical cores only',
|
||||
affinityExcludeCPU0: 'Exclude CPU 0',
|
||||
affinityOnlyPCores: 'P-cores only',
|
||||
affinityAvoidLPE: 'Exclude LP-E',
|
||||
affinitySelectedSummary: '{selected} / {total} logical CPUs selected · Mask {mask}',
|
||||
affinityLiveMask: 'Active in Windows: {mask} ({count} threads)',
|
||||
affinityOversubWarn: 'Only {selected} logical CPUs selected for {vcpus} guest vCPUs; this may cause noticeable stalls.',
|
||||
affinityNeedOne: 'Select at least 1 logical CPU',
|
||||
affinityEcoQoS: 'Disable Windows EcoQoS power throttling',
|
||||
affinityEcoQoSDesc: 'Prevents Windows 11 from parking unfocused/background QEMU threads onto 2 low-power cores',
|
||||
affinityApplyNow: 'Apply Now',
|
||||
affinitySave: 'Save',
|
||||
affinitySummaryAuto: 'Auto ({eff} · {count}T)',
|
||||
affinitySummaryAll: 'All CPUs ({count}T)',
|
||||
affinitySummaryPCores: 'P-Cores ({count}T · {mask})',
|
||||
affinitySummaryNonLPE: 'P + E ({count}T · {mask})',
|
||||
affinitySummaryCustom: 'Custom ({count}T · {mask})',
|
||||
toastAffinityApplied: 'Processor affinity applied ({count} logical CPUs · {mask})',
|
||||
toastAffinitySaved: 'Processor affinity saved for next start',
|
||||
failAffinity: 'Could not update processor affinity',
|
||||
networkDesc: 'Shares the host connection through NAT',
|
||||
sshForward: 'SSH port forwarding',
|
||||
sshOffDesc: 'Forwards a host port to port 22 in macOS',
|
||||
@@ -946,6 +1246,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',
|
||||
@@ -959,9 +1264,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',
|
||||
@@ -1009,6 +1317,26 @@ const dict = {
|
||||
toastBorderlessNextStart: 'Fullscreen launch saved — applies on next restart',
|
||||
statsCPU: 'QEMU CPU',
|
||||
statsMemory: 'Host RAM',
|
||||
on: 'On',
|
||||
netShared: 'Shared network',
|
||||
netOff: 'No network',
|
||||
specCPUTip: '{n} CPU cores',
|
||||
specCPULiveTip: '{n} CPU cores, {pct}% in use',
|
||||
specMemTip: '{mem} memory',
|
||||
specMemLiveTip: '{mem} memory; the VM uses {used} on this PC',
|
||||
specNetTip: 'Shares this PC’s network connection',
|
||||
specNetSSHTip: 'Shares this PC’s network connection; SSH on port {port}',
|
||||
specNetOffTip: 'The VM has no network',
|
||||
gtStatusConnected: 'Connected',
|
||||
gtStatusWaiting: 'Not connected',
|
||||
gtStatusWaitingTip: 'Connects once the install command has run in macOS',
|
||||
gtStatusEnabled: 'Enabled',
|
||||
gtStatusNone: 'Not installed',
|
||||
gtStatusUpgrade: 'Update needed',
|
||||
gtInstall: 'Install…',
|
||||
gtUpdate: 'Update…',
|
||||
gtInstallSub: 'Run in macOS Terminal',
|
||||
pendingRestartHint: 'Takes effect after a restart',
|
||||
statsDisk: 'Disk usage',
|
||||
statsUptime: 'Uptime',
|
||||
statsDiskSub: '{actual} actual / {virtual} max',
|
||||
|
||||
@@ -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
|
||||
@@ -187,3 +228,28 @@ export function splitLangLabel(value: string, text: string): { value: string; la
|
||||
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
|
||||
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
|
||||
}
|
||||
|
||||
/**
|
||||
* A change saved while the VM runs, as the user would say it:
|
||||
* `memory 8G→16G` becomes "内存 8 GB → 16 GB". Field names come from
|
||||
* PendingChange in internal/app/app.go.
|
||||
*/
|
||||
export function pendingChangeText(locale: Locale, p: { field: string; from: string; to: string }, host: HostReport): string {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const bool = (v: string) => tr(v === 'true' ? 'on' : 'off')
|
||||
const lang = (v: string) => splitLangLabel('', guestLangLabel(locale, v)).label
|
||||
const fields: Record<string, { label: I18nKey; fmt: (v: string) => string }> = {
|
||||
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
|
||||
memory: { label: 'factMemory', fmt: formatMemory },
|
||||
resolution: { label: 'resolution', fmt: resolutionLabel },
|
||||
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
|
||||
displays: { label: 'displays', fmt: (v) => v },
|
||||
borderless: { label: 'borderless', fmt: bool },
|
||||
audio: { label: 'fieldAudio', fmt: bool },
|
||||
audio_backend: { label: 'fieldAudio', fmt: (v) => v },
|
||||
guest_lang: { label: 'specLang', fmt: lang },
|
||||
}
|
||||
const f = fields[p.field]
|
||||
if (!f) return `${p.field} ${p.from} → ${p.to}`
|
||||
return `${tr(f.label)} ${f.fmt(p.from)} → ${f.fmt(p.to)}`
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Which macOS major version a VM runs, for its icon. The release comes from
|
||||
// GetVMMacOS (.reims-go-macos, written at creation: "26.7.3" or "tahoe");
|
||||
// VMs without one are guessed from their name or display name.
|
||||
|
||||
const CODENAMES: [string, number][] = [
|
||||
['tahoe', 26],
|
||||
['sequoia', 15],
|
||||
['sonoma', 14],
|
||||
['ventura', 13],
|
||||
['monterey', 12],
|
||||
['bigsur', 11],
|
||||
['big sur', 11],
|
||||
['big-sur', 11],
|
||||
]
|
||||
|
||||
function fromText(text: string): number | null {
|
||||
const s = text.trim().toLowerCase()
|
||||
if (!s) return null
|
||||
const ver = /^(\d{2})(?:\.\d+)*$/.exec(s)
|
||||
if (ver) return Number(ver[1])
|
||||
for (const [name, major] of CODENAMES) if (s.includes(name)) return major
|
||||
const tagged = /macos[\s_-]*(\d{2})(?!\d)/.exec(s)
|
||||
if (tagged) {
|
||||
const n = Number(tagged[1])
|
||||
if (n >= 10 && n <= 60) return n
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The major version (26, 15, …) from the recorded release, else from the hints. */
|
||||
export function macOSMajor(release: string | undefined, ...hints: (string | undefined)[]): number | null {
|
||||
for (const text of [release, ...hints]) {
|
||||
const n = text ? fromText(text) : null
|
||||
if (n !== null) return n
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -1,6 +1,19 @@
|
||||
import { t } from '../i18n'
|
||||
import { Locale, Task } from '../types'
|
||||
|
||||
// Match the finished-task retention period in internal/app/tasks.go.
|
||||
export const finishedTaskTTL = 10 * 60 * 1000
|
||||
|
||||
export function pruneFinishedTasks(tasks: Record<string, Task>, cutoff: number): Record<string, Task> {
|
||||
let next = tasks
|
||||
for (const task of Object.values(tasks)) {
|
||||
if (task.status === 'running' || task.updated_at >= cutoff) continue
|
||||
if (next === tasks) next = { ...tasks }
|
||||
delete next[task.id]
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/** Insert or replace a task by id; events can arrive out of order, keep the newest. */
|
||||
export function upsertTask(prev: Record<string, Task>, task: Task): Record<string, Task> {
|
||||
const cur = prev[task.id]
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { VMStats } from '../types'
|
||||
import { api } from '../wails'
|
||||
|
||||
// Shared VM stats poller (stats_flow.go). Components that show stats
|
||||
// subscribe with useVMStats, so a tick re-renders only them, not the whole
|
||||
// App. One timer per VM however many subscribe; it pauses while the window
|
||||
// is hidden and samples once on return.
|
||||
|
||||
const RUNNING_MS = 3000
|
||||
// A stopped VM only changes disk usage, so it is sampled rarely.
|
||||
const STOPPED_MS = 30000
|
||||
|
||||
interface Entry {
|
||||
subs: Set<(s: VMStats) => void>
|
||||
running: boolean
|
||||
last: VMStats | null
|
||||
timer?: number
|
||||
}
|
||||
|
||||
const entries = new Map<string, Entry>()
|
||||
|
||||
function sample(name: string) {
|
||||
api.GetVMStats(name)
|
||||
.then((s) => {
|
||||
const e = entries.get(name)
|
||||
if (!e) return
|
||||
e.last = s
|
||||
e.subs.forEach((f) => f(s))
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
function schedule(name: string, e: Entry) {
|
||||
if (e.timer) window.clearInterval(e.timer)
|
||||
e.timer = undefined
|
||||
if (document.hidden || e.subs.size === 0) return
|
||||
e.timer = window.setInterval(() => sample(name), e.running ? RUNNING_MS : STOPPED_MS)
|
||||
}
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
entries.forEach((e, name) => {
|
||||
if (!document.hidden && e.subs.size > 0) sample(name)
|
||||
schedule(name, e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
|
||||
export function latestVMStats(name: string | undefined | null): VMStats | null {
|
||||
return name ? entries.get(name)?.last ?? null : null
|
||||
}
|
||||
|
||||
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
|
||||
export function useVMStats(name: string | null, running: boolean): VMStats | null {
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(name))
|
||||
|
||||
useEffect(() => {
|
||||
if (!name) { setStats(null); return }
|
||||
let e = entries.get(name)
|
||||
if (!e) {
|
||||
e = { subs: new Set(), running, last: null }
|
||||
entries.set(name, e)
|
||||
}
|
||||
setStats(e.last)
|
||||
const sub = (s: VMStats) => setStats(s)
|
||||
e.subs.add(sub)
|
||||
// A state change (start/stop) samples at once and re-paces the timer.
|
||||
e.running = running
|
||||
sample(name)
|
||||
schedule(name, e)
|
||||
return () => {
|
||||
const cur = entries.get(name)
|
||||
if (!cur) return
|
||||
cur.subs.delete(sub)
|
||||
if (cur.subs.size === 0) {
|
||||
if (cur.timer) window.clearInterval(cur.timer)
|
||||
entries.delete(name)
|
||||
}
|
||||
}
|
||||
}, [name, running])
|
||||
|
||||
return stats
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,26 @@
|
||||
// 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
|
||||
export type DisplayPreset = host.DisplayPreset
|
||||
export type AudioInfo = host.AudioInfo
|
||||
export type WHPXCapabilities = host.WHPXCapabilities
|
||||
export type LogicalCPUInfo = host.LogicalCPUInfo
|
||||
|
||||
export type GPUInfo = Model<host.GPUInfo> & {
|
||||
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
|
||||
@@ -40,15 +44,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,13 +64,25 @@ 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
|
||||
export type DriveShareSettings = Model<main.DriveShareSettings>
|
||||
/** 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>
|
||||
export type VMAffinityMode = 'auto' | 'all' | 'pcores' | 'non_lpe' | 'custom'
|
||||
export type VMAffinityUpdate = {
|
||||
mode: VMAffinityMode
|
||||
cpus?: number[]
|
||||
disable_eco_qos: boolean
|
||||
}
|
||||
export type VMAffinityStatus = Omit<Model<app.VMAffinityStatus>, 'mode' | 'effective_mode'> & {
|
||||
mode: VMAffinityMode
|
||||
effective_mode: VMAffinityMode
|
||||
}
|
||||
/** One frame of a VM's screen (internal/app/thumbnail_flow.go). Empty data_url: none yet. */
|
||||
export type VMThumbnail = app.VMThumbnail
|
||||
export type ValidationIssue = reims.ValidationIssue
|
||||
export type DiskResizeResult = reims.DiskResizeResult
|
||||
export type DiskCompactResult = reims.DiskCompactResult
|
||||
export type DiskSnapshot = reims.DiskSnapshot
|
||||
export type StorageBreakdown = Model<app.StorageBreakdown>
|
||||
export type SetOpts = reims.SetOpts
|
||||
|
||||
export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
@@ -82,8 +99,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
|
||||
}
|
||||
@@ -96,10 +113,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,14 +1,16 @@
|
||||
// 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'
|
||||
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task, VMAffinityStatus, VMAffinityUpdate } from './types'
|
||||
|
||||
export const api = {
|
||||
...Go,
|
||||
GetState: Go.GetState as () => Promise<AppState>,
|
||||
GetTasks: Go.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: Go.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: Go.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
ListInstallers: Go.ListInstallers as () => Promise<CachedInstaller[] | null>,
|
||||
ListRemoteRuntimes: Go.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
|
||||
SuggestDataRoots: Go.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
|
||||
@@ -18,4 +20,7 @@ export const events = {
|
||||
onTask: (cb: (task: Task) => void) => EventsOn('reims:task', cb),
|
||||
onStateChanged: (cb: () => void) => EventsOn('reims:state-changed', cb),
|
||||
onLog: (cb: (entry: LogEntry) => void) => EventsOn('reims:log', cb),
|
||||
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
|
||||
onTraySelectVM: (cb: (name: string) => void) => EventsOn('reims:tray-select-vm', cb),
|
||||
onTrayNewVM: (cb: () => void) => EventsOn('reims:tray-new-vm', cb),
|
||||
}
|
||||
@@ -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>;
|
||||
|
||||
@@ -24,14 +24,22 @@ export function CompactVMDisk(arg1:string):Promise<reims.DiskCompactResult>;
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshot(arg1:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DeliverFileToGuest(arg1:string):Promise<string>;
|
||||
|
||||
export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Array<string>>;
|
||||
|
||||
export function DetachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
@@ -50,17 +58,29 @@ export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function GetState():Promise<main.AppState>;
|
||||
export function FocusVMWindow(arg1:string):Promise<void>;
|
||||
|
||||
export function GetTasks():Promise<Array<main.Task>>;
|
||||
export function GetState():Promise<app.AppState>;
|
||||
|
||||
export function GetStorageBreakdown():Promise<app.StorageBreakdown>;
|
||||
|
||||
export function GetTasks():Promise<Array<app.Task>>;
|
||||
|
||||
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<main.DriveShareSettings>;
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<main.VMStats>;
|
||||
export function GetVMMacOS(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<main.VMThumbnail>;
|
||||
export function GetVMNote(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMSSHUser(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
|
||||
|
||||
@@ -72,12 +92,20 @@ export function ListOfflineReleases():Promise<Array<installer.Release>>;
|
||||
|
||||
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function PickDirectory(arg1:string):Promise<string>;
|
||||
|
||||
export function PickFile(arg1:string,arg2:string):Promise<string>;
|
||||
@@ -94,6 +122,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeRe
|
||||
|
||||
export function RestartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetDataRoot(arg1:string):Promise<void>;
|
||||
@@ -106,7 +136,15 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<main.DriveShareSettings>;
|
||||
export function SetRuntimeSource(arg1:string):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ShowMainWindow():Promise<void>;
|
||||
|
||||
@@ -114,7 +152,7 @@ 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>;
|
||||
|
||||
@@ -129,3 +167,5 @@ export function UseRuntime(arg1:string):Promise<void>;
|
||||
export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
|
||||
@@ -0,0 +1,331 @@
|
||||
// @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 CopyVMScreenshot(arg1) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
|
||||
}
|
||||
|
||||
export function CreateSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
return window['go']['app']['App']['CreateVM'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteInstaller(arg1) {
|
||||
return window['go']['app']['App']['DeleteInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function DeleteSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 DeliverPathsToGuest(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeliverPathsToGuest'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 FocusVMWindow(arg1) {
|
||||
return window['go']['app']['App']['FocusVMWindow'](arg1);
|
||||
}
|
||||
|
||||
export function GetState() {
|
||||
return window['go']['app']['App']['GetState']();
|
||||
}
|
||||
|
||||
export function GetStorageBreakdown() {
|
||||
return window['go']['app']['App']['GetStorageBreakdown']();
|
||||
}
|
||||
|
||||
export function GetTasks() {
|
||||
return window['go']['app']['App']['GetTasks']();
|
||||
}
|
||||
|
||||
export function GetVMAffinity(arg1) {
|
||||
return window['go']['app']['App']['GetVMAffinity'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['app']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMMacOS(arg1) {
|
||||
return window['go']['app']['App']['GetVMMacOS'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMNote(arg1) {
|
||||
return window['go']['app']['App']['GetVMNote'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSSHUser(arg1) {
|
||||
return window['go']['app']['App']['GetVMSSHUser'](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 ListSnapshots(arg1) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1);
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
return window['go']['app']['App']['OpenProcessorScheduling']();
|
||||
}
|
||||
|
||||
export function OpenSSHTerminal(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 OpenVSCodeSSH(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 RestoreSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 SetVMAffinity(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMNote(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMNote'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMSSHUser(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function WriteSSHConfig(arg1, arg2) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
|
||||
}
|
||||
@@ -1,251 +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 GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['main']['App']['GetVMDriveShareSettings'](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 SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
return window['go']['main']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -1,301 +1,4 @@
|
||||
export namespace config {
|
||||
|
||||
export class Config {
|
||||
data_root: string;
|
||||
locale: string;
|
||||
active_runtime?: string;
|
||||
auto_pin_pcores: boolean;
|
||||
default_gpu?: string;
|
||||
runtime_channel?: string;
|
||||
minimize_to_tray?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Config(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.data_root = source["data_root"];
|
||||
this.locale = source["locale"];
|
||||
this.active_runtime = source["active_runtime"];
|
||||
this.auto_pin_pcores = source["auto_pin_pcores"];
|
||||
this.default_gpu = source["default_gpu"];
|
||||
this.runtime_channel = source["runtime_channel"];
|
||||
this.minimize_to_tray = source["minimize_to_tray"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace host {
|
||||
|
||||
export class AudioInfo {
|
||||
output_count: number;
|
||||
input_count: number;
|
||||
output_devices?: string[];
|
||||
input_devices?: string[];
|
||||
default_backend?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AudioInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.output_count = source["output_count"];
|
||||
this.input_count = source["input_count"];
|
||||
this.output_devices = source["output_devices"];
|
||||
this.input_devices = source["input_devices"];
|
||||
this.default_backend = source["default_backend"];
|
||||
}
|
||||
}
|
||||
export class DisplayInfo {
|
||||
name?: string;
|
||||
width: number;
|
||||
height: number;
|
||||
scale_pct: number;
|
||||
refresh_hz?: number;
|
||||
primary: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DisplayInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.width = source["width"];
|
||||
this.height = source["height"];
|
||||
this.scale_pct = source["scale_pct"];
|
||||
this.refresh_hz = source["refresh_hz"];
|
||||
this.primary = source["primary"];
|
||||
}
|
||||
}
|
||||
export class DisplayPreset {
|
||||
resolution: string;
|
||||
label: string;
|
||||
hidpi: boolean;
|
||||
recommended?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DisplayPreset(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.resolution = source["resolution"];
|
||||
this.label = source["label"];
|
||||
this.hidpi = source["hidpi"];
|
||||
this.recommended = source["recommended"];
|
||||
}
|
||||
}
|
||||
export class GPUInfo {
|
||||
name: string;
|
||||
vulkan_icd: string;
|
||||
kind: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new GPUInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.vulkan_icd = source["vulkan_icd"];
|
||||
this.kind = source["kind"];
|
||||
}
|
||||
}
|
||||
export class Optimization {
|
||||
id: string;
|
||||
status: string;
|
||||
supported: boolean;
|
||||
recommended: boolean;
|
||||
detail?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Optimization(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.status = source["status"];
|
||||
this.supported = source["supported"];
|
||||
this.recommended = source["recommended"];
|
||||
this.detail = source["detail"];
|
||||
}
|
||||
}
|
||||
export class WHPXCapabilities {
|
||||
modern_os: boolean;
|
||||
apic_emulation: boolean;
|
||||
kernel_irqchip_available: boolean;
|
||||
nested_virt_property: boolean;
|
||||
nested_virt_probe_error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new WHPXCapabilities(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.modern_os = source["modern_os"];
|
||||
this.apic_emulation = source["apic_emulation"];
|
||||
this.kernel_irqchip_available = source["kernel_irqchip_available"];
|
||||
this.nested_virt_property = source["nested_virt_property"];
|
||||
this.nested_virt_probe_error = source["nested_virt_probe_error"];
|
||||
}
|
||||
}
|
||||
export class Report {
|
||||
os: string;
|
||||
arch: string;
|
||||
logical_cpus: number;
|
||||
physical_cores: number;
|
||||
has_hybrid_cores: boolean;
|
||||
p_core_count: number;
|
||||
e_core_count: number;
|
||||
lpe_core_count?: number;
|
||||
p_core_mask: number;
|
||||
p_core_mask_hex: string;
|
||||
p_core_logical_cpus?: number[];
|
||||
e_core_logical_cpus?: number[];
|
||||
non_lpe_mask?: number;
|
||||
non_lpe_mask_hex?: string;
|
||||
non_lpe_logical_cpus?: number[];
|
||||
total_ram_gb: number;
|
||||
avail_ram_gb: number;
|
||||
memory_load_pct: number;
|
||||
commit_avail_gb: number;
|
||||
commit_limit_gb: number;
|
||||
data_root: string;
|
||||
data_root_drive_type?: string;
|
||||
free_disk_gb: number;
|
||||
whpx: string;
|
||||
whpx_caps: WHPXCapabilities;
|
||||
needs_cold_reboot_workaround: boolean;
|
||||
gpus: GPUInfo[];
|
||||
recommended_gpu?: GPUInfo;
|
||||
displays?: DisplayInfo[];
|
||||
primary_display?: DisplayInfo;
|
||||
recommended_resolution?: string;
|
||||
display_presets?: DisplayPreset[];
|
||||
audio: AudioInfo;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Report(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.os = source["os"];
|
||||
this.arch = source["arch"];
|
||||
this.logical_cpus = source["logical_cpus"];
|
||||
this.physical_cores = source["physical_cores"];
|
||||
this.has_hybrid_cores = source["has_hybrid_cores"];
|
||||
this.p_core_count = source["p_core_count"];
|
||||
this.e_core_count = source["e_core_count"];
|
||||
this.lpe_core_count = source["lpe_core_count"];
|
||||
this.p_core_mask = source["p_core_mask"];
|
||||
this.p_core_mask_hex = source["p_core_mask_hex"];
|
||||
this.p_core_logical_cpus = source["p_core_logical_cpus"];
|
||||
this.e_core_logical_cpus = source["e_core_logical_cpus"];
|
||||
this.non_lpe_mask = source["non_lpe_mask"];
|
||||
this.non_lpe_mask_hex = source["non_lpe_mask_hex"];
|
||||
this.non_lpe_logical_cpus = source["non_lpe_logical_cpus"];
|
||||
this.total_ram_gb = source["total_ram_gb"];
|
||||
this.avail_ram_gb = source["avail_ram_gb"];
|
||||
this.memory_load_pct = source["memory_load_pct"];
|
||||
this.commit_avail_gb = source["commit_avail_gb"];
|
||||
this.commit_limit_gb = source["commit_limit_gb"];
|
||||
this.data_root = source["data_root"];
|
||||
this.data_root_drive_type = source["data_root_drive_type"];
|
||||
this.free_disk_gb = source["free_disk_gb"];
|
||||
this.whpx = source["whpx"];
|
||||
this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities);
|
||||
this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"];
|
||||
this.gpus = this.convertValues(source["gpus"], GPUInfo);
|
||||
this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo);
|
||||
this.displays = this.convertValues(source["displays"], DisplayInfo);
|
||||
this.primary_display = this.convertValues(source["primary_display"], DisplayInfo);
|
||||
this.recommended_resolution = source["recommended_resolution"];
|
||||
this.display_presets = this.convertValues(source["display_presets"], DisplayPreset);
|
||||
this.audio = this.convertValues(source["audio"], AudioInfo);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
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 namespace installer {
|
||||
|
||||
export class Cached {
|
||||
name: string;
|
||||
path: string;
|
||||
bytes: number;
|
||||
kind: string;
|
||||
partial: boolean;
|
||||
title?: string;
|
||||
version?: string;
|
||||
build?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Cached(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.path = source["path"];
|
||||
this.bytes = source["bytes"];
|
||||
this.kind = source["kind"];
|
||||
this.partial = source["partial"];
|
||||
this.title = source["title"];
|
||||
this.version = source["version"];
|
||||
this.build = source["build"];
|
||||
}
|
||||
}
|
||||
export class Release {
|
||||
product: string;
|
||||
title: string;
|
||||
version: string;
|
||||
build: string;
|
||||
posted: string;
|
||||
size: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Release(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.product = source["product"];
|
||||
this.title = source["title"];
|
||||
this.version = source["version"];
|
||||
this.build = source["build"];
|
||||
this.posted = source["posted"];
|
||||
this.size = source["size"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace main {
|
||||
export namespace app {
|
||||
|
||||
export class AppState {
|
||||
config?: config.Config;
|
||||
@@ -392,11 +95,11 @@ export namespace main {
|
||||
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"];
|
||||
@@ -410,11 +113,11 @@ export namespace main {
|
||||
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"];
|
||||
@@ -422,7 +125,7 @@ export namespace main {
|
||||
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;
|
||||
@@ -457,6 +160,58 @@ export namespace main {
|
||||
this.to = source["to"];
|
||||
}
|
||||
}
|
||||
export class VMStorageItem {
|
||||
name: string;
|
||||
bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMStorageItem(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.bytes = source["bytes"];
|
||||
}
|
||||
}
|
||||
export class StorageBreakdown {
|
||||
vms_bytes: number;
|
||||
installers_bytes: number;
|
||||
runtimes_bytes: number;
|
||||
total_bytes: number;
|
||||
vms: VMStorageItem[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new StorageBreakdown(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.vms_bytes = source["vms_bytes"];
|
||||
this.installers_bytes = source["installers_bytes"];
|
||||
this.runtimes_bytes = source["runtimes_bytes"];
|
||||
this.total_bytes = source["total_bytes"];
|
||||
this.vms = this.convertValues(source["vms"], VMStorageItem);
|
||||
}
|
||||
|
||||
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 Task {
|
||||
id: string;
|
||||
kind: string;
|
||||
@@ -497,6 +252,58 @@ export namespace main {
|
||||
this.updated_at = source["updated_at"];
|
||||
}
|
||||
}
|
||||
export class VMAffinityStatus {
|
||||
mode: string;
|
||||
cpus: number[];
|
||||
disable_eco_qos: boolean;
|
||||
effective_mode: string;
|
||||
effective_cpus: number[];
|
||||
effective_mask_hex: string;
|
||||
vcpus: number;
|
||||
oversubscribed: boolean;
|
||||
running: boolean;
|
||||
pid?: number;
|
||||
live_cpus?: number[];
|
||||
live_mask_hex?: string;
|
||||
live_read_error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMAffinityStatus(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.mode = source["mode"];
|
||||
this.cpus = source["cpus"];
|
||||
this.disable_eco_qos = source["disable_eco_qos"];
|
||||
this.effective_mode = source["effective_mode"];
|
||||
this.effective_cpus = source["effective_cpus"];
|
||||
this.effective_mask_hex = source["effective_mask_hex"];
|
||||
this.vcpus = source["vcpus"];
|
||||
this.oversubscribed = source["oversubscribed"];
|
||||
this.running = source["running"];
|
||||
this.pid = source["pid"];
|
||||
this.live_cpus = source["live_cpus"];
|
||||
this.live_mask_hex = source["live_mask_hex"];
|
||||
this.live_read_error = source["live_read_error"];
|
||||
}
|
||||
}
|
||||
export class VMAffinityUpdate {
|
||||
mode: string;
|
||||
cpus?: number[];
|
||||
disable_eco_qos: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMAffinityUpdate(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.mode = source["mode"];
|
||||
this.cpus = source["cpus"];
|
||||
this.disable_eco_qos = source["disable_eco_qos"];
|
||||
}
|
||||
}
|
||||
export class VMStats {
|
||||
name: string;
|
||||
running: boolean;
|
||||
@@ -533,6 +340,7 @@ export namespace main {
|
||||
this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"];
|
||||
}
|
||||
}
|
||||
|
||||
export class VMThumbnail {
|
||||
data_url: string;
|
||||
captured_at: number;
|
||||
@@ -552,6 +360,335 @@ export namespace main {
|
||||
|
||||
}
|
||||
|
||||
export namespace config {
|
||||
|
||||
export class Config {
|
||||
data_root: string;
|
||||
locale: string;
|
||||
active_runtime?: string;
|
||||
auto_pin_pcores: boolean;
|
||||
default_gpu?: string;
|
||||
runtime_channel?: string;
|
||||
runtime_source?: string;
|
||||
minimize_to_tray?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Config(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.data_root = source["data_root"];
|
||||
this.locale = source["locale"];
|
||||
this.active_runtime = source["active_runtime"];
|
||||
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"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace host {
|
||||
|
||||
export class AudioInfo {
|
||||
output_count: number;
|
||||
input_count: number;
|
||||
output_devices?: string[];
|
||||
input_devices?: string[];
|
||||
default_backend?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AudioInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.output_count = source["output_count"];
|
||||
this.input_count = source["input_count"];
|
||||
this.output_devices = source["output_devices"];
|
||||
this.input_devices = source["input_devices"];
|
||||
this.default_backend = source["default_backend"];
|
||||
}
|
||||
}
|
||||
export class DisplayInfo {
|
||||
name?: string;
|
||||
width: number;
|
||||
height: number;
|
||||
scale_pct: number;
|
||||
refresh_hz?: number;
|
||||
primary: boolean;
|
||||
work_width?: number;
|
||||
work_height?: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DisplayInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.width = source["width"];
|
||||
this.height = source["height"];
|
||||
this.scale_pct = source["scale_pct"];
|
||||
this.refresh_hz = source["refresh_hz"];
|
||||
this.primary = source["primary"];
|
||||
this.work_width = source["work_width"];
|
||||
this.work_height = source["work_height"];
|
||||
}
|
||||
}
|
||||
export class DisplayPreset {
|
||||
resolution: string;
|
||||
label: string;
|
||||
hidpi: boolean;
|
||||
recommended?: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DisplayPreset(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.resolution = source["resolution"];
|
||||
this.label = source["label"];
|
||||
this.hidpi = source["hidpi"];
|
||||
this.recommended = source["recommended"];
|
||||
}
|
||||
}
|
||||
export class GPUInfo {
|
||||
name: string;
|
||||
vulkan_icd: string;
|
||||
kind: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new GPUInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.vulkan_icd = source["vulkan_icd"];
|
||||
this.kind = source["kind"];
|
||||
}
|
||||
}
|
||||
export class LogicalCPUInfo {
|
||||
index: number;
|
||||
core_index: number;
|
||||
tier: string;
|
||||
smt: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new LogicalCPUInfo(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.index = source["index"];
|
||||
this.core_index = source["core_index"];
|
||||
this.tier = source["tier"];
|
||||
this.smt = source["smt"];
|
||||
}
|
||||
}
|
||||
export class Optimization {
|
||||
id: string;
|
||||
status: string;
|
||||
supported: boolean;
|
||||
recommended: boolean;
|
||||
detail?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Optimization(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.status = source["status"];
|
||||
this.supported = source["supported"];
|
||||
this.recommended = source["recommended"];
|
||||
this.detail = source["detail"];
|
||||
}
|
||||
}
|
||||
export class WHPXCapabilities {
|
||||
modern_os: boolean;
|
||||
apic_emulation: boolean;
|
||||
kernel_irqchip_available: boolean;
|
||||
nested_virt_property: boolean;
|
||||
nested_virt_probe_error?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new WHPXCapabilities(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.modern_os = source["modern_os"];
|
||||
this.apic_emulation = source["apic_emulation"];
|
||||
this.kernel_irqchip_available = source["kernel_irqchip_available"];
|
||||
this.nested_virt_property = source["nested_virt_property"];
|
||||
this.nested_virt_probe_error = source["nested_virt_probe_error"];
|
||||
}
|
||||
}
|
||||
export class Report {
|
||||
os: string;
|
||||
arch: string;
|
||||
logical_cpus: number;
|
||||
physical_cores: number;
|
||||
has_hybrid_cores: boolean;
|
||||
p_core_count: number;
|
||||
e_core_count: number;
|
||||
lpe_core_count?: number;
|
||||
p_core_mask: number;
|
||||
p_core_mask_hex: string;
|
||||
p_core_logical_cpus?: number[];
|
||||
e_core_logical_cpus?: number[];
|
||||
non_lpe_mask?: number;
|
||||
non_lpe_mask_hex?: string;
|
||||
non_lpe_logical_cpus?: number[];
|
||||
cpu_topology?: LogicalCPUInfo[];
|
||||
total_ram_gb: number;
|
||||
avail_ram_gb: number;
|
||||
memory_load_pct: number;
|
||||
commit_avail_gb: number;
|
||||
commit_limit_gb: number;
|
||||
data_root: string;
|
||||
data_root_drive_type?: string;
|
||||
free_disk_gb: number;
|
||||
whpx: string;
|
||||
whpx_caps: WHPXCapabilities;
|
||||
needs_cold_reboot_workaround: boolean;
|
||||
gpus: GPUInfo[];
|
||||
recommended_gpu?: GPUInfo;
|
||||
displays?: DisplayInfo[];
|
||||
primary_display?: DisplayInfo;
|
||||
recommended_resolution?: string;
|
||||
display_presets?: DisplayPreset[];
|
||||
hidpi_advice?: string;
|
||||
fullscreen_hidpi: boolean;
|
||||
processor_scheduling?: string;
|
||||
audio: AudioInfo;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Report(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.os = source["os"];
|
||||
this.arch = source["arch"];
|
||||
this.logical_cpus = source["logical_cpus"];
|
||||
this.physical_cores = source["physical_cores"];
|
||||
this.has_hybrid_cores = source["has_hybrid_cores"];
|
||||
this.p_core_count = source["p_core_count"];
|
||||
this.e_core_count = source["e_core_count"];
|
||||
this.lpe_core_count = source["lpe_core_count"];
|
||||
this.p_core_mask = source["p_core_mask"];
|
||||
this.p_core_mask_hex = source["p_core_mask_hex"];
|
||||
this.p_core_logical_cpus = source["p_core_logical_cpus"];
|
||||
this.e_core_logical_cpus = source["e_core_logical_cpus"];
|
||||
this.non_lpe_mask = source["non_lpe_mask"];
|
||||
this.non_lpe_mask_hex = source["non_lpe_mask_hex"];
|
||||
this.non_lpe_logical_cpus = source["non_lpe_logical_cpus"];
|
||||
this.cpu_topology = this.convertValues(source["cpu_topology"], LogicalCPUInfo);
|
||||
this.total_ram_gb = source["total_ram_gb"];
|
||||
this.avail_ram_gb = source["avail_ram_gb"];
|
||||
this.memory_load_pct = source["memory_load_pct"];
|
||||
this.commit_avail_gb = source["commit_avail_gb"];
|
||||
this.commit_limit_gb = source["commit_limit_gb"];
|
||||
this.data_root = source["data_root"];
|
||||
this.data_root_drive_type = source["data_root_drive_type"];
|
||||
this.free_disk_gb = source["free_disk_gb"];
|
||||
this.whpx = source["whpx"];
|
||||
this.whpx_caps = this.convertValues(source["whpx_caps"], WHPXCapabilities);
|
||||
this.needs_cold_reboot_workaround = source["needs_cold_reboot_workaround"];
|
||||
this.gpus = this.convertValues(source["gpus"], GPUInfo);
|
||||
this.recommended_gpu = this.convertValues(source["recommended_gpu"], GPUInfo);
|
||||
this.displays = this.convertValues(source["displays"], DisplayInfo);
|
||||
this.primary_display = this.convertValues(source["primary_display"], DisplayInfo);
|
||||
this.recommended_resolution = source["recommended_resolution"];
|
||||
this.display_presets = this.convertValues(source["display_presets"], DisplayPreset);
|
||||
this.hidpi_advice = source["hidpi_advice"];
|
||||
this.fullscreen_hidpi = source["fullscreen_hidpi"];
|
||||
this.processor_scheduling = source["processor_scheduling"];
|
||||
this.audio = this.convertValues(source["audio"], AudioInfo);
|
||||
}
|
||||
|
||||
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 namespace installer {
|
||||
|
||||
export class Cached {
|
||||
name: string;
|
||||
path: string;
|
||||
bytes: number;
|
||||
kind: string;
|
||||
partial: boolean;
|
||||
title?: string;
|
||||
version?: string;
|
||||
build?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Cached(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
this.path = source["path"];
|
||||
this.bytes = source["bytes"];
|
||||
this.kind = source["kind"];
|
||||
this.partial = source["partial"];
|
||||
this.title = source["title"];
|
||||
this.version = source["version"];
|
||||
this.build = source["build"];
|
||||
}
|
||||
}
|
||||
export class Release {
|
||||
product: string;
|
||||
title: string;
|
||||
version: string;
|
||||
build: string;
|
||||
posted: string;
|
||||
size: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Release(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.product = source["product"];
|
||||
this.title = source["title"];
|
||||
this.version = source["version"];
|
||||
this.build = source["build"];
|
||||
this.posted = source["posted"];
|
||||
this.size = source["size"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace reims {
|
||||
|
||||
export class CreateOpts {
|
||||
@@ -648,6 +785,24 @@ export namespace reims {
|
||||
this.guest_expand_cmd = source["guest_expand_cmd"];
|
||||
}
|
||||
}
|
||||
export class DiskSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: number;
|
||||
vm_state_bytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DiskSnapshot(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.name = source["name"];
|
||||
this.created_at = source["created_at"];
|
||||
this.vm_state_bytes = source["vm_state_bytes"];
|
||||
}
|
||||
}
|
||||
export class SetOpts {
|
||||
name: string;
|
||||
cpus?: number;
|
||||
@@ -949,6 +1104,7 @@ export namespace runtime {
|
||||
commit: string;
|
||||
tag: string;
|
||||
channel: string;
|
||||
source?: string;
|
||||
published_at: string;
|
||||
page_url: string;
|
||||
archive_name: string;
|
||||
@@ -967,6 +1123,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"];
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// VMAffinityUpdate is the payload passed from the UI to save and live-apply a
|
||||
// VM's CPU affinity mapping and EcoQoS power-throttling policy.
|
||||
type VMAffinityUpdate struct {
|
||||
Mode string `json:"mode"`
|
||||
CPUs []int `json:"cpus,omitempty"`
|
||||
DisableEcoQoS bool `json:"disable_eco_qos"`
|
||||
}
|
||||
|
||||
// VMAffinityStatus describes both the saved per-VM affinity policy and the live
|
||||
// QEMU process affinity state (when the VM is running).
|
||||
type VMAffinityStatus struct {
|
||||
Mode string `json:"mode"`
|
||||
CPUs []int `json:"cpus"`
|
||||
DisableEcoQoS bool `json:"disable_eco_qos"`
|
||||
EffectiveMode string `json:"effective_mode"`
|
||||
EffectiveCPUs []int `json:"effective_cpus"`
|
||||
EffectiveMaskHex string `json:"effective_mask_hex"`
|
||||
VCPUs int `json:"vcpus"`
|
||||
Oversubscribed bool `json:"oversubscribed"`
|
||||
Running bool `json:"running"`
|
||||
PID int `json:"pid,omitempty"`
|
||||
LiveCPUs []int `json:"live_cpus,omitempty"`
|
||||
LiveMaskHex string `json:"live_mask_hex,omitempty"`
|
||||
LiveReadError string `json:"live_read_error,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) findRunningVMPID(ctx context.Context, name string) int {
|
||||
if c, err := a.client(); err == nil {
|
||||
if vms, lerr := c.List(ctx); lerr == nil {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return *vm.PID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, vm := range a.lastVMs {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
return *vm.PID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func buildVMAffinityStatus(detail reims.VMDetail, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
cfg := vmstart.ReadVMAffinity(detail.Directory)
|
||||
res := vmstart.ResolveVMAffinity(cfg, globalAutoPin, rep, detail.CPUs)
|
||||
savedCPUs := cfg.CPUs
|
||||
if savedCPUs == nil {
|
||||
savedCPUs = []int{}
|
||||
}
|
||||
effCPUs := res.CPUs
|
||||
if effCPUs == nil {
|
||||
effCPUs = []int{}
|
||||
}
|
||||
st := VMAffinityStatus{
|
||||
Mode: string(res.ConfigMode),
|
||||
CPUs: savedCPUs,
|
||||
DisableEcoQoS: res.DisableEcoQoS,
|
||||
EffectiveMode: string(res.EffectiveMode),
|
||||
EffectiveCPUs: effCPUs,
|
||||
EffectiveMaskHex: res.MaskHex,
|
||||
VCPUs: detail.CPUs,
|
||||
Oversubscribed: detail.CPUs > 0 && len(effCPUs) > 0 && len(effCPUs) < detail.CPUs,
|
||||
Running: detail.State == "running" || pid > 0,
|
||||
PID: pid,
|
||||
}
|
||||
if pid > 0 {
|
||||
if procMask, _, err := host.GetProcessAffinityMask(uint32(pid)); err == nil {
|
||||
limit := rep.LogicalCPUs
|
||||
if limit <= 0 || limit > 64 {
|
||||
limit = 64
|
||||
}
|
||||
st.LiveCPUs = host.MaskToCPUs(procMask, limit)
|
||||
st.LiveMaskHex = fmt.Sprintf("0x%X", procMask)
|
||||
} else {
|
||||
st.LiveReadError = err.Error()
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
|
||||
// effective CPU set, and live QEMU process affinity mask when running.
|
||||
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
globalAutoPin := a.cfg.AutoPinPCores
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
}
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
|
||||
// SetVMAffinity saves a VM's processor affinity mapping and immediately applies
|
||||
// it (plus EcoQoS power-throttling control) to the running QEMU process if active.
|
||||
func (a *App) SetVMAffinity(name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
detail, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
if detail.Directory == "" {
|
||||
return VMAffinityStatus{}, fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
globalAutoPin := a.cfg.AutoPinPCores
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(root)
|
||||
eco := req.DisableEcoQoS
|
||||
if _, err := vmstart.SaveVMAffinity(detail.Directory, vmstart.VMAffinityConfig{
|
||||
Mode: vmstart.AffinityMode(req.Mode),
|
||||
CPUs: req.CPUs,
|
||||
DisableEcoQoS: &eco,
|
||||
}, rep.LogicalCPUs); err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
|
||||
pid := 0
|
||||
if detail.State == "running" {
|
||||
pid = a.findRunningVMPID(a.baseCtx(), name)
|
||||
}
|
||||
if pid > 0 {
|
||||
line, applyErr := vmstart.ApplyVMAffinity(loc, rep, detail.Directory, globalAutoPin, pid, detail.CPUs, true)
|
||||
if line != "" {
|
||||
a.emitLog(name, line)
|
||||
}
|
||||
if applyErr != nil {
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
|
||||
}
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func TestBuildVMAffinityStatus(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
eco := true
|
||||
if _, err := vmstart.SaveVMAffinity(dir, vmstart.VMAffinityConfig{
|
||||
Mode: vmstart.AffinityCustom,
|
||||
CPUs: []int{0, 2, 4, 6},
|
||||
DisableEcoQoS: &eco,
|
||||
}, 16); err != nil {
|
||||
t.Fatalf("SaveVMAffinity: %v", err)
|
||||
}
|
||||
|
||||
rep := host.Report{LogicalCPUs: 16}
|
||||
st := buildVMAffinityStatus(reims.VMDetail{
|
||||
Name: "test-vm",
|
||||
Directory: dir,
|
||||
CPUs: 6,
|
||||
State: "stopped",
|
||||
}, rep, true, 0)
|
||||
|
||||
if st.Mode != "custom" || st.EffectiveMode != "custom" {
|
||||
t.Fatalf("modes = (%s, %s), want custom", st.Mode, st.EffectiveMode)
|
||||
}
|
||||
if !reflect.DeepEqual(st.EffectiveCPUs, []int{0, 2, 4, 6}) {
|
||||
t.Fatalf("EffectiveCPUs = %v", st.EffectiveCPUs)
|
||||
}
|
||||
if st.EffectiveMaskHex != "0x55" {
|
||||
t.Fatalf("EffectiveMaskHex = %s, want 0x55", st.EffectiveMaskHex)
|
||||
}
|
||||
if !st.Oversubscribed {
|
||||
t.Fatalf("expected Oversubscribed=true for 4 CPUs < 6 vCPUs")
|
||||
}
|
||||
if !st.DisableEcoQoS {
|
||||
t.Fatalf("expected DisableEcoQoS=true")
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -21,6 +23,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"
|
||||
)
|
||||
|
||||
@@ -70,17 +73,29 @@ type App struct {
|
||||
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),
|
||||
@@ -88,6 +103,12 @@ func NewApp() *App {
|
||||
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) {
|
||||
@@ -155,6 +176,7 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
_ = gt.Close(shutCtx)
|
||||
cancel()
|
||||
}
|
||||
releaseVMTyping("")
|
||||
}
|
||||
|
||||
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
|
||||
@@ -162,7 +184,9 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
// Start, stop and delete call wakePoll so their result shows up at once.
|
||||
const (
|
||||
pollBusy = 2 * time.Second
|
||||
pollSteady = 5 * time.Second
|
||||
// Exits are caught at once by watchExits and GUI actions call wakePoll, so
|
||||
// the steady tick only has to notice VMs started or removed elsewhere (CLI).
|
||||
pollSteady = 10 * 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
|
||||
@@ -178,6 +202,7 @@ 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 {
|
||||
@@ -197,16 +222,16 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
watchExits(ctx, vms, exitWatched, a.wakePoll)
|
||||
type pinCandidate struct {
|
||||
name string
|
||||
dir 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
|
||||
@@ -230,17 +255,65 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
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 vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{name: vm.Name, dir: vm.Dir, pid: *vm.PID})
|
||||
}
|
||||
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
|
||||
}
|
||||
sig := b.String()
|
||||
ib := a.imeBridge
|
||||
liveVMs := make(map[string]struct{}, len(vms))
|
||||
for _, vm := range vms {
|
||||
liveVMs[vm.Name] = struct{}{}
|
||||
}
|
||||
removedVMs := make(map[string]struct{})
|
||||
for _, vm := range a.lastVMs {
|
||||
if _, ok := liveVMs[vm.Name]; !ok {
|
||||
removedVMs[vm.Name] = struct{}{}
|
||||
}
|
||||
}
|
||||
for name := range a.rebootWatchers {
|
||||
if _, ok := liveVMs[name]; !ok {
|
||||
removedVMs[name] = struct{}{}
|
||||
}
|
||||
}
|
||||
for name := range a.diskPaths {
|
||||
if _, ok := liveVMs[name]; !ok {
|
||||
removedVMs[name] = struct{}{}
|
||||
}
|
||||
}
|
||||
for name := range a.procSamples {
|
||||
if _, ok := liveVMs[name]; !ok {
|
||||
removedVMs[name] = struct{}{}
|
||||
}
|
||||
}
|
||||
maps.DeleteFunc(a.diskPaths, func(name string, _ cachedDiskPath) bool {
|
||||
_, ok := liveVMs[name]
|
||||
return !ok
|
||||
})
|
||||
maps.DeleteFunc(a.procSamples, func(name string, _ host.ProcessSample) bool {
|
||||
_, ok := liveVMs[name]
|
||||
return !ok
|
||||
})
|
||||
gt := a.guestTools
|
||||
a.lastVMs = append([]reims.VMListItem(nil), vms...)
|
||||
a.lastVMsAt = time.Now()
|
||||
a.mu.Unlock()
|
||||
prunePinnedPIDs(pinnedPIDs, vms)
|
||||
for name := range removedVMs {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, name)
|
||||
delete(a.pendingChanges, name)
|
||||
a.mu.Unlock()
|
||||
stopVMMonitor(name)
|
||||
a.cancelRebootWatcher(name)
|
||||
releaseVMTyping(name)
|
||||
releaseVMThumbnail(name)
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(name)
|
||||
}
|
||||
}
|
||||
if ib != nil {
|
||||
ib.SetTargets(imeTargets)
|
||||
}
|
||||
@@ -257,12 +330,18 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
for _, cand := range toPin {
|
||||
vmCPUs := 0
|
||||
vmDir := cand.dir
|
||||
if c, cerr := a.client(); cerr == nil {
|
||||
if det, derr := c.Show(ctx, cand.name); derr == nil {
|
||||
vmCPUs = det.CPUs
|
||||
if vmDir == "" {
|
||||
vmDir = det.Directory
|
||||
}
|
||||
}
|
||||
}
|
||||
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
|
||||
if line, _ := vmstart.ApplyVMAffinity(loc, cachedHost, vmDir, autoPin, cand.pid, vmCPUs, false); line != "" {
|
||||
a.emitLog(cand.name, line)
|
||||
}
|
||||
}
|
||||
if sig != lastSig {
|
||||
lastSig = sig
|
||||
@@ -290,6 +369,53 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func prunePinnedPIDs(pinned map[int]bool, vms []reims.VMListItem) {
|
||||
running := make(map[int]struct{}, len(vms))
|
||||
for _, vm := range vms {
|
||||
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
running[*vm.PID] = struct{}{}
|
||||
}
|
||||
}
|
||||
for pid := range pinned {
|
||||
if _, ok := running[pid]; !ok {
|
||||
delete(pinned, 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.
|
||||
@@ -399,7 +525,9 @@ func (a *App) GetState() AppState {
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
runtimes, _ := rt.List(&cfgCopy)
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
vms, _ := a.listVMsInternal(context.Background())
|
||||
// The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after
|
||||
// start/stop/delete) instead of another `reims-ctl list` per refresh.
|
||||
vms, _ := a.polledVMs(context.Background())
|
||||
|
||||
var activePatches []string
|
||||
if active != nil {
|
||||
@@ -498,19 +626,17 @@ 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()
|
||||
},
|
||||
OnStartVM: func(name string) {
|
||||
_ = a.StartVM(name)
|
||||
},
|
||||
OnStopVM: func(name string) {
|
||||
_ = a.StopVM(name, false)
|
||||
},
|
||||
OnOpenSharedDir: func(name string) {
|
||||
_ = a.OpenSharedFolder(name)
|
||||
OnNewVM: func() {
|
||||
a.ShowMainWindow()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:tray-new-vm")
|
||||
}
|
||||
},
|
||||
OnVMAction: a.trayVMAction,
|
||||
OnQuit: func() {
|
||||
a.QuitApp()
|
||||
},
|
||||
@@ -518,6 +644,10 @@ func (a *App) startTray() {
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
cached := append([]reims.VMListItem(nil), a.lastVMs...)
|
||||
transitions := make(map[string]string, len(a.transitions))
|
||||
for k, v := range a.transitions {
|
||||
transitions[k] = v
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if len(cached) == 0 {
|
||||
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
||||
@@ -526,10 +656,19 @@ func (a *App) startTray() {
|
||||
}
|
||||
items := make([]tray.VMItem, 0, len(cached))
|
||||
for _, vm := range cached {
|
||||
items = append(items, tray.VMItem{
|
||||
Name: vm.Name,
|
||||
Running: vm.State == "running",
|
||||
})
|
||||
state := vm.State
|
||||
if t := transitions[vm.Name]; t != "" {
|
||||
state = t
|
||||
}
|
||||
// The display name is the VM's note, read straight from its
|
||||
// folder (no reims-ctl call while the menu is opening).
|
||||
label := ""
|
||||
if vm.Dir != "" {
|
||||
if b, err := os.ReadFile(filepath.Join(vm.Dir, vmNoteFileName)); err == nil {
|
||||
label = sanitizeVMNote(string(b))
|
||||
}
|
||||
}
|
||||
items = append(items, tray.VMItem{Name: vm.Name, Label: label, State: state})
|
||||
}
|
||||
return tray.Snapshot{
|
||||
LocaleZh: loc == i18n.ZhCN,
|
||||
@@ -546,6 +685,54 @@ func (a *App) startTray() {
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// trayVMAction runs a command picked from the tray menu. The main window may
|
||||
// be hidden, so failures (and a copied screenshot, which has no other visible
|
||||
// result) are reported as a Windows notification from the tray icon.
|
||||
func (a *App) trayVMAction(name string, act tray.Action) {
|
||||
a.mu.Lock()
|
||||
zh := a.cfg.Locale == i18n.ZhCN
|
||||
tm := a.trayMgr
|
||||
a.mu.Unlock()
|
||||
pick := func(cn, en string) string {
|
||||
if zh {
|
||||
return cn
|
||||
}
|
||||
return en
|
||||
}
|
||||
var err error
|
||||
var failTitle string
|
||||
switch act {
|
||||
case tray.ActStart:
|
||||
err, failTitle = a.StartVM(name), pick("无法启动 ", "Couldn't start ")+name
|
||||
case tray.ActStop:
|
||||
err, failTitle = a.StopVM(name, false), pick("无法关机 ", "Couldn't shut down ")+name
|
||||
case tray.ActForceStop:
|
||||
err, failTitle = a.StopVM(name, true), pick("无法强制关机 ", "Couldn't force shut down ")+name
|
||||
case tray.ActRestart:
|
||||
err, failTitle = a.RestartVM(name), pick("无法重启 ", "Couldn't restart ")+name
|
||||
case tray.ActShowWindow:
|
||||
err, failTitle = a.FocusVMWindow(name), pick("找不到 ", "Couldn't find the window of ")+name+pick(" 的窗口", "")
|
||||
case tray.ActScreenshot:
|
||||
if err = a.CopyVMScreenshot(name); err == nil && tm != nil {
|
||||
tm.Notify(pick("已复制屏幕截图", "Screenshot copied"), name, false)
|
||||
}
|
||||
failTitle = pick("截图失败:", "Screenshot failed: ") + name
|
||||
case tray.ActSharedFolder:
|
||||
err, failTitle = a.OpenSharedFolder(name), pick("无法打开共享文件夹", "Couldn't open the shared folder")
|
||||
case tray.ActOpenInApp:
|
||||
a.ShowMainWindow()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:tray-select-vm", name)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.emitLog(name, failTitle+": "+err.Error())
|
||||
if tm != nil {
|
||||
tm.Notify(failTitle, err.Error(), true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) SetDataRoot(dir string) error {
|
||||
dir = strings.TrimSpace(dir)
|
||||
if dir == "" {
|
||||
@@ -583,6 +770,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
|
||||
@@ -958,7 +1158,14 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
|
||||
delete(a.pendingChanges, name)
|
||||
delete(a.transitions, name)
|
||||
delete(a.diskPaths, name)
|
||||
delete(a.procSamples, name)
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
releaseVMTyping(name)
|
||||
releaseVMThumbnail(name)
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(name)
|
||||
}
|
||||
a.wakePoll()
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
return nil
|
||||
@@ -0,0 +1,123 @@
|
||||
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 TestPrunePinnedPIDs(t *testing.T) {
|
||||
runningPID, stoppedPID := 42, 43
|
||||
pinned := map[int]bool{runningPID: true, stoppedPID: true, 44: true}
|
||||
prunePinnedPIDs(pinned, []reims.VMListItem{
|
||||
{Name: "running", State: "running", PID: &runningPID},
|
||||
{Name: "stopped", State: "stopped", PID: &stoppedPID},
|
||||
})
|
||||
if len(pinned) != 1 || !pinned[runningPID] {
|
||||
t.Fatalf("pinned = %v, want only running PID %d", pinned, runningPID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseVMTypingDrainsAndRemovesQueue(t *testing.T) {
|
||||
const name = "typing-release-test"
|
||||
done := make(chan struct{})
|
||||
a := &App{}
|
||||
typing.mu.Lock()
|
||||
ch := make(chan remoteTextItem)
|
||||
typing.remoteQueues[name] = ch
|
||||
typing.lastHintAt[name] = time.Now()
|
||||
typing.mu.Unlock()
|
||||
go func() {
|
||||
a.runRemoteTextQueue(name, ch)
|
||||
close(done)
|
||||
}()
|
||||
releaseVMTyping(name)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("remote typing worker did not exit")
|
||||
}
|
||||
typing.mu.Lock()
|
||||
defer typing.mu.Unlock()
|
||||
if len(typing.remoteQueues) != 0 || len(typing.lastHintAt) != 0 || len(typing.closing) != 0 {
|
||||
t.Fatal("typing state remains after VM release")
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
@@ -116,14 +116,24 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone settings: %v", serr))
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" {
|
||||
if src.GuestLang != "" || vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if cloned, serr := c.Show(ctx, cloneName); serr == nil && cloned.Directory != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
if src.GuestLang != "" {
|
||||
prep, lerr := a.prep(cloneName)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
}
|
||||
}
|
||||
if lerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not apply clone language (%s): %v", src.GuestLang, lerr))
|
||||
if werr := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); werr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy macOS release: %v", werr))
|
||||
}
|
||||
if vmstart.HasSavedVMAffinity(src.Directory) {
|
||||
if _, aerr := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); aerr != nil {
|
||||
a.emitLog(cloneName, fmt.Sprintf("Warning: could not copy CPU affinity setting: %v", aerr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -106,13 +106,23 @@ func (a *App) createVMFlow(opts reims.CreateOpts) error {
|
||||
if guestLang == "" && opts.SourceMode != "disk" {
|
||||
guestLang = opencore.DefaultGuestLang(cfgCopy.Locale)
|
||||
}
|
||||
if guestLang != "" {
|
||||
vmDir := strings.TrimSpace(opts.Dir)
|
||||
release := ""
|
||||
if opts.SourceMode != "disk" {
|
||||
release = strings.TrimSpace(opts.MacOS)
|
||||
}
|
||||
vmDir := ""
|
||||
if guestLang != "" || release != "" {
|
||||
vmDir = strings.TrimSpace(opts.Dir)
|
||||
if d, serr := c.Show(ctx, opts.Name); serr == nil && d.Directory != "" {
|
||||
vmDir = d.Directory
|
||||
} else if vmDir == "" {
|
||||
vmDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
||||
}
|
||||
}
|
||||
if werr := writeVMMacOS(vmDir, release); werr != nil {
|
||||
a.emitLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
|
||||
}
|
||||
if guestLang != "" {
|
||||
prep, lerr := a.prep(opts.Name)
|
||||
if lerr == nil {
|
||||
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
|
||||
@@ -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"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
@@ -0,0 +1,142 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
)
|
||||
|
||||
const vmNoteFileName = ".reims-go-note"
|
||||
|
||||
// VMStorageItem is one VM's disk footprint under DataRoot.
|
||||
type VMStorageItem struct {
|
||||
Name string `json:"name"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
// StorageBreakdown summarizes how DataRoot space is distributed across VM files,
|
||||
// cached macOS installers, and all other Reims-Go data.
|
||||
type StorageBreakdown struct {
|
||||
VMsBytes int64 `json:"vms_bytes"`
|
||||
InstallersBytes int64 `json:"installers_bytes"`
|
||||
RuntimesBytes int64 `json:"runtimes_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
VMs []VMStorageItem `json:"vms"`
|
||||
}
|
||||
|
||||
// vmDirectory finds a VM's folder from the list pollVMs already holds, so
|
||||
// per-VM file reads (the note) don't each run `reims-ctl show`; it falls
|
||||
// back to show when the list has no entry or no folder for it.
|
||||
func (a *App) vmDirectory(name string) string {
|
||||
if vms, err := a.polledVMs(context.Background()); err == nil {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.Dir != "" {
|
||||
return vm.Dir
|
||||
}
|
||||
}
|
||||
}
|
||||
if d, err := a.GetVMDetail(name); err == nil {
|
||||
return d.Directory
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetVMNote returns the optional single-line note saved for a VM.
|
||||
func (a *App) GetVMNote(name string) string {
|
||||
dir := a.vmDirectory(name)
|
||||
if dir == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(dir, vmNoteFileName))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// SetVMNote stores a short single-line note next to the VM directory.
|
||||
func (a *App) SetVMNote(name, note string) error {
|
||||
note = sanitizeVMNote(note)
|
||||
dir := a.vmDirectory(name)
|
||||
if dir == "" {
|
||||
return fmt.Errorf("VM directory not found")
|
||||
}
|
||||
p := filepath.Join(dir, vmNoteFileName)
|
||||
if note == "" {
|
||||
_ = os.Remove(p)
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(p, []byte(note+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func sanitizeVMNote(note string) string {
|
||||
note = strings.ReplaceAll(note, "\r", " ")
|
||||
note = strings.ReplaceAll(note, "\n", " ")
|
||||
note = strings.TrimSpace(note)
|
||||
runes := []rune(note)
|
||||
if len(runes) > 120 {
|
||||
return string(runes[:120])
|
||||
}
|
||||
return note
|
||||
}
|
||||
|
||||
// GetStorageBreakdown computes disk usage across DataRoot subdirectories.
|
||||
func (a *App) GetStorageBreakdown() StorageBreakdown {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
vmsDir := filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms")
|
||||
return computeStorageBreakdown(cfgCopy.DataRoot, vmsDir, installer.Dir(&cfgCopy), cfgCopy.ImagesDir())
|
||||
}
|
||||
|
||||
func computeStorageBreakdown(dataRoot, vmsDir, installersDir, imagesDir string) StorageBreakdown {
|
||||
var out StorageBreakdown
|
||||
if entries, err := os.ReadDir(vmsDir); err == nil {
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
sz := dirSizeBytes(filepath.Join(vmsDir, e.Name()))
|
||||
out.VMs = append(out.VMs, VMStorageItem{Name: e.Name(), Bytes: sz})
|
||||
out.VMsBytes += sz
|
||||
}
|
||||
}
|
||||
if imgBytes := dirSizeBytes(imagesDir); imgBytes > 0 {
|
||||
out.VMsBytes += imgBytes
|
||||
}
|
||||
sort.Slice(out.VMs, func(i, j int) bool {
|
||||
return out.VMs[i].Bytes > out.VMs[j].Bytes
|
||||
})
|
||||
out.InstallersBytes = dirSizeBytes(installersDir)
|
||||
// Keep the existing JSON field for frontend compatibility, but attribute all
|
||||
// remaining DataRoot usage (runtimes, config, cache, releases, etc.) to Reims-Go.
|
||||
out.RuntimesBytes = dirSizeBytes(dataRoot) - out.VMsBytes - out.InstallersBytes
|
||||
if out.RuntimesBytes < 0 {
|
||||
out.RuntimesBytes = 0
|
||||
}
|
||||
out.TotalBytes = out.VMsBytes + out.InstallersBytes + out.RuntimesBytes
|
||||
return out
|
||||
}
|
||||
|
||||
func dirSizeBytes(root string) int64 {
|
||||
if root == "" {
|
||||
return 0
|
||||
}
|
||||
var total int64
|
||||
_ = filepath.WalkDir(root, func(_ string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if info, err := d.Info(); err == nil {
|
||||
total += info.Size()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return total
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
)
|
||||
|
||||
func TestParseDiskSnapshotsJSON(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"format": "qcow2",
|
||||
"snapshots": [
|
||||
{"id": "1", "name": "before-ota", "vm-state-size": 0, "date-sec": 1764400000},
|
||||
{"id": "2", "name": "clean-xcode", "vm-state-size": 0, "date-sec": 1764403600}
|
||||
]
|
||||
}`)
|
||||
fmtName, snaps, err := reims.ParseDiskSnapshotsJSON(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fmtName != "qcow2" || len(snaps) != 2 || snaps[0].Name != "before-ota" || snaps[1].CreatedAt != 1764403600 {
|
||||
t.Fatalf("unexpected snapshots: format=%q snaps=%+v", fmtName, snaps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotName(t *testing.T) {
|
||||
if got, err := reims.ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" {
|
||||
t.Fatalf("valid name failed: %q %v", got, err)
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(" "); err == nil {
|
||||
t.Fatal("expected error for empty snapshot name")
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(`bad"quote`); err == nil {
|
||||
t.Fatal("expected error for quote in snapshot name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeVMNoteAndStorageBreakdown(t *testing.T) {
|
||||
if got := sanitizeVMNote(" Xcode 26\nBuilder "); got != "Xcode 26 Builder" {
|
||||
t.Fatalf("sanitizeVMNote = %q", got)
|
||||
}
|
||||
root := t.TempDir()
|
||||
vms := filepath.Join(root, "vms")
|
||||
inst := filepath.Join(root, "installers")
|
||||
rtDir := filepath.Join(root, "runtimes")
|
||||
_ = os.MkdirAll(filepath.Join(vms, "mac-a"), 0o755)
|
||||
_ = os.MkdirAll(filepath.Join(vms, "mac-b"), 0o755)
|
||||
_ = os.MkdirAll(inst, 0o755)
|
||||
_ = os.MkdirAll(rtDir, 0o755)
|
||||
_ = os.MkdirAll(filepath.Join(root, "cache"), 0o755)
|
||||
_ = os.WriteFile(filepath.Join(vms, "mac-a", "disk.qcow2"), make([]byte, 200), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(vms, "mac-b", "disk.qcow2"), make([]byte, 500), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(inst, "tahoe.img"), make([]byte, 1000), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(rtDir, "qemu.exe"), make([]byte, 300), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(root, "cache", "download.tmp"), make([]byte, 75), 0o644)
|
||||
_ = os.WriteFile(filepath.Join(root, "reims-go.json"), make([]byte, 25), 0o644)
|
||||
|
||||
bd := computeStorageBreakdown(root, vms, inst, "")
|
||||
if bd.VMsBytes != 700 || bd.InstallersBytes != 1000 || bd.RuntimesBytes != 400 || bd.TotalBytes != 2100 {
|
||||
t.Fatalf("breakdown = %+v", bd)
|
||||
}
|
||||
if len(bd.VMs) != 2 || bd.VMs[0].Name != "mac-b" || bd.VMs[0].Bytes != 500 {
|
||||
t.Fatalf("VMs order = %+v", bd.VMs)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
@@ -311,6 +312,43 @@ func (a *App) DeliverFileToGuest(name string) (string, error) {
|
||||
if err != nil || picked == "" {
|
||||
return "", err
|
||||
}
|
||||
return a.deliverHostFile(name, picked)
|
||||
}
|
||||
|
||||
// DeliverPathsToGuest copies one or more dropped host file paths into
|
||||
// `<DataRoot>/shared/<vmName>`, skipping directories.
|
||||
func (a *App) DeliverPathsToGuest(name string, paths []string) ([]string, error) {
|
||||
if len(paths) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var delivered []string
|
||||
var lastErr error
|
||||
for _, p := range paths {
|
||||
if strings.TrimSpace(p) == "" {
|
||||
continue
|
||||
}
|
||||
st, err := os.Stat(p)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if st.IsDir() {
|
||||
continue
|
||||
}
|
||||
base, err := a.deliverHostFile(name, p)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
delivered = append(delivered, base)
|
||||
}
|
||||
if len(delivered) == 0 && lastErr != nil {
|
||||
return nil, lastErr
|
||||
}
|
||||
return delivered, nil
|
||||
}
|
||||
|
||||
func (a *App) deliverHostFile(name, picked string) (string, error) {
|
||||
sharedDir := a.vmSharedDir(name)
|
||||
if err := os.MkdirAll(sharedDir, 0o755); err != nil {
|
||||
return "", err
|
||||
@@ -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).
|
||||
@@ -0,0 +1,40 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// vmMacOSFileName records which macOS release a VM was created with, for its
|
||||
// icon. reims-ctl keeps no such field in vm.toml.
|
||||
const vmMacOSFileName = ".reims-go-macos"
|
||||
|
||||
// GetVMMacOS returns the macOS release recorded when the VM was created: an
|
||||
// installer version such as "26.7.3", or a codename such as "tahoe" for an
|
||||
// online-recovery install. It is "" for VMs made from an existing disk or
|
||||
// before this was recorded; the UI then guesses from the VM's name.
|
||||
func (a *App) GetVMMacOS(name string) string {
|
||||
dir := a.vmDirectory(name)
|
||||
if dir == "" {
|
||||
return ""
|
||||
}
|
||||
return readVMMacOS(dir)
|
||||
}
|
||||
|
||||
func readVMMacOS(dir string) string {
|
||||
b, err := os.ReadFile(filepath.Join(dir, vmMacOSFileName))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// writeVMMacOS stores release next to vm.toml; an empty release writes nothing.
|
||||
func writeVMMacOS(dir, release string) error {
|
||||
release = strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(release, "\r", ""), "\n", ""))
|
||||
if dir == "" || release == "" {
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(filepath.Join(dir, vmMacOSFileName), []byte(release+"\n"), 0o644)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestVMMacOSRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if got := readVMMacOS(dir); got != "" {
|
||||
t.Fatalf("empty dir: got %q", got)
|
||||
}
|
||||
if err := writeVMMacOS(dir, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := readVMMacOS(dir); got != "" {
|
||||
t.Fatalf("empty release wrote %q", got)
|
||||
}
|
||||
if err := writeVMMacOS(dir, " 26.7.3\r\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := readVMMacOS(dir); got != "26.7.3" {
|
||||
t.Fatalf("got %q, want 26.7.3", got)
|
||||
}
|
||||
if err := writeVMMacOS("", "tahoe"); err != nil {
|
||||
t.Fatalf("no dir should be a no-op, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
@@ -0,0 +1,91 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// ListSnapshots returns all internal qcow2 restore points for a VM, newest first.
|
||||
func (a *App) ListSnapshots(name string) ([]reims.DiskSnapshot, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return nil, nil
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
snaps, err := reims.ListDiskSnapshots(a.baseCtx(), active.QemuImgPath(), env, diskPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(snaps, func(i, j int) bool {
|
||||
return snaps[i].CreatedAt > snaps[j].CreatedAt
|
||||
})
|
||||
return snaps, nil
|
||||
}
|
||||
|
||||
// CreateSnapshot creates a named offline restore point inside a stopped VM's qcow2 disk.
|
||||
func (a *App) CreateSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-c", snapName, "Created restore point")
|
||||
}
|
||||
|
||||
// RestoreSnapshot rolls back a stopped VM's qcow2 disk to the named restore point.
|
||||
func (a *App) RestoreSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-a", snapName, "Restored restore point")
|
||||
}
|
||||
|
||||
// DeleteSnapshot removes a named restore point from a stopped VM's qcow2 disk.
|
||||
func (a *App) DeleteSnapshot(name, snapName string) error {
|
||||
return a.runSnapshotOp(name, "-d", snapName, "Deleted restore point")
|
||||
}
|
||||
|
||||
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return fmt.Errorf("stop %s before managing restore points", name)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return fmt.Errorf("VM %s has no disk path", name)
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return fmt.Errorf("restore points are only supported on .qcow2 disks")
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, snapName, diskPath); err != nil {
|
||||
return err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("%s %q", verb, strings.TrimSpace(snapName)))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const sshUserFileName = ".reims-go-ssh-user"
|
||||
|
||||
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
|
||||
func sshHostAlias(vmName string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("reims-")
|
||||
for _, r := range strings.ToLower(strings.TrimSpace(vmName)) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('-')
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset).
|
||||
func (a *App) GetVMSSHUser(name string) string {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil || d.Directory == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(d.Directory, sshUserFileName))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// SetVMSSHUser persists the preferred SSH login user for a VM.
|
||||
func (a *App) SetVMSSHUser(name, user string) error {
|
||||
user = strings.TrimSpace(user)
|
||||
if user != "" && !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM directory not found")
|
||||
}
|
||||
p := filepath.Join(d.Directory, sshUserFileName)
|
||||
if user == "" {
|
||||
_ = os.Remove(p)
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(p, []byte(user+"\n"), 0o644)
|
||||
}
|
||||
|
||||
// OpenSSHTerminal launches an interactive Windows Terminal (falling back to
|
||||
// PowerShell) connected to the VM's forwarded SSH port.
|
||||
func (a *App) OpenSSHTerminal(name, user string) error {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !d.Network || d.SSHPort <= 0 {
|
||||
return fmt.Errorf("SSH port forwarding is not enabled for %s", name)
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
}
|
||||
target := "127.0.0.1"
|
||||
if user != "" {
|
||||
target = user + "@127.0.0.1"
|
||||
}
|
||||
portStr := fmt.Sprintf("%d", d.SSHPort)
|
||||
var cmd *exec.Cmd
|
||||
if wt, err := exec.LookPath("wt.exe"); err == nil {
|
||||
cmd = exec.Command(wt, "new-tab", "--title", name, "ssh", "-p", portStr, target)
|
||||
} else if ps, err := exec.LookPath("powershell.exe"); err == nil {
|
||||
cmd = exec.Command(ps, "-NoExit", "-Command", fmt.Sprintf("ssh -p %s %s", portStr, target))
|
||||
} else {
|
||||
return fmt.Errorf("neither Windows Terminal (wt.exe) nor powershell.exe was found")
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("open SSH terminal: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr))
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteSSHConfig idempotently writes or updates a Host block for the VM in
|
||||
// ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe").
|
||||
func (a *App) WriteSSHConfig(name, user string) (string, error) {
|
||||
d, err := a.GetVMDetail(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !d.Network || d.SSHPort <= 0 {
|
||||
return "", fmt.Errorf("SSH port forwarding is not enabled for %s", name)
|
||||
}
|
||||
user = strings.TrimSpace(user)
|
||||
if user == "" {
|
||||
user = a.GetVMSSHUser(name)
|
||||
} else if !safeSSHUserRe.MatchString(user) {
|
||||
return "", fmt.Errorf("invalid SSH username %q", user)
|
||||
} else {
|
||||
_ = a.SetVMSSHUser(name, user)
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("locate home directory: %w", err)
|
||||
}
|
||||
sshDir := filepath.Join(home, ".ssh")
|
||||
if err := os.MkdirAll(sshDir, 0o700); err != nil {
|
||||
return "", fmt.Errorf("create ~/.ssh: %w", err)
|
||||
}
|
||||
cfgPath := filepath.Join(sshDir, "config")
|
||||
alias := sshHostAlias(name)
|
||||
if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort))
|
||||
return alias, nil
|
||||
}
|
||||
|
||||
// OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and
|
||||
// launches VS Code (falling back to Cursor) in Remote-SSH mode.
|
||||
func (a *App) OpenVSCodeSSH(name, user string) error {
|
||||
alias, err := a.WriteSSHConfig(name, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var bin string
|
||||
for _, cand := range []string{"code.cmd", "code", "cursor.cmd", "cursor"} {
|
||||
if p, err := exec.LookPath(cand); err == nil {
|
||||
bin = p
|
||||
break
|
||||
}
|
||||
}
|
||||
if bin == "" {
|
||||
return fmt.Errorf("VS Code or Cursor CLI not found on PATH (Host %s has been written to ~/.ssh/config)", alias)
|
||||
}
|
||||
cmd := exec.Command(bin, "--remote", "ssh-remote+"+alias)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("launch editor Remote-SSH: %w", err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias))
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error {
|
||||
startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName)
|
||||
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
|
||||
|
||||
var block strings.Builder
|
||||
block.WriteString(startMark + "\n")
|
||||
block.WriteString(fmt.Sprintf("Host %s\n", alias))
|
||||
block.WriteString(" HostName 127.0.0.1\n")
|
||||
block.WriteString(fmt.Sprintf(" Port %d\n", port))
|
||||
if user != "" {
|
||||
block.WriteString(fmt.Sprintf(" User %s\n", user))
|
||||
}
|
||||
block.WriteString(" StrictHostKeyChecking accept-new\n")
|
||||
block.WriteString(endMark + "\n")
|
||||
|
||||
existingBytes, err := os.ReadFile(cfgPath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
content := strings.ReplaceAll(string(existingBytes), "\r\n", "\n")
|
||||
|
||||
var updated string
|
||||
if si := strings.Index(content, startMark); si >= 0 {
|
||||
if ei := strings.Index(content[si:], endMark); ei >= 0 {
|
||||
endPos := si + ei + len(endMark)
|
||||
if endPos < len(content) && content[endPos] == '\n' {
|
||||
endPos++
|
||||
}
|
||||
updated = content[:si] + block.String() + content[endPos:]
|
||||
}
|
||||
}
|
||||
if updated == "" {
|
||||
if content != "" && !strings.HasSuffix(content, "\n") {
|
||||
content += "\n"
|
||||
}
|
||||
if content != "" && !strings.HasSuffix(content, "\n\n") {
|
||||
content += "\n"
|
||||
}
|
||||
updated = content + block.String()
|
||||
}
|
||||
return os.WriteFile(cfgPath, []byte(updated), 0o600)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSSHHostAlias(t *testing.T) {
|
||||
if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
if got := sshHostAlias("My Mac 26"); got != "reims-my-mac-26" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertSSHConfigBlockIdempotent(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config")
|
||||
initial := "Host prod\n HostName 10.0.0.5\n"
|
||||
if err := os.WriteFile(cfg, []byte(initial), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2222, "alice"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b1, _ := os.ReadFile(cfg)
|
||||
s1 := string(b1)
|
||||
if !strings.Contains(s1, "Host prod") || !strings.Contains(s1, "Host reims-macos-tahoe") || !strings.Contains(s1, "Port 2222") || !strings.Contains(s1, "User alice") {
|
||||
t.Fatalf("unexpected first config:\n%s", s1)
|
||||
}
|
||||
|
||||
// Updating port and user must replace the block in place without duplicating it.
|
||||
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2223, "bob"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b2, _ := os.ReadFile(cfg)
|
||||
s2 := string(b2)
|
||||
if strings.Count(s2, "Host reims-macos-tahoe") != 1 {
|
||||
t.Fatalf("expected single block, got:\n%s", s2)
|
||||
}
|
||||
if !strings.Contains(s2, "Port 2223") || !strings.Contains(s2, "User bob") || strings.Contains(s2, "User alice") {
|
||||
t.Fatalf("block not updated:\n%s", s2)
|
||||
}
|
||||
if !strings.Contains(s2, "Host prod") {
|
||||
t.Fatalf("existing user config lost:\n%s", s2)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -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
|
||||
@@ -6,13 +6,17 @@ package main
|
||||
// show its last screen. Nothing here touches vm.toml or the guest.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
@@ -29,7 +33,10 @@ const thumbWidth = 640
|
||||
|
||||
// thumbLocks keeps one capture per VM in flight: QMP serves a single client
|
||||
// and the page polls on a timer.
|
||||
var thumbLocks sync.Map // name → *sync.Mutex
|
||||
var thumbLocks = struct {
|
||||
mu sync.Mutex
|
||||
locks map[string]*sync.Mutex
|
||||
}{locks: make(map[string]*sync.Mutex)}
|
||||
|
||||
func (a *App) thumbPath(name string) string {
|
||||
a.mu.Lock()
|
||||
@@ -38,12 +45,35 @@ func (a *App) thumbPath(name string) string {
|
||||
return filepath.Join(dir, "thumbs", name+".jpg")
|
||||
}
|
||||
|
||||
func vmThumbLock(name string) *sync.Mutex {
|
||||
thumbLocks.mu.Lock()
|
||||
defer thumbLocks.mu.Unlock()
|
||||
mu := thumbLocks.locks[name]
|
||||
if mu == nil {
|
||||
mu = &sync.Mutex{}
|
||||
thumbLocks.locks[name] = mu
|
||||
}
|
||||
return mu
|
||||
}
|
||||
|
||||
// releaseVMThumbnail waits for an in-flight capture before releasing its lock,
|
||||
// so an old request cannot install a new lock after the VM has been deleted.
|
||||
func releaseVMThumbnail(name string) {
|
||||
mu := vmThumbLock(name)
|
||||
mu.Lock()
|
||||
thumbLocks.mu.Lock()
|
||||
if thumbLocks.locks[name] == mu {
|
||||
delete(thumbLocks.locks, name)
|
||||
}
|
||||
thumbLocks.mu.Unlock()
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// GetVMThumbnail returns the VM's screen: a fresh frame while it runs, else
|
||||
// the last one saved. An empty DataURL means there is no frame to show.
|
||||
func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
path := a.thumbPath(name)
|
||||
l, _ := thumbLocks.LoadOrStore(name, &sync.Mutex{})
|
||||
mu := l.(*sync.Mutex)
|
||||
mu := vmThumbLock(name)
|
||||
if mu.TryLock() {
|
||||
defer mu.Unlock()
|
||||
if t, ok := a.captureThumb(name, path); ok {
|
||||
@@ -53,6 +83,60 @@ func (a *App) GetVMThumbnail(name string) (VMThumbnail, error) {
|
||||
return readThumb(path, false), nil
|
||||
}
|
||||
|
||||
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
|
||||
// restoring it first if minimized (docs/ui-redesign.md §6 B5).
|
||||
func (a *App) FocusVMWindow(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
if !ok || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
if !host.FocusProcessWindow(uint32(*vm.PID)) {
|
||||
return fmt.Errorf("could not locate display window for %s", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyVMScreenshot captures a full-resolution frame from a running VM over QMP
|
||||
// and writes it as a PNG/DIB image to the Windows clipboard.
|
||||
func (a *App) CopyVMScreenshot(name string) error {
|
||||
vm, ok := a.polledVM(name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return fmt.Errorf("VM %s is not running", name)
|
||||
}
|
||||
mu := vmThumbLock(name)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
a.mu.Lock()
|
||||
tmp := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
raw := filepath.Join(tmp, "screenshot-"+name)
|
||||
defer os.Remove(raw)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("capture screen: %w", err)
|
||||
}
|
||||
img, err := thumb.Load(raw, format)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode screen: %w", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return fmt.Errorf("encode PNG: %w", err)
|
||||
}
|
||||
if err := (guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil {
|
||||
return fmt.Errorf("copy image to clipboard: %w", err)
|
||||
}
|
||||
a.emitLog(name, "Copied VM screenshot to clipboard")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
typing.mu.Lock()
|
||||
busy := typing.busy[name]
|
||||
@@ -85,11 +169,11 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
img, err := thumb.Load(raw, format)
|
||||
if err != nil || thumb.Blank(img) {
|
||||
img, err := thumb.LoadPreview(raw, format, thumbWidth)
|
||||
if err != nil || img == nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
jpg, err := thumb.JPEG(thumb.Scale(img, thumbWidth), 80)
|
||||
jpg, err := thumb.JPEG(img, 80)
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestReleaseVMThumbnailRemovesLock(t *testing.T) {
|
||||
const name = "thumbnail-release-test"
|
||||
t.Cleanup(func() { releaseVMThumbnail(name) })
|
||||
first := vmThumbLock(name)
|
||||
if got := vmThumbLock(name); got != first {
|
||||
t.Fatal("same VM should share a thumbnail lock")
|
||||
}
|
||||
releaseVMThumbnail(name)
|
||||
thumbLocks.mu.Lock()
|
||||
remaining := len(thumbLocks.locks)
|
||||
thumbLocks.mu.Unlock()
|
||||
if remaining != 0 {
|
||||
t.Fatalf("thumbnail locks remain after release: %d", remaining)
|
||||
}
|
||||
if got := vmThumbLock(name); got == first {
|
||||
t.Fatal("released lock was reused")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -34,10 +34,12 @@ var typing = struct {
|
||||
busy map[string]bool
|
||||
lastHintAt map[string]time.Time
|
||||
remoteQueues map[string]chan remoteTextItem
|
||||
closing map[string]bool
|
||||
}{
|
||||
busy: map[string]bool{},
|
||||
lastHintAt: map[string]time.Time{},
|
||||
remoteQueues: map[string]chan remoteTextItem{},
|
||||
closing: map[string]bool{},
|
||||
}
|
||||
|
||||
// ErrNotTypeable is what the UI matches to show its own message.
|
||||
@@ -184,15 +186,48 @@ func (a *App) injectRemoteText(vmName, vmDir, text string) {
|
||||
typing.remoteQueues[vmName] = ch
|
||||
go a.runRemoteTextQueue(vmName, ch)
|
||||
}
|
||||
typing.mu.Unlock()
|
||||
|
||||
if typing.closing[vmName] {
|
||||
typing.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// releaseVMTyping closes ch under this lock. Keep the nonblocking send
|
||||
// inside the same critical section as the closing check.
|
||||
select {
|
||||
case ch <- remoteTextItem{vmDir: vmDir, text: text}:
|
||||
default:
|
||||
}
|
||||
typing.mu.Unlock()
|
||||
}
|
||||
|
||||
func releaseVMTyping(vmName string) {
|
||||
typing.mu.Lock()
|
||||
names := []string{vmName}
|
||||
if vmName == "" {
|
||||
names = make([]string, 0, len(typing.remoteQueues))
|
||||
for name := range typing.remoteQueues {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
for _, name := range names {
|
||||
ch := typing.remoteQueues[name]
|
||||
if ch == nil {
|
||||
delete(typing.lastHintAt, name)
|
||||
} else if !typing.closing[name] {
|
||||
typing.closing[name] = true
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
typing.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) {
|
||||
defer func() {
|
||||
typing.mu.Lock()
|
||||
delete(typing.remoteQueues, vmName)
|
||||
delete(typing.lastHintAt, vmName)
|
||||
delete(typing.closing, vmName)
|
||||
typing.mu.Unlock()
|
||||
}()
|
||||
for item := range ch {
|
||||
dir := item.vmDir
|
||||
combined := item.text
|
||||
@@ -201,7 +236,10 @@ func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) {
|
||||
if !isControlOnlyText(combined) {
|
||||
for draining := true; draining; {
|
||||
select {
|
||||
case next := <-ch:
|
||||
case next, ok := <-ch:
|
||||
if !ok {
|
||||
return // the VM was removed while draining the queue
|
||||
}
|
||||
if isControlOnlyText(next.text) {
|
||||
_, _ = a.injectTextIntoVM(vmName, dir, combined, true)
|
||||
combined = next.text
|
||||
@@ -0,0 +1,22 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRemoteTextWorkerExitsWithPendingTextOnClosedQueue(t *testing.T) {
|
||||
queue := make(chan remoteTextItem, 1)
|
||||
queue <- remoteTextItem{text: "pending input"}
|
||||
close(queue)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
new(App).runRemoteTextQueue("removed-test-vm", queue)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("worker kept draining the closed queue")
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// vmMonitors holds per-VM background log tailers & boot/install heartbeats.
|
||||
@@ -49,12 +50,15 @@ func stopAllVMMonitors() {
|
||||
}
|
||||
|
||||
func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Time) {
|
||||
stopVMMonitor(name)
|
||||
if detail.Directory == "" {
|
||||
stopVMMonitor(name)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(a.baseCtx())
|
||||
vmMonitors.mu.Lock()
|
||||
if cur, ok := vmMonitors.entries[name]; ok {
|
||||
cur.cancel()
|
||||
}
|
||||
vmMonitors.seq++
|
||||
myID := vmMonitors.seq
|
||||
vmMonitors.entries[name] = struct {
|
||||
@@ -82,9 +86,8 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
diskPath := filepath.Join(detail.Directory, "disk.qcow2")
|
||||
|
||||
// Only read logs belonging to this boot (ignore files last touched before StartVM).
|
||||
serialOff := initialLogOffset(serialPath, startAt)
|
||||
qemuOff := initialLogOffset(qemuPath, startAt)
|
||||
var serialPartial, qemuPartial string
|
||||
serial := logTail{offset: initialLogOffset(serialPath, startAt)}
|
||||
qemu := logTail{offset: initialLogOffset(qemuPath, startAt)}
|
||||
seenEvents := map[string]bool{}
|
||||
|
||||
lastDiskSize := fileSizeBytes(diskPath)
|
||||
@@ -104,16 +107,13 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-logTicker.C:
|
||||
var newLines []string
|
||||
serialOff, serialPartial, newLines = readNewLogLines(serialPath, serialOff, serialPartial)
|
||||
for _, line := range newLines {
|
||||
for _, line := range serial.read(serialPath) {
|
||||
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
|
||||
seenEvents[key] = true
|
||||
a.emitLog(name, msg)
|
||||
}
|
||||
}
|
||||
qemuOff, qemuPartial, newLines = readNewLogLines(qemuPath, qemuOff, qemuPartial)
|
||||
for _, line := range newLines {
|
||||
for _, line := range qemu.read(qemuPath) {
|
||||
if key, msg := parseQemuMilestone(loc, line); msg != "" {
|
||||
if key != "" && seenEvents[key] {
|
||||
continue
|
||||
@@ -214,44 +214,57 @@ func initialLogOffset(path string, startAt time.Time) int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func readNewLogLines(path string, offset int64, partial string) (int64, string, []string) {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return offset, partial, nil
|
||||
}
|
||||
// Log rotated or recreated (e.g., new boot overwrote serial.log / qemu.log).
|
||||
if info.Size() < offset {
|
||||
offset = 0
|
||||
partial = ""
|
||||
}
|
||||
if info.Size() == offset {
|
||||
return offset, partial, nil
|
||||
}
|
||||
const maxMonitorLine = 64 << 10
|
||||
|
||||
type logTail struct {
|
||||
offset int64
|
||||
partial string
|
||||
skipping bool // an oversized line continues into the next read
|
||||
}
|
||||
|
||||
func (t *logTail) read(path string) []string {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return offset, partial, nil
|
||||
return nil
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.Seek(offset, io.SeekStart); err != nil {
|
||||
return offset, partial, nil
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
// Log rotated or recreated (e.g., new boot overwrote serial.log / qemu.log).
|
||||
if info.Size() < t.offset {
|
||||
*t = logTail{}
|
||||
}
|
||||
if info.Size() == t.offset {
|
||||
return nil
|
||||
}
|
||||
const maxChunk = 256 * 1024
|
||||
data, err := io.ReadAll(io.LimitReader(f, maxChunk))
|
||||
if err != nil || len(data) == 0 {
|
||||
return offset, partial, nil
|
||||
data := make([]byte, min(info.Size()-t.offset, maxChunk))
|
||||
n, err := f.ReadAt(data, t.offset)
|
||||
if (err != nil && err != io.EOF) || n == 0 {
|
||||
return nil
|
||||
}
|
||||
offset += int64(len(data))
|
||||
combined := partial + string(data)
|
||||
parts := strings.Split(combined, "\n")
|
||||
partial = parts[len(parts)-1]
|
||||
lines := make([]string, 0, len(parts)-1)
|
||||
for _, p := range parts[:len(parts)-1] {
|
||||
s := strings.TrimSpace(strings.TrimRight(p, "\r"))
|
||||
if s != "" {
|
||||
t.offset += int64(n)
|
||||
var lines []string
|
||||
for rest := string(data[:n]); rest != ""; {
|
||||
line, after, complete := strings.Cut(rest, "\n")
|
||||
rest = after
|
||||
if t.skipping || len(t.partial)+len(line) > maxMonitorLine {
|
||||
t.partial = ""
|
||||
t.skipping = !complete
|
||||
continue
|
||||
}
|
||||
if !complete {
|
||||
t.partial = strings.Clone(t.partial + line)
|
||||
break
|
||||
}
|
||||
if s := strings.TrimSpace(t.partial + line); s != "" {
|
||||
lines = append(lines, s)
|
||||
}
|
||||
t.partial = ""
|
||||
}
|
||||
return offset, partial, lines
|
||||
return lines
|
||||
}
|
||||
|
||||
func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) {
|
||||
@@ -364,24 +377,13 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
case strings.Contains(lowExtra, "kernel-irqchip=on"):
|
||||
irqMode = "on"
|
||||
}
|
||||
plan := host.SelectSafeAffinity(rep, detail.CPUs)
|
||||
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
|
||||
if loc == i18n.ZhCN {
|
||||
coldStr := "关闭"
|
||||
if qmpAddr != "" {
|
||||
coldStr = "开启"
|
||||
}
|
||||
pinStr := "关"
|
||||
if pinPCores && rep.HasHybridCores {
|
||||
switch plan.Mode {
|
||||
case "pcores":
|
||||
pinStr = fmt.Sprintf("开(%dP/%d线程)", plan.CoreCount, plan.ThreadCount)
|
||||
case "non_lpe":
|
||||
pinStr = fmt.Sprintf("P+E(%d核/%d线程,避开LP-E)", plan.CoreCount, plan.ThreadCount)
|
||||
default:
|
||||
pinStr = fmt.Sprintf("自动跳过(%d核≥%dP线程)", detail.CPUs, plan.PThreads)
|
||||
}
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 绑P核=%s · Win10冷重启=%s",
|
||||
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 核心映射=%s · Win10冷重启=%s",
|
||||
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
|
||||
return
|
||||
}
|
||||
@@ -389,17 +391,6 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
if qmpAddr != "" {
|
||||
coldStr = "on"
|
||||
}
|
||||
pinStr := "off"
|
||||
if pinPCores && rep.HasHybridCores {
|
||||
switch plan.Mode {
|
||||
case "pcores":
|
||||
pinStr = fmt.Sprintf("on(%dP/%dT)", plan.CoreCount, plan.ThreadCount)
|
||||
case "non_lpe":
|
||||
pinStr = fmt.Sprintf("P+E(%dC/%dT,no-LPE)", plan.CoreCount, plan.ThreadCount)
|
||||
default:
|
||||
pinStr = fmt.Sprintf("skipped(%dvCPU>=%dPT)", detail.CPUs, plan.PThreads)
|
||||
}
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · P-core=%s · Win10-cold-reboot=%s",
|
||||
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · affinity=%s · Win10-cold-reboot=%s",
|
||||
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -9,6 +12,44 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestLogTailDiscardsOversizeLinesAndResumes(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "serial.log")
|
||||
write := func(flags int, text string) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|flags, 0o600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.WriteString(text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var tail logTail
|
||||
write(os.O_TRUNC, "boot\r\n"+strings.Repeat("x", maxMonitorLine))
|
||||
if got := tail.read(path); !slices.Equal(got, []string{"boot"}) || len(tail.partial) != maxMonitorLine {
|
||||
t.Fatal("expected a complete line and an unfinished line at the limit")
|
||||
}
|
||||
for range 12 {
|
||||
write(os.O_APPEND, strings.Repeat("y", maxMonitorLine))
|
||||
if got := tail.read(path); len(got) != 0 || !tail.skipping || len(tail.partial) != 0 {
|
||||
t.Fatal("oversized line retained across polls")
|
||||
}
|
||||
}
|
||||
write(os.O_APPEND, "ignored\r\nnext\r\npar")
|
||||
if got := tail.read(path); !slices.Equal(got, []string{"next"}) {
|
||||
t.Fatalf("after discarded line: %q", got)
|
||||
}
|
||||
write(os.O_APPEND, "tial\n"+strings.Repeat("z", maxMonitorLine+1))
|
||||
if got := tail.read(path); !slices.Equal(got, []string{"partial"}) || !tail.skipping {
|
||||
t.Fatalf("after split line: %q", got)
|
||||
}
|
||||
write(os.O_TRUNC, "new boot\n")
|
||||
if got := tail.read(path); !slices.Equal(got, []string{"new boot"}) {
|
||||
t.Fatalf("after truncation: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSerialAndQemuMilestones(t *testing.T) {
|
||||
k, msg := parseSerialMilestone(i18n.ZhCN, `BdsDxe: starting Boot0002 "UEFI QEMU HARDDISK"`)
|
||||
if k != "serial:boot" || !strings.Contains(msg, "OpenCore") {
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
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
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -51,16 +51,19 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
|
||||
}); 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))
|
||||
vmDir := vm.Dir
|
||||
if vmDir == "" {
|
||||
vmDir = d.Directory
|
||||
}
|
||||
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -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,118 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DiskSnapshot describes one internal qcow2 snapshot returned by `qemu-img info --output=json`.
|
||||
type DiskSnapshot struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt int64 `json:"created_at"` // Unix seconds
|
||||
VMStateBytes int64 `json:"vm_state_bytes"` // 0 for offline disk-only snapshots
|
||||
}
|
||||
|
||||
type qemuImgInfoJSON struct {
|
||||
Format string `json:"format"`
|
||||
Snapshots []struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
VMStateSize int64 `json:"vm-state-size"`
|
||||
DateSec int64 `json:"date-sec"`
|
||||
} `json:"snapshots"`
|
||||
}
|
||||
|
||||
// ParseDiskSnapshotsJSON parses `qemu-img info --output=json` output.
|
||||
func ParseDiskSnapshotsJSON(raw []byte) (string, []DiskSnapshot, error) {
|
||||
var info qemuImgInfoJSON
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
return "", nil, fmt.Errorf("parse qemu-img info json: %w", err)
|
||||
}
|
||||
out := make([]DiskSnapshot, 0, len(info.Snapshots))
|
||||
for _, s := range info.Snapshots {
|
||||
out = append(out, DiskSnapshot{
|
||||
ID: s.ID,
|
||||
Name: s.Name,
|
||||
CreatedAt: s.DateSec,
|
||||
VMStateBytes: s.VMStateSize,
|
||||
})
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(info.Format)), out, nil
|
||||
}
|
||||
|
||||
// ListDiskSnapshots lists internal qcow2 snapshots via `qemu-img info --output=json`.
|
||||
func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, diskPath string) ([]DiskSnapshot, error) {
|
||||
if _, err := os.Stat(qemuImgPath); err != nil {
|
||||
return nil, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--output=json", diskPath)
|
||||
configureCmd(cmd)
|
||||
cmd.Env = env
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg != "" {
|
||||
return nil, fmt.Errorf("qemu-img info %s: %s", filepath.Base(diskPath), msg)
|
||||
}
|
||||
return nil, fmt.Errorf("qemu-img info %s: %w", filepath.Base(diskPath), err)
|
||||
}
|
||||
format, snaps, err := ParseDiskSnapshotsJSON(stdout.Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if format != "qcow2" {
|
||||
return nil, nil
|
||||
}
|
||||
return snaps, nil
|
||||
}
|
||||
|
||||
// ValidateSnapshotName checks that a snapshot tag is safe for `qemu-img snapshot`.
|
||||
func ValidateSnapshotName(snapName string) (string, error) {
|
||||
snapName = strings.TrimSpace(snapName)
|
||||
if snapName == "" {
|
||||
return "", fmt.Errorf("snapshot name is required")
|
||||
}
|
||||
if len([]rune(snapName)) > 64 {
|
||||
return "", fmt.Errorf("snapshot name must be 64 characters or fewer")
|
||||
}
|
||||
for _, r := range snapName {
|
||||
if r < 0x20 || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {
|
||||
return "", fmt.Errorf("snapshot name contains invalid characters")
|
||||
}
|
||||
}
|
||||
return snapName, nil
|
||||
}
|
||||
|
||||
// RunDiskSnapshot executes `qemu-img snapshot <flag> <snapName> <diskPath>`
|
||||
// where flag is "-c" (create), "-a" (apply/restore), or "-d" (delete).
|
||||
func RunDiskSnapshot(ctx context.Context, qemuImgPath string, env []string, flag, snapName, diskPath string) error {
|
||||
if _, err := os.Stat(qemuImgPath); err != nil {
|
||||
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
||||
}
|
||||
snapName, err := ValidateSnapshotName(snapName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, qemuImgPath, "snapshot", flag, snapName, diskPath)
|
||||
configureCmd(cmd)
|
||||
cmd.Env = env
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg != "" {
|
||||
return fmt.Errorf("qemu-img snapshot %s %q: %s", flag, snapName, msg)
|
||||
}
|
||||
return fmt.Errorf("qemu-img snapshot %s %q: %w", flag, snapName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -276,6 +276,26 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnregisterVMReleasesVMState(t *testing.T) {
|
||||
srv := NewServer(&memClipboard{})
|
||||
cfg := VMConfig{VMName: "deleted-vm", Token: strings.Repeat("a", 64), SharedDir: t.TempDir()}
|
||||
srv.RegisterVM(cfg)
|
||||
if _, err := srv.getOrCreateDAVHandler(cfg.VMName, cfg.SharedDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.mu.Lock()
|
||||
srv.davHandlers[cfg.VMName+"/drives/C"] = srv.davHandlers[cfg.VMName]
|
||||
srv.davRoots[cfg.VMName+"/drives/C"] = `C:\`
|
||||
srv.mu.Unlock()
|
||||
|
||||
srv.UnregisterVM(cfg.VMName)
|
||||
srv.mu.RLock()
|
||||
defer srv.mu.RUnlock()
|
||||
if len(srv.vms) != 0 || len(srv.davHandlers) != 0 || len(srv.davRoots) != 0 {
|
||||
t.Fatalf("VM state remains: vms=%d davHandlers=%d davRoots=%d", len(srv.vms), len(srv.davHandlers), len(srv.davRoots))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerWebDAVAuthAndOperations(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
vmDir := filepath.Join(tmp, "vm")
|
||||
|
||||
@@ -381,6 +381,22 @@ func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// UnregisterVM releases all host-side state owned by a deleted VM. In-flight
|
||||
// requests retain only their own snapshot and fail authentication on retry.
|
||||
func (s *Server) UnregisterVM(vmName string) {
|
||||
s.mu.Lock()
|
||||
delete(s.vms, vmName)
|
||||
delete(s.davHandlers, vmName)
|
||||
delete(s.davRoots, vmName)
|
||||
for key := range s.davHandlers {
|
||||
if strings.HasPrefix(key, vmName+"/") {
|
||||
delete(s.davHandlers, key)
|
||||
delete(s.davRoots, key)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetHostTextHandler registers a callback invoked when a host-side window hook
|
||||
// (e.g. reims-vgpu-window WM_CHAR bridge) submits Unicode text to POST /v1/host-text.
|
||||
func (s *Server) SetHostTextHandler(fn func(vmName, text string)) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||